Implement Lambda REQUEST authorizer invocation for HTTP API routes
configured with authorizationType=CUSTOM. Previously, Floci silently
skipped authorization for these routes.
Supports:
- Payload format version 1.0 (REST API-compatible event shape)
- Payload format version 2.0 (HTTP API-native event shape)
- Simple responses (isAuthorized: true/false) when enableSimpleResponses=true
- IAM policy document responses (policyDocument with Allow/Deny)
- Identity source validation ($request.header.X, $request.querystring.X)
returning 401 without invoking Lambda when sources are missing
Closes#812
ensureStarted() reserved a port from the 5100-5199 pool but never
released it when the registry container failed to start. Because
PortAllocator is @ApplicationScoped, each failed start leaked a port
permanently, eventually exhausting the pool and masking the real
failure with "No free port available in range 5100-5199".
Widen the try to cover spec building and addPersistenceMounts (the
first Docker call in named-volume mode) and release the port on
failure unless the container started, mirroring the existing pattern
in RuntimeApiServerFactory and Ec2ContainerManager.
UpdateStage patch paths of the form /<resourcePath>/<httpMethod>/<settingKey>
(e.g. /*/*/metrics/enabled, /*/*/throttling/burstLimit, /pets/GET/caching/enabled)
were silently accepted but discarded, so GetStage returned no methodSettings
field and the Terraform aws_api_gateway_method_settings resource failed with
"empty result" when read after apply.
Adds a MethodSetting POJO with the AWS-documented fields, stores them on
Stage in a Map keyed by "<resourcePath>/<httpMethod>", parses the patch path
suffix against the canonical setting keys (metrics, logging, throttling,
caching), and serialises the map under "methodSettings" in toStageNode so
GetStage round-trips the values the patch wrote.
New ApiGatewayStageMethodSettingsIntegrationTest covers the three Terraform
scenarios (wildcard throttling + logging, wildcard caching, and per-method
overrides); verified failing on main and passing with this change.
* 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>
Real AWS SNS PublishBatch surfaces an attribute parsing error
(e.g. invalid base64 in a BinaryValue) as a Failed entry with
InvalidParameterValue + SenderFault=true, and continues publishing
the remaining valid entries.
Both SnsQueryHandler and SnsJsonHandler used to let the AwsException
from parseMessageAttributes propagate out of the batch loop, returning
a 400 (Query) or letting the exception bubble (JSON) and aborting the
whole batch. They now catch the per-entry parse failure, record it as
a Failed entry, and merge it with the regular batch result.
Fix#992
* fix(lifecycle,appconfig): TLS startup readiness and listHostedConfigurationVersions
Fixes two independent issues:
is enabled, Quarkus binds the HTTP backend on port 4510 and the HttpServerStart
event fires with that port, so markStartCompleted/markReadyCompleted were never
called and /_floci/init always returned ready=false. Fix: derive the expected
port from config.tls().enabled() at observer time.
/applications/{appId}/configurationprofiles/{profileId}/hostedconfigurationversions.
Unmatched requests fell through to S3Controller's catch-all and returned a
NoSuchBucket XML error. Fix: add HostedConfigurationVersionSummary model,
listHostedConfigurationVersions service method, and the missing GET route.
* fix(commit-checks): fix action that check commit format
S3 object keys under .well-known/ (e.g. bucket/.well-known/jwks.json) were
being routed to CognitoWellKnownController instead of S3Controller. The
controller threw ResourceNotFoundException ("User pool not found"), masking
the S3 object even though list-objects-v2 and head-object returned it.
Real Cognito UserPool IDs always contain an underscore (region prefix +
underscore + random suffix, e.g. us-east-1_xxx); AWS S3 bucket names forbid
underscores. Constraining the {poolId} path parameter to "[^/_]+_[^/]+"
ensures that any first path segment without an underscore falls through to
S3Controller, restoring the documented S3 behaviour without affecting
existing Cognito tests.
Adds S3WellKnownKeyIntegrationTest covering both jwks.json and
openid-configuration object keys; verified failing on main and passing with
this fix.
* fix(sns): preserve binary message attributes through publish and fan-out
Parse BinaryValue on Publish/PublishBatch in both JSON and Query handlers,
and base64-encode binary attributes in the SNS-to-SQS and Lambda JSON
envelopes so binary attributes survive fan-out instead of being dropped.
Closes#988
* fix(sns): return AWS-style 400 for invalid base64 and align DataType default
Address Copilot PR feedback:
- Catch IllegalArgumentException from Base64 decoding in both Publish and
PublishBatch attribute parsing (JSON + Query handlers) and surface an
InvalidParameterValue / HTTP 400 error consistent with other SNS errors.
- Default DataType to "Binary" in SnsJsonHandler when only BinaryValue is
provided, matching SnsQueryHandler behavior.
- Extract a shared parseMessageAttributes helper in each handler to remove
duplication between Publish and PublishBatch.
* fix(sns): give new tests distinct @Order values and drop Base64 FQN
Address maintainer review feedback:
- Move new binary-attribute tests off @Order(9) (already used by
publish_fanOutToSqsSubscriber) to @Order(18)/@Order(19) so their
drainQueue calls don't race with other order-9 tests.
- Import java.util.Base64 in SnsQueryHandler, SnsJsonHandler, and
SnsService and drop the fully-qualified references.
PUT /{bucket}?requestPayment was not recognised as a sub-resource by
S3Controller, so the request fell through to the bucket-creation
handler. For any pre-existing bucket that returned
BucketAlreadyOwnedByYou (HTTP 409) — which broke real workloads such as
Terraform's aws_s3_bucket_request_payment_configuration on every
re-apply.
Add explicit handling for the requestPayment sub-resource, mirroring
the existing OwnershipControls / Acl flow:
- Bucket model gains a requestPaymentPayer field.
- S3Service.putBucketRequestPayment validates the bucket exists
(NoSuchBucket / 404) and the payer value (BucketOwner | Requester);
invalid payers return MalformedXML / 400 to match real S3.
- S3Service.getBucketRequestPayment returns the canonical
RequestPaymentConfiguration XML, defaulting to BucketOwner when never
set — real S3 never returns 404 for GetBucketRequestPayment.
- Controller dispatches PUT and GET ?requestPayment to the new methods.
No DELETE handler is added; AWS does not expose one.
Regression test asserts the original Terraform-breaking case (a second
PUT on an existing bucket must return 200, not 409) along with default
GET, MalformedXML on invalid payer, and NoSuchBucket on missing bucket.
* fix(s3): restore object on delete marker removal and add missing version headers
* fix(s3): use millisecond precision for version ordering to avoid same-second race condition
* test(s3): add regression tests for versioned delete behaviors and response headers
* fix(sts): honour 12-digit access key as account ID
GetCallerIdentity, AssumeRole, AssumeRoleWithWebIdentity,
AssumeRoleWithSAML, and GetFederationToken now resolve the account ID
from the request-scoped RegionResolver instead of the static IAM
default, so ARNs match the per-account namespace used by SNS, SQS, S3,
etc. Closes#981.
* fix(sts): derive AssumedRoleUser account from RoleArn
AssumeRole, AssumeRoleWithWebIdentity, and AssumeRoleWithSAML now build
AssumedRoleUser.Arn using the account ID parsed from the supplied
RoleArn, falling back to the caller's account only when the ARN is
missing or unparseable. This matches AWS cross-account assume-role
behaviour: the resulting ARN belongs to the target role's account, not
the caller's.
AWS SQS resolves a plain queue name (e.g. "TestQueue") to the full queue URL transparently. Floci required the full URL, causing NonExistentQueue errors for clients that pass only the name - a pattern common in AWS SDK for Java v2 applications.
Add normalizeQueueUrl() which expands bare names to the canonical {baseUrl}/{accountId}/{queueName} form before storage-key computation, covering all SQS operations that accept a QueueUrl parameter.
* fix(s3): accept region-qualified virtual-host form bucket.s3.<region>.<host>
AWS SDKs may send Host: bucket.s3.<region>.<host> for virtual-hosted
style requests. Recognize this form against both the configured base
hostname and the localhost fallback so the bucket is extracted correctly.
Closes#977
* test(s3): add integration coverage for region-qualified virtual-host
Exercise Host: <bucket>.s3.<region>.localhost end-to-end: HEAD returns
404 for a missing bucket, PUT creates it, HEAD then returns 200, and
PUT/GET on an object roundtrips.
GetObjectLockConfiguration was returning a 200 with ObjectLockEnabled=Enabled
for every bucket regardless of whether object lock was enabled at creation time.
Real AWS returns ObjectLockConfigurationNotFoundError (HTTP 404) when the bucket
was not created with x-amz-bucket-object-lock-enabled: true.
Added an isObjectLockEnabled() guard in S3Service before returning the retention
configuration. The controller's existing try-catch routes the AwsException to
the XML error response with no additional changes needed.
Fixes#960
The Smithy RPC v2 CBOR protocol spec requires the response header to be
sent as `smithy-protocol` (lowercase). The previous casing `Smithy-Protocol`
caused SDK clients that perform a case-sensitive check on the response header
to fail protocol negotiation.
## Summary
S3 `PutObject` was echoing the object's `Content-Encoding` (and `Content-Disposition`, `Cache-Control`, `x-amz-meta-*`) onto a response whose body is always empty. Real AWS S3 omits all of those on PutObject — they only belong on `GetObject` / `HeadObject`, where there is a body to describe.
The user-visible symptom is `Content-Encoding: gzip` on the PutObject response: AWS SDK for Java v2's `Crc32Validation.decompressing` interceptor sees the header, wraps the empty stream in `GZIPInputStream`, and throws `EOFException` from `readHeader`. The object is stored correctly server-side, but every gzip-encoded `PutObject` through the SDK fails before returning — breaking, for example, Spring Cloud AWS's `S3Template.upload(...)` with gzip metadata.
`S3Controller#putObject` now calls a new `appendPutObjectResponseHeaders(resp, obj)` that emits only the headers AWS returns on PutObject (storage-class when set, SSE when set, checksum, object-lock) and intentionally omits `Content-Encoding`, `Content-Disposition`, `Cache-Control`, `Content-Language`, `Expires`, and `x-amz-meta-*`. The shared `appendObjectHeaders` is untouched, so GET / HEAD / CopyObject — including the persistence behavior added by #56 / PR #57 — are unchanged.
Closes#944
## Type of change
- [x] Bug fix (`fix:`)
- [ ] New feature (`feat:`)
- [ ] Breaking change (`feat!:` or `fix!:`)
- [ ] Docs / chore
## AWS Compatibility
Incorrect behavior: PutObject's response copied the object's persisted `Content-Encoding` / `Content-Disposition` / `Cache-Control` / `x-amz-meta-*` headers onto a response that has no body.
Verified against real AWS S3 (`us-west-2`) with AWS CLI v2 (`aws-cli/2.27.58`) and AWS SDK for Java v2 (`software.amazon.awssdk:s3:2.42.24`). Eight `PutObject` scenarios were captured from botocore's `--debug` response-headers log, each with one additional request header. For every header this PR changes Floci's behavior on, the post-PR response matches AWS:
| Request includes | Pre-PR Floci response | Real AWS response | Post-PR Floci response |
|---|---|---|---|
| `Content-Encoding: gzip` | emits `Content-Encoding: gzip` | omits | omits |
| `Cache-Control: max-age=…` | emits `Cache-Control` | omits | omits |
| `Content-Disposition: …` | emits `Content-Disposition` | omits | omits |
| `x-amz-meta-owner: team-a` | emits `x-amz-meta-owner` | omits | omits |
(`Content-Language` and `Expires` exist in the old `appendObjectHeaders` only via `ResponseHeaderOverrides`, and the PutObject path passes `ResponseHeaderOverrides.NONE`, so they were never actually emitted on PutObject responses.)
Regression coverage, both layers:
- New SDK-level test `compatibility-tests/sdk-test-java/S3Test#putObjectWithContentEncodingDoesNotBreakSdkDecompression` uses a real `S3Client` to `PutObject` a gzip-encoded object. Before the fix it throws the exact `EOFException → Crc32Validation.decompressing → DefaultS3Client.putObject` stack from #944; with the fix it passes.
- Existing in-process `S3IntegrationTest#putObjectWithContentEncoding` gains assertions that `Content-Encoding`, `Content-Disposition`, and `Cache-Control` are absent from the PutObject response. Adjacent tests (`getObjectReturnsContentEncoding`, `headObjectReturnsContentEncoding`, `copyObjectPreservesContentEncoding`, and the Cache-Control / Content-Disposition equivalents) continue to assert those headers ARE returned on GET / HEAD / CopyObject — protecting the behavior fixed by #56 / PR #57.
## Checklist
- [x] `./mvnw test` passes locally (4700 tests, 0 failures, 0 errors, 8 skipped)
- [x] New or updated integration test added (RestAssured regression assertions in `S3IntegrationTest#putObjectWithContentEncoding`, plus new SDK test `S3Test#putObjectWithContentEncodingDoesNotBreakSdkDecompression` in `compatibility-tests/sdk-test-java`)
- [x] Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/)
* feat(config): add AWS Config service emulation (#913)
* docs: add AWS Config service page and align service counts across all docs
Add docs/services/config.md with all 20 supported actions, CLI examples,
and configuration reference. Add 5 services that had doc pages but were
missing from the service matrix (Textract, Pricing, Cost Explorer, CUR,
BCM Data Exports). Reconcile service count to 51 across README,
docs/index.md, and docs/services/index.md.
* feat(sqs): persist and return AWSTraceHeader system attribute
SendMessage's MessageSystemAttributes parameter is restricted by AWS
to AWSTraceHeader (the X-Ray trace context). Both the JSON and Query
handlers were silently dropping it, so a subsequent ReceiveMessage
with MessageSystemAttributeNames=["All"] returned only the four
auto-derived attributes instead of the expected five.
Add awsTraceHeader to the Message model, parse it from the
MessageSystemAttributes.AWSTraceHeader.StringValue location on the
wire (both JSON 1.0 and Query protocol), thread a new sendMessage
overload through SqsService, and surface it as a system attribute
when "All" or "AWSTraceHeader" is requested on receive. The existing
overloads remain so internal callers (SNS delivery, ESM polling, etc.)
are unaffected.
* feat(sqs): parse AWSTraceHeader on SendMessageBatch entries and add wire tests
Review feedback on #909:
- SendMessageBatch (both JSON 1.0 and Query) was still ignoring per-entry
MessageSystemAttributes, so AWSTraceHeader was dropped in batched
sends even after the single-SendMessage fix. Parse it the same way as
the single-message path on both protocols and pass it through to the
existing sendMessage overload.
- Coverage was service-level only. Add wire-level tests that assert
AWSTraceHeader is parsed off MessageSystemAttribute(s) and emitted
under Attributes.AWSTraceHeader on ReceiveMessage for both single
SendMessage and SendMessageBatch on both protocols.
- Reword the awsTraceHeader field comment to make clear the value is
caller-supplied via MessageSystemAttributes, not server-generated.
When listing with a prefix and a marker, the v1 ListObjects API was
ignoring the marker entirely, causing the same page to be returned on
every paginated call. Pass the marker as startAfter to
listObjectsWithPrefixes for v1 requests so pagination advances
correctly. Also emit <Marker> and <NextMarker> in the v1 XML response.
* fix(sqs): validate SendMessageBatch total payload size up-front
The batch handlers processed entries one at a time and only caught
per-entry size errors, so a batch whose combined payload exceeded the
queue's MaximumMessageSize landed in the response Failed collection
instead of triggering the batch-level BatchRequestTooLong error the
AWS SDK expects (and the BatchRequestTooLongException it surfaces).
Sum each entry's size up-front (using the same body + attribute
accounting as SendMessage), then call a new
SqsService.validateBatchPayloadSize that throws BatchRequestTooLong
when the total exceeds the queue's configured MaximumMessageSize.
Per-entry processing is unchanged -- individual entries that violate
other rules still surface as Failed entries.
* test(sqs): protocol-level coverage for oversized SendMessageBatch
Review feedback on #907: the new validateBatchPayloadSize path was only
exercised by direct SqsService unit tests. Add wire-level tests against
both protocols so the parse/sum/error path can't regress:
- SqsJsonProtocolTest: oversized JSON 1.0 batch returns 400 with
__type containing BatchRequestTooLong.
- SqsIntegrationTest: oversized Query/form batch returns 400 with
the BatchRequestTooLong code in the body.
Both confirm the top-level error is emitted before any per-entry
Successful results.
`Api` does not currently model `corsConfiguration`, so neither
`ApiGatewayV2Service.createApi` / `updateApi` accept the field from the
inbound request nor do the two response builders
(`ApiGatewayController.toV2ApiNode` and `ApiGatewayV2JsonHandler.toApiNode`)
emit it. Terraform's `aws_apigatewayv2_api.cors_configuration` is therefore
always perceived as drift on every plan against a correctly-configured
emulator.
Introduces a nested `Api.Cors` record mirroring the `Authorizer.JwtConfiguration`
pattern (six AWS-documented sub-fields: allowOrigins, allowMethods, allowHeaders,
exposeHeaders, maxAge, allowCredentials). Adds request extraction via a shared
`toCors(Map)` helper (boolean uses the same defensive
`Boolean.parseBoolean(String.valueOf(...))` style as `Stage.autoDeploy`) and
emits the value from both REST and JSON 1.1 response paths.
Covered by a focused regression test (`ApiCorsConfigurationResponseTest`)
exercising create/get/list, PATCH update, omitted-when-null, the
containsKey-guard against future regression on PATCH-other-field, and a
JSON 1.1 round-trip via `X-Amz-Target` dispatch.
Same Terraform-drift class as #887 (`Route.authorizerId`) and #931
(`Integration.connectionType`, `Authorizer.enableSimpleResponses`).
JAX-RS's ContainerRequestContext.getMediaType() parses the Content-Type
header value and throws IllegalArgumentException when the value is an
empty string (as opposed to null/absent). Some S3 clients (e.g.
Paperclip) send 'Content-Type: ""' for uploads without a detected type,
which caused every such request to fail with a 500 error.
Replace ctx.getMediaType() with ctx.getHeaderString("Content-Type") so
the raw value is used for protocol detection without triggering the
JAX-RS media-type parser.
When PutFunctionConcurrency hits the regional reservation cap, the
LimitExceededException response is AWS-correct but the cause is
invisible in floci logs. Operators see only terraform retrying for
minutes (AWS SDK Go v2 plus the provider's MaxAttempts=25) while the
underlying reason (total reservations exceed regionLimit minus
unreservedMin) sits silently in the limiter.
Emit a WARN on every limit hit with the offending numbers and the
env var to raise the cap. Error code, body and status remain
identical to real AWS; this is observability only.
* fix(dynamodb): return current table status on DeleteTable and support PartiQL scan pagination
DeleteTable now builds the response before removing the table, returning
the ACTIVE status that AWS documents. PartiQL SELECT without a WHERE
clause performs a full table scan with Limit/NextToken pagination support.
* feat(secretsmanager): implement RestoreSecret operation
Cancels a scheduled deletion by clearing the deletedDate on a
soft-deleted secret, matching the AWS RestoreSecret API contract.
* test(lambda): assert PortAllocator never reuses a port still in use
* fix(lambda): make PortAllocator a checkout/release pool
The previous modular counter (basePort + offset % range) wrapped
silently when allocations exceeded the configured range, handing the
same port to two RuntimeApiServers. The second listen() either failed
with EADDRINUSE or bound on top of a draining socket (in both cases
producing a runtime API the Lambda bootstrap could not reach).
PortAllocator now tracks in-use ports in a Set and throws
IllegalStateException on exhaustion. RuntimeApiServerFactory releases
the port on start failure; ContainerLauncher releases it after the
server is stopped.
Vert.x defaults maxWebSocketFrameSize to 64 KB. The Node.js ws library
sends messages as a single frame (no fragmentation), so payloads at or
above 128 KB are silently rejected at the transport level before reaching
the application-level size check in WebSocketHandler.
This caused the sdk-test-node compatibility tests for payload size limits
to timeout waiting for the 'Message too long' error response that never
arrived.
Raise both maxWebSocketFrameSize and maxWebSocketMessageSize to 256 KB
so that oversized frames reach the handler, which then enforces the AWS
128 KB limit and returns a proper error frame.
Co-authored-by: Dixit R Jain <dixitrjain@Mac-1086.lan>
Two HTTP API v2 fields are silently dropped on serialization, causing
Terraform to report drift on every plan even when the resources are
correctly configured:
- Integration.connectionType (INTERNET / VPC_LINK) — exposed by
`aws_apigatewayv2_integration.connection_type`. Neither persisted from
the inbound request by `ApiGatewayV2Service.createIntegration` /
`updateIntegration` nor emitted by `toV2IntegrationNode` /
`toIntegrationNode`.
- Authorizer.enableSimpleResponses (HTTP API Lambda authorizer payload
v2.0) — exposed by `aws_apigatewayv2_authorizer.enable_simple_responses`.
Same gap across `createAuthorizer` / `updateAuthorizer` and both
response builders.
Adds the missing model fields, request extraction (Boolean uses the same
defensive `Boolean.parseBoolean(String.valueOf(...))` pattern as
`Stage.autoDeploy`), and emits the values from both the REST and JSON 1.1
response paths. Covered by a focused regression test exercising
create/get/list, the PATCH update path, omitted-when-null behaviour, and
JSON 1.1 round-trip via `X-Amz-Target` dispatch.
Same Terraform-drift class as #887 (`Route.authorizerId`).
The Query-protocol handler for sns:PublishBatch was extracting Id,
Message, Subject, MessageGroupId and MessageDeduplicationId per entry
but skipped the per-entry MessageAttributes parsing loop that the
single-entry sns:Publish handler already had. As a result every batched
message reached subscribers (SQS, HTTP, Lambda) with an empty attribute
map, even though the AWS API contract treats MessageAttributes as a
first-class field on PublishBatchRequestEntry.
This caused consumers that rely on attributes for metadata (e.g.
CloudEvents binary content-mode: ce-type, ce-id, ce-source, …) to
discard the messages because the routing headers were missing.
Mirror the loop from handlePublish, parsing
PublishBatchRequestEntries.member.N.MessageAttributes.entry.M.* per
entry, and only attach the attributes map when non-empty so the
SnsService receives the same shape as the single-Publish path.
Adds:
- Handler unit regression test covering attribute forwarding and
per-entry isolation (entry without attrs must not inherit from
sibling entries).
- AWS SDK v2 compatibility test asserting end-to-end fan-out.
Existing single Publish behaviour is unchanged.
* feat(ecs): add loadBalancers to the ECS service model
* feat(ecs): register ECS service containers as ELBv2 targets
* test(ecs): cover loadBalancers parsing and ELBv2 target registration
* fix(ecs): reject malformed loadBalancers entries on CreateService
* refactor(ecs): gate loadBalancer deregister hook on dockerMode
* refactor(ecs): collapse EcsService to a single constructor
* fix(ecs): prefer a routable network when resolving container IP
* test(lambda): assert RuntimeApiServer.stop() releases its port synchronously
* fix(lambda): await HttpServer close in RuntimeApiServer.stop()
stop() returned before httpServer.close() completed. Under warm-pool
churn the PortAllocator could hand the just-released port to a new
server while the kernel still held the old socket in LISTEN, producing
a ghost listener that bound but never accepted - Lambda bootstraps
then timed out polling AWS_LAMBDA_RUNTIME_API.
stop() now returns CompletableFuture<Void>; ContainerLauncher awaits
it. Idempotent via a cached future.
* fix(apigateway): accept any Content-Type on PutRestApi and ImportRestApi
The class-level @Consumes restricted these endpoints to application/json
and application/json-patch+json, so JAX-RS returned 415 for any other
Content-Type. The Terraform AWS provider sends the OpenAPI body as
application/octet-stream, which broke aws_api_gateway_rest_api with an
inline body.
Use @Consumes(WILDCARD) on createRestApi and putRestApi, matching the
pattern already used for opaque-body endpoints in BedrockRuntime,
S3Control, and AppConfig. The underlying Swagger parser content-sniffs
the body, so JSON and YAML payloads keep working regardless of the
declared Content-Type.
Closes#855
* ci: re-trigger sdk-test-node after transient npm registry 404
Per the S3 API, six query parameters override response headers on GetObject
and HeadObject (presigned URLs are the canonical use case): response-content-type,
response-content-language, response-expires, response-cache-control,
response-content-disposition, response-content-encoding. Floci previously ignored
them and emitted only the values stored on the object at upload time.
Adds the six @QueryParam bindings, threads them through getObject, headObject,
and handleRangeRequest, and lets them win over stored values when present.
Empty query values are normalized to null to match AWS behavior of ignoring
empty response-* overrides. Routing range responses through appendObjectHeaders
also closes a pre-existing gap where 206 responses dropped stored
Content-Disposition / Cache-Control / Content-Encoding and version-id headers.
Closes#916
* feat(elasticache): add Memcached CreateCacheCluster/DescribeCacheClusters/DeleteCacheCluster support
Closes#928
* fix(elasticache): stop Memcached containers on emulator shutdown
Wire ElastiCacheMemcachedContainerManager into EmulatorLifecycle so that
Memcached containers are stopped and removed when the emulator shuts down,
preventing orphaned containers.
* 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.
* feat(sqs): implement MessageMoveTask tracking, cancel, and validation
StartMessageMoveTask was a synchronous drain that returned a throwaway
task handle. ListMessageMoveTasks always returned [] and
CancelMessageMoveTask was not implemented at all. This change keeps
the synchronous-move semantics but introduces a per-account in-memory
task store and proper validation around the API.
Changes
-------
- Add SqsService.MoveTask record (handle, source, destination, max
rate, status, counters, timestamps, failure reason).
- ConcurrentHashMap<taskHandle, MoveTask> retained for the lifetime
of the process so List/Cancel can find tasks that have already
completed.
- StartMessageMoveTask:
* Accepts MaxNumberOfMessagesPerSecond and stores it on the task.
* Validates source ARN parses and queue exists (NonExistentQueue).
* Validates source is referenced as a DLQ by at least one other
queue's RedrivePolicy; otherwise throws InvalidParameterValue.
* Validates destination queue exists when provided; otherwise
throws ResourceNotFoundException (was a generic AmazonSQSException).
* Rejects a second concurrent task on the same source with
UnsupportedOperation.
- ListMessageMoveTasks returns tasks for the given source, newest
first, capped by MaxResults.
- CancelMessageMoveTask marks the task CANCELLED and returns
ApproximateNumberOfMessagesMoved; ResourceNotFoundException for
unknown handles.
- Both JSON 1.0 and Query handlers wired through; CancelMessageMoveTask
dispatch added to both.
Known follow-ups
----------------
- StartMessageMoveTask with no DestinationArn currently drops drained
messages; AWS semantics is "return each message to its original
source queue", which requires tracking per-message origin on the
DLQ side. Left for a future change.
* feat(sqs): async + rate-limited StartMessageMoveTask, reset receive state, NoDestinationArn returns messages to origin
The synchronous move-task implementation had several gaps that surfaced
under realistic client behavior:
* MaxNumberOfMessagesPerSecond was accepted but ignored -- the move
completed instantly, so a low rate with a follow-up cancel could
never actually catch the worker mid-flight.
* Cancel was effectively a no-op for the same reason.
* Two-task-for-same-source rejection couldn't fire because the first
task was already done.
* NoDestinationArn dropped the messages instead of returning them to
the queue they were DLQ'd from.
* Messages moved from a DLQ back to a queue with maxReceiveCount=1
retained their old receiveCount, so the very first ReceiveMessage
re-triggered the DLQ rule and silently round-tripped them back.
This change reworks the move task to run on a background worker that:
* Drains the source one message at a time (so the source queue stays
observably populated while the move is in flight at low rates).
* Throttles to the requested MaxNumberOfMessagesPerSecond (sleep
1000/rate ms between deliveries; 0 = no throttle).
* Resets receiveCount / firstReceiveTimestamp / receiptHandle /
visibleAt on each moved message so it starts a fresh life on the
destination queue.
* Honours a cancellation flag that CancelMessageMoveTask flips; the
worker observes it between iterations and transitions the task to
CANCELLED in its finally block.
* Routes per-message origin when no DestinationArn is supplied. The
receive path now records the source queue URL on each message it
routes to a DLQ via the redrive policy.
* Moves the very first message synchronously inside the request scope
so callers that poll the destination immediately after the call
returns see motion without racing the executor's thread start.
The two-task concurrency check trips on a recent task (started within
the last second) as well as a still-RUNNING one, which catches the
back-to-back-call pattern AWS rejects without spuriously blocking
legitimate re-runs minutes later.
* fix(sqs): MessageMoveTask review fixes - exact ARN match + AWS-aligned error
Review feedback on #910:
- Concurrent-task rejection used "AWS.SimpleQueueService.UnsupportedOperation".
Real AWS uses InvalidParameterValue with the message "There is already a
task running. Only one active task is allowed for a source queue arn at a
given time." Align the error code and message with the observed AWS
response so SDK exception typing works correctly.
- isDeadLetterQueue and listDeadLetterSourceQueues substring-matched the
raw RedrivePolicy JSON, so a queue ARN that happened to be a prefix of
another queue's ARN was falsely identified as a DLQ. Parse the
RedrivePolicy and compare deadLetterTargetArn exactly. Add a regression
test covering both the StartMessageMoveTask and ListDeadLetterSourceQueues
paths.
- Update the stale comment describing the concurrent-task race window so
it reflects the background-worker design (the move is no longer
synchronous).
* fix(ec2): add missing instance response fields to fix Terraform nil pointer dereference (#871)
The ENI <attachment> block was absent from Floci's RunInstances and
DescribeInstances XML responses. Terraform provider AWS v5.x iterates
network interfaces and reads iface.Attachment.DeviceIndex without nil-checking
Attachment, causing a panic in resourceInstanceRead.
Additional fields required by the provider were also missing: cpuOptions,
metadataOptions, maintenanceOptions, enclaveOptions, hibernationOptions,
privateDnsNameOptions, capacityReservationSpecification, stateReason,
and blockDeviceMapping.
- Add attachmentId and deviceIndex to InstanceNetworkInterface model
- Populate both fields at ENI creation time in Ec2Service.runInstances
- Emit <attachment> and <privateIpAddressesSet> inside each ENI item in instanceXml()
- Emit all missing instance-level fields in instanceXml()
- Add Ec2InstanceResponseShapeTest compatibility test (16 assertions)
* fix(ec2): fix ec2 unit tests
* fix(sns): emit correct error codes for Publish size violations
Publish was throwing AwsException with the SDK class name
"InvalidParameterException" as the error code, which the AWS SDK
unmarshaller doesn't recognise (it expects the AWS Query protocol
code "InvalidParameter"). Result: the SDK fell back to the base
AmazonSimpleNotificationServiceException instead of the typed
InvalidParameterException.
Use the canonical AWS error codes:
- body alone > 256 KiB -> "InvalidParameter" (-> InvalidParameterException)
- body + subject + attributes > 256 KiB -> "InvalidParameterValue"
(-> InvalidParameterValueException), matching real SNS which
blames the attribute set when the body itself fits.
* refactor(sns): avoid double UTF-8 encoding of message in publish size check
Reuse the precomputed messageBytes when calling computePublishSize so
the message body isn't encoded twice for the body-only and combined
payload checks.
* fix(sns): align both Publish size-violation branches to InvalidParameter
Review feedback on #906: validation against real AWS SNS (eu-west-1)
showed both the body-only and combined-payload overflow cases return
the same error: InvalidParameter / "Invalid parameter: Message too long".
The two-code split in the PR followed the SDK documentation but diverged
from observed wire behaviour.
Collapse to a single check using the already-computed payload size, and
drop the misleading "MessageAttributes Reason: ..." message text since
the overflow can come from any combination of body, subject, or
attributes. Update the corresponding test name and assertion.
* fix(sqs): skip JSON null values in TagQueue tags and attribute maps
JsonNode.asText() returns the literal string "null" for explicit JSON
null values. This caused TagQueue with {"Tags":{"NullTag":null}} to
store the four-character string "null" as the tag value, surfacing on
the wire as <Value>null</Value> when read back via ListQueueTags.
Same path is used for CreateQueue / SetQueueAttributes attribute maps,
where a null-valued attribute would have stored the same literal.
Skip null/missing JsonNode values in jsonNodeToMap so the absent key
round-trips as absent rather than as the string "null".
* fix(sqs): reject JSON null tag/attribute values with InvalidParameterValue
Match real AWS behavior: return HTTP 400 InvalidParameterValue with
'the parameter "value" may not be null' when a JSON 1.0 TagQueue,
CreateQueue, or SetQueueAttributes request contains a null map value,
rather than silently skipping the entry.
Adds regression coverage for TagQueue, CreateQueue (tags + attributes),
and SetQueueAttributes.
* fix(sqs): scope FIFO dedup per MessageGroupId when DeduplicationScope=messageGroup
FIFO queues default to queue-wide deduplication, but the high-throughput
configuration (DeduplicationScope=messageGroup,
FifoThroughputLimit=perMessageGroupId) scopes dedup to each
MessageGroupId. Floci was always keying the dedup cache by
MessageDeduplicationId alone, so two SendMessage calls that shared a
dedupId across different message groups would have the second silently
swallowed even when the queue's DeduplicationScope said they were
distinct.
When DeduplicationScope=messageGroup, key the dedup cache by
(messageGroupId, dedupId) and constrain the duplicate-lookup helper
to the same group. Queue-scoped behavior is unchanged (still keyed
on dedupId alone, lookup spans all groups), and a regression test
covers both paths.
* fix(sqs): use NUL delimiter for group-scoped FIFO dedup key
'|' is in the allowed character set for both MessageGroupId and
MessageDeduplicationId, so the composite key collides — e.g.
(group="a", dedup="b|c") and (group="a|b", dedup="c") both produce
"a|b|c". Use NUL (which is not allowed in either field) so the
composite key is unambiguous, and add a regression test.
* feat(sns): implement HTTP/HTTPS endpoint delivery (#841)
Add HTTP/HTTPS webhook delivery to SNS topics. When a message is
published to a topic with HTTP(S) subscribers, a POST is now made to
the endpoint with the SNS notification envelope and standard headers.
* fix(sns): address review feedback for HTTP/HTTPS delivery
- Use proper SubscriptionConfirmation flow instead of auto-confirm
- Make HTTP delivery async with sendAsync to avoid blocking Publish
- Log non-2xx responses as warnings instead of successful deliveries
- Fix field name SigningCertUrl -> SigningCertURL for HTTP notifications
- Add x-amz-sns-rawdelivery header for raw message delivery
- Validate endpoint scheme matches protocol on subscribe
- Use BodyHandlers.discarding() since response body is unused
- Pass null HttpClient in test constructor to avoid real connections
- Add message attributes coverage to integration test
* fix(sns): correct subscription-arn header and binary attribute serialization
- Send PendingConfirmation as x-amz-sns-subscription-arn header in
SubscriptionConfirmation requests, matching AWS wire protocol
- Base64-encode binary MessageAttributes in HTTP notification envelope
instead of producing null
- Add header assertion to subscription confirmation integration test