Commit Graph
40 Commits
Author SHA1 Message Date
TATSUNO “Taz” Yasuhiro 382218204b test(compat): cover Lambda Web Functions in the Node SDK suite (#7002) 2026-10-30 07:58:27 -04:00
jwoa95andPriamo 7c4d1c913a fix(ses): delete by id and filter by source in /_aws/ses (#5159)
* fix(ses): delete by id and filter by source in /_aws/ses

The inspection endpoint follows LocalStack's contract, as
docs/services/ses.md says, but differed from it in two ways. LocalStack
documents that "The query parameter id can be used to delete only a
specific message", and that "Query parameters id and email can be used
to filter by message ID and message source respectively".

- DELETE /_aws/ses?id=<id> cleared every message. It now deletes only
  that message, in whichever region it was sent. An unknown id deletes
  nothing.
- GET /_aws/ses?email=<address> matched the address against each
  message's ToAddresses. It now matches the message's Source, as
  LocalStack does.

GET also listed messages in storage hash order. It now lists them
oldest first by Timestamp, the order LocalStack keeps them in.

Floci's own tests read Cognito codes and other mail with
?email=<recipient>. They now list the mailbox and pick the recipient's
messages out of it, through a new SesMailbox test helper in src/test and
the same filtering in the Java and Node compatibility tests. A raw
send's mailbox entry shows RawData without its recipients, so the test
for recipients read from a raw message's headers checks the stored
record.

* fix(codeartifact): run the pypiserver sidecar under an init process so a stop ends it at once

The pypiserver image's entrypoint execs pypi-server, which installs no SIGTERM handler. The kernel
gives PID 1 no default signal actions, so the container ignored every stop request and went only
when Docker sent SIGKILL at the end of the 5-second timeout: each reset, repository delete and
shutdown waited that long for every pypi repository's container, one after another.

ContainerBuilder gains withInit(), carried on ContainerSpec as init and passed to Docker as
HostConfig.Init (docker run --init), and PypiserverSidecarManager uses it. Docker's init runs as
PID 1 and forwards the SIGTERM, so a stop now returns in a fraction of a second. Verdaccio already
handles the signal itself and is unchanged.

* fix(firehose): check buffers every second so delivery follows the buffering interval

AWS delivers a Firehose buffer once the first buffer condition is met. Floci checked for elapsed
buffering intervals on a 10-second tick, so a buffer was delivered up to 10 seconds after its
IntervalInSeconds ended: a 5-second interval landed anywhere from 5 to 15 seconds after the first
record. The default tick is now one second; the check is a scan of the in-memory buffers.

FirehoseFlushIntegrationTest's profile only set the same one-second tick, so it is removed and the
class shares the default test application. The compat tests that wait for a delivery checked S3
every 2 or 5 seconds; against Floci they now check every 250 ms, and keep their cadence against
real AWS.

* test: make subclass mocks the default so mocking stays cheap in a loaded test JVM

Mockito's default inline mock maker redefines every class it mocks in the running JVM. A
redefinition gets slow once the test JVM has loaded the Quarkus applications of the classes that
ran before, which in CI is most of the run: a unit class's first test spent seconds building its
mocks, and EmulatorLifecycleTest, which mocks some fifty types, spent 22 seconds. Subclass mocks
generate a subclass instead and redefine nothing. After twelve Quarkus applications in one JVM, the
fourteen Mockito classes whose first test was slowest in CI take 20.5 seconds instead of 41.9, and
their first tests 6.9 seconds instead of 27.8.

mockito-extensions/org.mockito.plugins.MockMaker makes the subclass mock maker the default. A
subclass cannot extend a final class, record or enum, so those mocks go through
InlineMocks.inlineMock and inlineSpy, or @Mock(mockMaker = MockMakers.INLINE), and
EmulatorLifecycleTest's static mock of Quarkus asks for the inline maker. The ContainerSpec mocks
a mocked ContainerBuilder.Builder returned were opaque values, so they are real specs now.

* fix(cloudformation): leave the last rollback's failed delete to ContinueUpdateRollback

#4949 refuses an update over UPDATE_ROLLBACK_FAILED until ContinueUpdateRollback finishes the
rollback, as AWS does. #4834, merged minutes earlier, had seven tests that update over that
status, and main has failed them since c4a809f47.

Six are in CloudFormationSchedulerScheduleIntegrationTest. They now reach their next update the
way AWS requires: ContinueUpdateRollback, which retries the schedule's own rollback, or, where the
replacement's delete has to keep failing, a skip of the schedule. The two whose update was meant to
be blocked by the pending rollback now check that the update is refused.

The seventh shows a real clash. #4949 made a second ReplacementCleanup.rollback retry the delete
the first one could not make, which is ContinueUpdateRollback's job. The Scheduler provisioner also
calls rollbackUpdate inside an update, to undo its own failed call, so after a skip a failed group
move deleted the earlier orphan there and then, and a failure of that delete would have failed the
move's restore. An update now ends that retry as it starts, through
ReplacementCleanup.endRollbackRetry, so the orphan stays owed for the next committed update or the
stack delete, as both changes document.

Three more provisioners roll an update back before ReplacementCleanup.record has cleared the retry,
and each returns as soon as the retry ran, skipping its own restore. CloudWatchDashboard and
IotAuthorizer unwind a failed in-place update that way, and CognitoResourceServer's failed attempt
is rolled back the same way, so after a skip the update's snapshot was never put back while the
resource was reported restored. They end the retry as an update starts too.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-10-14 10:04:48 -04:00
Vũ Thế Huy 436c15ca38 fix(sts): reject AssumeRole for roles that do not exist (#4463)
* fix(sts): từ chối AssumeRole khi role không tồn tại trong IAM

AssumeRole trước đây cấp credential cho mọi role ARN, kể cả role chưa
từng được tạo (iam:GetRole trả NoSuchEntity). Giờ trả AccessDenied như
AWS, bất kể enforcement có bật hay không; trust policy vẫn chỉ được
đánh giá khi enforcement bật. Các test cũ assume role chưa tạo được sửa
để tạo role trước.

Closes #4392

* fix(sts): so sánh chính xác role ARN và cập nhật compatibility tests

- StsQueryHandler: kiểm tra roleArn khớp chính xác role.getArn() để tránh chấp nhận role cùng tên khác path

- StsQueryHandlerTest: đổi tham số helper sang IamRole thay vì Optional, bổ sung test case từ chối role khác path

- AssumeRoleTrustPolicyIntegrationTest: sửa Javadoc mô tả đúng hành vi từ chối unknown role

- Cập nhật compatibility tests (Java, Node, Python, AWS CLI) để tạo role trước khi assume và kiểm tra lỗi 403 khi role không tồn tại

* fix(sts): accept partition-correct role ARNs and strictly catch cleanup exceptions

- StsQueryHandler: match role ARN structurally using AwsArnUtils to admit valid noncommercial partition ARNs

- StsQueryHandler: preserve caller partition when generating assumedRoleArn

- StsTest, test_sts.py, sts.test.ts: only ignore NoSuchEntity/EntityAlreadyExists in cleanup, re-raising unexpected errors per AGENTS.md

- StsQueryHandlerTest, AssumeRoleTrustPolicyIntegrationTest: add unit and integration coverage for partition-correct role ARNs

* fix(sts): preserve role partition in resolved session caller ARN

* fix(sts): preserve stored role partition in assumed identity

* fix(sts): validate web identity role ARN

* fix(sts): require role existence in AssumeRoleWithWebIdentity and reuse path helpers

* fix(sts): keep IAM ARN partition behavior unchanged

* fix(sts): derive trust caller account from identity ARN

* fix(iam): migrate legacy credential reports by partition

* fix(iam): serialize legacy credential report migration

* test(iam): make credential report race deterministic

* fix(sts): address review feedback

* fix(sts): reuse IAM role path normalization
2026-10-01 13:18:07 -04:00
Priamo Germosen 06007deea8 fix(cognito): default ExplicitAuthFlows to refresh, SRP and custom auth (#4081)
A user pool client created without ExplicitAuthFlows was treated as allowing every auth flow, where AWS defaults such a client to ALLOW_REFRESH_TOKEN_AUTH, ALLOW_USER_SRP_AUTH and ALLOW_CUSTOM_AUTH. USER_PASSWORD_AUTH against a no-list client succeeded on Floci and is refused on AWS.

Apply that default at auth time, in the existing gate added by #3974. CreateUserPoolClient, UpdateUserPoolClient and DescribeUserPoolClient keep storing and returning exactly what was normalized, empty when unset, matching AWS: Terraform's Cognito acceptance tests confirm the empty read-back for both an omitted list and an explicit empty one, and materialising the default into storage would fail Terraform apply with an inconsistent-result error.

Tests and compatibility fixtures that created a no-list client and then signed in with a flow outside the default now enable that flow on their client.
2026-09-22 07:41:58 -05:00
Ovidiu (Ovi) fb82fb29ae fix(apigateway): answer an unmatched REST request with 403, not 404/405 (#3547)
* fix(apigateway): fall back to a parameterised sibling on method mismatch

A literal resource that declares some methods but not the requested one
returned 405 even when a parameterised sibling could serve it. Resource
candidates are ordered exact, then parameterised, then greedy, and the
selection loop stopped at the first candidate with any methods configured.

For /users/me declaring only PATCH, GET /users/me therefore returned 405
instead of resolving against /users/{userId}, where "me" is an ordinary
parameter value. Adding a literal child for one method silently removes
every other method a parameterised sibling already served, so this surfaces
as a regression in an application that was working.

The stop was there for a narrower reason, which the existing tests pin: a
method mismatch on a concrete resource must not be absorbed by a greedy
/{proxy+} catch-all. That rule is kept. Only the concrete-to-concrete case
changes, so a literal now yields to a parameterised sibling that can serve
the method, while /devices declaring POST still returns 405 for GET rather
than falling through to /{proxy+}.

Extends ApiGatewayRoutingFallthroughIntegrationTest, which already covers
the greedy cases, with /users/{userId} GET alongside a literal /users/me
PATCH: GET /users/me resolves to the parameterised resource, PATCH still
prefers the literal, and an ordinary id is unaffected.

* fix(apigateway): resolve the method against every matching resource

The selection loop stopped considering less specific siblings once a
resource declaring methods had been passed, so a method mismatch on a
concrete resource was terminal for the greedy half of the rule.

Captured against a real REST API in us-west-2: AWS picks the most
specific resource that can serve the requested method, searching
literal, then path parameter, then greedy {proxy+}, and refuses the
request only when no candidate declares it.

Drop concreteWithMethodsSeen and the greedy break so both fallbacks
follow that single rule. /users/me declaring only PATCH no longer hides
GET /users/{userId}, and /devices declaring only POST now falls through
to GET /{proxy+}.

getDevicesReturns405 pinned the greedy half of the old behaviour and is
updated to assert the fallthrough. Adds compatibility coverage for the
sibling and greedy fallbacks from the same AWS repro.

The no-match response is unchanged: AWS returns 403 Missing
Authentication Token where floci returns 405, tracked separately.

* fix(apigateway): answer an unmatched REST request with 403, not 404/405

A REST request that reached no method returned 404 "Not Found" when the
path matched nothing and 405 "Method Not Allowed" when it matched
resources declaring no usable method. AWS returns neither.

Captured against a real REST API in us-west-2 with /users/{userId} GET
and a literal /users/me PATCH deployed. POST /users/me, DELETE
/users/abc123, GET /zzz, GET /users/a/b/c and GET / all answered:

    403  {"message":"Missing Authentication Token"}
    x-amzn-ErrorType: MissingAuthenticationTokenException

AWS resolves the path and the method as one step, so an unknown path and
a known path carrying no usable method are the same failure and share one
response. This is the well-known "Missing Authentication Token" result of
calling a REST API with the wrong verb, which callers match on.

Route both branches through restNoMatch(), rendering the status, body and
error-type header AWS pairs with this failure, alongside the existing
AWS_IAM MISSING rejection that already returns that shape.

HTTP APIs are untouched: they answer an unmatched route with 404
{"message":"Not Found"}, which the v2 dispatch path continues to do.

* test(apigateway): expect 403 for a path that reaches no resource

ApiGatewayGreedyPathParameterIntegrationTest arrived on main after this
branch was cut, and pinned the old 404 for a REST path matching no
resource. This branch changes that contract to 403 "Missing Authentication
Token", so the assertion was stale rather than a real regression.

The test's intent is unchanged: /other/img/logo.png must not be swallowed
by the greedy resource. Only the no-match response it asserts moves.

HTTP API v2 is untouched and still answers an unmatched route with 404
"Not Found".
2026-09-14 09:42:36 -04:00
Ovidiu (Ovi) e8edc3d4b1 fix(apigateway): take the last value of a repeated query string parameter (#3548)
A REST proxy event built queryStringParameters from the FIRST value of a
repeated parameter, so ?x=1&x=2&x=3 reached the integration as "1".

Captured against a real REST API in us-west-2 with a Lambda proxy
integration: AWS collapses a repeated parameter to the LAST value,
yielding {"x":"3"}, while multiValueQueryStringParameters keeps every
value in order as ["1","2","3"]. A trailing empty value still wins, so
?x=1&x= yields "".

This is the same rule putSingleValueHeaders already applies to duplicate
request headers one method above, where the comment notes that taking the
first value diverged from AWS. Query strings were left on the old
behaviour; they now match.

Also pins two properties that were already correct, so they stay that
way: a bracketed name such as filter[status]=open reaches the integration
unchanged, and an absent query string nulls both maps.

putQueryStringParameters and putMultiValueQueryStringParameters become
package-private for the unit test, matching putSingleValueHeaders and
putMultiValueHeaders next to them.

HTTP APIs are untouched. Their payload formats join duplicates with a
comma rather than taking one value, which is a different rule and is not
measured here.
2026-09-13 18:41:22 -04:00
Ovidiu (Ovi) f03a716e90 fix(apigateway): fall back to a parameterised sibling on method mismatch (#3399)
* fix(apigateway): fall back to a parameterised sibling on method mismatch

A literal resource that declares some methods but not the requested one
returned 405 even when a parameterised sibling could serve it. Resource
candidates are ordered exact, then parameterised, then greedy, and the
selection loop stopped at the first candidate with any methods configured.

For /users/me declaring only PATCH, GET /users/me therefore returned 405
instead of resolving against /users/{userId}, where "me" is an ordinary
parameter value. Adding a literal child for one method silently removes
every other method a parameterised sibling already served, so this surfaces
as a regression in an application that was working.

The stop was there for a narrower reason, which the existing tests pin: a
method mismatch on a concrete resource must not be absorbed by a greedy
/{proxy+} catch-all. That rule is kept. Only the concrete-to-concrete case
changes, so a literal now yields to a parameterised sibling that can serve
the method, while /devices declaring POST still returns 405 for GET rather
than falling through to /{proxy+}.

Extends ApiGatewayRoutingFallthroughIntegrationTest, which already covers
the greedy cases, with /users/{userId} GET alongside a literal /users/me
PATCH: GET /users/me resolves to the parameterised resource, PATCH still
prefers the literal, and an ordinary id is unaffected.

* fix(apigateway): resolve the method against every matching resource

The selection loop stopped considering less specific siblings once a
resource declaring methods had been passed, so a method mismatch on a
concrete resource was terminal for the greedy half of the rule.

Captured against a real REST API in us-west-2: AWS picks the most
specific resource that can serve the requested method, searching
literal, then path parameter, then greedy {proxy+}, and refuses the
request only when no candidate declares it.

Drop concreteWithMethodsSeen and the greedy break so both fallbacks
follow that single rule. /users/me declaring only PATCH no longer hides
GET /users/{userId}, and /devices declaring only POST now falls through
to GET /{proxy+}.

getDevicesReturns405 pinned the greedy half of the old behaviour and is
updated to assert the fallthrough. Adds compatibility coverage for the
sibling and greedy fallbacks from the same AWS repro.

The no-match response is unchanged: AWS returns 403 Missing
Authentication Token where floci returns 405, tracked separately.
2026-09-13 14:45:50 -04:00
Niels Kootstra bf49390969 fix(compat): avoid CloudWatch statistics time race (#3320) 2026-09-09 22:46:00 -04:00
Mihai BlidaruandMihai Blidaru 724be0a6a7 fix(s3): return composite multipart checksums and match S3 on UploadPart, GetObjectAttributes and CopyObject responses (#3093)
* fix(s3): return composite checksums for multipart uploads

CompleteMultipartUpload stored the checksum of the whole object but labelled
it COMPOSITE, so clients that recompute the composite value from the part
checksums, as the AWS documentation describes, never matched it.

Follow the AWS checksum type rules, verified against real S3:

- SHA1/SHA256 are always COMPOSITE, CRC32/CRC32C default to COMPOSITE and
  CRC64NVME is always FULL_OBJECT. x-amz-checksum-type on CreateMultipartUpload
  selects FULL_OBJECT for CRC32/CRC32C; incompatible combinations fail with
  InvalidRequest, and the response echoes x-amz-checksum-algorithm/-type.
- The composite value is the algorithm applied to the concatenated binary part
  checksums, Base64 encoded, with a "-<part count>" suffix. It is returned by
  CompleteMultipartUpload, HeadObject and GetObject (with x-amz-checksum-type),
  while GetObjectAttributes omits the suffix, as AWS does.
- A checksum sent on CompleteMultipartUpload is validated against the stored
  type: a mismatching value is a BadDigest (the composite is accepted with or
  without its suffix), a checksum type different from the one the upload was
  created with is an InvalidRequest, per-part checksums in the request body
  that do not match the uploaded parts are an InvalidPart, and a COMPOSITE
  upload completed without the checksum of every part is an InvalidRequest
  (FULL_OBJECT uploads need none, as on S3). A non-numeric
  PartNumber is a MalformedXML instead of a 500.
- UploadPart echoes the part checksum (x-amz-checksum-<algorithm>) when the
  upload declared an algorithm, as S3 does; without one no header is returned.
- CopyObject writes a single object without a part manifest; a composite source
  gets a full-object checksum recomputed with its algorithm, and CopyObjectResult
  carries the checksum elements, matching AWS.
- GetObjectAttributes lists part-level checksums only for COMPOSITE objects: a
  FULL_OBJECT multipart object reports its PartsCount alone and a single-part
  object has no ObjectParts element.

The algorithm and type rules live in two new enums, ChecksumAlgorithm and
ChecksumType, parsed once from the request headers; S3Checksum builds the
full-object, composite and GetObjectAttributes views of a checksum.

The boto3 compatibility suite gains multipart upload_file cases for SHA256 and
for the SDK's default CRC32, asserting the composite value and the part list.

The S3 docs drop the stale note that checksum responses focus on SHA-1 and
SHA-256 (CRC32, CRC32C and CRC64NVME have been supported since #877) and list
the AWS algorithms Floci rejects.

* fix(s3): return the GetObjectAttributes ETag without quotes

S3 returns the ETag element of GetObjectAttributes without the surrounding
quotes that HeadObject, ListParts and CompleteMultipartUpload keep. Verified
against real S3 with the same object: head_object gives "af3c...-3" while
get_object_attributes gives af3c...-3, and the AWS CLI reference shows the same
in its get-object-attributes example. Floci echoed the quoted value, so a client
comparing both saw different strings on Floci and equal ones nowhere.

* fix(s3): give a copied object its own ETag

CopyObject kept the ETag of the source, so the copy of a multipart object
carried the "<md5-of-md5s>-N" value of its parts. S3 writes a copy as a single
object and returns the MD5 of the whole content as its ETag, in CopyObjectResult
and HeadObject alike (verified against real S3: source "af3c...-3", copy
"a5f04f..."). The copy now keeps the ETag storeObject computes.

* fix(s3): send CopyObjectResult as application/xml

The CopyObject response carried Content-Type: text/plain;charset=UTF-8 for an
XML body. S3 labels it application/xml like every other XML response.

* test(s3): cover multipart checksums in every SDK compatibility suite

Each SDK implements flexible checksums differently, so the multipart flows are
exercised per client rather than once: the Go transfer manager (what
terraform-provider-aws uses), @aws-sdk/lib-storage for Node, the Java SDK v2 both
low-level and through S3TransferManager on the multipart-enabled async client, the
AWS CLI (s3api, aws s3 cp --checksum-algorithm and a plain aws s3 cp that goes
multipart on its own) and boto3. Every case asserts the composite or full-object value computed in the
test itself, the UploadPart echo, the suffix-less GetObjectAttributes checksum
and unquoted ETag, the rejected Complete without part checksums, and the copy
of a multipart object as a single full object with its own ETag. The default
algorithm cases accept whatever the SDK version declares (CRC32 composite or
full object, or none) and check the stored value against it.

* test(terraform): upload a large aws_s3_object with Terraform and OpenTofu

The IaC suites created buckets but never an object, so the code path that
surfaced the composite checksum bug, an aws_s3_object above the provider's part
size uploaded through the SDK transfer manager, was not covered. Both suites now
upload a 12 MiB file generated by the test setup with checksum_algorithm SHA256
and check that HeadObject reports a COMPOSITE checksum equal to the composite
computed locally over the part sizes GetObjectAttributes lists, that the state
attribute holds the same value, and that re-planning the object shows no drift.

compat-opentofu moves to the same aws-cli image as compat-terraform (2.34.32):
2.15 predates the S3 checksum type and cannot show ChecksumType in its output.

* fix(s3): reject x-amz-checksum-type without a checksum algorithm

CreateMultipartUpload only parsed x-amz-checksum-type when an algorithm was
declared, so a type sent on its own, valid or not, was silently ignored. S3
validates the header regardless: an unknown value is InvalidRequest "Value for
x-amz-checksum-type header is invalid." and a valid one without an algorithm is
InvalidRequest "The x-amz-checksum-type header can only be used with the
x-amz-checksum-algorithm header." (both verified against real S3).

* test(s3): log cleanup failures in the multipart checksum compat tests

The Java, Node and Go cases swallowed errors while deleting their objects and
bucket. They now report what could not be deleted and why, so a leftover is
diagnosable instead of silent.

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-09-05 15:12:13 -04:00
Vũ Thế Huy 262495df67 fix(dynamodb): reject unused ExpressionAttributeNames/Values on PutItem, DeleteItem, Scan, Query (#2923)
* fix(dynamodb): reject unused ExpressionAttributeNames/Values on PutItem, DeleteItem, Scan, Query

The checkUnusedEan / checkUnusedEav helpers were only wired into handleUpdateItem
and (names only) handleQuery, so PutItem, DeleteItem and Scan accepted expression
attribute entries not referenced by any expression and performed the operation,
where AWS returns ValidationException. Query accepted unused values for the same
reason.

Wire both helpers into handlePutItem, handleDeleteItem and handleScan, and add the
missing checkUnusedEav call to handleQuery, each checking against the tokens
actually referenced by that operation's expressions.

Closes #2893

* fix(dynamodb): also reject unused EAV on legacy KeyConditions + FilterExpression Query

Addresses PR review: the unused ExpressionAttributeNames/Values check in
handleQuery was gated on KeyConditionExpression != null, so a Query combining
legacy KeyConditions with FilterExpression skipped it. Widen the guard to fire
whenever any expression parameter (KCE, FilterExpression, ProjectionExpression)
is present, and add an integration case for the mixed path. Also replace an em
dash in the new test comment per repo style.

* test(dynamodb): reference the aliased name in the reserved-word conformance case

The sdk-test-node "reserved word aliased via ExpressionAttributeNames passes"
case supplied ExpressionAttributeNames {#st: status} on a PutItem whose
ConditionExpression (attribute_not_exists(pk)) never referenced #st. Real AWS —
and now Floci, per #2893 — rejects unused ExpressionAttributeNames entries with
ValidationException. Point the ConditionExpression at #st so the alias is
actually used; the reserved-word aliasing behaviour under test is unchanged.

* fix(dynamodb): run Query unused EAN/EAV check unconditionally

Addresses PR review: the previous guard (keyConditionExpr || filterExpr ||
projectionExpression) still let a legacy KeyConditions Query carrying a stray
ExpressionAttributeNames/Values map through without validation. Drop the guard
so the checks always run; the token sets are still derived only from the
expressions that can legitimately reference those maps, so a correct request is
unaffected. Add an integration case for legacy KeyConditions with no expression
parameter.

* test(dynamodb): reference the aliased name in the sdk-test-java reserved-word case

Mirror of the sdk-test-node fix: reservedWordWithAliasPasses supplied an unused
ExpressionAttributeNames {#st: status} on a PutItem whose ConditionExpression
referenced pk, which #2893 now correctly rejects. Point the condition at #st.

* fix(dynamodb): AWS "can only be specified when using expressions" wording for PutItem/DeleteItem

Addresses PR review: when ExpressionAttributeNames/Values is supplied with no
expression parameter at all, this PR's new checkUnusedEan/checkUnusedEav calls
reported "Value provided in ExpressionAttributeNames unused in expressions:
keys: {...}". Real AWS answers that sub-case with "<param> can only be
specified when using expressions: ConditionExpression is null" instead.

Add rejectExprAttrsWithoutExpression, parameterised on the null-expression
message, and wire it into handlePutItem and handleDeleteItem ahead of the
unused-alias checks. Both operations only accept ConditionExpression, so the
named param is unambiguous; the wording matches the pre-existing PutItem+EAV
guard from #826. EAV is checked before EAN to preserve that guard's order.

Scan and Query still return the "unused in expressions" 400 for this sub-case:
those ops accept multiple expression parameters and AWS's exact wording there
is unverified. The helper is parameterised so it is a one-line change per op
once the strings are measured.
2026-09-03 10:49:08 -04:00
Brian Taylor 906717a510 feat(cognito): implement SetUserPoolMfaConfig (#2831)
* feat(cognito): implement SetUserPoolMfaConfig

The action was unrouted, so the dispatcher answered UnsupportedOperation
and any caller configuring pool MFA failed. GetUserPoolMfaConfig already
existed but reported only MfaConfiguration, so a software-token setting
could not round-trip even once it could be set.

SetUserPoolMfaConfig now stores the MFA mode and the software-token
setting, and both actions answer with the shape measured on the live
service: only configured factors appear, so SoftwareTokenMfaConfiguration
is omitted until it is set.

SMS, email and WebAuthn MFA are accepted and deliberately not stored —
Floci has no path to deliver those factors, and retaining the config
would claim a capability that does not exist.

* test(cognito): cover MFA configuration through the AWS SDK

The integration test drives the endpoint over raw HTTP, so nothing
exercised the new action through a real SDK client. Adds coverage for
the three cases that matter to a caller: an unconfigured pool reports
OFF with no software-token member, a set round-trips through Get, and an
invalid MfaConfiguration is rejected.

* fix(cognito): follow the measured SetUserPoolMfaConfig semantics

Three behaviours were taken from the API reference and turned out wrong
when measured against the live service:

  - an absent MfaConfiguration means OFF, not "leave the current mode
    alone", so a pool set to OPTIONAL is reset by a request that omits it
  - turning MFA off drops the factor configuration with it; the service
    answers OFF alone afterwards
  - sending a factor while the effective mode is OFF is rejected with
    "can't turn off MFA and configure an MFA together"

The enum in the validation message is also ordered [OPTIONAL, OFF, ON],
as the service emits it. Two tests asserted the previous guesses and
passed, which is how a guess becomes apparent evidence; both now pin the
measured behaviour.

* fix(cognito): apply the MFA factor rules to email and SMS, not just the software token

Review flagged that a request combining an effective OFF mode with
EmailMfaConfiguration or SmsMfaConfiguration was accepted, since only
SoftwareTokenMfaConfiguration was read. Measured against the live
service, and the finding holds for email and SMS but not for WebAuthn:

  - OFF + EmailMfaConfiguration is rejected with the same message as
    OFF + SoftwareTokenMfaConfiguration
  - OFF + WebAuthnConfiguration returns 200 and echoes the block back
  - the rule fires on the member being present, not on Enabled: OFF
    alongside SoftwareTokenMfaConfiguration{Enabled:false} is rejected

The same pass turned up the mirror rule, which was also missing: ON or
OPTIONAL with none of the three factors present is rejected with
"SMS MFA, Email MFA, or Software Token MFA must be enabled". Despite
that wording it is again presence, not value - ON alongside
SoftwareTokenMfaConfiguration{Enabled:false} is accepted - and WebAuthn
does not satisfy it, so it sits outside both rules in both directions.

One existing test set ON with no factor at all, which the live service
refuses; it now sends a factor.

* test(cognito): read the MFA config tests in their execution order

The methods were laid out 1, 2, 3, 4, 5, 8, 6, 10, 7, 9, 11, 12, 13, an
artifact of adding cases across three review rounds. The chain is stateful,
so a reader following the pool through it had to jump around the file.

Pure move: the methods are reordered to match their @Order values, no
annotation value and no test body is changed, so the execution order is
exactly what it was.

* chore(cognito): drop the em-dashes this branch introduced

AGENTS.md asks for none in any content. Seven had leaked into the MFA
prose: the docs table row, two service comments, the handler javadoc and
two in the test class. Replaced with colons and commas, no wording change
beyond the punctuation.

Pre-existing em-dashes elsewhere in these files are left alone.

* revert: "chore(cognito): drop the em-dashes this branch introduced"

This reverts commit d7a0ad10. The rule it cited does not exist: AGENTS.md
says nothing about em-dashes, and the repo uses them throughout, including
in CONTRIBUTING.md's own commit-type table and in the pull request template.
I asserted a house style that is not the house style, so the prose goes back
to how it read when you reviewed it.

Nothing in this PR's behaviour was affected either way. The @Order fix in
63086a30 is unrelated and stands.

* chore(cognito): drop the em-dashes this branch introduced

Reinstates d7a0ad10, which b4a283e3 reverted in error.

The rule is real: AGENTS.md line 333, under Documentation Style, "No
em-dashes anywhere, in any content. Use colons, commas, or periods." I
grepped this branch's copy of AGENTS.md rather than origin/main and found
nothing, so I concluded it did not exist. It was added in 10a70ba1 on
31 Aug, after this branch's merge base at b0fe8311, which is why the
branch's copy predates it.

Seven occurrences on six lines: the docs table row, two comments in
CognitoService, the handler javadoc and two in the test class. Punctuation
only, no wording change. Pre-existing em-dashes elsewhere in these files
are left alone, since the rule is about content this branch adds.
2026-09-03 00:16:01 -04:00
Brian Taylor 0a3bc030f6 feat(cognito): implement identity provider configuration CRUD (#2858)
* feat(cognito): implement identity provider configuration CRUD

CreateIdentityProvider, DescribeIdentityProvider, ListIdentityProviders,
UpdateIdentityProvider and DeleteIdentityProvider were unsupported, so
infrastructure tooling could not manage a user pool's federated providers.

Stores provider configuration alongside the other user pool sub-resources and
matches the response and update semantics measured against the live API:

- IdpIdentifiers is echoed by create and update only when the request supplied
  the member, whatever the stored value; describe always returns it
- AttributeMapping defaults to username -> sub when the member is absent at
  create, while an explicitly empty map is stored as given
- members a request omits are preserved rather than cleared
- a duplicate provider name raises DuplicateProviderException
- ListIdentityProviders returns name/type/date summaries, never ProviderDetails

Federated sign-in itself is out of scope: Floci has no /oauth2/authorize or
/oauth2/idpresponse endpoint, so providers are stored configuration only.

* test(cognito): match identity provider exceptions on the SDK error name

`rejects.toThrow(/re/)` matches the error message, but the JS SDK maps the wire
`__type` onto `error.name` and puts the AWS text in `message`, so the duplicate
provider assertion never matched. Assert the name, and pin the enum text with
an explicit message matcher.

* fix(cognito): delete a pool's identity providers with the pool, and update a copy

Two review findings, both reproduced first.

DeleteUserPool left provider records behind. A pool recreated on a pinned id
(`floci:override-id`) then inherited the dead pool's providers, ProviderDetails
client_secret included. Pool deletion now removes them the way it already
removes groups.

UpdateIdentityProvider mutated the instance the store handed back, so two
concurrent updates could interleave into a state matching neither request. It
now writes a copy, which makes the losing update simply lose — what AWS does.

* fix(cognito): serialise identity provider mutations

UpdateIdentityProvider is a read-modify-write: it copies the stored provider,
applies only the members the request supplied and writes the whole record back.
Two overlapping updates copied the same base, so the later write restored the
other's omitted members to their stale values and silently dropped an update.

Live Cognito merges omitted members rather than clearing them, and applies that
merge atomically, so both updates survive there. One lock now guards every
mutating path, since create (check-then-put) and delete (check-then-act) carry
the same race, matching the existing identityLinkLock idiom.

The regression test runs two writers touching different optional members across
25 rounds; it fails on the first round with the lock reverted.

* fix(cognito): guard the pool deletion provider cascade with the same lock

DeleteUserPool clears a pool's identity providers outside identityProviderLock,
so a create or update interleaving with the cascade could reinstate a provider
for a pool that is going away. It now takes the same lock as the mutations it
races, closing the last unguarded path in that set.

* fix(cognito): recheck the pool under the lock when creating a provider

CreateIdentityProvider validated the pool before taking identityProviderLock and
never rechecked it, so a DeleteUserPool whose cascade ran in between left the
create writing a provider for a pool that no longer exists. It now reasserts the
pool inside the lock, immediately before the duplicate check and the write.

UpdateIdentityProvider needs no equivalent: the cascade deletes the provider, so
its own lookup throws ResourceNotFoundException. The outer validation stays where
it is to keep error ordering unchanged for ordinary single-request calls.
2026-09-02 12:00:26 -04:00
Aniket Shukla 7d693de663 fix(dynamodb): reject QueryFilter with KeyConditionExpression (#2935)
* fix(dynamodb): reject QueryFilter with key expression

* test(dynamodb): keep QueryFilter test legacy
2026-09-02 11:41:14 -04:00
Brian Taylor ca4c84c9e0 fix(lambda): delete only the named version when DeleteFunction has a Qualifier (#2824)
* fix(lambda): delete only the named version when DeleteFunction has a Qualifier

DeleteFunction accepted a Qualifier and dropped it: the controller never
bound the query parameter, so every call took the unqualified path and
removed the function, $LATEST and every other version. A caller pruning
one old version silently lost the whole function, with a success
response and no warning.

The qualified path now removes that version alone. Error behaviour
follows the live service rather than the reference, which documents none
of it: deleting $LATEST by qualifier and naming an alias are both
InvalidParameterValueException, a version an alias references is a
ResourceConflictException, and a version that does not exist is a silent
success rather than a 404.

Closes #2819

* test(lambda): cover qualified DeleteFunction through the AWS SDK

The integration test drives the endpoint over raw HTTP, so nothing
exercised the qualified delete through a real SDK client. Adds SDK
coverage for the four cases: deleting one version leaves the function
and its other versions, $LATEST cannot be deleted by qualifier, a
version an alias references is refused, and an absent version is a
no-op.

* fix(lambda): pattern-validate the DeleteFunction qualifier

Character.isDigit accepts non-ASCII decimal digits, so a full-width or
Arabic-Indic digit was read as a version number and answered with a
silent 204 instead of being rejected. The live service pattern-validates
the qualifier before anything else and its constraint is ASCII-only;
that check now runs first, and the digit test no longer relies on
Character.isDigit.
2026-08-31 22:01:34 -04:00
Brian Taylor 44629631ca fix(lambda): honour ListLayers and ListLayerVersions query parameters (#2817)
* fix(lambda): honour ListLayers and ListLayerVersions query parameters

CompatibleRuntime, CompatibleArchitecture, MaxItems and Marker were
accepted and ignored, and NextMarker was never emitted, so a client
paginating with MaxItems saw a single page and silently got the whole
list, while a runtime or architecture filter returned layers that do
not match it.

Both actions now filter, paginate and emit NextMarker. Validation
follows the live service rather than the API reference: range and enum
failures accumulate into one ValidationException in a fixed member
order, a non-integer MaxItems is a SerializationException that
short-circuits validation, and a Marker the service did not issue is
InvalidParameterValueException "Invalid pagination key.".

Under a filter, LatestMatchingVersion is the newest version that
matches rather than the newest overall, so ListLayers needs every
version of each layer rather than the latest of each.

Closes #2808

* fix(lambda): sign layer pagination markers

The tag identifying a Marker as Floci's was a fixed string, so a caller
could base64 a cursor of their own with the same prefix and have it
accepted. That cursor was then applied to the page, silently skipping
results or emptying the list where AWS rejects an unissued token.

Markers now carry an HMAC over the cursor, keyed per process, so a
fabricated or edited token fails the check. A marker from an earlier run
is stale for the same reason, which is what AWS does with an expired one.

* test(lambda): cover layer listing parameters through the AWS SDK

AGENTS.md prefers SDK clients over raw HTTP for management-plane
validation. The integration test covers the parameters through the wire
protocol; this adds the same filtering, pagination and enum rejection
through @aws-sdk/client-lambda, so a marshalling regression that only
the SDK would notice does not pass unseen.
2026-08-31 19:38:30 -04:00
Brian Taylor a7b2b79492 fix(lambda): honour Publish on CreateFunction and UpdateFunctionCode (#2825)
The Publish flag was never read on either path, so no version was ever
created unless the caller made a separate PublishVersion call, and both
actions reported Version as $LATEST. Terraform reads Version and
qualified_arn straight from that response, so every aws_lambda_function
with publish = true recorded $LATEST — which Lambda@Edge cannot use.

Both actions now publish and report the new version. The ARN they return
differs, following the live service rather than the reference, which does
not distinguish them: CreateFunction keeps the unqualified FunctionArn
while UpdateFunctionCode returns the qualified one, as PublishVersion
does.

Closes #2820
2026-08-31 14:52:19 -04:00
Dixit R Jain b45de1bb7d feat(s3tables): emulate metadata service (#2322)
* feat(s3tables): emulate metadata service

* fix(s3tables): serialize metadata updates
2026-08-15 12:48:27 -04:00
Dixit R Jain 3cfa983479 fix(apigateway): honor configured execute-api hostname (#2286)
* fix(apigateway): honor configured execute-api hostname

* refactor(apigateway): cache execute-api hostname
2026-08-15 11:02:52 -04:00
Dixit R Jain 45bb37f1fb feat(apigatewayv2): route execute-api hosts to WebSocket $connect and @connections (#2188)
Consolidates AWS-style execute-api virtual-host support for WebSocket APIs onto the
existing ApiGatewayExecuteApiHostFilter (added in #2054) plus the WebSocket handler,
instead of adding a second host filter.

- @connections (#1846): ApiGatewayExecuteApiHostFilter now also rewrites a WebSocket
  API's @connections management calls (.../{stage}/@connections/{id}) to the canonical
  /execute-api/{apiId}/{stage}/... route, behind the same disableExecuteApiEndpoint->404
  check. It previously bailed for non-HTTP APIs, so @connections on the execute-api host
  was swallowed by the S3 controller.
- $connect (#1871): WebSocketHandler accepts the execute-api host for the WS handshake
  and resolves the API region -- from the host's region label when present, else a
  cross-region apiId lookup (ApiGatewayV2Service.resolveApiRegion) -- fixing the 403 for
  APIs created in a non-default region.
- Widen the filter host regex to accept the region-bearing AWS form
  ({apiId}.execute-api.{region}.localhost|amazonaws.com) alongside Floci's regionless
  built-in suffixes (.execute-api.localhost.floci.io / .localstack.cloud).
- Fix RegionResolver.resolveRegionFromHost to treat only a real region label as the
  region and return null for the built-in suffixes -- the old pattern parsed "localhost"
  as the region and broke the lookup.
- Remove the separate ExecuteApiSubdomainFilter; host parsing is shared via
  ApiGatewayExecuteApiHostFilter.extractApiId.
- Update docs and add Java unit + Node SDK compatibility coverage for both host forms.

Closes #1871
Closes #1846
2026-08-13 14:40:50 -04:00
shrimptails-f 5e6bcca401 fix(cognito): align sign-up confirmation with AWS behavior (#1488)
* fix(cognito): align sign-up confirmation with AWS behavior

* fix(cognito): centralize constructor initialization

* fix(cognito): use issued sign-up confirmation code in node compatibility test

* fix(cognito): align signup confirmation tests with issued codes
2026-06-24 22:35:57 -05:00
nblomquist 30a598f080 feat(kms): add GenerateRandom action (#1036)
- Add GenerateRandom action routing and handler in KmsJsonHandler
- Add SecureRandom field, constructor overload, and generateRandom() method with bounds validation
- Reject unsupported Recipient and CustomKeyStoreId fields
- Add integration tests for happy path, boundaries, validation, and unsupported fields
- Add SDK compatibility tests for Java, Python, and Node
2026-06-03 17:42:40 -05:00
Dixit R Jain 7e43b015e6 feat(lambda): Lambda layer support (PublishLayerVersion, GetLayerVersion, ListLayerVersions, DeleteLayerVersion) (#1015)
* feat: support PublishLayerVersion, GetLayerVersion, ListLayerVersions, DeleteLayerVersion and layer attachment

Implements full Lambda Layer lifecycle:
- PublishLayerVersion: POST /2018-10-31/layers/{name}/versions
- GetLayerVersion: GET /2018-10-31/layers/{name}/versions/{ver}
- ListLayerVersions: GET /2018-10-31/layers/{name}/versions
- DeleteLayerVersion: DELETE /2018-10-31/layers/{name}/versions/{ver}
- ListLayers: GET /2018-10-31/layers (now returns real data)

Layer content is extracted to disk and copied into Lambda containers
at /opt during launch, matching real AWS behavior where layers are
available at /opt/nodejs/node_modules/ etc.

CreateFunction and UpdateFunctionConfiguration already stored layer
ARNs; this commit makes the layer data actually resolvable and
mountable at runtime.

Closes #875

* feat: add Node SDK compatibility tests for Lambda Layers

Adds lambda-layers.test.ts covering:
- PublishLayerVersion (version 1 and 2)
- GetLayerVersion (success and 404)
- ListLayerVersions
- ListLayers
- DeleteLayerVersion (success, idempotent for non-existent)
- Layer attachment on CreateFunction
- Layer round-trip via GetFunctionConfiguration
- Layer update/removal via UpdateFunctionConfiguration
2026-05-24 15:05:56 -05:00
3a31c792fa fix(apigateway): populate full APIGatewayRequestAuthorizerEvent for REQUEST authorizers (#1002)
* fix: populate full APIGatewayRequestAuthorizerEvent for REQUEST authorizers

Closes #807.

Previously, REQUEST-type Lambda authorizers received only 'type' and
'methodArn'. This commit populates the complete event shape matching
real AWS behavior:

- headers, multiValueHeaders
- queryStringParameters, multiValueQueryStringParameters
- pathParameters (empty object when none, not null)
- stageVariables (from Stage config, null when unconfigured)
- requestContext with accountId, apiId, resourceId, resourcePath,
  path, httpMethod, stage, requestId, requestTimeEpoch
- requestContext.identity with sourceIp, userAgent, apiKey, clientCert

Also enriches the AWS_PROXY integration event (buildProxyEvent) with:
- Full identity object (all null fields matching AWS wire format)
- domainName, domainPrefix, protocol, requestTime, extendedRequestId
- stageVariables from Stage configuration
- API key resolution from usage plan keys

Refactors shared logic into reusable helpers:
- putSingleValueHeaders, putMultiValueHeaders
- putQueryStringParameters, putMultiValueQueryStringParameters

Resolves API key once per request (not duplicated across authorizer
and proxy event builders).

* fix: remove AWS SDK deps from main pom, rewrite test with RestAssured

Addresses review feedback: AWS SDK dependencies should not be in the
main Floci project. Rewrites ApiGatewayRequestAuthorizerIntegrationTest
to use only RestAssured for management-plane and execute-api calls,
matching the established pattern of all other @QuarkusTest tests.

---------

Co-authored-by: Dixit R Jain <dixitrjain@Dixits-MacBook-Pro.local>
Co-authored-by: Dixit R Jain <dixitrjain@Mac.lan>
2026-05-23 22:38:09 -05:00
Nitesh K JainandHector Ventura b71cf0f827 feat(neptune): Neptune control plane, Gremlin Docker backend, and SDK compatibility tests (#958)
Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
2026-05-20 18:02:00 -05:00
Ricardo Medina c426289879 fix(cognito): correct USER_SRP_AUTH PASSWORD_VERIFIER signature (#912)
* fix(cognito): correct USER_SRP_AUTH PASSWORD_VERIFIER signature

Server-side SRP-6a produced HMAC signatures that never matched what
AWS Amplify / SDKs compute, so USER_SRP_AUTH always failed with
NotAuthorizedException. Five independent bugs in the byte layout and
key-derivation chain:

1. SRP multiplier k: hashed N and g left-padded to N_BYTES (384 bytes).
   Cognito/Amplify hash the minimal two's-complement representation
   (385 bytes for N — sign byte prepended because MSB is set — and
   1 byte for g = 2). k participates in both server B = k*v + g^b and
   client S = (B - k*g^x)^(a+ux), so a divergent k breaks the protocol.
   Use N.toByteArray() and G.toByteArray() directly.

2. Session key derivation: previously ran an undocumented "Caldera
   interleaved hash" over S, then fed that into HKDF with a zero salt.
   Cognito applies HKDF-Expand directly over S with the scrambling
   parameter U as salt:
     PRK  = HMAC-SHA256(U_bytes, S_bytes)
     T(1) = HMAC-SHA256(PRK, "Caldera Derived Key" || 0x01)
     key  = T(1)[0..16]
   Inline that HKDF in computeSessionKey; drop interleaved hash + the
   auxiliary hkdf() helper.

3. HKDF output length: helper returned 32 bytes; Amplify uses the first
   16. Return Arrays.copyOf(t1, 16).

4. computeSignature double-HKDF: when sessionKey was already the final
   HMAC key, computeSignature ran HKDF on it again. Use it as-is.

5. computeU / computeX byte layout: U was hashed with A and B
   left-padded to N_BYTES; salt was decoded as raw hex bytes. Amplify
   feeds the minimal two's-complement representation (with sign byte
   for positive MSB-set values). Use BigInteger.toByteArray() for A/B
   and round-trip the hex salt through BigInteger so a sign byte is
   prepended when needed.

Verified by reproducing floci's exact server-side computation in
JavaScript using Amplify's byte conventions: the JS replay reproduces
floci's expected HMAC byte-for-byte (proving the server is internally
consistent) and the divergence from the client's claimed HMAC traces
entirely to k differing. After the fix, USER_SRP_AUTH end-to-end signin
from Amplify v6 (React Native) against floci succeeds.

Compat note: users whose verifier was stored under the previous
computeX with a salt whose first byte has the MSB set (~50% of
generate-salt outputs) will produce a different x and must reset their
password. New signups against this fix are interoperable with Amplify.

Also drops the now-unused padTo() helper.

* test(compatibility): add USER_SRP_AUTH round-trip tests for Node + Java SDKs

The existing CognitoSrpTest only validated that PASSWORD_VERIFIER was
returned by InitiateAuth; nothing exercised the full handshake. With the
server-side SRP math now spec-compliant, add end-to-end tests that prove
real AWS SDK clients authenticate against floci.

Java (sdk-test-java/CognitoSrpTest):
 - Add step 4: compute PASSWORD_CLAIM_SIGNATURE from the challenge using
   the AWS "Caldera" SRP variant, send RespondToAuthChallenge, assert
   AuthenticationResult contains valid JWT id/access/refresh tokens.
 - Helper math (computeX / computeU / computeK / calderaHkdf /
   hmacSha256 / formatCognitoTimestamp) inlined since the AWS Java SDK
   v2 does not expose a public SRP client.

Node (sdk-test-node/tests/cognito-srp.test.ts):
 - New round-trip test using amazon-cognito-identity-js 6.3.16 — the
   canonical JS SRP impl that @aws-amplify/auth wraps internally.
 - Pool is provisioned via AdminCreateUser + AdminSetUserPassword so the
   test doesn't depend on an email-delivered verification code.
 - Validates tokens come back as well-formed JWTs.

Both tests pass against floci with the fix from the previous commit and
fail (CodeMismatchException / NotAuthorizedException) without it.
2026-05-18 23:02:49 -05:00
Hector Ventura 5ab178e10d fix(dynamodb): improve conformance across validation, expressions, and queries (#826)
* fix(dynamodb): improve conformance across validation, expressions, and queries

- Rename InvalidParameterValue → ValidationException for table-name errors
- Enforce min-length 3 on table names for all operations, not just CreateTable
- ListTables: alphabetical order, Limit validation (1–100), pagination
- Enum validation (ReturnValues, ReturnConsumedCapacity) fires before table lookup
- ProjectionExpression support on GetItem, Query, Scan, BatchGetItem
- Select=COUNT returns Count/ScannedCount and omits Items
- Parallel scan: Segment/TotalSegments validation and hash-based sharding
- Reserved words rejected in FilterExpression, ConditionExpression, UpdateExpression
- Legacy API: AttributesToGet, AttributeUpdates, QueryFilter, ScanFilter, KeyConditions
- TransactWriteItems idempotency token with payload-hash conflict detection
- ReturnValuesOnConditionCheckFailure on PutItem, UpdateItem, DeleteItem
- Item size limit (400 KB) and number normalization on write
- Tags API: TagResource, UntagResource, ListTagsOfResource with ARN validation
- New Java and Node SDK conformance tests covering all changes above

* fix(dynamodb): fix unit testing
2026-05-13 02:14:00 -05:00
5befe8b619 feat: optional TLS/HTTPS support with self-signed certificate generation (#754)
* feat: optional TLS/HTTPS support with self-signed certificate generation

- Add TlsConfigSource (MicroProfile ConfigSource SPI) that injects Quarkus
  TLS properties before the HTTP server starts
- Auto-generate self-signed certificates with correct SANs including custom
  hostnames from FLOCI_HOSTNAME and FLOCI_BASE_URL
- Persist certificate metadata for change detection across restarts
- Fix CertificateGenerator to encode IP addresses as iPAddress SANs (RFC 5280)
- Serve HTTP + HTTPS simultaneously (LocalStack parity)
- Support user-provided certificates via FLOCI_TLS_CERT_PATH/KEY_PATH
- Add TLS configuration documentation
- Add Node.js SDK compatibility test for HTTPS connectivity
- Add comprehensive unit and integration tests (79 test cases)

Closes #711

* feat(tls): add TLS proxy server and WebSocket-over-TLS tests

- Add TlsProxyServer: TCP proxy on port 4566 that detects TLS ClientHello
  and routes to HTTPS (4511) or HTTP (4510) backend accordingly
- Add apigatewayv2-websocket-tls.test.ts: WSS compatibility tests covering
  connect/disconnect, route selection, broadcast, authorization,
  @connections API, binary frames, and payload size limits
- Update CI workflow to enable FLOCI_TLS_ENABLED=true for compat tests
- Update sdk-test-node Dockerfile with NODE_TLS_REJECT_UNAUTHORIZED=0
- Update tls.test.ts for HTTPS SDK client tests
- Update README with WebSocket-over-TLS test documentation

* fix(tls): address review comments — LocalStack parity and floci.io SANs

- Add USE_SSL and CUSTOM_SSL_CERT_PATH mappings to localstack-parity.sh
- Add localhost.floci.io and *.localhost.floci.io to default certificate SANs
- Update affected tests and documentation

---------

Co-authored-by: Dixit R Jain <dixitrjain@Mac-379.lan>
Co-authored-by: Dixit R Jain <dixitrjain@Mac.lan>
2026-05-10 10:21:03 -05:00
Dixit R Jain 3ae5c7b467 feat(apigatewayv2): Add WebSocket data-plane support (#712)
* feat: implement API Gateway v2 WebSocket data-plane support Implement full WebSocket data-plane for API Gateway v2, including: - Real WebSocket connection handling via Vert.x (ws://localhost:4566/ws/{apiId}/{stage}) - $connect/$disconnect/$default route lifecycle with Lambda integration - Custom route selection via routeSelectionExpression ($request.body.{field}) - @connections management API (POST/GET/DELETE) for server-to-client messaging - Lambda REQUEST authorizer support on $connect with identity source validation - Stage variable substitution in integration URIs - Multiple integration types: AWS_PROXY, AWS (VTL), HTTP_PROXY, HTTP (VTL), MOCK - Route response selection expression for bidirectional messaging - Binary frame support (isBase64Encoded: true) - 128 KB payload size limit enforcement (frames and @connections POST) - 10-minute idle timeout and 2-hour max connection duration - GoneException (410) for disconnected connections - $connect response headers propagation - Server-initiated close via @connections DELETE (skips $disconnect Lambda) Also includes: - Refactored LambdaArnUtils.extractFunctionNameFromUri as shared utility - Extended Authorizer/Integration/Stage models with new fields - Comprehensive Java integration tests (WebSocket lifecycle, routing, auth, etc.) - Node.js SDK compatibility tests using ws client and @aws-sdk/client-apigatewaymanagementapi - Updated documentation with full feature matrix

* test(apigatewayv2): support custom WebSocket endpoint via env var

- Update wsUrl helper to read FLOCI_ENDPOINT environment variable
- Convert http/https schemes to ws/wss for WebSocket compatibility
- Strip trailing slashes from endpoint URL for consistent formatting
- Enable testing against non-localhost endpoints for CI/CD flexibility

* fix: use AwsErrorResponse for @connections API error responses

Replace raw JSON string literals in handlePostToConnection,
handleGetConnectionInfo, and handleDeleteConnection with the
project-standard AwsErrorResponse record, which serialises to
the correct {"__type": ..., "message": ...} wire shape.

* fix: simplify extractFunctionNameFromUri using AwsArnUtils.parse

Adopt AwsArnUtils.parse() as the core of the implementation per
reviewer suggestion. One addition beyond the suggested snippet:
the API Gateway v1 integration URI format embeds a Lambda ARN
inside an apigateway ARN (resource starts with 'path/.../functions/'),
so we detect that pattern and recurse on the embedded ARN before
applying the standard function-name extraction. All 43
LambdaArnUtilsTest cases pass, including the API Gateway v1 style URI.
2026-05-08 17:15:35 -05:00
Dixit R Jain 8fe2bf4c97 feat(apigatewayv2): add WebSocket API support, Update ops, Route/Integration Responses, Models, and Tagging (#682)
Closes #526

Add 27 new API Gateway v2 operations (21 → 48 total):

- WebSocket protocol: CreateApi with WEBSOCKET, wss:// endpoints,
  routeSelectionExpression validation, routeResponseSelectionExpression
- Update operations: UpdateApi, UpdateRoute, UpdateIntegration,
  UpdateAuthorizer, UpdateStage, UpdateDeployment
- Route Responses: full CRUD (5 ops)
- Integration Responses: full CRUD (5 ops)
- Models: full CRUD (5 ops)
- Tagging: TagResource, UntagResource, GetTags
2026-05-02 07:53:13 -05:00
Yorí 8eeb2244a7 Feat/lambda image config working directory (#673)
* feat(lambda): support ImageConfig.WorkingDirectory override

Propagate WorkingDirectory from the Lambda ImageConfig through the full
stack so container images that rely on a specific WORKDIR can be invoked
correctly, matching real AWS behavior.

- LambdaFunction: add imageConfigWorkingDirectory field + getter/setter
- LambdaService: parse WorkingDirectory on CreateFunction and
  UpdateFunctionConfiguration
- ContainerSpec: add workingDir record component
- ContainerBuilder: add withWorkingDir() fluent method
- ContainerLifecycleManager: pass workingDir to Docker via withWorkingDir()
- ContainerLauncher: apply workingDir when building the container spec
- LambdaController: serialize WorkingDirectory in ImageConfigResponse

* test(lambda): add tests for ImageConfig.WorkingDirectory

Unit tests (LambdaImageConfigTest):
- CreateFunction stores WorkingDirectory alongside Command/EntryPoint
- createFunction with all three fields together
- updateFunctionConfiguration updates and clears WorkingDirectory
- ContainerLauncher passes workingDir to ContainerSpec

Compat tests across all SDKs:
- awscli (lambda.bats): create/get/update WorkingDirectory round-trip
- Java SDK (LambdaFunctionConfigTest): ImageConfig.WorkingDirectory round-trip
- Python (test_lambda_function_config.py): TestImageConfigWorkingDirectory class
- Node (lambda.test.ts): create/update WorkingDirectory assertions
- Go (lambda_test.go): TestLambdaImageConfigWorkingDirectory subtests
- Rust (lambda_test.rs): full create/get/update round-trip
2026-04-30 17:25:03 -05:00
Yorí 1cccf43f7b feat(cognito): include all standard attributes in DescribeUserPool Schema (#642)
* feat(cognito): include all standard attributes in DescribeUserPool SchemaAttributes

AWS Cognito always returns all 20 standard OIDC attributes (sub, name,
email, phone_number, etc.) in SchemaAttributes when describing a user
pool, even if none were explicitly configured. Floci was returning only
what was passed in Schema during creation.

Adds CognitoStandardAttributes with the full default set and a merge()
helper that overlays explicit schema overrides and appends custom:
attributes after the standard ones.

* test(cognito): add compat tests for standard SchemaAttributes across all SDKs

Adds DescribeUserPool SchemaAttributes coverage to all compatibility test
suites (AWS CLI/bats, Go, Java, Node, Python, Rust), verifying that all
20 standard OIDC attributes are returned and that sub is required and
immutable.
2026-04-29 00:01:48 -05:00
Christine Nguyen eed72e6222 feat(pipes): add filtering, input templates, batch sizes, and DLQ routing (#576) 2026-04-23 22:56:05 -05:00
Christine Nguyen 51bf4f8480 feat(pipes): add source polling and target invocation for EventBridge Pipes (#555) 2026-04-22 23:36:48 -05:00
Conor Heine a0ed51e9d1 feat: ecr (#337) 2026-04-11 09:59:05 -05:00
Hector Ventura 9ca82e5748 feat(eventbridge): add InputTransformer support and S3 event notifications (#294)
* feat(eventbridge): add InputTransformer support for rule targets

Support InputPathsMap + InputTemplate on EventBridge targets so events
can be projected to a subset of fields before delivery to SQS/SNS/Lambda.

- Add InputTransformer model with inputPathsMap and inputTemplate fields
- Parse and serialize InputTransformer in PutTargets / ListTargetsByRule
- Apply transformer in invokeTarget: extract JSONPath variables, substitute
  <varName> placeholders in the template
- Use Jackson JsonPointer for JSONPath resolution ($.a.b.c → /a/b/c)
- Add unit tests for extractJsonPath and applyInputTransformer edge cases
- Add integration tests covering full put/list/deliver/transform flow

Fixes #140
2026-04-08 16:23:59 -05:00
Hector Ventura 4724db97be feat: add KMS GetKeyPolicy, PutKeyPolicy and fix CreateKey Tags (#258 #259 #269) (#280) 2026-04-08 01:37:38 -05:00
Hector Ventura 5e8b39c1aa fix: resolve Cognito auth, token, and user lookup issues (#218 #220 #228 #229 #233 #234 #235) (#279) 2026-04-08 01:30:26 -05:00
Conor Heine 13916913e8 fix: handle base64-encoded ACM cert imports (#248) 2026-04-07 13:20:27 -05:00
Conor Heine f4f1752b0d fix: return 400 when encoded s3 copy source is malformed (#244)
fix: replace silent exception swallowing and add per-test timeout in Python test suite

test: misc compatibility-tests cleanups

- Added sync comments to both main.tf files
- Created compatibility-tests/.dockerignore
- Cached CRC32 table in Node setup.ts
- Removed >/dev/null 2>&1 from 3 Dockerfiles

test: add missing .terraform.lock.hcl

chore: remove .terraform.lock.hcl
2026-04-06 16:53:14 -05:00
Conor Heine eeefb729c4 test: move compatibility tests into this repo (#225)
* test: move compatibility tests into this repo
* fix: add StatisticValues parsing to CloudWatchMetricsJsonHandler
* fix: add missing required abstract methods to EmulatorConfig in EventBridgeSchedulerIntegrationTest
* test: add sdk tests for multipart S3 copy coverage
* fix: cover and fix smithy cbor and multipart s3 copy regressions
* test: migrate more test coverage to new folder
* test: add missing ec2 expectation in healthcheck test
* docs: update READMEs in `./compatibility-tests`
2026-04-06 09:35:53 -05:00