Commit Graph
458 Commits
Author SHA1 Message Date
Stuart Lang 788ddf751f fix(sts): honour 12-digit access key as account ID in STS responses (#983)
* 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.
2026-05-21 20:36:28 -05:00
dagrammy ff40a2fc0a fix(sqs): accept bare queue name in QueueUrl field (#980)
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.
2026-05-21 20:35:12 -05:00
Stuart Lang be4eba1c20 fix(s3): accept region-qualified virtual-host form bucket.s3.<region>.<host> (#978)
* 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.
2026-05-21 18:22:50 -05:00
Arthur Tristram 1cdb4389a6 fix(sqs-sns): add ContentBasedDeduplication and SNS Subscription provisioning (#974) 2026-05-21 18:19:37 -05:00
Hector Ventura 4edb6f93f6 fix(s3): return ObjectLockConfigurationNotFoundError for non-lock buckets (#971)
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
2026-05-20 23:43:56 -05:00
Hector Ventura b200280a83 feat(cloudfront): implement CloudFront service emulation (#969)
* feat(cloudfront): implement CloudFront service emulation

Adds full CloudFront emulation covering both core and extended operations using the REST XML protocol (2020-05-31 API).

Core resources:
- Distributions (CRUDL, copy, enable/disable, ETag concurrency)
- Cache Behaviors (default + ordered)
- Invalidations (create, get, list)
- Origin Access Controls and Origin Access Identities
- CloudFront Functions (create, update, publish, test, describe)

Extended resources:
- Continuous Deployment Policies
- Public Keys and Key Groups
- Realtime Log Configs (non-standard POST-based get/delete)
- Streaming Distributions (legacy RTMP, enforces disabled before delete)
- Field-Level Encryption Configs and Profiles
- Monitoring Subscriptions

Infrastructure:
- Registers CloudFrontController in ResolvedServiceCatalog as REST_XML
- Adds CloudFrontServiceConfig and CloudFrontStorageConfig to EmulatorConfig
- Adds CLOUDFRONT namespace constant to AwsNamespaces
- Registers CloudFrontService for GraalVM runtime initialization to avoid SecureRandom heap-baking in native builds
- Wires storage through StorageFactory with per-resource JSON files
- Adds cloudfront.md documentation page

* docs: revert docker-compose.yml
2026-05-20 23:12:03 -05:00
Hector Ventura eda92677dd fix(cbor): lowercase smithy-protocol response header casing (#968)
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.
2026-05-20 22:20:02 -05:00
Darrell Draney 70958b1091 fix(s3): omit body-description headers and user metadata from PutObject response (#948)
## 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/)
2026-05-20 18:03:54 -05:00
Marvelous Ikponmwosa 5f4dd43b5a feat(apigatewayv2): forward HTTP API requests through ALB listener (#941)
* feat(apigatewayv2): forward HTTP API requests through ALB listener
* implemented copilot feedbacks
* refactor(apigatewayv2): apply maintainer feedback
2026-05-20 18:00:30 -05:00
Albert Einshutoin 0a8732b349 fix(rds): persist metadata across storage-backed restarts (#945) 2026-05-20 17:36:54 -05:00
Federico Mariani 96a6fa6517 feat(config): add AWS Config service emulation (#934)
* 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.
2026-05-20 17:15:38 -05:00
Stuart Lang 9bdb5436f0 feat(sqs): persist and return AWSTraceHeader system attribute (#909)
* 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.
2026-05-20 17:13:56 -05:00
Mike Mangino ce1f565003 Fix ListObjects v1 marker pagination (#939)
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.
2026-05-19 21:55:19 -05:00
nblomquist 6819bce493 feat(kms): implement GenerateMac and VerifyMac (#927)
* feat(kms): implement GenerateMac and VerifyMac
* fix(kms): remove unused MAC message type handling
* test(kms): add MAC JSON handler integration coverage
* fix(kms): avoid duplicate MAC key resolution
2026-05-19 21:53:30 -05:00
Stuart Lang 24bbd81988 fix(sqs): reject SendMessageBatch when combined payload exceeds MaximumMessageSize (#907)
* 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.
2026-05-19 21:49:38 -05:00
Yoshiyuki Ohta 4c156df10b fix(apigatewayv2): include corsConfiguration on Api management responses (#933)
`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`).
2026-05-19 21:45:41 -05:00
Mike Mangino c6928128ff Fix crash when request Content-Type header is empty string (#940)
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.
2026-05-19 18:09:48 -05:00
Steve 60c4edda55 fix(lambda): log actionable hint when concurrency pool is exhausted (#935)
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.
2026-05-19 18:08:12 -05:00
Federico Mariani 291a201efa fix: DynamoDB DeleteTable status and PartiQL scan, add SecretsManager RestoreSecret (#915)
* 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.
2026-05-19 18:05:06 -05:00
Steve 040ef033b4 fix(lambda): make PortAllocator a checkout/release pool (#936)
* 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.
2026-05-19 18:01:19 -05:00
Dixit R JainandDixit R Jain c0d6b71eb1 fix(apigatewayv2): raise Vert.x WebSocket frame size limit to 256 KB (#938)
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>
2026-05-19 17:58:04 -05:00
Yoshiyuki Ohta 43332cef77 fix(apigatewayv2): include connectionType and enableSimpleResponses on Integration/Authorizer responses (#931)
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`).
2026-05-19 00:52:35 -05:00
ram-sarf e54a8e502c fix(sns): preserve per-entry MessageAttributes in PublishBatch (#891)
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.
2026-05-19 00:49:01 -05:00
Steve Sanders a51e434386 feat(apigatway): handle requests to custom domains (#922)
* feat(apigatway): handle requests to custom domains
* refactor: remove  routing
* refactor: enforce unique custom domain name
2026-05-19 00:48:19 -05:00
Marvelous Ikponmwosa eb1ca7b674 feat(ecs): register ECS service containers as ELBv2 targets (#929)
* 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
2026-05-19 00:47:07 -05:00
Steve 9e7cbe012f fix(lambda): await HttpServer close in RuntimeApiServer.stop() (#926)
* 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.
2026-05-19 00:43:33 -05:00
Ahmed Soliman b8d1b817c9 fix(apigateway): accept any Content-Type on Put/ImportRestApi (#925)
* 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
2026-05-19 00:42:26 -05:00
Ahmed Soliman d89270c538 fix(s3): honor response-* query parameters on GetObject and HeadObject (#923)
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
2026-05-19 00:31:41 -05:00
Lucas Costa 6a9af6057c feat(elasticache): add Memcached CreateCacheCluster/DescribeCacheClus… (#930)
* 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.
2026-05-19 00:22:33 -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
Stuart Lang 5dedeff9e4 feat(sqs): implement StartMessageMoveTask / List / Cancel with async drain + rate limiting (#910)
* 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).
2026-05-18 23:01:30 -05:00
Hector Ventura fd660e03ed fix(ec2): add missing instance response fields to fix Terraform nil pointer dereference (#871) (#883)
* 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
2026-05-18 22:55:22 -05:00
Stuart Lang b65b7aa07f fix(sns): emit canonical error codes for Publish size violations (#906)
* 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.
2026-05-18 21:03:58 -05:00
Stuart Lang aec85f993a fix(sqs): skip JSON null tag/attribute values instead of storing literal "null" (#905)
* 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.
2026-05-18 20:55:15 -05:00
Stuart Lang 337b35c938 fix(sqs): scope FIFO dedup per MessageGroupId when DeduplicationScope=messageGroup (#908)
* 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.
2026-05-18 20:53:33 -05:00
Rafael Almonte 86dc64fc7e feat(sns): implement HTTP/HTTPS endpoint delivery (#841) (#865)
* 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
2026-05-18 18:58:09 -05:00
Eduardo Lugo Vela e1fa8ae8c7 fix(s3): return correct checksum algorithm on PutObject (#877)
* fix(s3): return correct checksum algorithm on PutObject
* fix(s3): use client-provided checksum header when present
* fix(s3): use correct reflected polynomial for CRC64NVME checksum
* fix(s3): validate CRC32, CRC32C and CRC64NVME client-provided checksums
2026-05-17 23:56:21 -05:00
Nitesh K Jain 371dd02404 feat:add neptune graph database support (#881) 2026-05-17 23:44:11 -05:00
Prakhar Kapoor 15720e2ee6 feat(apigateway): implement account management endpoints and models (#867)
* feat(apigateway): implement account management endpoints and models
* feat(apigateway): enhance patch operation validation and update throttle settings defaults
* feat(api-gateway): add account management operations to API Gateway v1
* feat(api-gateway): add compatibility tests for account management and update logic
* feat(api-gateway): add missing import for assertions in account compatibility test
2026-05-17 23:42:09 -05:00
Hector Ventura 647b170494 fix(dynamodb): honor legacy Expected condition in UpdateItem (#888)
UpdateItem was silently ignoring the legacy `Expected` parameter sent
by AWS SDK v1 clients, causing conditional writes to always succeed
regardless of the condition.

Two bugs fixed:
- `handleUpdateItem` never read the `Expected` field from the request
- `evaluateLegacyExpected` passed conditions directly to
  `matchesKeyConditionPublic`, which reads `AttributeValueList`, but
  the legacy wire format uses the singular `Value` field instead

The fix reads `Expected` and `ConditionalOperator` in `handleUpdateItem`,
validates mutual exclusion with `ConditionExpression`, fetches the
existing item before the update, and normalizes `{"Value": x}` →
`{"AttributeValueList": [x]}` before delegating to the condition
evaluator.

Closes #848
2026-05-17 23:36:36 -05:00
Yoshiyuki Ohta becbbea5f9 fix(apigatewayv2): include authorizerId on Route management API responses (#887)
`Route` already stores `authorizerId` (set by `createRoute`/`updateRoute` and
read at runtime by `WebSocketHandler` and `ApiGatewayExecuteController` for JWT
and Lambda authorizer invocation), but `ApiGatewayController.toV2RouteNode`
omitted it from the JSON returned by `POST/PATCH/GET /v2/apis/{apiId}/routes`.
Get-route therefore always reported `authorizerId = null`, which causes IaC
tools like Terraform's `aws_apigatewayv2_route` to see drift on every plan
even when the route is configured correctly.

Adds the missing emit alongside the other optional Route fields and a focused
regression test (`RouteAuthorizerIdResponseTest`) covering create/get/list and
the PATCH update path.
2026-05-17 23:36:02 -05:00
Yoshiyuki Ohta ff80dac780 fix(eventbridge): keep persisted rules from disappearing on reload (#878)
Rule.getRegion() is a derived getter (computed from the rule's ARN) but
has no matching setter. When EventBridgeService runs in any non-memory
storage mode, PersistentStorage's ObjectMapper writes "region" into
eventbridge-rules.json on save, then throws UnrecognizedPropertyException
on the next startup because Rule cannot deserialize it. The exception is
swallowed by PersistentStorage.load(), so the rule store comes up empty
and every PutRule made before the restart silently disappears.

Two changes on Rule:

- @JsonIgnore on getRegion() so the derived field is no longer written
  to disk.
- @JsonIgnoreProperties(ignoreUnknown = true) on the class to match the
  convention used by Target, InputTransformer, SqsParameters and most
  other persisted models, and to let a file that includes "region"
  (written before this change) still load cleanly after upgrade.

Adds RulePersistenceTest covering the PersistentStorage round-trip and
unknown-property tolerance.
2026-05-17 11:24:30 -05:00
Hector Ventura 70e61dcbda fix(eks): use container IP for readiness polling and handle startup failures (#873) 2026-05-17 08:39:16 -05:00
Ricardo Medina dc2efe75e8 feat(apigatewayv2): HTTP_PROXY integration with request parameter mapping (#860)
* feat(apigatewayv2): HTTP_PROXY integration with request parameter mapping

Adds full HTTP_PROXY support to API Gateway v2 dispatch, replacing the
previous Lambda-only assumption. Integrations with IntegrationType=HTTP_PROXY
now forward the inbound request to the configured IntegrationUri,
applying RequestParameters transformations.

Supported RequestParameters action × target combinations:
  overwrite | append | remove  ×  path | header.<name> | querystring.<name>

Supported source value expressions:
  $context.authorizer.claims.<name>     JWT claim from authorizer
  $context.authorizer.<name>            authorizer context value
  $context.requestId                    UUID assigned per request
  $context.identity.sourceIp            client IP
  $request.header.<name>                case-insensitive header lookup
  $request.querystring.<name>           query parameter
  $request.path.<name>                  captured path parameter
  literal strings                       returned unchanged

The IntegrationUri may contain {proxy} or {paramName} placeholders,
substituted with captured path parameters from the matched route.
overwrite:path values may also embed $request.path.X / $context.X
substrings which are resolved in-place.

Implementation:
- New package services.apigatewayv2.proxy with RequestContext (DTO),
  ContextValueResolver (source expression parser), PathTemplateResolver
  (URI template substitution), ProxyRequestBuilder (mutable outgoing
  request), RequestParameterMapper (applies RequestParameters), and
  HttpProxyInvoker (orchestrator using java.net.http.HttpClient).
- ApiGatewayExecuteController.dispatchV2 now branches on
  integration.getIntegrationType() and routes HTTP_PROXY requests to
  HttpProxyInvoker, building a RequestContext from the controller state
  including parsed JWT claims for $context.authorizer.claims.X.
- Integration v2 model gains a requestParameters Map field, persisted
  by ApiGatewayV2Service create/update and serialized by both the
  AWS JSON 1.1 handler and the REST controller.

Bug fixes (encountered during integration testing):
- routeKeyMatchesPath now treats `ANY` as the AWS wildcard method,
  matching any inbound HTTP method (previously did literal string
  comparison and rejected ANY routes for non-ANY requests).
- JWT authorizer audience check now also accepts `client_id` claim,
  which Cognito access tokens use instead of `aud` (only ID tokens
  carry `aud`). AWS API Gateway accepts either; floci now matches.

Tests:
- 11 ContextValueResolver tests covering each source expression form
- 7 PathTemplateResolver tests covering placeholder substitution
- 13 RequestParameterMapper tests covering each action × target
- 7 HttpProxyInvokerTest tests using JDK com.sun.net.httpserver as a
  real backend, verifying method/path/headers/body forwarding,
  RequestParameters application, hop-by-hop header stripping, and
  502 error mapping for backend failures
- 1 round-trip integration test confirming RequestParameters survive
  CreateIntegration → GetIntegration via the AWS JSON 1.1 handler

* perf(apigatewayv2): cache compiled route-template patterns per route key

extractV2PathParams compiled both the routing regex and the
parameter-name extraction regex on every inbound request. Route
keys are stable after creation, so this is wasted work on every
request — visible under load on frequently-hit paths.

Cache the routing regex in a ConcurrentHashMap<String, Pattern>
keyed by the raw template string, and hoist the constant
parameter-name pattern to a static final field.

Adds ApiGatewayExecuteControllerTest with 8 cases covering greedy,
non-greedy, mixed, and edge inputs, plus a hot-loop assertion that
repeated calls against the same route key return stable results
(the cache itself is an internal implementation detail and is not
asserted directly).

* fix(apigatewayv2): accept {name+} greedy placeholder in IntegrationUri

PathTemplateResolver's PLACEHOLDER regex matched {paramName} but not
{paramName+}, so configuring IntegrationUri = "http://backend/{proxy+}"
forwarded the literal string "{proxy+}" to the backend and the call
silently 404'd. The mismatch is surprising because {proxy+} is the
canonical AWS form already accepted by route keys (e.g.
"ANY /wallet/{proxy+}"), so most users mirroring the route shape in
the IntegrationUri hit this.

Extend the placeholder pattern with \+? so {name} and {name+} both
resolve to the same parameter keyed by name. Captured path params
are still stored under the bare name (no + suffix), matching the
existing extractV2PathParams behavior, so no other call sites change.

Picked this over documenting the limitation because the AWS
convention is widely expected and the fix is one character.

Adds 4 tests to PathTemplateResolverTest for {name+}: greedy proxy,
greedy named, mixed greedy + non-greedy, and missing-key fallback.
2026-05-17 00:35:42 -05:00
Hector Ventura 2608b8d6d6 feat(dynamodb): implement ExecuteStatement, ExecuteTransaction, BatchExecuteStatement (#864)
Adds PartiQL support for DynamoDB via a hand-rolled tokenizer and
recursive-descent parser that translates SELECT, INSERT, UPDATE, and
DELETE statements into existing DynamoDbService calls.

  - DynamoDbPartiQLParser: tokenizer + AST (sealed interfaces) with
    positional ? placeholder resolution from Parameters array
  - DynamoDbPartiQLHandler: translates AST to GetItem/Query, PutItem,
    UpdateItem, DeleteItem; always uses ExpressionAttributeNames to avoid
    reserved-keyword conflicts; routes pk-only WHERE to Query (not GetItem)
    when the table has a composite key
  - DynamoDbJsonHandler: wires ExecuteStatement, ExecuteTransaction, and
    BatchExecuteStatement; BatchExecuteStatement captures per-statement
    errors without aborting the batch
  - DynamoDbPartiQLTest: 13 compatibility tests covering INSERT, SELECT
    (pk-only, range, projection, begins_with, ? placeholders), UPDATE
    SET/REMOVE, DELETE, ExecuteTransaction, and BatchExecuteStatement
2026-05-16 19:34:33 -05:00
Kenshin Okinaka 9a10f81fb7 feat(sns): support FilterPolicyScope=MessageBody (#863)
Parse the message body as JSON and evaluate the subscription filter
policy against the parsed tree, with nested-key descent and type-aware
rule matching (string/number/boolean/null values, array-value OR,
exists/prefix/anything-but/numeric). Previously the scope was accepted
but filtering was skipped, so all messages were delivered. Bodies that
are not valid JSON fail closed.

The body is parsed lazily once per publish, only when at least one
subscription uses MessageBody scope, to avoid O(N-subscriptions) parses.
The MessageAttributes scope evaluator is untouched.
2026-05-16 19:21:37 -05:00
Arthur Tristram 43ba8a73b0 fix(eventbridge): propagate region for correct SQS queue resolution (#870)
Ensure the EventBridge region is correctly passed through downstream
processing so that SQS queue lookup uses the intended region instead of
defaulting to the primary region.
2026-05-16 15:28:49 -05:00
Ricardo Medina e1c3f7fcf6 feat(cognito): fire PostConfirmation and PreSignUp triggers (#859)
Adds support for two Cognito user-pool Lambda triggers that were not yet
wired in floci:

PostConfirmation:
  Fires on ConfirmSignUp with triggerSource=PostConfirmation_ConfirmSignUp.
  Errors are logged but do not block the confirm operation, matching
  AWS Cognito fire-and-forget semantics for post-* triggers.

PreSignUp:
  Fires on SignUp with triggerSource=PreSignUp_SignUp BEFORE the user is
  persisted. Lambda errors block the signup (NotAuthorizedException). The
  trigger response can auto-confirm the user and auto-verify email/phone
  via the documented response fields:
    response.autoConfirmUser
    response.autoVerifyEmail
    response.autoVerifyPhone

When PreSignUp returns autoConfirmUser=true, PostConfirmation is also
invoked, matching AWS Cognito's documented chain behavior:
  https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html

Tests cover happy path, error handling, response application, the
auto-confirm → post-confirmation chain, and not-configured no-op behavior
for both triggers.
2026-05-16 13:55:44 -05:00
Kenshin Okinaka 010bbd15cd feat(ses): add v2 PutAccountSuppressionAttributes (#853)
Implements PUT /v2/email/account/suppression so callers can change the
account-level suppression list reasons (BOUNCE / COMPLAINT). Entries
are persisted per region in ses-account-suppression.json via a new
AccountSuppressionAttributes model.

GetAccount's response is extended with a SuppressionAttributes object
that carries the stored SuppressedReasons. The setting itself is
metadata-only — floci does not synthesise bounce/complaint events so
no auto-suppression is triggered; the configuration round-trips for
SDK users and tooling that introspects account-level settings.

Behaviour aligned with real-AWS verification:

- SuppressedReasons accepts BOUNCE / COMPLAINT, validated against the
  AWS-canonical nested "Member must satisfy constraint:
  [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]" wording
  (verbatim match against real AWS).
- SuppressedReasons may be omitted (treated as empty list) or supplied
  as an empty array (clears the reasons) — both return 200.
- Non-textual array members (JSON null, numeric, etc.) are rejected
  with BadRequestException.
- Fresh regions report the AWS-default [BOUNCE, COMPLAINT] via
  GetAccount; an explicit PUT (including an empty list) overrides it.
- The optional ValidationAttributes body field is accepted but not
  parsed (Tier S scope).

Tests:
- SesV2IntegrationTest gains nine cases covering store-and-list,
  clear-with-empty-array, missing field defaulting to empty, invalid
  Reason (with the AWS-canonical nested message asserted), non-array
  SuppressedReasons, JSON null array member, numeric array member,
  optional ValidationAttributes, and the default-on-fresh-region
  assertion in the existing getAccount case.
- SesAccountSuppressionTest exercises the Java SDK round trip and an
  explicit empty list through SesV2Client; @BeforeAll captures the
  caller's existing SuppressedReasons and @AfterAll restores it with
  failures surfaced so a real-AWS run cannot silently leave the
  account with auto-suppression disabled.
2026-05-15 22:59:14 -05:00
Shubham Srivastava 6d36f66e5f feat(cur, bcm-data-exports): add Cost and Usage Reports + BCM Data Exports (#850)
Implements PR 3 of the 3-PR billing-API scope discussed in #791. Adds
two service surfaces that share one underlying export pipeline:

- `cur:*` — legacy Cost and Usage Reports management plane, target
  prefix `AWSOrigamiServiceGatewayService.*`.
- `bcm-data-exports:*` — modern Billing and Cost Management Data
  Exports management plane, target prefix
  `AWSBillingAndCostManagementDataExports.*`.

Both run as JSON 1.1 services dispatched through the existing
`AwsJson11Controller`.

## Operations

CUR (7):

- `PutReportDefinition`, `ModifyReportDefinition`,
  `DescribeReportDefinitions`, `DeleteReportDefinition`
- `TagResource` / `UntagResource` / `ListTagsForResource` (stubs)

BCM Data Exports (7):

- `CreateExport`, `GetExport`, `ListExports`, `UpdateExport`,
  `DeleteExport`
- `ListExecutions`, `GetExecution`

AWS-shaped error codes throughout: `DuplicateReportNameException`,
`ReportLimitReachedException`, `ReportNotFoundException`,
`ResourceNotFoundException`, `ValidationException`,
`UnknownOperationException`. Storage keys are account-scoped
(`<accountId>::<region>::<reportName>` for CUR;
`<accountId>::<exportArn>` and `<accountId>::<exportArn>::<executionId>`
for BCM) so both services participate in Floci's per-account
isolation.

## Parquet emission

The same `ResourceUsageEnumerator` SPI introduced in #832 (Cost
Explorer) backs the Parquet artifact:

1. `EmissionEngine` collects `UsageLine` rows from every
   `@ApplicationScoped` enumerator bean.
2. `FocusRowProjector` projects them into FOCUS 1.2 / CUR 2.0 column
   shape, reusing #821's bundled Pricing snapshot for unit prices.
3. Rows are staged as newline-delimited JSON in
   `s3://floci-cur-staging/...` via Floci's S3 service — escape-safe
   for tags, descriptions, and resource identifiers.
4. The `floci-duck` sidecar runs
   `COPY (SELECT * FROM read_json_auto('s3://...')) TO 's3://...'
   (FORMAT PARQUET)` so Parquet writes happen inside DuckDB, not in
   the Java process. This avoids pulling Apache Parquet / Hadoop /
   Avro into Floci's classpath and keeps the native binary footprint
   unchanged.
5. Staging objects are removed in a best-effort `finally` block; each
   run carries a fresh `runId` (UUID) in both staging and
   destination keys so concurrent emissions cannot clobber each other.

The emission engine is shared between CUR and BCM, but the management
planes are otherwise independent — they each own their own validation,
storage, and JSON dispatch.

## Run modes

`FLOCI_SERVICES_CUR_EMIT_MODE` and
`FLOCI_SERVICES_BCM_DATA_EXPORTS_EMIT_MODE`:

- `synchronous` (default): emit on every report/export mutation
- `daily`: emit once per 24h via a CUR-owned single-thread
  `ScheduledExecutorService` — separate from the EventBridge
  Scheduler dispatcher, so internal billing exports do not surface as
  user-visible Scheduler resources.
- `off`: management plane only

Emission failures never roll back the management mutation. Failures
surface as `ReportStatus.LastStatus = ERROR` on CUR and
`Execution.ExecutionStatus.StatusCode = DELIVERY_FAILURE` on BCM.

## Tests

42 new tests across 5 classes:

- `CurIntegrationTest` (11) — full CRUD on report definitions,
  duplicate / not-found / validation paths
- `BcmDataExportsIntegrationTest` (16) — full CRUD on exports +
  executions, all validation paths
- `FocusRowProjectorTest` (9) — pure-unit projection: usage rows,
  USD-denominated record types (Credit / Refund / Tax), missing
  resource id, tags JSON, billing-period anchoring, region+account
  flow-through, rate cache reuse
- `ParquetEmitterIntegrationTest` (3) — DuckDB readback,
  staging cleanup, concurrent run isolation
- `CurEmissionIntegrationTest` (3) — end-to-end:
  PutReportDefinition -> emit -> Parquet readable through DuckDB;
  ReportStatus updates; CreateExport produces an execution record

Full Floci suite stays green (4194/4194, excluding the pre-existing
local-env flakes documented during PR #821 / #832 and the two
duck-required tests added here that need the `floci-duck` sidecar
and a fixed Floci HTTP port to verify cross-container S3 access).

## Documentation

- `docs/services/cur.md` — operations, validation rules, emission
  pipeline, configuration, examples.
- `docs/services/bcm-data-exports.md` — operations, validation,
  execution lifecycle, configuration, examples.
- README service table updated with rows for both, plus a note that
  CUR / BCM Data Exports share one Parquet engine.

Refs: https://github.com/orgs/floci-io/discussions/791
Refs: #823
Builds on: #821, #832
2026-05-15 22:55:11 -05:00