Commit Graph
190 Commits
Author SHA1 Message Date
TiM d75c32c9f7 fix(lambda): accept name, partial ARN, and full ARN for {FunctionName} (#450)
Real AWS accepts bare name, partial ARN (ACCT:function:NAME), and full
ARN (arn:aws:lambda:REGION:ACCT:function:NAME) for every endpoint that
takes {FunctionName}, optionally suffixed with :qualifier. Floci only
matched the stored short name, so ~20 Lambda endpoints 404'd on ARN
forms.

Introduce LambdaArnUtils.resolve() as the single parse point; normalize
inputs in LambdaService at every user-facing method so downstream store,
warm-pool, code-store, and alias-store operations all use the canonical
short name. createFunction now deduplicates across name/ARN forms.

- Enforce region match when a full function ARN is supplied (400 on
  mismatch with the request region or with an event-source ARN region).
- Tag endpoints require an unqualified full function ARN; reject
  qualified ARNs and partial ARNs.
- URL config endpoints reconcile ARN-embedded qualifier with ?Qualifier=
  and 400 on conflict.
- listEventSourceMappings normalizes its FunctionName filter so partial
  ARNs no longer miss stored mappings.

Fixes floci-io/floci#434.
2026-04-14 22:12:58 -05:00
Christine Nguyen ba62ae6b5d feat(eventbridge): implement TagResource and UntagResource (#453) 2026-04-14 22:12:06 -05:00
TiM e62f2a64d7 fix(kinesis): return time-based MillisBehindLatest (#444)
AWS Kinesis GetRecords documents MillisBehindLatest as the time delta
between the consumer position and the shard tip in milliseconds.
Floci was returning the count of records remaining in the shard instead,
so downstream iterator-age metrics and lag-based alerting were wrong
(e.g. 10 records ahead surfaced as 10ms of lag).

Use the ApproximateArrivalTimestamp already stamped at PutRecord time to
compute the delta. Returns 0 when the consumer is at the shard tip, the
shard is empty, or no records were returned.
2026-04-14 16:24:27 -05:00
yusuke-uranaka a0cd0ac511 refactor(dynamodb): extract KinesisStreamingForwarder from DynamoDbStreamService (#428)
Move Kinesis streaming destination forwarding logic into a dedicated
KinesisStreamingForwarder class, injected directly into DynamoDbService.

This decouples Kinesis forwarding from DynamoDB Streams at the DI level —
the two features are independent in real AWS and should not share a
null-guard or lifecycle dependency.
2026-04-14 16:23:23 -05:00
Conor Heine 5f16792a35 fix: fall back to named volume for ECR registry when host-persistent-path is unset in containers (#442)
Main's PR #419 solves the in-container case when FLOCI_STORAGE_HOST_PERSISTENT_PATH is set to an absolute host path (via the updated docker-compose.yml). This adds a zero-config fallback: when Floci detects it's running inside a container and host-persistent-path is still its relative default (./data), bind-mounting into a sibling container fails on Docker Desktop. In that case, use a dedicated named volume (floci-ecr-registry-data) so docker compose up works without requiring users to update their compose file.
2026-04-14 16:21:39 -05:00
Kenshin Okinaka fb26731131 feat(lambda): enforce reserved and per-region concurrency (#424)
* feat(lambda): enforce reserved concurrency at invocation time

Introduce LambdaConcurrencyLimiter using AtomicInteger + CAS. Acquire a
permit before invoke and release in finally for both sync and async
paths. DryRun skips enforcement. Functions without a reserved value are
not enforced in this step (account-pool enforcement will follow).

Reset inflight counters when a function is deleted to prevent leaks.

* test(lambda): use JUnit Assertions in LambdaConcurrencyLimiterTest

AssertJ is not on the unit-test classpath; switch to the Jupiter
assertions already used by sibling tests.

* feat(lambda): enforce account-wide concurrency pool and validate Put

Extend LambdaConcurrencyLimiter with an account-shared unreserved pool
sized as accountLimit - Σreserved. Functions without a reserved value
now share this pool; exhaustion returns TooManyRequestsException.

PutFunctionConcurrency rejects values that would leave less than
unreserved-concurrency-min (AWS default: 100) available, matching AWS's
LimitExceededException behavior.

Config: floci.services.lambda.account-concurrency-limit (default 1000)
and floci.services.lambda.unreserved-concurrency-min (default 100).
Docs and controller javadoc updated accordingly.

* feat(lambda): rehydrate reserved concurrency and handle throttle in pollers

On startup, LambdaService walks functionStore.listAll() and re-registers
reserved values with the limiter so validatePut and the unreserved pool
see the correct totals before the first Put of the session.

SQS/Kinesis/DynamoDB Streams pollers now catch TooManyRequestsException
explicitly. SQS lets messages return via visibility timeout; Kinesis and
DynamoDB Streams skip advancing the shard iterator, so records are
redelivered on the next poll.

* test(lambda): add SDK compatibility tests for concurrency enforcement

Verify end-to-end wire behavior: LimitExceededException on Put that
violates unreserved-min, TooManyRequestsException on Event invoke when
reserved=0, and DryRun bypassing the concurrency gate.

* fix(lambda): close concurrency races in limiter and rehydrate

- Recompute cap inside the unreserved CAS loop so concurrent setReserved
  does not leave permits granted above the live pool.
- Replace validatePut + setReserved with a single validateAndSetReserved
  guarded by a reservedLock; concurrent Puts for different functions
  can no longer each pass validation against stale totals.
- Rehydrate only $LATEST entries so published versions do not
  double-count into totalReserved().

* fix(lambda): address PR review feedback

- Partition limiter state by region. AWS Lambda concurrency is per
  account-per-region; functions in different regions no longer share
  the same reserved totals or unreserved pool.
- PutFunctionConcurrency and DeleteFunctionConcurrency now roll back
  the limiter update if functionStore.save() fails, so limiter and
  persisted state stay consistent.
- Replace the awkward (InvokeResult) null cast in the DynamoDB Streams
  poller with a plain forward declaration.

* refactor(lambda): rename account-concurrency-limit to region-concurrency-limit

The limit applies per-region (AWS Lambda's "account-level" quota is
actually per-account-per-region). Rename the config key, field, and
accessor to match what the value controls, and clarify the doc note.

No functional change.

* fix(lambda): O(1) region total and compare-and-rollback on save failure

- Maintain per-region AtomicInteger running total of reserved values,
  updated under reservedLock on every mutation. acquireUnreserved reads
  the cap in O(1) without iterating the map, eliminating the weakly-
  consistent partial-sum window that existed when reads happened off
  the lock while writes were serialized.
- Replace unconditional rollback with rollbackReservedIfExpected: the
  limiter only restores the previous value if the current entry still
  matches what the caller wrote, so a concurrent successful Put cannot
  be clobbered by an earlier request's rollback after its save fails.

* docs(lambda): scrub remaining account-wide wording and document drain semantics

Replace lingering "account-wide" / "account pool" phrasing with
per-region terminology in the controller javadoc and unit-test comment.
Two references remain by design: EmulatorConfig and the lambda service
doc quote AWS's own "account-level" label to explain the renamed key.

Also fold two follow-up review items into this change:
- Replace fully-qualified AwsException / InvokeResult references in the
  SQS, Kinesis, and DynamoDB Streams pollers with normal imports.
- Document that reducing or clearing a reserved value does not kill
  already-inflight invocations, mirroring AWS behavior and causing a
  brief drain window where total inflight may exceed the region limit.

* fix(lambda): serialize Put/Delete per function and preserve busy inflight

- Wrap PutFunctionConcurrency and DeleteFunctionConcurrency in a
  per-function lock so concurrent requests for the same ARN can't
  interleave the limiter update and the store save in a way that
  leaves them out of sync.
- Retain the inflight counter on reset when permits are still open,
  so an ARN recreated under load sees the remaining inflight rather
  than starting fresh and briefly allowing more than reserved capacity.
  Idle counters (value 0) are still dropped to prevent leaks.
- Tests now close acquired permits via try-with-resources and cover
  both the retain-while-busy and drop-when-idle reset behaviors.

* test(lambda): close all permits via try-with-resources

Close the acquire() result in regions_areIndependent so the test leaves
no inflight state behind and accurately asserts both the exhausted and
recovered cases.

* perf(lambda): avoid regex split in regionOf on the invoke hot path

regionOf() runs on every acquire/release. Replace String.split(":"),
which uses regex and allocates an array, with a single pass that finds
the fourth ':' segment and returns a substring — same semantics, no
allocation beyond the returned region string.

* fix(lambda): keep per-function lock map and tighten compat assertion

- deleteFunction no longer removes the per-function entry from
  concurrencyOpLocks. Removing it could race with a concurrent
  Put/Delete still synchronized on the old lock object, letting the
  next request create a fresh lock and run in parallel — defeating
  the very serialization the map provides. The map grows by one
  Object per deleted function, acceptable for a local emulator.
- LambdaConcurrencyTest now asserts the wire-level error identity
  (400 status + "LimitExceededException" errorCode) for the Put
  rejection. The Lambda SDK v2 model does not declare a typed
  LimitExceededException class, so wire-level assertions catch
  protocol-fidelity regressions more precisely than the previous
  generic LambdaException check.

* fix(lambda): retain inflight counter on reset and allow over-committed reductions

- reset() no longer drops idle inflight counters. The previous
  counter.get()==0 + remove pattern races with a concurrent
  acquireReserved that has already obtained the AtomicInteger
  reference and is about to increment it: a successful remove
  between those two moments would leave the next acquire to
  allocate a fresh counter and silently undercount inflight,
  permitting reserved over-subscription.
- validateAndSetReserved now allows any value <= the function's
  current reservation unconditionally. Reductions cannot worsen
  unreserved capacity, so blocking them in an already over-committed
  state (e.g. after lowering region-concurrency-limit at runtime)
  prevented operators from recovering. Increases still go through
  the unreserved-min check.

* fix(lambda): take per-function lock in deleteFunction

A concurrent deleteFunction + Put/DeleteFunctionConcurrency for the
same ARN could interleave the limiter reset and the store delete,
leaving the limiter holding (or clearing) state for a function the
store no longer knows about. Wrap the limiter+store mutations in the
same lockForConcurrencyOp(arn) used by the concurrency endpoints.

Tighten the surrounding comment so it describes the current code
rather than the lock-removal call that earlier revisions used to have.

* test(lambda): wire a real concurrency limiter into the test constructor

The package-private LambdaService constructor used by unit tests passed
null for concurrencyLimiter, so the null-guards in
putFunctionConcurrency / deleteFunctionConcurrency / deleteFunction made
those paths silently skip validation and limiter bookkeeping under tests.
That hid divergence from production behavior.

Construct a default LambdaConcurrencyLimiter (AWS defaults: 1000 / 100)
in the test ctor so the same enforcement runs in unit tests.

* test(lambda): cover concurrent PutFunctionConcurrency for the same ARN

Verify that the per-function lock in LambdaService serializes racing
Puts so the limiter and the functionStore always agree on whichever
write landed last. 50 iterations across two threads against the same
function exercise the lock discipline and assert store/limiter
consistency on every iteration.

* docs: document reserved concurrency config keys

- docs/services/lambda.md: drop redundant "(enforced at invocation)"
  from the PutFunctionConcurrency table entry (the admonition below
  already explains enforcement); add region-concurrency-limit and
  unreserved-concurrency-min to the Configuration YAML sample.
- docs/configuration/application-yml.md: mirror the two new keys in
  the top-level reference sample so every known lambda setting is
  discoverable in one place.

* refactor(lambda): address review feedback (A)

- LambdaServiceTest.concurrentPutFunctionConcurrency now asserts against
  limiter.totalReserved(region) instead of getFunctionConcurrency(), which
  read the same field as the value under test. The new assertion actually
  proves the limiter and the persisted store stayed in agreement.
- Expose a package-private concurrencyLimiter() accessor on LambdaService
  so tests can inspect limiter state without reflection.
- Drop unused Permit.NOOP: the reserved=null path now runs through
  acquireUnreserved and always returns a real decrement closure.
- Document the intentional unbounded growth of the inflight counter map
  (race avoidance on reset) and concurrencyOpLocks (race avoidance on
  deleteFunction). Both are acceptable for a local emulator workload.

* test(lambda): add rehydrate, multi-ARN race, and qualified-invoke coverage

- LambdaServiceTest.rehydrateConcurrency_restoresReservedFromStore
  prepopulates a LambdaFunctionStore with reserved values, builds a
  fresh LambdaService over it, and verifies totalReserved(region) goes
  from 0 to the expected sum after the @PostConstruct hook runs.
- LambdaServiceTest.multiArnPutFunctionConcurrency_respectsRegionTotalUnderContention
  races two Puts on different ARNs that would together push the region
  below unreserved-min. reservedLock must let exactly one win; the
  other must fail with LimitExceededException and the limiter's total
  must reflect only the winning reservation.
- Compat LambdaConcurrencyTest.invoke_withVersionQualifier_stillHonorsReservedOnLatest
  publishes a version, sets reserved=0, and invokes with the qualifier
  set. Today Floci drops the qualifier and routes to $LATEST, so the
  reservation throttles the call. This test locks the behavior in: a
  future qualifier-routing change must either copy the reservation onto
  the snapshot or key the limiter off the base ARN to keep it green.

* refactor(lambda): idempotent permits, warn on malformed ARN, more tests

- Wrap acquire()/release() counter closures in an AtomicBoolean guard so
  a double-close of a Permit can never drive the inflight counter
  negative. Future callers that mix try-with-resources with explicit
  close, or that add retry logic around invoke, stay safe by default.
- regionOf() now warns once per unique malformed input instead of
  silently coalescing everything into "unknown". The first occurrence
  is logged so a bug that passes a bare function name into the limiter
  is debuggable without spamming the log.
- New LambdaServiceTest.putFunctionConcurrency_rollsBackLimiterIfSaveFails
  injects a failing LambdaFunctionStore and verifies the limiter total
  is restored when functionStore.save throws.
- New LambdaServiceTest.deleteFunction_preservesInflightPermitUntilItCloses
  holds a permit through a deleteFunction call and asserts the inflight
  counter stays live until the permit is closed.
- New LambdaConcurrencyLimiterTest.permit_closeIsIdempotent locks in the
  double-close guarantee.
2026-04-14 01:09:22 -05:00
yusuke-uranaka 467f5e0f79 feat(dynamodb): add EnableKinesisStreamingDestination support (#427)
* feat(dynamodb): add EnableKinesisStreamingDestination support

Implement EnableKinesisStreamingDestination, DisableKinesisStreamingDestination,
and DescribeKinesisStreamingDestination API actions for DynamoDB.

When a Kinesis streaming destination is enabled on a table, all item mutations
(INSERT/MODIFY/REMOVE) are automatically forwarded to the configured Kinesis
stream. The Kinesis record payload matches the AWS format with awsRegion,
eventName, tableName, and dynamodb (Keys, NewImage, OldImage, etc.).

Closes #426

* fix(dynamodb): address review feedback for KinesisStreamingDestination

- Decouple Kinesis forwarding from DDB Streams: forwardToKinesisDestinations
  is now called directly from DynamoDbService mutation hooks, independent of
  whether DDB Streams is enabled
- Fix ApproximateCreationDateTime to use milliseconds (was seconds)
- Remove SequenceNumber and StreamViewType from Kinesis payload (not present
  in real AWS)
- Add ApproximateCreationDateTimePrecision inside dynamodb record node
- Return ValidationException when disabling an already-disabled destination
- Simplify persistTable to accept TableDefinition directly
- Add test for disable-already-disabled and payload format assertions
2026-04-13 21:07:41 -05:00
sf-jin-ku 994eddc0ba fix(s3): honor canned object ACLs on write paths (#422)
* fix(s3): honor canned object ACLs on write paths
* fix(s3): fail fast on invalid multipart ACLs
2026-04-13 20:24:50 -05:00
Hector Ventura 91071aaae7 feat: implement Amazon MSK service with Redpanda orchestration (#419)
* feat: implement Amazon MSK service with Redpanda orchestration
* fix: adding missing msk service on the test
2026-04-13 20:22:37 -05:00
TiM ed553c6cbf fix(cognito): return only description fields in ListUserPoolClients (#416) (#420)
ListUserPoolClients was returning full UserPoolClient objects including
ClientSecret, GenerateSecret, AllowedOAuthFlows, AllowedOAuthScopes,
CreationDate and LastModifiedDate. Per the AWS API spec, this action
returns UserPoolClientDescription containing only ClientId, ClientName
and UserPoolId.

Add clientToDescriptionNode() for the list response, matching the
existing pattern where ListUserPools uses userPoolToDescriptionNode().
DescribeUserPoolClient continues to return the full object via
clientToNode().
2026-04-13 20:15:21 -05:00
TiM 0ef82f0079 fix(dynamodb): support REMOVE for nested map paths (#402) (#421)
applyRemoveClause() only handled top-level attributes, treating
"ratings.foo" as a literal key name instead of navigating into the
map structure. Add removeValueAtPath() that splits the path into
segments, resolves expression attribute names, and navigates through
nested Map wrappers (M field) to remove the target key.

Includes unit tests for nested paths, expression attribute names,
non-existent paths, and 3-level deep nesting, plus an AWS CLI
compat test reproducing the original report.
2026-04-13 20:07:58 -05:00
TiM d16945f30d fix(lambda): raise Jackson maxStringLength for large inline zip uploads (#412) (#418)
Jackson 2.15+ defaults StreamReadConstraints.maxStringLength to 20 MB,
blocking Lambda CreateFunction when the base64-encoded ZipFile exceeds
that limit. AWS allows up to 50 MB direct upload (~67 MB base64).

Add an ObjectMapperCustomizer that raises the limit to 100 MB, and an
integration test that sends a >20 MB base64 payload to verify it works.
2026-04-13 17:42:06 -05:00
TiM cf9eb32516 feat(kinesis): implement EnableEnhancedMonitoring and DisableEnhancedMonitoring (#417)
Terraform fails when shard_level_metrics is configured because these
operations returned UnsupportedOperation. Store requested metrics on
the stream model and return them in DescribeStream/DescribeStreamSummary
responses. Validates metric names and handles the ALL expansion.

Closes #410
2026-04-13 16:14:11 -05:00
Mikołaj Kłosowski db21bc9ec6 fix(sqs): use queue-level VisibilityTimeout as fallback in ReceiveMessage (#413)
When ReceiveMessage does not specify a VisibilityTimeout parameter,
doReceiveMessage falls back to the global default (30s) instead of the
queue's own VisibilityTimeout attribute. This causes messages to stay
invisible far longer than expected, which in turn breaks DLQ redrive
for queues configured with a short visibility timeout — the message
never becomes visible within a reasonable window for the receive-count
check to trigger.

Read the queue's VisibilityTimeout attribute as the intermediate
fallback before using the global default.
2026-04-13 16:12:22 -05:00
TiM bffc374406 fix(dynamodb): implement DELETE action for set attributes (#312) (#415)
The DELETE clause in UpdateExpression was stubbed out with a
break statement, silently ignoring the operation. This caused
DELETE on SS/NS/BS sets to be a no-op.

Add applyDeleteClause (clause parser) and applyDeleteOperation
(set subtraction) mirroring the existing ADD implementation.
Empty sets after removal trigger attribute deletion per the
DynamoDB spec.
2026-04-13 15:34:49 -05:00
Hector Ventura cfe48dfabe fix(iam): enforce iam when it turned on (#411)
* fix: iam enforment feature
* fix: adding iam enforment test
* fix: adding iam enforment and update documentation
2026-04-13 14:21:47 -05:00
sf-jin-ku 0c4eb1380c feat(sfn): add SQS sendMessage integrations (#409)
* feat(sfn): add SQS sendMessage integrations
* fix(sfn): normalize aws-sdk SQS errors
* test(sfn): assert queue cleanup succeeds
* fix(sfn): support aws-sdk waitForTaskToken for SQS
2026-04-13 14:20:51 -05:00
Christine Nguyen f183cf2fb5 fix(lambda): resolve handler paths with subdirectories and skip validation for dotnet runtimes (#404) 2026-04-13 14:19:46 -05:00
sf-jin-ku c8797e2456 feat(s3): preserve Content-Disposition on object responses (#408)
* feat(s3): preserve Content-Disposition on object responses
* fix(s3): preserve Content-Disposition for multipart uploads
* test(s3): avoid duplicate order annotations
2026-04-13 14:18:14 -05:00
Christine Nguyen 3621c32b88 fix(s3): remove XML declaration from GetBucketLocation response (#403) 2026-04-13 14:17:22 -05:00
Takahiro Tsuruda 300bfa4356 feat(iam): seed AWS managed policies at startup (#400)
* feat(iam): seed AWS managed policies at startup

Seed 14 commonly-used AWS managed policies (e.g.
AWSLambdaBasicExecutionRole, AdministratorAccess) into the IAM
policy store on startup via @PostConstruct. This ensures that
documented examples using attach-role-policy with standard AWS
policy ARNs work out of the box.

Also adds Scope filter support to ListPolicies (AWS/Local/All).

Closes #329

* fix(iam): reject mutations on AWS managed policies and validate Scope param

AWS managed policies (arn:aws:iam::aws:policy/...) are now immutable —
deletePolicy, createPolicyVersion, deletePolicyVersion,
setDefaultPolicyVersion, tagPolicy, and untagPolicy return AccessDenied
(403) for these ARNs, matching real AWS behavior.

Also adds Scope validation to listPolicies: unrecognized values now
return ValidationError (400) instead of silently falling through to All.
2026-04-13 11:25:01 -05:00
TiM eb6749870b fix(elasticache,rds): prevent orphaned Docker containers on shutdown and restart (#398)
ElastiCache and RDS container managers used deterministic container names
without conflict handling, causing 409 errors when restarting after an
interrupted run. Containers were also never cleaned up on shutdown.

- Force-remove stale containers by name before creating new ones
- Track active containers in ConcurrentHashMap with stopAll() for shutdown
- Add container cleanup to EmulatorLifecycle.onStop() (proxies first, then containers)
- Add @AfterAll safety net to ElastiCacheIntegrationTest
2026-04-13 11:07:49 -05:00
Victor Sanchez Velasco bc8caa43f8 fix(cloudformation): populate SQS queue ARN in resource attributes (#396)
When provisioning AWS::SQS::Queue via CloudFormation, the resource's
'Arn' attribute was being read from Queue#getAttributes(), but QueueArn
is a computed attribute in SqsService#getQueueAttributes() — it is not
stored on the Queue object itself. As a result, the Arn attribute was
set to an empty string.

This broke Fn::GetAtt references to queue ARNs. For example, an
EventBridge Rule target built with CDK's SqsQueue target construct
would end up with an empty Arn, silently dropping all events:

  "Targets": [{
    "Arn": {"Fn::GetAtt": ["MyQueue", "Arn"]}
  }]

Fix: build the ARN from region + accountId + queueName, matching the
format used by SqsService#getQueueAttributes.

Added integration test that verifies Fn::GetAtt resolves correctly
when used for an EventBridge Rule target ARN.
2026-04-13 11:05:06 -05:00
TiM cd62fda111 fix(apigatewayv2): add missing JSON handler operations and stageName auto-deploy (#393)
* fix(apigatewayv2): add missing JSON handler operations and stageName auto-deploy

The JSON 1.1 handler was missing GetDeployment, DeleteDeployment, and
DeleteIntegration operations. Callers using the X-Amz-Target path
(non-SDK, Terraform, CLI --cli-input-json) would get UnknownOperation
errors for these actions.

Additionally, the handler passed PascalCase map keys from the JSON 1.1
payload directly to service methods that expect lowerCamelCase. Added
key normalization so both REST and JSON 1.1 paths produce consistent
input for the service layer.

createDeployment now respects the stageName parameter: when provided,
it auto-deploys by updating the named stage's deploymentId and
lastUpdatedDate, matching AWS behavior. Throws NotFoundException if
the stage doesn't exist.

- Add GetDeployment, DeleteDeployment, DeleteIntegration switch cases
- Add toLowerCamelCase() key normalizer for JSON 1.1 map inputs
- Implement stageName auto-deploy in createDeployment
- 9 new integration tests covering the full deployment lifecycle,
  stageName auto-deploy, missing stage 404, and delete operations

* fix: address review feedback on apigatewayv2 changes

- Validate stage exists before persisting deployment to prevent
  orphan deployments on invalid stageName (Codex finding)
- Add JSON 1.1 path tests using X-Amz-Target and PascalCase keys
  to directly exercise the handler's normalization and new switch
  cases (both reviewers)
- Handle List values in toLowerCamelCase normalization for nested
  object arrays (Gemini suggestion)
- Add orphan deployment assertion to missing-stage 404 test
2026-04-13 11:01:03 -05:00
TiM f053db583a fix(auth): bind SigV4 token identity and use timing-safe comparison (#389)
RDS and ElastiCache SigV4 validators accepted any valid token regardless
of which user it was signed for. A token signed for user A could
authenticate as user B if the signature was cryptographically valid.

- RdsSigV4Validator.validate() now takes clientUsername and rejects
  tokens where DBUser doesn't match the connecting PostgreSQL user
- ElastiCache SigV4Validator.validate() now takes expectedUsername and
  rejects tokens where User doesn't match the AUTH username
- PostgresProtocolHandler passes clientUsername to the validator
- ElastiCacheAuthProxy passes the AUTH username to the validator
- Both validators use MessageDigest.isEqual() for signature comparison
  instead of String.equals() to prevent timing side-channel attacks
- 4 new test cases: wrong-user rejection + null-username backwards compat
  for both RDS and ElastiCache validators
2026-04-12 23:16:17 -05:00
TiM 903eab9737 fix(elasticache): scope single-arg AUTH to default user per Redis ACL spec (#390)
Redis 6+ ACL spec defines that AUTH <password> (single-arg form) only
authenticates the "default" user. The previous implementation matched
any PASSWORD user associated with the group, allowing a non-default
user's password to authenticate without specifying a username.

- Filter single-arg AUTH fallback to only match users with
  userName "default" within the group's associated user set
- Add ElastiCacheServiceTest with 3 unit tests covering single-arg
  default-only matching, two-arg named user matching, and group
  auth token fallback
2026-04-12 22:15:46 -05:00
Hector Ventura 035a99d018 fix(cloudformation): resolve stacks by ARN in addition to name (#386) 2026-04-12 21:16:59 -05:00
Hector Ventura e3e8903ffa fix(s3): implement S3 Control ListTagsForResource, TagResource, Untag… (#363)
* fix(s3): implement S3 Control ListTagsForResource, TagResource, UntagResource (#341)
* fix(s3): implement S3 Control ListTagsForResource, TagResource, UntagResource (#341)
2026-04-12 20:24:23 -05:00
TiMandHector Ventura e2680cf5f5 test(apigatewayv2): execute-api dispatch compat suite (#372)
* fix(apigatewayv2): fix route matching for path-parameter routes

routeKeyMatchesPath() used String.replace() on Pattern.quote() output,
which performs literal string matching. Path-parameter placeholders like
{id} and {proxy+} were wrapped in \Q...\E by Pattern.quote(), making
them invisible to the replace() calls. All parameterized routes silently
failed to match.

Rewritten to iterate over placeholders with a regex Matcher, quoting
only the literal segments between them. {param} maps to [^/]+ and
{proxy+} maps to .+ as before.

* test(apigatewayv2): add execute-api dispatch compat suite

New ApiGatewayV2ExecuteTest exercises the v2 execute-api dispatch
path end-to-end: create HTTP API, deploy a Lambda backend via
LambdaClient, wire integration/route/stage/deployment, then invoke
through the execute-api URL and assert the Lambda response flows
back through the gateway.

Scope (per PLAN_FLOCI_2 Phase 7 prerequisite decisions):
- pins current dispatch behavior where stage existence and deployment
  status are NOT checked before dispatch (see
  ApiGatewayExecuteController.java:842-847)
- JWT/token authorizer dispatch path only (REQUEST authorizer has no
  dispatch path today - out of scope)
- no mapping templates / request transforms (no layer exists in
  apigatewayv2/model/Integration.java)

Cross-service blame attribution: if this suite fails while the
existing LambdaTest compat suite passes in the same run, the failure
is on the gateway side.

Gated on Docker for the Lambda backend.

* fix(apigatewayv2): support ANY method and empty proxy in route matching

routeKeyMatchesPath now treats ANY as a wildcard that matches all HTTP
methods, matching AWS API Gateway v2 behavior. Also relaxed {proxy+}
regex from .+ to .* so /echo/{proxy+} matches /echo/ with an empty
proxy value.

* fix(test): skip Lambda-dependent execute tests when dispatch unavailable

CI may not support Docker-in-Docker for Lambda containers. Gate
dispatch and JWT+dispatch tests on the first dispatch response so
they skip instead of fail.

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
2026-04-12 20:23:40 -05:00
TiM 58c0ebbabd test(apigatewayv2): management API compat suite with deploymentId fix (#371)
* fix(apigatewayv2): propagate deploymentId when creating a stage

ApiGatewayV2Service.createStage was dropping the deploymentId field
from the CreateStage request, so stages were being created without
their stage->deployment linkage. The management API handler now
stores deploymentId on the Stage model.

Required for stage->deployment round-trip verification; surfaced by
the upcoming ApiGatewayV2ManagementTest which asserts GetStage
returns the deploymentId that CreateStage was called with.

* test(apigatewayv2): add management API compat suite

New ApiGatewayV2ManagementTest covering the control-plane CRUD
surface: API, route, integration, stage, deployment, authorizer
create/get/list/delete round-trips via ApiGatewayV2Client.

Scope:
- create/get/list/delete for each resource
- JWT authorizer shape (token path only)
- stage->deployment linkage (depends on the createStage
  deploymentId fix in the preceding commit)
- round-trips that assert response field shapes match the SDK model

Out of scope (intentional, per PLAN_FLOCI_2 Phase 2):
- No update endpoints - @PATCH/@PUT handlers do not exist in the
  v2 management block (ApiGatewayController.java:783-1020)
- No execute-api / dispatch / Lambda invocation - that is Phase 7
- No REQUEST authorizer coverage - no dispatch path exists today

* fix(test): assert deploymentId in getStages list response

Codex review flagged that the list endpoint assertion only checked
stageName but not deploymentId. Added filtered assertion to verify the
deployment reference survives the list round-trip.

* fix(test): use deploymentStatusAsString() for enum comparison

SDK returns DeploymentStatus enum, not a String. Using
deploymentStatusAsString() avoids type mismatch assertion failure.
2026-04-12 20:01:27 -05:00
TiM 9e79859cea fix(apigatewayv2): fix route matching for path-parameter routes (#368)
routeKeyMatchesPath() used String.replace() on Pattern.quote() output,
which performs literal string matching. Path-parameter placeholders like
{id} and {proxy+} were wrapped in \Q...\E by Pattern.quote(), making
them invisible to the replace() calls. All parameterized routes silently
failed to match.

Rewritten to iterate over placeholders with a regex Matcher, quoting
only the literal segments between them. {param} maps to [^/]+ and
{proxy+} maps to .+ as before.
2026-04-12 19:57:25 -05:00
TiM 66141049b5 fix(elasticache): scope user auth to groups, use StorageFactory, throw NotFoundFault (#367)
Four bugs fixed:

1. Cross-group auth bypass: validatePassword() scanned all users globally,
   so credentials from group A worked against group B. Now only checks
   users explicitly associated via ModifyReplicationGroup.

2. StorageFactory violation: ElastiCacheService instantiated InMemoryStorage
   directly, bypassing persistence configuration. Now uses StorageFactory
   with "elasticache" storage key.

3. Missing NotFoundFault: listReplicationGroups/listUsers returned empty
   lists for non-existent IDs instead of throwing. AWS SDK expects
   ReplicationGroupNotFoundException/UserNotFoundException.

4. Hardcoded localhost: endpoint address was hardcoded to "localhost",
   ignoring FLOCI_HOSTNAME configuration. Now uses config.hostname().

Also adds ModifyReplicationGroup handler for user-group association and
registers elasticache in the storage config hierarchy.
2026-04-12 19:52:56 -05:00
Hector Ventura 812ecf6880 fix(lambda): correct Function URL config path from /url-config to /url (#364) 2026-04-12 03:15:22 -05:00
Hector Ventura 12775e836d fix(secretsmanager): resolve partial ARNs without random suffix (#360) 2026-04-11 21:30:42 -05:00
Hector Ventura 5129897946 fix(s3): include non-versioned objects in ListObjectVersions response (#359) 2026-04-11 21:26:12 -05:00
Hector Ventura fddb1c7bfd fix(cognito): correct HMAC signature computation in USER_SRP_AUTH (#358) 2026-04-11 21:06:43 -05:00
Hector Ventura 095eefc90b fix(eventbridge): implement advanced content filtering operators (#356) 2026-04-11 20:23:18 -05:00
TiM 88b7ed1bb0 refactor(core): unify service metadata behind descriptor-backed catalog (#357)
Replace scattered service-keyed switch statements in ServiceRegistry,
ServiceEnabledFilter, StorageFactory, and the Aws{Query,Json,Json11,JsonCbor}
controllers with a single immutable ServiceDescriptor catalog. EmulatorConfig
is snapshotted once at @Startup into ResolvedServiceCatalog, which exposes
O(1) lookups by external key, storage key, target prefix, credential scope,
resource class, and CBOR SDK service id. Adding a service now requires one
descriptor entry plus handler wiring instead of touching six to eight
unrelated switches.

Deliberate behavior fixes bundled with the refactor:

- ec2/ecs were present in getServices() but missing from getEnabledServices();
  both now iterate allStatusDescriptors() so they cannot drift again.
- ServiceEnabledFilter did not recognize CertificateManager. or
  AmazonEC2ContainerServiceV20141113. target prefixes, so disabling acm or
  ecs in config had no effect on targeted requests. Both are now gated.
- The disabled-service response format was chosen by header sniffing
  (Accept/Content-Type). Auth-only REST GETs to Lambda and OpenSearch
  received XML when the SDK expected JSON. The filter now resolves the
  protocol from the descriptor's defaultProtocol.
- floci.storage.services.acm.{mode,flushIntervalMs} was wired in
  EmulatorConfig but never read by StorageFactory. It now takes effect.

The default-true fallback in isServiceEnabled for unknown service names is
preserved and pinned by a test, since non-inventoried AWS calls rely on it.
SqsQueueUrlRouterFilter remains imperative (its SQS identity is load-bearing
for queue-URL POST routing). AwsNamespaces and per-controller target-prefix
constant cleanup are deferred to a follow-up.

New integration tests cover the regression floor: Query XML, JSON 1.0,
JSON 1.1, CBOR (target-prefix and smithy-path), and REST disabled responses;
default-true fallback; ec2/ecs status parity; iam/sts shared enablement;
sesv2 credential scope alias; and the ACM storage override.
2026-04-11 20:23:02 -05:00
Hector Ventura 101d45e2b0 fix(kms): implement real asymmetric sign/verify and GetPublicKey (#355)
* fix(kms): implement real asymmetric sign/verify and GetPublicKey

* fix(kms): implement real asymmetric sign/verify and GetPublicKey
2026-04-11 18:14:51 -05:00
Hector Ventura 788ccc8404 fix(ecr,s3): fix CDK compatibility and resolve macOS ECR port conflict (#354)
* fix(ecr,s3): fix CDK compatibility and resolve macOS ECR port conflict
* fix: remove go.mod
2026-04-11 15:32:06 -05:00
Christian Franzen e6266fde0f fix(sns): recognize attributes set during creation of a subscription (#353) 2026-04-11 14:26:50 -05:00
TiM 98a6bd5639 fix(kinesis): accept same-value Increase/DecreaseStreamRetentionPeriod (#352)
Real AWS treats same-value retention updates as no-ops, which is
required for Terraform idempotency: terraform-provider-aws calls
IncreaseStreamRetentionPeriod unconditionally on stream creation
with the configured retention_period, so every default-retention
(24h) TF stream would fail on first apply if the emulator rejected
same-value. Change the strict <= / >= checks to < / > and return
early when the requested value already matches. Adds integration
coverage for both no-op paths. Fixes #342.
2026-04-11 11:37:06 -05:00
TiM a067db0117 fix(cognito): return sub UUID as UserSub in SignUp response (#351)
The SignUp handler was returning the username (email) as UserSub instead
of the generated UUID. Real AWS Cognito returns the user's immutable sub
attribute, and SDKs/terraform rely on this to get a stable identifier.

CognitoService.signUp already generates and stores the sub UUID on the
user, so the fix is a one-line handler change plus a handler-level test
that asserts UserSub is a UUID, not the username.

Fixes #346
2026-04-11 11:34:57 -05:00
Kenshin Okinaka 3d3f12d912 fix(dynamodb): attach X-Amz-Crc32 header to JSON protocol responses (#347)
* fix(dynamodb): attach X-Amz-Crc32 header to JSON protocol responses

The AWS SDK for Go v2 DynamoDB client wraps every response body in a
CRC32-verifying reader and emits "failed to close HTTP response body,
this may affect connection reuse" on every call when the header is
missing. Real AWS DynamoDB includes this header on all responses.

Add it at the JSON protocol boundary (AwsJsonController) for both
DynamoDB and DynamoDBStreams, using a new DynamoDbResponses helper
that serializes the entity to bytes, computes the CRC32, and rebuilds
the Response with the bytes + header. Error responses are wrapped as
well to match real AWS behavior.

The wrapping lives in AwsJsonController rather than DynamoDbJsonHandler
because the handler is also invoked from CBOR, API Gateway proxy, and
Step Functions task flows — those callers must keep the original
ObjectNode entity.

Add unit tests for DynamoDbResponses and an integration test that
verifies the header is present and matches the CRC32 of the response
body bytes on both success and error responses.

* test(dynamodb): use explicit UTF-8 charset in DynamoDbResponsesTest

Address Copilot review comment on floci-io/floci#347: ".getBytes()"
uses the platform default charset, which can make the test (and the
computed CRC32) vary across environments. The string is ASCII so the
bytes are the same on any sensible platform, but being explicit about
UTF-8 makes the determinism obvious and matches the rest of the
codebase.
2026-04-11 11:27:32 -05:00
Christian Franzen bc458235f3 feat: integrate ContainerDetector for improved container detection in ElastiCache, ECS, and RDS managers (#343) 2026-04-11 11:09:52 -05:00
Christine Nguyen 5ca47a5593 fix(s3): return empty LocationConstraint for us-east-1 buckets (#336) 2026-04-11 10:29:22 -05:00
Christine Nguyen 7b28155e26 fix: topologically sort CloudFormation resources before provisioning (#332) 2026-04-11 10:28:37 -05:00
Conor Heine a0ed51e9d1 feat: ecr (#337) 2026-04-11 09:59:05 -05:00
Christine Nguyen 68311a5b47 fix(eventbridge): apply InputPath when delivering events to targets (#335) 2026-04-11 09:52:14 -05:00
Benedikt Schneppe f98abd6e0e fix(sqs): make per-queue message operations atomic (#333)
* fix(sqs): make per-queue message operations atomic with GuardedMessageQueue

Introduce GuardedMessageQueue to wrap the per-queue message list with a
ReentrantLock, eliminating race conditions where concurrent receiveMessage
calls could both see the same message as visible and return it as a
duplicate delivery.

All message operations (send, receive, delete, change visibility, purge,
move) now acquire the lock before touching the list, and persistence
runs inside the lock boundary for consistent snapshots.

* fix(sqs): defer DLQ candidate removal until destination resolves

Review found that claimVisibleMessages eagerly removed DLQ candidates
from the source queue before SqsService verified the DLQ ARN was
resolvable. An invalid ARN would silently drop messages. Now candidates
stay in the source queue until routing succeeds, matching prior behavior.

* fix(sqs): address PR review comments

- Expand wildcard imports to explicit in test file
- Wrap executor lifecycle in try/finally with shutdownNow to prevent
  thread leaks on test failure
- Add closed flag to GuardedMessageQueue so persist() becomes a no-op
  after deleteQueue, preventing resurrection of deleted queue state
2026-04-11 09:51:26 -05:00