Commit Graph
877 Commits
Author SHA1 Message Date
Alex Banna a4356f25fb fix(tls): reuse the persisted self-signed certificate across restarts (#1799)
TlsConfigSource is a MicroProfile ConfigSource, so it runs before CDI
startup and before quarkus-security registers its runtime security
providers. BouncyCastle was therefore not yet registered when the source
checked whether the persisted certificate could be reused. isSelfSigned()
calls CertificateGenerator.parseCertificate(), which failed with
"no such provider: BC", so isSelfSigned() returned false and the
self-signed certificate was needlessly regenerated on every restart.

Register BouncyCastle at the top of the constructor (before any
certificate parsing) by hoisting the existing inline registration in
generateSelfSignedCert() into a shared ensureBouncyCastleRegistered()
helper. The reuse check now parses the existing certificate successfully
and keeps it across restarts.
2026-07-29 21:47:15 -05:00
soreavis 418ec1bdae fix(athena): report the result CSV object key as OutputLocation (#1895)
GetQueryExecution reported OutputLocation as a directory prefix
(<base>/<queryId>/) while the result was written to results.csv
inside it, so a client GET on the reported location failed with
NoSuchKey. Real Athena names result files <QueryID>.csv and saves
them directly to the result location for API queries.

Resolve the location to <base>/<queryId>.csv and write the CSV to
exactly that key. The reader lists by prefix, so it finds the new
form and still reads executions persisted with the old prefix form.

Closes #1752
2026-07-29 21:46:29 -05:00
Mike Attara 444e4a6e89 feat(eks): add option to disable k3s's bundled CNI (#1793)
* feat(eks): add option to disable k3s's bundled CNI

Adds eks.disable-cni config to start k3s with --flannel-backend=none
--disable-network-policy --disable-kube-proxy, since flannel and
kube-proxy run embedded in the k3s server process and can't be evicted
after the fact — a real CNI like Cilium can only take over if k3s never
starts its own. Also makes / rshared before k3s starts so Cilium's BPF
filesystem mount succeeds inside the nested container.

* fix(eks): surface rshare mount failures and document disable-cni

Addresses review feedback: a failed mount --make-rshared / was
silently swallowed, making later CNI failures confusing to trace back;
it's now reported to stderr instead. Also reworded comments claiming
the entrypoint used only sh builtins (it calls mount and k3s, both
external commands), and added the disable-cni knob to application.yml
alongside the other EKS options so it's discoverable.
2026-07-28 22:04:12 -05:00
Ravi Arnan Irianto 9b6695c321 fix(dynamodb): tokenize UpdateExpression whitespace-insensitively (#1862)
* fix(dynamodb): tokenize UpdateExpression whitespace-insensitively

Clause dispatch keyed on the literal "SET " prefix (keyword plus a single space) in both the request pre-validation and the parser, so a newline or tab after a clause keyword was rejected with 'Syntax error; token: "SET"'. Real AWS tokenizes UpdateExpression whitespace-insensitively; collapse whitespace runs before matching keywords.

Fixes #1640

* test(dynamodb): make createAndSeed tolerate a pre-existing table

CreateTable was asserted to return 200, so re-running the whitespace
tests against a persisted store failed on the second run when the table
already existed. Accept 200 or 400 (ResourceInUseException) for the
create; PutItem still overwrites, keeping the seed deterministic.

* test(dynamodb): cover ADD/DELETE, multiline RHS and 3-clause chains

Extends the UpdateExpression whitespace regression suite along the axes most
likely to hide a follow-on regression:

- ADD and DELETE with a newline after the keyword. Both reach their own clause
  parsers via a separate startsWith dispatch, independent of the SET path.
- A multiline function and arithmetic right-hand side: list_append(#l,\n:more)
  and if_not_exists(#c, :zero)\n+ :inc, so the depth-aware comma scan and the
  arithmetic operator scan are exercised on a wrapped expression.
- A chain of three clauses separated by newlines, so the clause-boundary scan
  runs repeatedly rather than once.

All three newlines sit after the clause keyword. A newline only before a
keyword already parsed on main, because indexOfKeyword's boundary check accepts
any whitespace, while the keyword itself is matched with a literal trailing
space. Verified red on main (2x 'Syntax error; token: "SET"', 1x '"ADD"') and
green with the fix.

* refactor(dynamodb): reserved-word check on the normalized expression

DynamoDbReservedWords.check ran on the raw UpdateExpression while clause
dispatch ran on the whitespace-normalized one. Its function-call lookahead in
extractBareIdentifiers skips only literal spaces, so a raw "if_not_exists\n(...)"
was read there as a bare identifier rather than a function name. Harmless today
since those names are not reserved, but running the check on the normalized
string keeps both entry points consistent.
2026-07-28 21:56:28 -05:00
Vinod Kumar Bengaluru 2f435fd1c9 fix(cognito): prefer phone delivery for signup verification (#1839)
Signed-off-by: Vinod Kumar <codingkiddo@gmail.com>
2026-07-28 21:25:52 -05:00
Leandro-ft 8f3597c205 fix(ec2): apply cidr-block filter in DescribeSubnets (#1864)
* fix(ec2): apply cidr-block filter in DescribeSubnets
DescribeSubnets ignored Name=cidr-block and returned all subnets
in the VPC. Match AWS aliases cidr-block, cidrBlock, and cidr.
Fixes #1643

* test(ec2): set describeSubnetsByCidrBlockFilter Order to 23
2026-07-28 21:24:01 -05:00
Ahmed khaled fe531e2be8 fix(neptune): throw a mappable capacity fault when the proxy-port range is exhausted (#1879)
allocateProxyPort threw AwsException("InsufficientNeptuneCapacity"), a code
that does not exist in Neptune's API, so the SDK could not map it and callers
got a generic NeptuneException. Use the wire code InsufficientStorageClusterCapacity
(the InsufficientStorageClusterCapacityFault that CreateDBCluster declares), 400,
so the SDK deserializes it to a typed exception.
2026-07-28 21:21:55 -05:00
Kenshin Okinaka 881c45b393 feat(ses): implement identity (sending authorization) policies for v1 and v2 (#1750)
* feat(ses): implement identity (sending authorization) policies for v1 and v2

Add the SES identity-policy APIs across both protocols, backed by one shared
StorageFactory store (key policy::<region>::<identity>::<policyName>):

- v1 Query: PutIdentityPolicy (upsert), GetIdentityPolicies, ListIdentityPolicies,
  DeleteIdentityPolicy (idempotent).
- v2 REST JSON: CreateEmailIdentityPolicy (fails on duplicate),
  GetEmailIdentityPolicies, UpdateEmailIdentityPolicy (fails when missing),
  DeleteEmailIdentityPolicy.

Behaviour and error shapes were verified against real AWS: the per-identity
limit of 20, the v1/v2 create/update/delete strictness asymmetry, PolicyName
constraints, and the shared v1<->v2 store. Floci stores and returns policies but
does not enforce the authorization (Principal-account existence, Resource-ARN
match) or gate sending on them.

* test(ses): inject policyStore into the test SesService constructor

Thread the identity-policy store through the package-private constructors as a
parameter instead of hardcoding a new InMemoryStorage, matching every other
store and keeping the test constructor aligned with the production wiring.
2026-07-27 22:36:47 -05:00
iam-ssrivastav 4c9f61dfe8 fix(firehose): return ResourceInUseException on duplicate CreateDeliveryStream (#1738) 2026-07-27 22:27:35 -05:00
Alex BannaandAlexy Grabov 264b909e87 fix(cloudformation): model AWS::IAM::Policy as an inline policy (Fixes #1531) (#1800)
* fix(cloudformation): model AWS::IAM::Policy as an inline policy (Fixes #1531)

AWS::IAM::Policy is an inline policy embedded in the roles/users/groups it
names (PutRolePolicy/PutUserPolicy/PutGroupPolicy), not a standalone
managed policy. Floci provisioned it via iamService.createPolicy, giving
it an account-global name. When two stacks reused the same construct
sub-tree — as CDK does, emitting the same auto-generated PolicyName
(IamTaskRoleDefaultPolicy<hash>) on different roles — the second stack
failed with "Policy ... already exists" and rolled back, even though real
AWS scopes an inline policy's name to its owning principal.

Provision AWS::IAM::Policy as an inline policy attached to each named
principal, and remember the targets so a resource/stack delete detaches it
cleanly (an inline policy has no ARN and is removed with its principal).
AWS::IAM::ManagedPolicy keeps its standalone managed-policy behaviour and
now honours ManagedPolicyName. Two stacks reusing the same inline policy
name on different roles both deploy.

* fix(cloudformation): address review — log inline-detach failures, safe delimiter, test delete

Review feedback on the AWS::IAM::Policy inline-policy handling:

- detachInline no longer swallows exceptions silently (AGENTS.md forbids
  empty catch blocks); it logs at debug like the sibling *Safe helpers.
- Inline-policy target principals are joined/split on a newline instead of
  a comma. IAM friendly names permit commas ([\w+=,.@-]+) but never
  newlines, so a role/user/group name containing a comma no longer
  corrupts the target list and orphans the inline policy on delete.
- Added a test that deletes the stack and asserts the inline policy is
  detached (GetRolePolicy -> NoSuchEntity) from a role created outside the
  stack, so the detach path (deleteInlinePolicySafe/detachInline) is
  exercised rather than a cascade role delete.

* fix(cloudformation): surface IAM attachment failures

* fix(cloudformation): roll back IAM resources safely

* fix(cloudformation): roll back partial inline policies

* fix(cloudformation): detach removed IAM targets

* fix(cloudformation): verify IAM policy target updates

* fix(cloudformation): preserve inline policy update state

* fix(cloudformation): migrate legacy IAM policies

* fix(cloudformation): roll back legacy policy migration

---------

Co-authored-by: Alexy Grabov <Alexy.Grabov@cyberark.com>
2026-07-27 22:24:46 -05:00
Hector Ventura 468e943c83 fix(elbv2): move persisted-listener restore out of @PostConstruct (#2015)
* fix(elbv2): move persisted-listener restore out of @PostConstruct

ElbV2Service called back into itself through its own CDI client proxy while it
was still being constructed. rebuildIndexes(), reached from the @PostConstruct
initializeStorage(), called dataPlane.startListener() for every restored
listener; ElbV2DataPlane.binding() then called elbV2Service.getLoadBalancer(),
and because Arc had not yet registered the instance in the ApplicationScoped
context the proxy started another bean creation. That recursed until the process
died.

Only reproducible after a restart with persistent storage: on a fresh boot the
listener map is empty, so rebuildIndexes() never reaches startListener and the
callback never happens.

rebuildIndexes() now only builds the in-memory indexes. Starting the data plane
and the health checks moved to restorePersistedRuntime(), invoked from
EmulatorLifecycle after storageFactory.loadAll() alongside the four services that
already restore persisted runtime there. With the bean fully constructed before
any listener starts, the callback resolves normally.

The blast radius was wider than the issue title: the bean is created lazily on
first use, so after a restart every ELBv2 operation failed, not just DeleteStack.
DescribeLoadBalancers and DescribeTargetGroups both returned 500.

Note the symptom changed with #1931: the storage dedupe removed the per-level
allocation, so current main raises StackOverflowError where 1.5.32 exhausted the
heap and was OOM-killed.

Closes #1913

* test(elbv2): cover the enabled and disabled lifecycle restore paths

elbv2 was stubbed disabled in setup, so nothing exercised the new
EmulatorLifecycle call: dropping it entirely would have left the suite green.

Pin both halves of the gate — restore runs after loadAll when elbv2 is enabled,
and does not run when it is disabled. Verified the ordering assertion fails with
'Wanted but not invoked' when the lifecycle call is removed.

Refs #1913
2026-07-27 22:23:50 -05:00
Hector Ventura 836c162136 fix(core): stop unknown-service REST requests falling through to S3 (#1967)
* fix(core): stop unknown-service REST requests falling through to S3

REST requests whose SigV4 credential scope names a service Floci does not
implement matched no JAX-RS resource and fell through to S3's path-style
wildcard routes, surfacing as misleading NoSuchBucket XML and triggering SDK
retry storms. Reject them with UnknownOperationException instead.

The guard fires only on positive identification: a parseable SigV4 scope
naming a service absent from the catalog. Unsigned, presigned, Bearer/Basic
and SigV4a requests are untouched.

Also declares the EKS read-only sub-resource lists the emulator does not
model (ListAccessEntries, ListAddons, ListIdentityProviderConfigs,
ListPodIdentityAssociations) as explicit routes, so they outrank the S3
catch-all and answer with each operation's model-exact empty result key,
or ResourceNotFoundException for a missing cluster.

Closes #1754

* fix(iam): normalise signing-scope aliases before IAM enforcement

S3 accepts requests signed under the s3express scope, but IAM action rules,
resource ARNs and condition keys are all keyed by the canonical signing name.
An alias therefore resolved to no action, which IamEnforcementFilter treats as
ALLOW, so policy-protected S3 operations were reachable without a policy check.

Resolve the scope through the catalog before enforcement runs. Only aliases are
rewritten: a service whose external key is not itself one of its credential
scopes (CloudWatch Logs signs as logs) is left unchanged, as is any scope the
catalog does not know.

Also documents why SigV4a stays outside the unknown-service guard — its
credential omits the region segment, so SigV4CredentialScope does not match it
— and pins that with a test, since widening the pattern would silently start
rejecting SigV4a traffic.

Refs #1754

* fix(iot): declare the iot-jobs-data signing scope so its routes stay reachable

The IoT Jobs Data Plane (GetPendingJobExecutions, DescribeJobExecution,
StartNextPendingJobExecution, UpdateJobExecution) signs under iot-jobs-data
while IotController serves its /things/{thing}/jobs routes. The scope was not
in the catalog, so the unknown-service guard rejected requests to routes Floci
does implement. The Go, Java and Python SDK compat suites all caught it on
GetPendingJobExecutions.

Audited the other sibling signing names for the same failure mode:
ssmmessages, eks-auth, ecr-public, cognito-identity and aoss have no Floci
routes, so rejecting those stays correct.

Refs #1754

* fix(iam): scope alias normalisation to an explicit table

Deriving the canonical scope from the descriptor's external key was wrong: the
external key is a routing key, not an IAM namespace. SES routes under email and
Bedrock Runtime under bedrock-runtime while their IAM namespaces are ses: and
bedrock:, so ses, sesv2 and bedrock were rewritten onto prefixes AWS never
issues. Every action would then resolve to null and enforcement would be
skipped for those services — the same bypass the s3express fix closed.

Replace the derivation with an explicit alias table holding the one case that
genuinely shares a namespace, s3express -> s3, and sweep every scope the catalog
declares in the test so any future rewrite has to be deliberate.

Refs #1754

* fix(core): make the unknown-service guard configurable and verify scope coverage

The guard is only as good as the catalog's scope list, and the iot-jobs-data
miss showed the list can be wrong. Two changes so that is recoverable and
detectable rather than a hard 404 nobody can work around.

Gate the rejection behind floci.protocols.reject-unknown-service-scope,
matching the other two abort paths in AwsProtocolClaimFilter, which are both
already gated. It defaults to true so #1754 stays fixed out of the box; turning
it off restores the previous fall-through for anyone blocked by a scope Floci
has not enumerated yet.

Add CredentialScopeCoverageTest, which walks botocore's models and fails when
Floci routes most of a service's operations without declaring the name that
service signs with. Removing iot-jobs-data from the catalog makes it fail with
'iot-jobs-data=2/3 routes served'. Thresholds are conservative because small
services share generic templates, so it is a tripwire rather than a proof, and
it skips where the gitignored botocore checkout is absent (CI runners).

Refs #1754

* fix(iam): resolve the iot-jobs-data signing scope to the iot namespace

Admitting iot-jobs-data to the catalog let the IoT Jobs Data Plane reach its
routes, but IAM enforcement still saw the raw scope. Its policy actions live
under iot: (iot:DescribeJobExecution and peers in the Service Authorization
Reference), so the scope belongs in the alias table next to s3express.

No behaviour change today: IamActionRegistry carries no iot rules at all, so
every IoT request resolves to no action and is allowed through regardless. This
makes the mapping correct ahead of those rules existing, rather than leaving a
scope that would silently escape them.

Refs #1754
2026-07-27 22:23:32 -05:00
Bill DeMoss 551df6371b fix(storage): dedupe backends by resolved file path (#1931)
* fix(storage): dedupe backends by resolved file path

StorageFactory.create() built a new backend on every call, so two
components opening the same file (DynamoDbService and
DynamoDbStreamService both open dynamodb-tables.json) got independent
in-memory stores. On graceful shutdown flushAll() flushed them in
registration order and the stale duplicate clobbered the file.

Cache backends by resolved file path so repeat create() calls reuse
the same backend. Add a regression test reproducing the clobber.

* fix(storage): guard lifecycle methods and harden dedup test

Synchronize loadAll/flushAll/clearAll/shutdownAll on the same monitor
as create(), so the /state/reset and /state/nuke endpoints can't
iterate allBackends while a lazily-created service mutates it.

Reset the singleton factory in the dedup test setup so it no longer
depends on backend startup state or test ordering.
2026-07-26 15:01:13 -05:00
Hector Ventura b0e56a9a45 fix: return 4xx client errors instead of 500 for malformed JSON-protocol input (#1926)
* fix: return 4xx client errors instead of 500 for malformed JSON-protocol input

Parse request bodies up front in both JSON dispatchers and return 400
SerializationException for unparseable payloads. Convert input-parsing
failures that previously fell into the catch-all 500 InternalFailure into
their modeled client errors: KMS base64 blob decodes (SerializationException),
Kinesis shard iterators and record data (InvalidArgumentException/
SerializationException), DynamoDB Streams iterator positions
(ValidationException), and EventBridge PutPermission Policy/Condition JSON
(ValidationException; a malformed Policy was previously stored raw and
silently accepted).

* fix: reject trailing content after a valid JSON request body

Jackson's default readTree stops at the first complete JSON value, so a
body like '{} garbage' bypassed the new up-front SerializationException
check and was processed as if the trailing content weren't there. Parse
dispatcher bodies and EventBridge PutPermission Policy/Condition with
FAIL_ON_TRAILING_TOKENS; trailing whitespace remains accepted.
2026-07-23 18:21:27 -04:00
Huan Jiang 1c8b851bea fix(cognito): build OIDC URLs from effectiveBaseUrl so FLOCI_HOSTNAME is honored (#1929)
* fix(cognito): build OIDC URLs from effectiveBaseUrl so FLOCI_HOSTNAME is honored

CognitoService was wired from the raw emulatorConfig.baseUrl(), so its
issuer, JWKS URI, and token/userInfo endpoints ignored FLOCI_HOSTNAME.
Every other response-facing service (SQS QueueUrl, SNS, S3 pre-signed
URLs, Lambda function URLs) uses effectiveBaseUrl(), which applies the
hostname override (and the TLS http->https switch).

These Cognito URLs are external-facing — they land in the JWT `iss`
claim and the .well-known/openid-configuration document that clients
must reach — so in a multi-container / Docker Compose setup with
FLOCI_HOSTNAME set they were emitted as http://localhost:4566/... and
unreachable, breaking OIDC discovery and JWT validation.

Switch the injection to effectiveBaseUrl(). It falls back to baseUrl()
when hostname is unset, so the default localhost behavior (and all
existing tests) are unchanged.

* test(cognito): drive real effectiveBaseUrl so the test reproduces the bug

Stub only effectiveBaseUrl()'s inputs (baseUrl, hostname, tls) and call
the real default method, instead of stubbing effectiveBaseUrl() itself.
The previous version asserted little more than "Cognito calls the getter
it was told to" — it stubbed away the very override logic under test and
would not fail against the old raw-baseUrl() wiring.

Now the localhost->floci host swap actually runs, so the test fails on a
revert. Also add a no-hostname case pinning the baseUrl() fallback.

* test(cognito): drop dedicated effectiveBaseUrl wiring test

On review of the repo's testing patterns this test isn't idiomatic and
adds little. Every peer service that reads effectiveBaseUrl() (SQS, SNS,
S3, Lambda, ECS, Pipes, IoT, SSM) either stubs it to a literal or is
constructed with a literal baseUrl — none has a dedicated test proving
the FLOCI_HOSTNAME override reaches its response URLs; the accessor
choice is simply trusted. The removed test was also the only
thenCallRealMethod on effectiveBaseUrl in the suite.

The existing issuerUrlForPinnedPoolResolvesAsBaseUrlSlashPoolId already
covers the getIssuer URL shape, and effectiveBaseUrl()'s own override
logic is exercised via TlsConfigSource tests. The fix is a one-token
consistency change aligning Cognito with its peers.
2026-07-23 12:27:46 -04:00
Hector Ventura 9308687f5a fix(s3): preserve literal question marks in copy source keys (#1924)
CopyObject and UploadPartCopy decoded the entire x-amz-copy-source header
before splitting bucket, key, and query. A key containing a literal '?'
(sent as %3F or raw) was then truncated at the first '?', so the copy
resolved the wrong key and returned NoSuchKey.

Split bucket/key/query on the raw header and decode each component
separately. A trailing '?...' is only treated as a query string when it
contains versionId=; otherwise the '?' is kept as part of the key. The
same parsing is used by both CopyObject and UploadPartCopy.

Adds a regression test covering encoded (%3F) and raw '?' copy sources.

Closes #1713
2026-07-22 09:47:45 -04:00
Matt Van Horn 526a62317f fix: return 400 MalformedXML for unparseable PutObjectRetention RetainUntilDate (#1631)
PutObjectRetention crashed with an uncaught DateTimeParseException when
RetainUntilDate could not be parsed, leaking as an HTTP 500 HTML page.
Wrap the Instant.parse call and throw an AwsException mapped to HTTP 400
MalformedXML, matching real AWS S3 behavior.

Fixes #1614
2026-07-22 08:58:12 -04:00
Juri Duval ac8a3d7c82 feat(sfn): support http invoke step (#1503)
* feat(1047): Http invocation support

* feat(1047): add tests for http invoke

* fix(1047): remove irrelevant headers

* fix(1047): fix assertion

* chore(sfn): merge main

* chore(sfn): add statusText

* chore(sfn): add correct timeout handling and improve http server tests

* chore(sfn): adress pr comments arount url encoded body handling

* chore(sfn): only allow https by default

* chore(sfn): better error message
2026-07-22 08:45:48 -04:00
Prabu Dzaky 2a9ab4598f fix(dynamodb): throw ValidationException when list_append operand is not a list type (#1702)
* fix(dynamodb): throw ValidationException when list_append operand is not a list type

list_append silently no-oped when either operand resolved to a non-list
attribute (e.g. NULL type), returning HTTP 200 with the item unchanged.
AWS returns a 400 ValidationException in this case.

* test(dynamodb): add integration test for list_append against missing attribute
2026-07-22 08:35:07 -04:00
Alex Banna b245632a2e feat(stepfunctions): implement States.JsonMerge intrinsic (#1662)
* feat(stepfunctions): implement States.JsonMerge intrinsic

The DPS provisioning state machine uses States.JsonMerge, which AslExecutor rejected with "Unsupported intrinsic function: States.JsonMerge". Implement the shallow merge (second object's top-level fields win on conflict); reject the deep-merge form (third argument true) and non-object arguments, as AWS does. Also resolve boolean/null literal intrinsic arguments so the third argument evaluates correctly. Covered by AslExecutorJsonMergeTest.

* fix(stepfunctions): reject a non-boolean States.JsonMerge third argument

The third (deep) argument was read with JsonNode.asBoolean(), which silently
coerces null/number/string/object nodes to false, so States.JsonMerge($.a,$.b,$.x)
with a non-boolean $.x quietly performed a shallow merge instead of failing.
Validate that the resolved third argument is a boolean and raise States.Runtime
otherwise. Covered by AslExecutorJsonMergeTest.nonBooleanThirdArgumentRejected.

* fix(stepfunctions): validate JsonMerge argument types before the deep-merge flag

AWS validates the argument types of States.JsonMerge before evaluating the deep-merge
flag, so two non-objects passed with true should report "requires two JSON objects"
rather than "shallow merge only". Reorder the object-type check ahead of the deep-flag
rejection and add a precedence test.

* test(stepfunctions): adapt JsonMerge test to main's AslExecutor constructor

main's AslExecutor constructor now takes EcsService and EcsJsonHandler; pass the
two new mocks. Also generalize a comment that named a specific downstream system.

* docs: regenerate action tables

* fix(stepfunctions): thread context into States.JsonMerge intrinsic args

The intrinsic pipeline gained a context argument on main (resolveIntrinsicArg /
evaluateIntrinsic now take three parameters). Thread the surrounding case's
root/context through the three States.JsonMerge argument resolutions so the branch
compiles against current main.

* fix: align JsonMerge intrinsic failures

* fix(athena): harden compatibility query polling
2026-07-21 12:14:35 -04:00
Guilherme Lima 024d74e5c4 feat(cloudtrail): in-process CloudTrail with S3 data event emission (#1460)
* feat(cloudtrail): in-process CloudTrail with S3 data event emission

New service supporting CreateTrail / DescribeTrails / DeleteTrail /
UpdateTrail / PutEventSelectors / GetEventSelectors / StartLogging /
StopLogging / GetTrailStatus.

S3 ops (PutObject / GetObject / HeadObject / DeleteObject / ListObjects
/ GetObjectAcl) emit CloudTrail data events through a per-trail buffer.
The CloudTrailLogWriter scheduler flushes pending records as gzipped
JSON envelopes into the destination bucket at AWS-shaped key paths
(AWSLogs/<account>/CloudTrail/<region>/yyyy/MM/dd/<file>.json.gz) on
a configurable cadence (default 60s).

IAM-enforcement denials emit matching AccessDenied records by hooking
IamEnforcementFilter. IamActionRegistry now distinguishes
s3:GetObjectAcl / PutObjectAcl / {Get|Put|Delete}ObjectTagging from
their base ops via ?acl / ?tagging query parameters so the right
event names land in the trail.

Seeded AWSCloudTrail_FullAccess / _ReadOnlyAccess managed policies.

* fix(cloudtrail): return LatestDeliveryTime in GetTrailStatus after StartLogging

The sdk-test-java compatibility test asserts latestDeliveryTime() is
non-null immediately after startLogging. Seed it with the startLoggingTime
so the field is always present once logging has been started.

* fix(cloudtrail): emit SnsTopicARN alongside SnsTopicName in CreateTrail/UpdateTrail responses

Accept both SnsTopicARN and SnsTopicName on input (SnsTopicARN takes
precedence). Emit both fields on output so clients reading the current
field name (SnsTopicARN) get a non-null value.

* fix(cloudtrail): wildcard S3 ARN matching, trail name validation, LookupEvents

- matchesS3DataResourceArn: handle bare "arn:aws:s3", "arn:aws:s3:::*", and
  "arn:aws:s3:::*/*" wildcard forms so trails configured via the AWS Console
  "capture everything" selector actually record events (previously fell through
  silently). Unit tests added to CloudTrailSelectorMatchingTest.

- createTrail: enforce AWS trail name rules (3–128 chars, start/end with letter
  or digit, only letters/numbers/./_/-). Integration tests in new
  CloudTrailNameValidationTest.

- CloudTrailJsonHandler: add LookupEvents stub returning an empty Events array,
  matching upstream's addition in #1603.

* fix(cloudtrail): log empty catches, key selectors/logging by trail home region

- CloudTrailLogWriter.stop(): log at WARN instead of silently swallowing the
  final-flush exception (AGENTS.md: never leave a catch block empty).

- CloudTrailService.putEventSelectors / getEventSelectors / startLogging /
  stopLogging / getTrailStatus: use trail.homeRegion() as the storage key
  instead of the request region. Previously a cross-region call (e.g. accessing
  a trail by ARN from a different-region endpoint) stored selectors and logging
  state in the wrong region's map, so trailsMatching() found an empty selector
  list and logging never fired.

- S3Controller.emitCloudTrailEvent / IamEnforcementFilter.emitS3DenialIfApplicable:
  replace empty inner catch blocks with LOG.tracev() so unexpected failures
  during request-context extraction surface at trace level.

* fix(iam): distinguish bucket-level vs object-level ?acl / ?tagging IAM actions

resolveS3SubResourceAction was always mapping ?acl and ?tagging to object-level
actions (s3:PutObjectAcl, s3:GetObjectAcl, etc.) regardless of path depth.
A PUT /{bucket}?acl request requires s3:PutBucketAcl, not s3:PutObjectAcl —
callers with the correct bucket-level permission were incorrectly denied.

Fix: inspect the URL path after stripping the leading slash. When there is no
slash (or the path ends with one), the target is a bucket; otherwise it is an
object. Applies to all six variants: GetBucketAcl, PutBucketAcl,
GetBucketTagging, PutBucketTagging, DeleteBucketTagging (and their object
counterparts).

* fix(cloudtrail): re-queue records on flush failure instead of dropping them

drainPendingRecords atomically dequeues all records before the S3 write.
If serializeAndGzip or s3Service.putObject threw, those records were gone —
permanently lost before the re-throw reached flushAll.

Fix: wrap the serialize+write block in a try-catch that calls requeueRecords
before rethrowing. Records are added back to the tail of the queue and will be
retried on the next flush cycle. The new CloudTrailService.requeueRecords helper
also makes the re-queue path unit-testable independently of flushTrail.

* fix(s3): emit GetObjectAcl error record under correct event name

getObjectAcl was called inside the outer GET-object try block. On any
AwsException (NoSuchKey, AccessDenied, etc.) the catch at the bottom fired
and emitted a GetObject error record. CloudTrail consumers auditing ACL
errors would see the wrong event name.

Wrap the acl branch in its own try-catch that emits GetObjectAcl on both
success and failure paths, mirroring the pattern used by the other hooked ops.

* ci: retrigger

* fix(test): pass CloudTrailService and CurrentVertxRequest to IamEnforcementFilter constructor

* fix(cloudtrail): persist trail state via StorageFactory instead of volatile in-memory maps

* fix(cloudtrail): address review feedback on region, name lookup, and ACL detection

- S3Controller: use request region (from credential scope) instead of
  getDefaultRegion() for CloudTrail event emission, matching the IAM
  denial hook behaviour so allowed and denied calls land in the same trail.

- CloudTrailService.findTrail: name lookup now uses regionKey(region, name)
  directly; ARNs still do a cross-region scan. Prevents two same-name
  single-region trails from resolving ambiguously by map iteration order.

- TrailKey: add eventRegion field so multi-region trail events are written
  to the correct S3 delivery path (CloudTrail/<eventRegion>/) rather than
  always the trail home region. drainPendingRecords/requeueRecords now take
  a TrailKey to carry all three dimensions.

- IamActionRegistry: fix isBucketLevel — trailing slash is a valid S3 key
  character, so /bucket/folder/?acl is an object ACL request. Replaced the
  endsWith("/") check with an index-based test. Add IamActionRegistryTest
  cases for the folder/ regression.

* docs(cloudtrail): sync action table order with make docs-sync
2026-07-21 12:10:19 -04:00
Hector Ventura e0b7b3f8ee fix(eks): register FargateProfileStatus for reflection (#1876) 2026-07-15 01:47:41 -04:00
Ioannis Lafiotis 095e167bae Nodegroups eks fargate eks (#1523)
* feat(eks): add nodegroups and fargate profiles

* docs: sync generated action tables
2026-07-15 01:03:24 -04:00
Krishnan MahadevanandKrishnan Mahadevan 43a80381ee fix(s3): honor ACL headers and explicit grants (#1768)
* fix(s3): honor ACL headers and explicit grants

Closes #1766 #1767

PutObjectAcl/PutBucketAcl ignored x-amz-acl and x-amz-grant-* headers,
storing the raw (often empty) request body as the ACL verbatim. AWS
SDKs send canned ACLs to these endpoints as a header with an empty
body, so a canned-ACL update corrupted the stored ACL and the next
GetObjectAcl failed client-side XML parsing with "Premature end of
file".

PutObject/CopyObject also silently dropped x-amz-grant-* (explicit
ACL grant) headers - no error, just a missing grant.

Add resolveObjectAclXml() to parse canned ACLs and explicit grant
headers (uri=/id=/emailAddress= tokens, comma-separated per grantee
header) into proper Grant XML, and wire it into all four call sites:
PutObject, CopyObject, PutObjectAcl, PutBucketAcl. emailAddress
grantees return 501 (no account directory to resolve them against).

Add regression coverage in S3AclIntegrationTest for both the
header-with-empty-body case and explicit multi-grantee headers.

* fix(s3): Fixing review comments

---------

Co-authored-by: Krishnan Mahadevan <kmahadevan-bidgely@users.noreply.github.com>
2026-07-15 00:55:49 -04:00
Jay 4a109b2f6c fix(cloudformation): carry PackageType through SAM Function expansion (#1772)
* fix(cloudformation): carry PackageType through SAM Function expansion

expandServerlessFunction/createLambdaFunction copied FunctionName, Handler,
and Runtime from AWS::Serverless::Function onto the expanded
AWS::Lambda::Function, but never PackageType. CloudFormationResourceProvisioner's
buildLambdaDesiredState defaults a missing PackageType to "Zip"
(resolveOrDefault(props, "PackageType", engine, "Zip")), which then also
forces Runtime/Handler defaults (nodejs18.x / index.handler) onto a
function that declared neither. Net effect: a SAM function declared with
PackageType: Image and an ImageUri silently deployed as a broken Zip
function running the wrong runtime instead of the real container image —
Code.ImageUri was preserved by buildLambdaCode, but nothing on the
resource said to actually use it as an image.

Found by deploying a real container-image SAM template end-to-end against
a build with #1758+#1759 applied: the function created successfully and
the stack reported CREATE_COMPLETE, but invoking it pulled
public.ecr.aws/lambda/nodejs:18 and failed with
Runtime.ImportModuleError ("Cannot find module 'index'") instead of
running the pushed image.

Adds a one-line copyIfPresent(properties, "PackageType", lambdaProps) fix,
a SamTransformProcessorTest unit test asserting the transform output
carries PackageType/ImageUri through with no synthesized Handler/Runtime,
and a CloudFormationIntegrationTest asserting the full create-stack ->
GetFunction round trip reports PackageType: Image.

* fix(cloudformation): carry ImageConfig through SAM Function expansion

Same class of omission as PackageType: CloudFormationResourceProvisioner
already reads ImageConfig off AWS::Lambda::Function (provisionLambda's
putResolvedMapIfPresent(configRequest, props, "ImageConfig", ...)), but
SamTransformProcessor.createLambdaFunction never copied it from the SAM
resource's Properties. A PackageType: Image SAM function combined with an
ImageConfig block (EntryPoint/Command/WorkingDirectory container overrides)
silently lost that configuration on the deployed function.

ImageConfig's SAM shape is identical to raw CFN's, so a plain
copyIfPresent is sufficient (no case conversion needed, unlike some other
SAM->CFN property mappings in this file).

Adds a unit test asserting the expanded resource carries ImageConfig
through, and an integration test asserting the full CreateStack ->
GetFunction round trip reports it under Configuration.ImageConfigResponse.

Addresses review feedback on #1772.
2026-07-15 00:54:27 -04:00
Hector Ventura fe49bee41e fix(s3): fail fast on unwritable data root instead of opaque 500s (#1868)
When the persistent path is not writable (read-only or root-owned bind
mounts), S3Service's constructor failed lazily and every S3 request
surfaced as an opaque plain-text 500 that REST-XML SDK parsers cannot
read.

- validate the persistent path at boot and refuse to start with an
  actionable error when any enabled service uses non-memory storage
- add class-scoped exception mappers so unhandled failures on S3 and
  S3-Control routes render the S3 InternalError XML contract instead of
  Quarkus's plain-text error page
- warn loudly from the container entrypoint when the state dir is not
  writable by the runtime user

Fixes #1664
2026-07-15 00:43:11 -04:00
Leandro-ft 1ba15f0ce7 fix(rds): return DBSubnetGroupNotFoundFault for missing DescribeDBSubnetGroups name (#1870)
DescribeDBSubnetGroups with a missing DBSubnetGroupName returned HTTP 200 and an empty list; reuse resolveDbSubnetGroupView so AWS clients get a 404 fault instead.
2026-07-15 00:37:59 -04:00
Raiden van Bronkhorst a7d33ba885 feat(cloudformation): Parse secrets in ContainerDefinitions (#1874)
* feat(cloudformation): Parse secrets in ContainerDefinitions

* test(cloudformation): cover TaskDefinition creation with secrets
2026-07-15 00:36:24 -04:00
Hector Ventura eae039fbd0 fix(lifecycle): tear down process-bound containers on shutdown (#1869)
Containers whose lifetime is bound to the emulator process (Lambda warm
pool, ECS tasks, EC2 instances, in-flight Batch and CodeBuild jobs) were
cleaned up ad hoc via @PreDestroy, which runs after the ShutdownEvent
observers when the storage flush schedulers are already stopped — so
containers could leak and state changes made during stop were lost.

Introduce a ContainerTeardown contract implemented by each runner and
invoke every implementation from EmulatorLifecycle.onStop before
StorageFactory.shutdownAll(), making teardown deterministic and keeping
its state changes in the final flush. Implementations stay idempotent,
with @PreDestroy retained as a fallback.
2026-07-14 23:10:03 -04:00
Jason van Zyl aa77d4ce46 fix(elbv2): expose target health reason parity (#1743) 2026-07-14 22:57:45 -04:00
Christine Nguyen e49bc432bd fix(scheduler): forward MessageAttributes in universal sns:publish target (#1706)
* fix(events): SNS universal target message attributes

* fix(scheduler): handle Binary MessageAttributes in universal sns:publish target
2026-07-14 22:46:54 -04:00
Robert Stupp 05302bc63b fix(iam): pass S3 list condition context to IAM enforcement (#1748)
IAM policy evaluation already supported condition keys, but request-time enforcement did not provide S3 list request parameters to the evaluator. As a result, assumed-role session policies that allowed s3:ListBucket only for a matching s3:prefix were denied because the condition context was empty.

Add an application-scoped IamConditionContextResolver and have IamEnforcementFilter pass resolved condition context into IamPolicyEvaluator. The resolver currently maps S3 ListBucket query parameters to s3:prefix, s3:delimiter, and s3:max-keys, keeping action-specific condition extraction out of the filter.

Add regression coverage for prefix-restricted STS session policies through direct integration tests and the Java SDK compatibility suite. The SDK test also uses a trust policy matching the root/test principal that performs AssumeRole when IAM enforcement is enabled.

Tests:

- ./mvnw test -Dtest=IamConditionContextResolverTest,IamEnforcementFilterTest,IamEnforcementIntegrationTest,StsSessionPolicyS3EnforcementIntegrationTest

- compatibility-tests/sdk-test-java: mvn -q -DskipTests test-compile
2026-07-14 22:38:05 -04:00
Ankit1324 f9360cbf86 fix(ec2): reject duplicate key pair names in ImportKeyPair (#1848)
ImportKeyPair accepted any KeyName even when a key pair with the same
name already existed in the region, so DescribeKeyPairs could list
multiple entries with the same name (e.g. after repeated terraform
apply runs). Real AWS rejects this with InvalidKeyPair.Duplicate.

Apply the same duplicate-name check that CreateKeyPair already
performs, scoped to the region.

Fixes #1845
2026-07-14 22:27:15 -04:00
Abhigya 28252763f5 feat: emit jti/origin_jti and support RevokeToken (#1705)
* feat: emit jti/origin_jti and support RevokeToken

* fix(cognito): authenticate RevokeToken caller before revocation-config check

Address PR review feedback on the jti/origin_jti + RevokeToken change:

- RevokeToken now validates the client secret before the
  EnableTokenRevocation check, so a confidential client with revocation
  disabled returns NotAuthorizedException (not UnsupportedOperationException)
  for a wrong/missing secret, matching AWS's identity-first ordering and
  avoiding leaking revocation state to unauthenticated callers.
- OriginJtiIntegrationTest guards the shared ordered-test state via
  requireSetup()/requireInitialAuthState() so a setup or initial-auth
  failure reports a clear cause instead of misleading downstream
  assertions, and adds a regression test for the auth-ordering fix.

* fix(cognito): revoke access tokens by origin_jti and use UnauthorizedException

Address review feedback on PR #1705:

- Check origin_jti (not just jti) when validating access tokens against
  the revocation store, so RevokeToken actually kills issued access tokens
  for GetUser, ChangePassword, UpdateUserAttributes and DeleteUserAttributes.
- Change RevokeToken error from NotAuthorizedException to UnauthorizedException
  to match the declared API model.
- Remove unused three-arg buildRefreshToken overload.
- Add Order(12) test proving GetUser fails after RevokeToken.
2026-07-11 15:27:22 -05:00
Abhigya 001e530aca feat: Implement Cognito GlobalSignOut (#1701)
* feat: Implement Cognito GlobalSignOut

* fix(cognito): validate user existence and jti in GlobalSignOut

Address PR #1701 review:
- Add adminGetUser existence check before revoking tokens so a crafted
  token referencing a nonexistent pool/user returns UserNotFoundException/
  ResourceNotFoundException instead of silently writing revocation records
  and returning 200, matching AdminUserGlobalSignOut and getUser.
- Include jti in the invalid-token guard so legacy tokens without a jti
  claim cannot be used as a sign-out credential, consistent with getUser.
- Cover the nonexistent-user path with an integration test.

* fix(cognito): error reporting

* fix: map ResourceNotFoundException -> NotAuthorizedException
2026-07-11 15:25:49 -05:00
Marius Volkhart 742bb8cf03 fix(s3): return default SSE-S3 from GetBucketEncryption instead of 404 (#1838)
* fix(s3): return default SSE-S3 from GetBucketEncryption instead of 404

Real S3 no longer 404s GetBucketEncryption for a bucket with no explicit
config: since 2023-01-05 every bucket has SSE-S3 (AES256) default encryption,
so GetBucketEncryption returns that config rather than
ServerSideEncryptionConfigurationNotFoundError.

  https://docs.aws.amazon.com/AmazonS3/latest/userguide/default-bucket-encryption.html
  "Amazon S3 now applies server-side encryption with Amazon S3 managed keys
   (SSE-S3) as the base level of encryption for every bucket in Amazon S3.
   Starting January 5, 2023, all new object uploads to Amazon S3 are
   automatically encrypted."

Floci still emulated the pre-2023 404-when-unset behavior.

Some software relies on the new behavior, such as AWS's AWS Controllers for K8s
s3-controller: its Bucket read-back catches the NotFound code but does not
return, then dereferences ServerSideEncryptionConfiguration.Rules on a nil
response (nil-pointer panic that loops the controller). ACK code for reference:

  https://github.com/aws-controllers-k8s/s3-controller/blob/v1.6.0/pkg/resource/bucket/hook.go

Return the AWS default SSE-S3 config when none is set; an explicit
PutBucketEncryption config is still echoed back, and a missing bucket still
404s NoSuchBucket. Mirrors GetBucketRequestPayment's existing default.

Closes #1836

* test(s3): cover GetBucketEncryption default after DeleteBucketEncryption

Greptile flagged the delete-then-get path was uncovered: after
DeleteBucketEncryption nulls the stored config, GetBucketEncryption must
fall back to the default SSE-S3 (AES256) rather than the prior KMS config
or a 404. Adds an ordered case exercising the ?encryption DELETE handler
plus the null-after-delete branch.
2026-07-11 15:19:27 -05:00
Marius Volkhart 2d250ccf3c fix(s3): handle DeleteBucketReplication instead of deleting the whole bucket (#1837)
DELETE /{bucket}?replication fell through the sub-resource switch (which handled
tagging/website/policy/cors/lifecycle/encryption/publicAccessBlock/ownershipControls
but not replication) to the unqualified DeleteBucket, silently destroying the
entire bucket and returning 204.

Real S3 DeleteBucketReplication removes only the replication configuration and
returns 204; a sub-resource-qualified DELETE never deletes the bucket:

  https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketReplication.html

Floci does not model replication, so DeleteBucketReplication is a no-op 204 --
handled explicitly so it cannot reach the bucket-delete fall-through.

Closes #1835
2026-07-11 15:18:41 -05:00
Hector VenturaandJuri Duval 3ec4dc65f2 feat(stepfunctions): support JSONata workflow variables (Assign) (#1824)
* feat(stepfunctions): support JSONata workflow variables (Assign)

Add support for execution-scoped workflow variables in JSONata state
machines. States may declare an `Assign` field whose values are
evaluated as JSONata and stored as variables that later states
reference as top-level `$name` bindings.

An execution-scoped `variables` object is threaded through every state
executor and mutated in place, so assignments persist across states.
Parallel branches and Map iterations each receive an isolated copy, so
assignments inside them do not leak back to the parent scope, matching
AWS.

Within a state, `Assign` is evaluated before `Output`, so a state's own
`Output` (and all later states) observe the newly assigned variables,
matching AWS evaluation order.

Assign is currently supported for JSONata states only; JSONPath-mode
Assign is left as a follow-up.

Closes #1507

Co-authored-by: Juri Duval <27741935+Mulgish@users.noreply.github.com>

* fix(stepfunctions): resolve JSONata Assign against the state-entry scope

Variable references in a state, including the state's own Output, must
resolve against the values the variables held on state entry. Assign and
Output are now both evaluated against the pre-assignment scope, and the
new values are committed afterwards, so they first become visible to the
next state.

Verified against a recorded AWS execution (localstack's AWS-validated
BASE_EVALUATION_ORDER_PASS_STATE snapshot): a state that assigns
answer="<omitted>" while reading $answer in its own output still emits
the state-entry value 42.

Workflow variables are also bound alongside $states rather than inside
it, since AWS reserves $states for input/result/errorOutput/context.

Tests:
- assignedVariablesAreNotVisibleUntilTheNextState replaces
  assignedVariableVisibleToSameStateOutput, which asserted the inverse.
  It follows the evaluation-order example from the AWS docs: from $x=3,
  $a=6, the block {"x": "{% $a %}", "nextX": "{% $x %}"} ends with $x=6
  and $nextX=3 while the assigning state's Output still emits 3.
- variablesAssignedInsideMapDoNotLeakToParentScope now uses a distinct
  inner variable name, mirroring AWS's own BASE_SCOPE_MAP fixture; AWS
  rejects an inner scope reusing an outer-scope variable name.

* feat(stepfunctions): apply JSONata Assign in Choice rules, Wait states and Catch blocks

Assign was only committed via applyJsonataOutput, which Choice and Wait never
call, so an Assign on either state was silently dropped and Catch blocks could
not assign at all. AWS supports Assign on Pass, Task, Map, Parallel, Choice and
Wait, plus inside Choice rules and Catch fields.

- Choice: a matched rule applies its own Assign and Output; the state-level ones
  apply only on the Default path.
- Wait: applies Assign and Output.
- Catch: applies Assign and Output with $states.errorOutput bound, into the scope
  the catching state lives in.
- Bind $states after the workflow variables so a variable named "states" cannot
  clobber the reserved binding.

Assign, Choice-rule and Catch blocks all keep the AWS evaluation rule already in
place for states: every expression is evaluated against the values held on state
entry, and the new values are committed only afterwards.

---------

Co-authored-by: Juri Duval <27741935+Mulgish@users.noreply.github.com>
2026-07-11 15:17:23 -05:00
Hector Ventura 6856c7f1e6 refactor(cloudformation): extract a per-service provisioner registry, migrate SQS (#1825)
First slice of decomposing CloudFormationResourceProvisioner (the repo's largest
class: ~30 injected services and 75 resource types in two switches).

Introduce the scaffolding for per-service provisioners:
- CfnResourceProvisioner: a provision/delete interface for one service's types.
- ProvisionContext: the {engine, region, accountId, stackName} handlers draw from,
  with resolveOptional/generatePhysicalName lifted verbatim from the monolith.
- CloudFormationResourceRegistry: a CDI-collected resource-type -> provisioner map,
  with a public factory constructor for tests; duplicate registration throws.

CloudFormationResourceProvisioner now consults the registry before its switch and
falls through for unmigrated types, so the two coexist during the migration. SQS is
the first extraction: SqsCfnProvisioner (injects only SqsService) owns Queue and
QueuePolicy; its switch cases and provisionXxx methods are removed. The registry is
added to the constructor once so later slices do not reshuffle positional args.

SqsCfnProvisionerTest exercises the provisioner with a single mocked service, the
payoff versus the ~30 mocks the monolith requires. Behavior is unchanged: the full
CloudFormation integration suite (174 tests) stays green.
2026-07-11 01:14:32 -05:00
Hector Ventura eb2fa9c25f fix(iam): default UserName to the calling access key's owner (#1801)
GetUser, ListAccessKeys and DeleteAccessKey treat UserName as optional: the
IAM model documents it as defaulting to the user making the request. Floci
ignored the caller and passed the missing name straight through, so GetUser
fell back to a "root" user that is never seeded and the access-key actions
passed null. Every one of them ended in NoSuchEntity.

Resolve UserName from the access key that signed the request, falling back to
NoSuchEntity (the model's code for these operations, 404, senderFault) when
the key maps to no stored user.

Those errors were also rendered wrong. Query handlers that catch AwsException
build their own error XML, but the ones that don't reach AwsExceptionMapper,
which emits JSON — a JSON error body on the XML wire, which SDK parsers fail
on before they can surface anything useful. AwsQueryController now renders
AwsException as the Query error contract, preserving the declared code and
status, and maps any other handler exception to InternalFailure rather than
letting Quarkus' JSON error page escape.

CloudWatch Metrics is the handler that renders no error XML of its own, so it
is the regression test for the pass-through: SetAlarmState on a missing alarm
must stay 404 ResourceNotFound and not collapse into a 500.

Closes #1753
2026-07-11 00:49:06 -05:00
Hector Ventura ad47b39800 fix(lambda): register EventSourceMapping nested types for native-image reflection (#1826)
EventSourceMapping.DestinationConfig and its nested OnFailure are reachable
from Lambda's persisted event-source-mapping storage but carried no
@RegisterForReflection (the annotation on the enclosing class does not cover
nested static classes). In native-image mode this breaks deserialization of a
mapping's failure destination on restart.

Annotate both nested classes with @RegisterForReflection, matching the existing
convention (IotPolicy.PolicyVersion, LambdaUrlConfig.Cors). Also add
@JsonIgnoreProperties(ignoreUnknown = true) — as the enclosing class already
has — so the nested wire shapes tolerate future AWS field additions rather than
failing deserialization. PersistedModelReflectionTest, the classpath-scan guard
that flagged this, now passes.

Refs #1629, #1781
2026-07-11 00:26:35 -05:00
Eduardo Lugo Vela 9b63b31530 fix(tls): add host.docker.internal to self-signed cert SANs (#1821)
Lambda containers reach Floci via host.docker.internal when Floci
runs on the host instead of in a container, but the cert never
included it as a SAN, failing TLS verification.
2026-07-10 23:24:03 -05:00
Jason van Zyl fe2008848f fix(rds): preserve network placement metadata (#1735)
* fix(rds): honor request region for subnet placement

* fix(rds): persist DB instance VPC security groups

* docs: sync service action tables

* fix(rds): tidy region-aware query dispatch
2026-07-10 23:17:28 -05:00
Kenshin Okinaka 10f799a2b7 feat(ses): implement Contact CRUD for SES v2 (#1723)
* feat(ses): implement Contact CRUD for SES v2

Add the SES v2 Contact APIs under /v2/email/contact-lists/{name}/contacts:
CreateContact, GetContact, ListContacts (POST .../contacts/list),
UpdateContact, DeleteContact. Contacts carry per-topic subscription
preferences, an unsubscribe-all flag, and free-form attributes;
TopicDefaultPreferences is derived at read time from the list's topics.

Behaviour is verified against real AWS: validation order (Smithy enum ->
EmailAddress format -> list existence -> topic existence), AlreadyExists /
NotFound / invalid-topic / invalid-email error shapes, and the UpdateContact
semantics (TopicPreferences merge by topic name; AttributesData and
UnsubscribeAll replaced). Covered by a RestAssured integration test and an
AWS Java SDK v2 compatibility test.

* refactor(ses): resolve contact list once for reads and delete under lock

Address review consistency findings on the Contact CRUD read/delete paths:

- getContact/listContacts returned only the contact(s), so the controller
  fetched the ContactList a second time to render TopicDefaultPreferences.
  Between the two calls a concurrent delete could turn a successful read into a
  misleading "List not found". The service now returns the resolved list
  alongside the contact(s) (ContactWithList / ContactsWithList), so the read is
  a single, consistent lookup.
- deleteContact re-checked list existence before acquiring contactMutationLock,
  unlike createContact/updateContact which re-check inside it. Move the
  getContactList check inside the lock so a concurrent deleteContactList
  surfaces "list not found" rather than "contact not found".
2026-07-10 23:15:59 -05:00
Mihai BlidaruandMihai Blidaru 48f310b63f fix(s3): omit checksum headers from GetObject/HeadObject unless x-amz-checksum-mode: ENABLED (#1633)
* fix(s3): omit checksum headers from GetObject/HeadObject unless x-amz-checksum-mode: ENABLED

Real AWS only returns x-amz-checksum-* headers on GetObject and HeadObject
responses when the client sends x-amz-checksum-mode: ENABLED. Without that
header, returning the checksum causes the PHP AWS SDK to attempt checksum
validation on a non-seekable streaming response body, throwing
"Stream is not seekable" and making fopen fail.

Closes #1632

* refactor(s3): drop dead appendObjectHeaders overloads, dedupe test @Order

Addresses Greptile review on PR #1633:

- Remove the now-unreachable 2-arg and 3-arg appendObjectHeaders overloads.
  All real callers pass includeChecksum explicitly to the 4-arg version, so the
  3-arg overload's hard-coded `true` was a footgun that could silently re-emit
  checksum headers. Also drops the now-orphaned ResponseHeaderOverrides.NONE.
- Move getObjectWithChecksumModeReturnsChecksum / headObjectWithChecksumMode...
  to the end of the 5-22 test block with unique @Order(23)/@Order(24), so they
  no longer share @Order(5)/@Order(7) with getObject/headObject.

All 117 S3IntegrationTest cases pass.

* fix(s3): include checksum in empty-object suffix-range response when requested

The empty-object suffix-range path returns a full 200 via fullObjectResponse
instead of a 206, so it must honor x-amz-checksum-mode: ENABLED like any
other full-object response. It previously hardcoded includeChecksum=false,
omitting the checksum even when the client asked for it.

Also extends the existing suffix-range test to assert the checksum is
omitted without the header, and adds a new test covering the
x-amz-checksum-mode: ENABLED case.

* fix(s3): resolve rebase-onto-main test conflicts for checksum-mode gate

Sends x-amz-checksum-mode: ENABLED on the GetObject verification calls
that require checksum headers in the response (copyObject,
copyObjectWithoutChecksumOverride, copyObjectPreservesNonDefaultChecksum),
consistent with the behavioral fix in this branch. Adds
getObjectWithChecksumModeReturnsChecksum and
headObjectWithChecksumModeReturnsChecksum as self-contained tests with
unique, non-colliding @Order values.

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-07-10 23:12:43 -05:00
Mikel Amuchastegui cd7370c730 feat(kms): support KeyId filter on ListAliases (#1651)
* feat(kms): support KeyId filter on ListAliases

* feat(kms): avoid null key ids in handler
2026-07-10 22:54:46 -05:00
Vinod Kumar Bengaluru af0ec51f98 fix(lambda): return event source mapping failure config (#1629)
Signed-off-by: Vinod Kumar <codingkiddo@gmail.com>
2026-07-10 22:52:38 -05:00
David Phillips a3e8bf5a8b fix: Support S3 auth enforcement (#1689) 2026-07-10 22:41:03 -05:00
Saliou Gaye 8590ffec34 fix(scheduler): honor target EventBridgeParameters DetailType/Source (#1489)
* fix(scheduler): honor target EventBridgeParameters DetailType/Source

* chore: update after review

* chore: update after greptile feedbacks

* chore(scheduler): add missing validation for eventbridge target

* chore: add missing test annotation

* chore: sync docs
2026-07-10 20:52:40 -05:00
AgustinBertagna f915622e36 feat(appsync): Phase 5 — Management API Coverage + AWS Behavior Alignment + Async Schema Creation (#1590)
* test(appsync): strengthen existing integration error tests with __type and message assertions

All 30 existing error assertions (400/404) previously checked only the HTTP
status code. Each now also verifies the AWS error body shape:
  {"__type":"<ExceptionClass>","message":"<...>"}

This locks in the __type field that the AWS SDK v2 uses to instantiate the
typed exception (NotFoundException, BadRequestException, etc.) and guards
against accidental changes to error codes and messages.

* test(appsync): add 409 conflict and 429 limit tests

Add 7 new integration tests covering previously untested error paths:

ConflictException (409):
- createDataSourceDuplicateReturns409
- createResolverDuplicateReturns409
- createTypeDuplicateReturns409
- createDomainNameDuplicateReturns409
- createChannelNamespaceDuplicateReturns409
- associateApiDuplicateReturns409 (domain already associated)

LimitExceededException (429):
- createApiKeyExceedsLimitReturns429 (3rd key exceeds max 2 per API)

All tests are self-contained: create resources, assert the error, then
clean up. Each asserts statusCode + __type + message substring.

* test(appsync): add 404 tests for update/delete and cross-resource create

Add 11 new integration tests covering previously untested 404 paths:

Update/delete of non-existent resources (8):
- updateResolverNonExistentReturns404
- deleteResolverNonExistentReturns404
- updateFunctionNonExistentReturns404
- deleteFunctionNonExistentReturns404
- updateApiKeyNonExistentReturns404
- deleteApiKeyNonExistentReturns404
- updateDomainNameNonExistentReturns404
- updateChannelNamespaceNonExistentReturns404

Cross-resource 404 on create (3) — missing referenced resource:
- createResolverMissingDataSourceReturns404
- createFunctionMissingDataSourceReturns404
- associateApiMissingDomainReturns404

Each asserts statusCode + __type=NotFoundException + message substring.

* test(appsync): add pagination, edge case, and updateChannelNamespace tests

Add 7 new integration tests:

Pagination for previously untested list operations (3):
- listDomainNamesWithMaxResults
- listChannelNamespacesWithMaxResults
- listSourceApiAssociationsWithMaxResults
Each creates >=2 items, verifies page size + nextToken, follows token,
and cleans up.

Pagination edge cases (3):
- listWithMaxResultsZero (empty page + nextToken present)
- listWithNegativeMaxResultsReturns400
- listWithInvalidNextTokenNonApiReturns400 (data sources path)

Update channel namespace (1):
- updateChannelNamespace (verify description field change)

* test(appsync): upgrade SDK error tests to typed exceptions

Upgrade 4 existing SDK error tests from the generic AppSyncException to
the typed exception classes that the AWS SDK v2 maps from the __type
response field:

- getNonExistentApiThrowsException -> NotFoundException
- getNonExistentDataSourceThrowsException -> NotFoundException
- getNonExistentTypeThrowsException -> NotFoundException
- startSchemaCreation_invalidSchema -> BadRequestException

Each now also asserts hasMessageContaining with the expected message
substring. This aligns AppSyncTest with the repo convention used by
ApiGatewayV2ManagementTest, SchedulerTest, and ElbV2Test.

Also strengthen two existing update tests with field assertions:
- updateChannelNamespace: now sets codeHandlers and verifies the response
- updateDomainName: now asserts description field equals updated value

* fix: correct environment variables API path case for SDK compatibility

The AppSync controller used lowercase /v1/apis/{apiId}/environmentvariables
but the AWS SDK v2 sends to /v1/apis/{apiId}/environmentVariables (capital V).
This broke both getGraphqlApiEnvironmentVariables and
putGraphqlApiEnvironmentVariables for all SDK clients.

Fix the @Path annotations in the controller and update integration test
paths to match the SDK-expected casing.

* fix(appsync): align error codes and messages with AWS AppSync behavior

- DataSource duplicate: ConflictException 409 → BadRequestException 400
- Resolver duplicate: ConflictException 409 → BadRequestException 400
- Type duplicate: ConflictException 409 → BadRequestException 400
- DomainName duplicate: ConflictException 409 → BadRequestException 400
- Domain association duplicate: ConflictException 409 → BadRequestException 400
- API key limit: LimitExceededException 429 → ApiKeyLimitExceededException 400
- Add duplicate validation for Source API associations
- Add checkDuplicateSourceApiAssociation helper method
- Update all integration and SDK test assertions to match AWS exact messages

* feat(core): add extended data support to AwsException for AWS error parity

Add optional extended data to AwsException so the exception mapper can
emit structured error payloads matching the AWS error contract (e.g.
AppSync BadRequestException with reason=CODE_ERROR and detail.codeErrors).

The mapper auto-detects extended data and serializes it as additional
JSON fields alongside __type and message. When extended data is null
the previous simple AwsErrorResponse is returned, preserving behavior
for every existing error site.

* fix(appsync): return ConcurrentModificationException for duplicate source API association

AWS AppSync's AssociateSourceGraphqlApi returns ConcurrentModificationException
(HTTP 409) when an association already exists for the same source and merged
API pair. Floci was returning BadRequestException (400) with an association
ID in the message that did not match AWS.

Also filter out associations in DELETION_SCHEDULED status so a new
association can be created after the previous one has been removed, matching
AWS behavior where the previous association is no longer 'live'.

Message format now mirrors AWS: 'Source API association already exists
for Source API ID: <id> and Merged API ID: <id>.'

* refactor(appsync): remove non-AWS endpoints getApiKey and listAllResolvers

AWS AppSync does not expose:
- GetApiKey: there is no GetApiKey operation in the AppSync API
  Reference. API keys can be listed, created, updated, and deleted
  but not retrieved by id.
- ListAllResolvers: ListResolvers requires typeName. There is no
  endpoint that lists resolvers across all types for an API.

Both endpoints were Floci-only and violated the 'no custom endpoint
shapes' rule. The associated service method (listResolvers) is also
removed. The corresponding integration tests are dropped in a
follow-up commit.

The getApiKey service helper stays because it is still used
internally by updateApiKey and deleteApiKey flows.

* feat(appsync): emit AWS-compatible BadRequestException extended format for SDL errors

AWS AppSync's StartSchemaCreation returns 400 BadRequestException with a
reason=CODE_ERROR field and a detail.codeErrors array. Each code error
carries errorType, value, and location{line, column, span}.

This commit:
- Catches SchemaProblem and InvalidSyntaxException from the parser and
  throws BadRequestException with extended data built from
  graphql-java's GraphQLError locations.
- Catches SchemaProblem from makeExecutableSchema for validation errors
  (unknown types, missing fields) with errorType=VALIDATION_ERROR.
- Catches generic RuntimeException without extended data so flow
  exceptions (NPE, OOM) do not produce a misleading codeErrors array.
- Validates unknown AppSync directives with errorType=VALIDATION_ERROR
  and line/column/span from the SDL.

The errorType values follow the AWS Javadoc (PARSER_ERROR, VALIDATION_ERROR)
and span defaults to -1 when unknown, matching CodeErrorLocation.span()
in the AWS SDK.

* test(appsync): cover AWS-aligned error format, dead-code cleanup

- Add Order 157: createSourceApiAssociationDuplicateReturns409 asserts
  ConcurrentModificationException 409 with the AWS message format.
- Add Order 158: createSourceApiAssociationReplacesDeletionScheduled
  covers the new DELETION_SCHEDULED filter (a new association can
  replace a previously deleted one).
- Add Orders 700, 701, 702: extended BadRequestException format for
  PARSER_ERROR (syntax), VALIDATION_ERROR (semantic), and unknown
  directive cases. Each asserts reason=CODE_ERROR, detail.codeErrors,
  and the location{line, column, span=-1} shape.
- Update Order 124 (deleteApiKeyStandalone): the verification step
  used the removed getApiKey endpoint, replace it with listApiKeys
  asserting the deleted key is no longer present.
- Update Orders 600 and 607 to assert the new extended format for
  generic SDL validation and unknown directive cases.
- Drop Order 32 (getApiKey) and Order 62 (listAllResolvers): the
  underlying endpoints no longer exist.
- Drop encodeArn helper and the URLEncoder / StandardCharsets
  imports that were no longer used by any test.

* test(sdk-java): cover AssociateSourceGraphqlApi 409 and extended schema error body

- Add Order 137 (createSourceApiAssociationDuplicateThrowsConcurrentModificationException):
  use the typed AWS SDK exception ConcurrentModificationException instead
  of the generic AppSyncException, validating the message format that
  AWS returns.
- Add Order 200 (startSchemaCreation_syntaxError_throwsBadRequestWithExtendedBody):
  send a raw HTTP POST with an invalid schema, then inspect the JSON body
  to assert the AWS-compatible shape (__type, reason, detail.codeErrors[],
  errorType=PARSER_ERROR, location{line, column, span=-1}). Uses a
  jackson mapper rather than the SDK to read the response body directly.
- Import java.util.List to support the new deserialization in Order 200.

* feat(appsync): async schema creation with 409 in-progress gates

StartSchemaCreation is asynchronous in AWS: the request returns 200 +
PROCESSING, and the schema compiles in a background thread, transitioning
to ACTIVE (success) or FAILED (error) with the extended error format in
the polled GetSchemaCreationStatus response.

This commit:

- Adds SchemaCreationWorker, a singleton executor with configurable
  thread count and graceful shutdown, that transitions the schema
  status asynchronously and serializes the AwsException extended data
  into the FAILED details string.
- Adds SchemaStatusStoreProducer so AppSyncService and the worker see
  the same in-memory state for the schema status store (otherwise
  two StorageFactory.create() calls would create independent maps).
- Refactors startSchemaCreation to set PROCESSING synchronously and
  hand off compilation to the worker.
- Removes the synchronous ACTIVE override from the controller.
- Gates 27 per-API mutations and 2 account-wide operations
  (CreateGraphqlApi, CreateApi) plus self-blocking on second
  StartSchemaCreation with ConcurrentModificationException 409,
  matching the AWS behavior documented in the AppSync API Reference
  and service-2.json.
- Adds recoverOrphans() to EmulatorLifecycle.onStart so schemas left
  in PROCESSING by a previous emulator run are marked FAILED instead
  of permanently blocking the API.
- Adds schemaWorkerThreads and schemaWorkerShutdownTimeoutSeconds
  to EmulatorConfig (FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_THREADS,
  FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_SHUTDOWN_TIMEOUT_SECONDS).

* test(appsync): cover async schema polling, FAILED state, and 409 gates

- Adapts the 7 existing schema creation tests to the async pattern:
  the post returns PROCESSING, tests poll for the terminal status with
  Awaitility, and the extended format body is now read from the
  polled FAILED details.
- Adds 9 new tests (Orders 703-711) covering the 409 in-progress gates
  for createDataSource, createResolver, createFunction, createType,
  putEnvironmentVariables, startSchemaCreation, createGraphqlApi,
  updateGraphqlApi, and deleteGraphqlApi. The gates are exercised by
  setting the status to PROCESSING directly via the shared store
  backend, which is deterministic and avoids the race window of
  waiting for the worker.
- Updates the EmulatorLifecycleTest constructor for the new
  SchemaCreationWorker dependency.

* test(sdk-java): cover async schema with typed SDK polling

- Adds awaitility 4.2.2 to pom.xml (test scope) so the SDK test for
  the polled status can use the same Awaitility DSL the integration
  tests use.
- Updates the existing getSchemaCreationStatus test (Order 11) to
  poll via the typed SDK call until the terminal status is reached
  (ACTIVE in this case) instead of a single request. Without this,
  the gate added in the previous commit would 409 every subsequent
  SDK test that runs while the schema is still PROCESSING.

* fix(build): remove duplicate awaitility declaration in pom.xml

The pre-existing version-less awaitility declaration (BOM-managed by
Quarkus) was shadowed by the pinned 4.2.2 declaration added in this PR.
Maven resolves the first declaration it encounters, silently ignoring
the BOM version. Removed the version-less dup so the pinned 4.2.2
takes effect.

Addresses P1 from Greptile review.

* fix(appsync): add missing 409 gates and synchronize startSchemaCreation

Validating all 43 ConcurrentModificationException operations from
service-2.json against the code surfaced 5 operations missing the
PROCESSING gate (Greptile caught 1, 4 more were found during review):

- getChannelNamespace: added assertSchemaNotBusy (protects both get
  and deleteChannelNamespace, matching getResolver/getFunction/getType)
- deleteDomainName: resolves the associated apiId from the domain
  association store and gates on it (no-op if no association exists)
- disassociateApi: same pattern as deleteDomainName
- deleteMergedApiAssociation: gate on sourceApiIdentifier
- updateDomainName: resolves the associated apiId and gates on it

Also wraps the startSchemaCreation check-and-set in synchronized(this)
to close the TOCTOU race window between assertSchemaNotBusy and the
PROCESSING put. The async submitSchemaCreation call stays outside the
lock to avoid blocking the worker thread.

Addresses P1 and P2 from Greptile review.

* chore(appsync): document schema worker config in application.yml

Adds the appsync section under storage.services in both main and test
application.yml, documenting the three AppSyncStorageConfig keys:

- flush-interval-ms (5000 main / 60000 test, matching other services)
- schema-worker-threads (4)
- schema-worker-shutdown-timeout-seconds (30)

These already had @WithDefault fallbacks so the code worked without
the YAML entries, but the repository convention (AGENTS.md) requires
storage config to be documented in application.yml as the source of
truth for operators.

Addresses P2 from Greptile review.

* test(appsync): cover additional 409 gates for domain and merged operations

Adds 5 new integration tests (Orders 712-716) covering the PROCESSING
409 gates added in the previous commit:

- 712: deleteChannelNamespace_busy_returns409
- 713: deleteDomainName_busy_returns409
- 714: disassociateApi_busy_returns409
- 715: disassociateMergedGraphqlApi_busy_returns409
- 716: updateDomainName_busy_returns409

Each test creates the necessary resources (temp API, channel namespace,
domain name + association, or merged API association) before setting
the schema status to PROCESSING directly via the shared store, then
asserts the gated operation returns 409 ConcurrentModificationException
with the AWS-style message.

Integration test count: 154 -> 159.

* fix(appsync): remove incorrect CME gate from getChannelNamespace, add to deleteChannelNamespace

GetChannelNamespace does not declare ConcurrentModificationException in
service-2.json or the AWS Java SDK v2. Only BadRequestException,
NotFoundException, UnauthorizedException, InternalFailureException, and
AccessDeniedException are declared. The gate was incorrectly returning
409 during PROCESSING for an undeclared error code.

DeleteChannelNamespace does declare CME, so the gate is now applied
directly in deleteChannelNamespace instead of being inherited from
getChannelNamespace.

* fix(appsync): account-aware schema creation and worker store isolation

Scope schema creation status to the requesting account so concurrent
accounts cannot interfere with each other's in-flight schema operations.

- Add accountId field to SchemaCreationStatus
- Worker uses AccountAwareStorageBackend (putForAccount/getForAccount)
- SchemaStatusStoreProducer now produces AccountAwareStorageBackend
- SchemaStoreProducer CDI bean shares schemaStore between service and worker
- schemaStore.put moved to worker success path only
- assertSchemaNotBusy scoped to current account via getForAccount
- assertNoSchemaBusyAnywhere scoped to keysForAccount
- currentAccountId() helper reads RequestContext
- Worker config moved from AppSyncStorageConfig to AppSyncServiceConfig

* fix(appsync): ACTIVE→SUCCESS terminal schema status

Match AWS behavior: a successfully compiled schema is SUCCESS, not
ACTIVE. ACTIVE is not a valid terminal status in real AppSync.

- Worker marks SUCCESS on successful compilation
- Integration tests assert SUCCESS
- SDK compatibility test asserts SUCCESS

* refactor(appsync): remove circular dependency between SchemaRegistry and SchemaCreationWorker

SchemaRegistry depended on SchemaCreationWorker solely to delegate
submitSchemaCreation calls, creating a circular dependency. AppSyncService
now calls the worker directly, making the delegation unnecessary.

- Remove SchemaCreationWorker dependency from SchemaRegistry
- Remove submitSchemaCreation method

* fix(appsync): add assertSchemaNotBusy to deleteResolver, deleteFunction, deleteType

These three delete operations mutate the schema and should be blocked
while a schema creation is in PROCESSING state, matching the 409 gates
on the other schema-mutating operations.

* fix(appsync): return PROCESSING status synchronously from StartSchemaCreation

The controller was re-reading the status from the store after submitting
to the worker pool. In fast environments the worker could complete
(fail) before the read, causing the POST response to return FAILED
instead of PROCESSING — breaking the SDK compatibility test.

startSchemaCreation now returns the PROCESSING status it just set, and
the controller uses it directly instead of re-reading.
2026-07-10 20:50:14 -05:00