PublishVersion builds its snapshot field by field and left accountId unset, so
every published version reported a null owning account while $LATEST reported
the real one for the same function. Consumers that key off the account then have
to re-derive it from the function ARN or fall back to a default: codeObjectKey
substitutes 000000000000 for a null account, and anything keying IAM state on
the function account has nothing to key on.
Copy accountId alongside the other snapshot fields so a version carries the same
owning account as the function it was published from. The account was never
lost, the version ARN already embeds it, it just was not on the model.
Fixes#2040
* feat(rum): add CloudWatch RUM app-monitor service
Adds a minimal CloudWatch RUM service (restJson1) covering the app-monitor
lifecycle — CreateAppMonitor, GetAppMonitor, UpdateAppMonitor, DeleteAppMonitor,
ListAppMonitors — backed by an in-memory store.
Previously restJson1 RUM requests (e.g. POST /appmonitor) fell through to the S3
path-style catch-all (@Path("/{bucket}")) and returned an XML error that
restJson1 SDKs (and the CDK AwsCustomResource used for RUM AppMonitor custom
resources) cannot parse. Literal /appmonitor and /appmonitors paths take JAX-RS
precedence over S3's /{bucket} template (the same mechanism eks/mq use), so the
routes win with no extra routing wiring.
Verified with aws-cli 2.33.18 against a dev-mode emulator: CreateAppMonitor
returns an Id, GetAppMonitor/ListAppMonitors round-trip, DeleteAppMonitor then
GetAppMonitor returns ResourceNotFoundException.
* fix(rum): make monitor updates atomic
* fix(rum): align app monitor lifecycle with AWS
* chore: retry flaky Node compatibility check
* fix(rum): address app-monitor review feedback
---------
Co-authored-by: abanna <abanna@users.noreply.github.com>
* feat(apigateway): support floci:override-id for v1 and v2
API IDs were generated randomly, so endpoint URLs changed on every
recreate. v1 accepted an undocumented `_custom_id_` tag and echoed it
back as a normal tag; v2 had no override at all. Other services already
pin IDs through the reserved `floci:override-id` tag.
Both CreateRestApi and CreateApi now accept `floci:override-id`, routed
through ReservedTags.getOverride so the value is validated rather than
used verbatim: non-blank, no whitespace or control characters, and no
`/`, `?`, `#`, since those break the endpoint URL. Override keys are
consumed rather than stored, so they no longer appear in the returned
tags, and supplying either key to TagResource is rejected because an ID
cannot change after creation.
`_custom_id_` keeps working as a deprecated fallback and is now stripped
the same way; `floci:override-id` wins when both are present so callers
can set both during a migration. The key stays API Gateway specific: the
shared strip and reject helpers are untouched, so KMS and Cognito still
treat `_custom_id_` as an ordinary tag.
Error code is BadRequestException, declared by CreateRestApi, CreateApi
and TagResource on both services. The shared reject helper's
ValidationException is declared by neither, which is why API Gateway gets
its own guard rather than reusing it.
Closes#1593
Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
* fix(apigateway): reject duplicate override ids with ConflictException
CreateRestApi (v1) and CreateApi (v2) now return 409 ConflictException
when the resolved API id already exists in the region, instead of
silently overwriting the existing API, matching how KMS and Cognito
treat duplicate override ids.
---------
Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
DescribeKeyPairs returned an empty list (HTTP 200 / CLI exit 0) when a
requested KeyName or KeyPairId did not exist, instead of the documented
InvalidKeyPair.NotFound fault. Idempotent callers that treat exit 0 as
"present" then skip creating the key pair.
Fail with InvalidKeyPair.NotFound (400) when any explicitly requested
name or id does not resolve, while an unfiltered describe on an empty
account still returns an empty list.
Fixes#1911
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.
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
* 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.
* 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.
* 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
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.
* 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.
* 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>
* 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
* 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
* 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.
* 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.
* 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.
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
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
* 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
* 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
* 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
* 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>
* 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.
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
DescribeDBSubnetGroups with a missing DBSubnetGroupName returned HTTP 200 and an empty list; reuse resolveDbSubnetGroupView so AWS clients get a 404 fault instead.
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.
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
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
* 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.
* 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
* 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.
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
* 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>
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.
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
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