Commit Graph
224 Commits
Author SHA1 Message Date
sheldon-nadarajah-sft be625023eb fix(appconfig): add DeleteConfigurationProfile/DeleteHostedConfigurationVersion/ListDeploymentStrategies/DeleteDeploymentStrategy (#2280)
* fix(appconfig): add DeleteConfigurationProfile/DeleteHostedConfigurationVersion/ListDeploymentStrategies/DeleteDeploymentStrategy

These four operations had no route at all, so a request fell through
to S3's generic path-style catch-all (GET/DELETE /{bucket}[/{key}])
and returned a misleading NoSuchBucket 404 instead of a real AppConfig
response - confirmed via both raw HTTP and the real AWS SDK for Java.

Adds the missing routes + AppConfigService methods, mirroring existing
precedent (DeleteConfigurationProfile/DeleteHostedConfigurationVersion/
DeleteDeploymentStrategy follow DeleteApplication's idempotent-delete
convention - no upfront existence check; ListDeploymentStrategies
includes the three predefined strategies alongside custom ones,
verified against the API reference's own sample response).

DeleteDeploymentStrategy's real path is /deployementstrategies/{id}
(extra "e" - a genuine, documented quirk in AWS's own API model; every
other deployment-strategy operation correctly uses
/deploymentstrategies). Confirmed against the API reference and
reproduced against the real SDK, which sends the misspelled path
literally - matched it rather than "fixing" it, since wire-protocol
fidelity to what AWS actually does is the point.

Regenerated docs/services/appconfig.md's Supported Operations list
(hand-maintained for REST controllers - not yet covered by
tools/docs/regen_action_docs.py, confirmed via services.yaml's own
Phase-1 scope comment).

Tests: AppConfigIntegrationTest (+4), compatibility-tests/sdk-test-java
AppConfigTest (+1, covering all four operations via the real SDK).
Ran locally (JDK 25):

AppConfigIntegrationTest (unit):        29/29 passed
AppConfigTest (SDK compat, live):       16/16 passed

* fix(appconfig): scope profile deletion to its application, reject deleting predefined strategies

Review feedback on #2280 (Copilot + Greptile, both independently):

- deleteConfigurationProfile ignored appId entirely and deleted by the
  bare, globally-keyed profileId - a caller could delete another
  application's profile just by guessing/reusing its ID, since
  sibling reads (getConfigurationProfile) already enforce this
  ownership check but the new delete route didn't. Now rejects with
  the same ResourceNotFoundException as a mismatched get; a profileId
  that doesn't exist anywhere is still an idempotent no-op, matching
  deleteApplication's existing convention - only an existing-but-
  wrongly-scoped one is rejected.
- Same method also now cascades the delete to that profile's hosted
  configuration versions - they aren't independently addressable
  outside a profile's lifecycle, so leaving them in versionStore after
  the profile was "deleted" let a caller keep fetching versions for a
  profile that supposedly no longer exists.
- deleteDeploymentStrategy silently reported success (204) for a
  predefined strategy (e.g. AppConfig.AllAtOnce) without doing
  anything, since builtins were never in strategyStore in the first
  place - the strategy would still exist and still show up in every
  subsequent Get/List call despite the "successful" delete. Now
  rejects with BadRequestException.

Also applied this project's own established cleanup-logging
convention (System.err.println on a best-effort catch, matching
several other compatibility-tests/sdk-test-java files) to the one new
try/finally block flagged by Greptile, rather than swallowing the
exception silently.

Tests: 2 new AppConfigIntegrationTest cases (cross-application delete
rejected + original untouched, predefined-strategy delete rejected +
still resolvable) and 2 new SDK compatibility tests using the real
AWS SDK for Java v2's exception types.

AppConfigIntegrationTest:                31/31 passed
AppConfigTest (SDK compat, live):        18/18 passed

* chore: retrigger CI
2026-08-17 14:22:17 -04:00
TiM 112602fc6e fix(cloudwatch): page FilterLogEvents forward with a usable nextToken (#2354)
FilterLogEvents returned UUID.randomUUID() as its nextToken and had no
nextToken parameter to accept one back, so a response could advertise more
results while giving a client no way to reach them. Truncation compounded it:
the time and pattern filters ran before .limit(maxEvents) over an
ascending-sorted list, so an over-cap query kept the oldest matches and the
newest were unreachable. The canonical use of this action is finding the error
that just happened across a group, which is exactly the event most likely to be
dropped.

Accept a nextToken and make it an f/<index> offset into the matched set,
reusing the parser GetLogEvents already validates its tokens with so a
malformed, negative or overflowing token raises InvalidParameterException here
too. The offset indexes matches rather than stored events, so a request
narrowed by pattern, time range or stream names pages through only what it
matched.

Emit the token only when a further page exists, unlike GetLogEvents which
echoes its forward token back. The two AWS actions signal exhaustion
differently: FilterLogEvents documents an absent nextToken as "pagination is
finished", and its SDK paginators keep requesting while the token is present
with no same-token guard, so echoing a final token would never terminate. Also
refuse to emit a cursor that cannot advance, which a max-events cap configured
to zero would otherwise produce, and compute the page end by subtracting from
the total so a cap near Integer.MAX_VALUE cannot overflow the index negative.

startFromHead is still unsupported, so results run oldest first.
2026-08-17 13:25:47 -04:00
Tucker 6779aa8270 feat(guardduty): add GuardDuty detector and organization configuration emulation (#2346) 2026-08-17 00:40:12 -05:00
1cc97d57c1 feat(cloudhsmv2): implement CloudHSM v2 service (#1776)
* feat(cloudhsmv2): implement CloudHSM v2 service

* refactor(cloudhsmv2): delete HSM parameters and docs

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

* fix: greptile bot reviews

* refactor(cloudhsmv2): delete HSM parameters and docs

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

* fix: greptile bot reviews

* fix(cloudhsmv2): fix backup retention policy parsing and SDK test cert usage

* fix(cloudhsmv2): fix CreateHsm IP generation, ModifyCluster validation, and duplicate test Order

* docs(cloudhsmv2): add service to mkdocs, readme, and index matrices

* fix(rds): preserve configured database images (#2035)

* fix(cloudhsmv2): resolve remaining AWS-compatibility edge cases

* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency (#1810)

* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency

A Map state ran its iterations one after another. AWS runs them
concurrently up to MaxConcurrency (default 0 = unlimited), which is a
correctness requirement, not just a speed-up: a Map whose iterations
coordinate — e.g. a dependency-ordered fan-out where one child blocks
until a sibling completes — deadlocks when the iterations are serialised.

Run each iteration on the shared executor under the execution's account,
gated by a Semaphore sized to MaxConcurrency (unlimited when 0). Results
are written into per-index slots so the output array preserves input order
regardless of completion order, MaxConcurrency=1 stays strictly sequential,
and a failed iteration cancels the rest and fails the Map (fail-fast,
matching the default ToleratedFailureCount of 0).

* fix(stepfunctions): cap Map worker threads with a bounded pool + handle interruption

Address review: submitting every iteration to the shared cached pool behind
a Semaphore spawned one thread per item (a 1000-item Map with
MaxConcurrency=5 created ~1000 threads, ~995 parked). Run iterations on a
fixed-size per-Map ThreadPoolExecutor sized to MaxConcurrency so live
threads are capped and the rest queue. shutdownNow() in finally stops the
iterations on any exit, and an InterruptedException from the driver now
preserves the interrupt status.

* fix(stepfunctions): make Map concurrency bounded and fail-fast

* docs(stepfunctions): document map concurrency

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after OpenTofu registry flake

* test(stepfunctions): pin Map item selection order

* perf(lambda): reuse a populated code volume across restarts via a completion marker (#1827)

* perf(lambda): reuse populated code volumes across restarts

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* ci: retry transient gosu downloads

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>

* fix(apigateway): apply MOCK integration response headers (#1822)

* fix(apigateway): apply mock response headers for OPTIONS

* refactor(apigateway): drop the OPTIONS route in favour of #1955

Both this PR and #1955 added an @OPTIONS method on the same @Path in
ApiGatewayExecuteController and ApiGatewayUserRequestController, so whichever
merged second would not have compiled.

#1955's version is the more complete one: it covers ApiGatewayAwsExecuteController
(the /_aws/execute-api path) as well, forwards the request body, and skips
GlobalCorsFilter for deployed-API paths -- without which a real browser preflight
is short-circuited before it ever reaches the route.

This PR keeps only its own contribution: invokeMock returned early on the
empty-response-template path and dropped static method.response.header.* mappings.
ApiGatewayMockCorsHeadersTest now exercises that over GET, since the dropped-header
bug is verb-agnostic, leaving the two PRs independently mergeable in either order.

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after autoscaling test flake

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>

* fix(cloudwatch): return logStreamName on FilterLogEvents results (#2259)

FilterLogEvents is the cross-stream search API, so a match is only
attributable if the response names the stream that emitted it. Floci
served FilterLogEvents and GetLogEvents from one serializer emitting
eventId, timestamp, message and ingestionTime, so a caller searching a
whole log group could tell which group a hit came from but not which
stream, and tooling written against real AWS lost that attribution
without any error.

Derive the stream from the event's storage key rather than persisting it
on the event. Keys are already
<region>::<group>::<stream>::<timestamp>::<uuid>, so the key is an
authoritative record of the emitter for every event in the store,
including ones written before this change. Storing the name on LogEvent
instead would leave every already-persisted event with a null
logStreamName and need a backfill pass to repair it. The stream is read
back between the group prefix and the trailing timestamp and uuid, both
generated here, so a stream name is recovered whole even though nothing
stops a caller from creating one that holds a ':'.

filterLogEvents walks the keyset once and pairs each event with its
stream, which also collapses the stream-restricted branch: it previously
ran one full keyset scan per requested stream, since a scan walks every
key regardless of the prefix it filters on.

GetLogEvents keeps its existing shape. Real AWS returns OutputLogEvent
there, which carries no logStreamName, because the caller named the
stream in the request.

Closes #2210

* fix(ec2): start sshd even when run-instances omits a key pair (#2245)

* fix(ec2): start sshd even when run-instances omits a key pair

Reported in #2184: run-instances without --key-name left every
container with no SSH daemon listening at all, "connection refused"
regardless of image (alpine, Amazon Linux 2023, Ubuntu all affected).

The cause: startSshd() only ran inside the same conditional as
injectSshKey(), so no key pair meant sshd never started. Real AWS AMIs
run sshd as part of normal boot regardless of whether a key pair is
attached - the daemon is always there, it just has nothing to
authenticate an unattached client with. Floci's behavior diverged by
not running the daemon at all in that case, rather than running it and
correctly having no way in.

Splits the two: injectSshKey still only runs when a key was actually
provided (nothing to inject otherwise), but startSshd now always runs.
It's fully self-contained already (installs openssh-server if absent,
generates host keys, starts the daemon) and never depended on anything
injectSshKey sets up, so making it unconditional needed no other
changes.

Verified: new test launches an instance with no public key and asserts
sshd still starts (and confirms nothing gets written to
authorized_keys, since there's no key to inject). Confirmed it fails
with the fix reverted (no /usr/sbin/sshd invocation happens without a
key) and passes with it restored. Full ec2 package regression is green
(268 tests) - including the several existing tests that already
launched with no key pair and needed no changes to keep passing.

* fix(ec2): stop silently claiming sshd started when it never actually did

Follow-up on a comment from duytanisme on #2245: sshd not starting even
when an SSH key IS provided, requiring a manual exec-in or a custom
user-data script to work around it.

Root cause: startSshd() ran every step through execInContainer(),
which discards the exec's exit code entirely and only throws if the
Docker API call itself fails. The install step's shell script is an
if/elif chain with no matching branch, or whose install command itself
failed (no network yet, apt lock held, etc.) - and a bash if/elif with
no matching branch and no else clause exits 0 by convention. So a
container without a package manager, or one where the install call
failed for any reason, still reported success, ssh-keygen and sshd
then both ran anyway against a daemon that was never installed, and
"Started sshd in EC2 instance" got logged regardless.

Switches every step to execInContainerForResult and checks its exit
code explicitly, following the exact pattern already used by
configureLinkLocalMetadataEndpoint for the same class of problem:
bail out and log a specific warning with the actual command output at
whichever step actually failed, instead of silently proceeding.

Also adds an explicit "command -v sshd" as the last statement of the
install script, so its own exit code is the real source of truth for
whether sshd is actually available afterward, and switches the start
command from a hardcoded /usr/sbin/sshd to a bare "sshd" resolved via
PATH (matching how ssh-keygen is already invoked two lines above),
since not every image installs it to that exact path.

Verified: new test forces the install probe to fail and asserts
ssh-keygen and the start command are never even attempted. Confirmed
it fails (proceeds anyway) with the exit-code check disabled and
passes with it restored. Updated the existing no-key-pair test for the
new bare "sshd" command. Full ec2 package regression is green (269
tests).

* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates (#1867)

* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): preserve log group on failed rename

* fix(cloudformation): scope update rollback to attempted resources

* fix(cloudformation): delete resources after stack updates

* test(cloudformation): wire cloudfront fixture dependency

* fix: include Step Functions update date in describe response

* fix: preserve Step Functions describe response shape

* fix: preserve generated Step Functions names

* fix(s3): derive S3 host suffix matching from DNS config (#1843)

* fix(s3): derive S3 host suffix matching from DNS config

S3VirtualHostFilter hardcoded the wildcard-DNS suffixes (localhost.floci.io,
localhost.localstack.cloud) in two places: the bare service-host check
(isS3ServiceEndpointHost) and the virtual-hosted bucket fallback (isAwsS3Domain).
Both now derive their suffix set from the embedded DNS source of truth plus any
configured floci.dns.extra-suffixes, so a custom DNS suffix is recognised the same
way the builtins are.

Why: the two literal lists duplicated what the DNS server already knows and could
drift from it silently. Deriving from EmbeddedDnsServer.BUILTIN_SUFFIXES keeps them
in lockstep, and folding in extra-suffixes means a user migrating from LocalStack
via a custom suffix gets consistent S3 host handling (bucket routing and service
endpoint detection), not just the DNS resolution they get today.

How:
- buildServiceHostSuffixes() computes {localhost} + BUILTIN_SUFFIXES + extra-suffixes
  once per instance; isS3ServiceEndpointHost() checks membership instead of literals.
- matchesConfiguredSuffixHost() routes the virtual-hosted forms bucket.<suffix>,
  bucket.s3.<suffix> and bucket.s3.<region>.<suffix> for every configured suffix,
  replacing the hardcoded localstack/floci branches in isAwsS3Domain.
- EmbeddedDnsServer.BUILTIN_SUFFIXES widened to public so the filter reuses the list.

The virtual-host match now requires the full builtin suffix (.localhost.localstack.cloud)
rather than the bare parent domain (.localstack.cloud), matching LocalStack's actual
wildcard DNS (*.localhost.localstack.cloud).

* test(s3): derive DEFAULT_SUFFIXES from the production factory

The test constant hardcoded a copy of the builtin suffix set, which would
silently drift if a new builtin were added to EmbeddedDnsServer.BUILTIN_SUFFIXES.
Widen buildServiceHostSuffixes() to package-private and reuse it in the test so
the two stay in sync automatically.

* fix(s3): include the configured hostname in the derived suffix set

EmbeddedDnsServer resolves builtins + floci.hostname + floci.dns.extra-suffixes,
but the derived service-host set carried only two of the three. The configured
hostname reaches the filter as baseHostname, and matchesEndpointHost excludes the
bare s3.<host> remainder by design, so the bucket form one level down
(bucket.s3.<hostname>) matched nothing. DNS still resolves that host, so the
request reached Floci and was then handled path-style, binding the first path
segment as the bucket, rather than being refused.

Carry the hostname into buildServiceHostSuffixes so all three DNS inputs are
mirrored and a host that resolves by wildcard DNS routes under the same rules.

* fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#2023)

* fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#1984)

Every instance was given PublicIpAddress 127.0.0.1 unconditionally in
Ec2ContainerManager, so a private-subnet instance wrongly reported an
internet-facing address (breaks the ssh-reachability / public-vs-private
distinction). runInstances now flags the instance (associatePublicIp) from its
subnet's MapPublicIpOnLaunch, and the container manager exposes a public
address only when that flag is set. Private-subnet instances get no
PublicIpAddress — DescribeInstances omits the element (XmlBuilder skips nulls),
matching real EC2. The value for public instances stays the host-reachable
127.0.0.1 (unchanged). Unit test covers the public-vs-private flag.

Supports the aws-bench project: un-excludes the ssh-reachability scenario.

* fix(ec2): honor the launch-time AssociatePublicIpAddress override

* fix(ec2): honor the top-level AssociatePublicIpAddress and an explicit-false launch configuration

Two gaps left by the previous commit, both flagged in review.

RunInstances only read the override off the primary network-interface spec
(NetworkInterface.1.AssociatePublicIpAddress), so the legacy top-level
AssociatePublicIpAddress parameter — what the CLI and older SDKs send — was
silently dropped and the subnet default decided instead. It is now read as a
fallback; AWS rejects both shapes at once, so the interface spec wins when
present.

The launch-configuration path was worse than before. LaunchConfiguration
stored a primitive boolean, so an absent flag and an explicit false were
indistinguishable, and the reconciler could only forward an explicit true.
An LC that set AssociatePublicIpAddress=false in a MapPublicIpOnLaunch subnet
still got a public address. The field is now a nullable Boolean the whole way
through (service, query handler, CFN provisioner), so false overrides the
subnet and only null falls back to it. DescribeLaunchConfigurations omits the
element when it was never set, as AWS does.

Tests: a handler-level test pins all four parse cases (top-level, interface
spec, both present, absent), and the reconciler test pins true/false/null
reaching runInstances unchanged.

* feat(cloudfront): enforce signed private content (#1831)

* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): enforce signed private content

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

* fix(cloudfront): wildcard aliases match exactly one subdomain level

wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched
a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the
wildcard at that level only:

  "you can't add alternate domain names that are at levels higher or lower than the
   wildcard. For example, you can't add the alternate domain names example.com or
   marketing.product.example.com."

  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

Practical effect: a distribution owning "*.example.com" would answer for
a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to
nobody. Require the label standing in for the wildcard to contain no dot.

wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour
(a.b.example.test resolving to the *.example.test distribution); it now asserts no
match, plus the same for a deeper wildcard.

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix(cloudfront): match wildcards in signed policy queries

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

- Fix malformed dummy certificate in sdk-test-java by generating a self-signed X.509 cert programmatically using BouncyCastle
- Apply fixes for tag operations targeting backups
- Escape backslashes in regex
- Resolve compilation issues

* fix(test): Add CloudFrontClient to TestFixtures to resolve merge conflict

* revert(test): revert CloudFrontClient addition to TestFixtures

* fix(cloudhsmv2): fix CSR public key mismatch in SDK tests by signing properly extracted CSR

* test(ec2): fix Ec2PublicIpOnLaunchTest compilation after StorageBackend changes

* fix(cloudhsmv2): remove explicit BouncyCastle JCA provider to fix native image certificate validation

* fix(cloudhsmv2): add null check for DestinationRegion in copy backup

* fix(test): correct storage imports in Ec2PublicIpOnLaunchTest after rebase

* fix(cloudhsmv2): resolve code review comments including AZ lookup and validation

* style(cloudhsmv2): remove trailing whitespace in CloudHsmV2Test

---------

Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in>
Co-authored-by: Aniket Shukla <aniketshukla619@gmail.com>
Co-authored-by: Alex Banna <alexanderbanna@gmail.com>
Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
Co-authored-by: TiM <tim@nuimarkets.com>
Co-authored-by: Olamide Kosile <64154023+Mide69@users.noreply.github.com>
Co-authored-by: lex00 <121451605+lex00@users.noreply.github.com>
2026-08-17 00:00:49 -05:00
Mihai BlidaruandMihai Blidaru bfda938f72 feat(firehose): honor BufferingHints with time and size based flush (#2314)
* feat(firehose): honor BufferingHints with time and size based flush

Buffers now flush when the stream's BufferingHints.SizeInMBs is reached
or when IntervalInSeconds has elapsed since the first buffered record,
replacing the hardcoded 5-record count trigger that matched neither AWS
nor LocalStack. A single-thread daemon flusher ticks every
floci.services.firehose.tick-interval-seconds (default 10).

Buffers are drained on ShutdownDelayInitiatedEvent so pending records
reach S3 before EmulatorLifecycle persists storage to disk.
DeleteDeliveryStream keeps discarding pending records, matching real
AWS (verified empirically: 3 records buffered under a 300s/5MB hint
never reached the bucket after deletion).

Fixes #1886

* feat(firehose): add opt-in flush-record-count trigger

Emulator-only volume trigger complementing BufferingHints: setting
floci.services.firehose.flush-record-count to N flushes a stream's
buffer as soon as it holds N records. Disabled by default (0) so
out-of-the-box delivery matches real AWS; 1 gives LocalStack-style
record-at-a-time delivery for interactive local dev, where stream
definitions mirror production intervals and waiting for
IntervalInSeconds is impractical. Covers the use case of #1852.

Co-Authored-By: yoshinori-aono-om <yoshinori.aono@omiai.inc>

* test(firehose): cover size and interval flush triggers at the wire level

The size trigger delivers inline on the writing request, and the
interval trigger runs through the real background flusher started on
StartupEvent — previously only verified manually. The test-scope Clock
is the frozen MutableClock alternative, so the interval test advances
it explicitly instead of sleeping through real time.

* fix(firehose): clamp the flush tick interval and mirror config keys in application.yml

A zero or negative floci.services.firehose.tick-interval-seconds reached
scheduleAtFixedRate unchanged, which throws IllegalArgumentException from
the StartupEvent observer and aborts startup. Clamp it to a 1s minimum,
the same guard RdsDataService applies to its cleanup interval.

Also list tick-interval-seconds and flush-record-count under the firehose
service in the main and test application.yml, matching how other tunable
service settings are surfaced there.

* test(firehose): wait for buffered delivery in DataLake and SES compatibility tests

DataLakeTest relied on the removed 5-record flush: with buffered
delivery its Athena query ran before anything reached S3, failing with
NoSuchBucket on floci-firehose-results (caught by the compatibility CI
job). Both tests now set explicit BufferingHints and poll for the
delivered object first. A 5s interval keeps the wait short — floci does
not enforce AWS's 60s server-side minimum and the SDK does no
client-side range validation.

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-08-16 23:28:09 -05:00
Kenshin Okinaka c745f821af test(ses): guard LastKeyGenerationTimestamp fractional-epoch wire format (#2323)
* test(ses): guard LastKeyGenerationTimestamp fractional-epoch wire format

GetEmailIdentity emits LastKeyGenerationTimestamp as a fractional unix epoch
(toEpochMilli()/1000.0) so the SDK's number unmarshaller keeps the sub-second
precision AWS sends; getEpochSecond() would silently drop it and nothing
caught that. Assert the SDK-unmarshalled DkimAttributes.lastKeyGenerationTimestamp
retains a sub-second component after PutEmailIdentityDkimSigningAttributes.

* test(ses): de-flake DKIM LastKeyGenerationTimestamp sub-second guard

The guard asserted getNano() != 0 against an uncontrolled server clock; a
regeneration landing on a whole millisecond-of-second (~0.1%) failed the test
even though the toEpochMilli()/1000.0 serialization was correct. Regenerate the
key (alternating length so a fresh key is minted each time) until a sub-second
component appears, keeping the whole-second-epoch regression check without the
rare flake.

* test(ses): sample distinct milliseconds when retrying the DKIM timestamp guard

The retry loop could in principle sample the same millisecond on every attempt,
so a first regeneration on a whole-second boundary would keep recording the same
zero-nanosecond instant and fail the guard. Wait briefly before each retry so the
next regeneration lands in a later millisecond and the samples stay independent.
2026-08-16 22:45:35 -05:00
Maciej d891425943 fix(cognito): mark verified contact attribute on ConfirmSignUp (#1881)
* fix(cognito): mark verified contact attribute on ConfirmSignUp

* fix(cognito): add null guard for resolveSignUpDeliveryTarget in confirmSignUp

* fix(cognito): update ConfirmSignUp test assertions for phone first delivery
2026-08-15 18:19:18 -05:00
soreavis 7a4fc45fdf fix(elasticache): store the user Engine instead of hardcoding redis (#2331)
CreateUser dropped the Engine parameter and userXml emitted a literal
redis, so a user created with Engine=valkey read back as redis on
CreateUser, DescribeUsers, ModifyUser and DeleteUser - the issue's
aws_elasticache_user resource plans a diff on every run and never
converges.

Store the engine on ElastiCacheUser, defaulting a missing value to
redis to keep the previous behavior for callers that omit it. Accept
Engine on ModifyUser too, which AWS models as an optional parameter,
validating it before the first setter so a rejected request leaves
the user untouched - the storage backends hand back the live stored
object, so a mutation applied before validation would survive the
400. Honor the documented Engine filter on DescribeUsers, which means
something now that users can differ by engine. Values are validated
redis/valkey case-insensitively, matching the handler's existing
memcached check. MinimumEngineVersion stays at 6.0, the only value
AWS documents for the element. Users persisted before the engine
field existed deserialize with the redis default.

Closes #2290
2026-08-15 18:16:57 -04:00
lex00 4e6e6df06d feat(bedrockagentcore): emulate the AgentCore control plane and InvokeAgentRuntime stub (#2316)
* docs(bedrockagentcore): add AgentCore emulation design + upgrade path

* feat(bedrockagentcore): add agent runtime CRUD control plane

Implements the bedrock-agentcore-control runtime registry (Phase 1):
Create/Get/List/Update/Delete AgentRuntime plus ListAgentRuntimeVersions,
with immutable version snapshots, cursor pagination, and ISO-8601 timestamps.

- REST-JSON controller + service + reflection-safe models
- ServiceRegistry descriptor + EmulatorConfig toggle
- Unit + RestAssured integration tests
- AWS SDK v2 compatibility test (sdk-test-java)
- Service docs page

Refs lex00/floci#2

* feat(bedrockagentcore): add agent runtime endpoints

Phase 2: Create/Get/Update/Delete/List AgentRuntimeEndpoint under
/runtimes/{id}/runtime-endpoints/, with a DEFAULT endpoint auto-created per
runtime and agentEndpoint/<uuid> ARNs. RestAssured + SDK v2 compat tests.

Refs lex00/floci#3

* feat(bedrockagentcore): add InvokeAgentRuntime data-plane stub

Phase 3: POST /runtimes/{agentRuntimeArn}/invocations returns a fixed,
configurable canned response ({"output":"yes"}) and echoes the runtime
session id. Opaque payload is never parsed; streaming is not emulated.
Separate stateless bedrock-agentcore service. RestAssured + SDK v2 compat tests.

Refs lex00/floci#4

* feat(bedrockagentcore): add tagging and workload identity

Phase 4:
- TagResource/UntagResource/ListTagsForResource for runtime ARNs via a
  TagHandler on the shared /tags/{arn} route
- Workload identity RPC CRUD (POST /identities/<Op>); each runtime auto-creates
  a resolvable workload identity
- Workload-identity timestamps are epoch-seconds (unixTimestamp), distinct from
  the runtime ISO-8601 timestamps

RestAssured + SDK v2 compat tests.

Refs lex00/floci#5

* feat(bedrockagentcore): add gateway and memory primitives

Phase 5 (optional): metadata-only CRUD registries.
- Gateways (POST /gateways/) + gateway targets, standard REST
- Memory (POST /memories/create, GET /memories/{id}/details, ...), action-suffix
- Gateway timestamps are ISO-8601; memory timestamps are epoch seconds
RestAssured + SDK v2 compat tests.

Refs lex00/floci#6

* fix(bedrockagentcore): correctness fixes from adversarial audit

- Fix ListAgentRuntimeVersions pagination cycling for >=10 versions: sort by
  the pagination cursor and zero-pad the version cursor (closes #7)
- Capture authorizerConfiguration/protocolConfiguration in version snapshots so
  GetAgentRuntime?version returns the requested version's config (closes #8)
- Support tagging AgentCore gateways (AWS-taggable): add tags to Gateway,
  dispatch the TagHandler by ARN resource type, store tags on CreateGateway;
  non-taggable AgentCore ARNs now 400 (closes #9)
- Validate maxResults range (1..N) across all list operations (closes #12)

Adds regression tests: version-pagination multi-page, version-config snapshot,
gateway tag round-trip (REST + SDK), unsupported-ARN 400, maxResults + malformed
nextToken validation, and an HTTP-level multi-page pagination test.

Refs lex00/floci#14

* feat(bedrockagentcore): clientToken idempotency, invoke existence flag, config docs

- clientToken idempotency for Runtime/Endpoint/Memory create+delete (lenient:
  same token returns the existing resource; completed-delete tokens tracked
  in-memory so a replayed delete returns 202 not 404) (closes #10)
- InvokeAgentRuntime existence check behind floci.services.bedrock-agent-core
  .validate-runtime-exists (default false, preserving permissive behavior);
  when on, unknown runtime ARNs return ResourceNotFoundException (closes #11)
- Document that YAML config keys are hyphenated (bedrock-agent-core-control),
  distinct from the reported service name (closes #13)

Adds unit tests (create/delete idempotency), a TestProfile integration test for
the existence flag, and an SDK v2 idempotency compat test.

Refs lex00/floci#10 lex00/floci#11 lex00/floci#13

* ci: trigger fork pipeline dry-run

* test(bedrockagentcore): add persistence, region-isolation, concurrency and boundary coverage

Closes the structural test gaps from the audit (issue #14):
- Persistence-across-restart: full AgentRuntime (JsonNode config, Instants,
  version snapshots, endpoints, tags, env vars) round-trips through
  PersistentStorage to disk and reloads intact
- Region isolation: a runtime is invisible/ungettable from another region
- Concurrency: concurrent creates all persist (no dropped inserts)
- Endpoint version retargeting, gateway + target update, duplicate-name 409,
  and memory eventExpiryDuration boundaries (2/3/365/366)

Refs lex00/floci#14

* fix(bedrockagentcore): validate endpoint versions and the identity in a tagging ARN

createEndpoint and updateEndpoint stored agentRuntimeVersion without resolving
it against the runtime, so a version that was never published produced a READY
endpoint whose generated runtime ARN resolves to nothing. Both now reject one
the runtime has not published.

Tag operations resolved a resource from the ARN's id suffix alone, so an ARN
naming another account or region but a local id reached the local runtime or
gateway and could read or change its tags. The shared tag dispatch now checks
both fields against the request, which covers runtimes and gateways in one
place, and reports not found rather than a validation error so the response
does not confirm what sits behind the foreign identity.
2026-08-15 16:24:46 -04:00
sheldon-nadarajah-sft 0818e5e2d6 fix(appconfig): accept top-level resource ARNs in TagResource/ListTagsForResource (#2279)
* fix(appconfig): accept top-level resource ARNs in TagResource/ListTagsForResource

AppConfigTagHandler#parseArn hardcoded the assumption that every AppConfig
resource ARN nests under application/... - true for environment and
configurationprofile, but AWS documents deploymentstrategy, extension, and
extensionassociation as top-level, taggable resources (see e.g. the Tags
property on AWS::AppConfig::DeploymentStrategy/Extension/ExtensionAssociation).
A deploymentstrategy/{id} ARN has parts[0] == "deploymentstrategy", not
"application", so it fell through to the 400 at the end of parseArn.

Adds a TOP_LEVEL_TYPES set for the three non-nested taggable types and checks
it before the application/ branch. Tag storage for these types remains a
no-op (same existing precedent as environment/configurationprofile) - this
fixes the ARN-shape rejection, not tag persistence for new resource types.

Verified real AWS support for all three via CloudFormation's own resource
docs before scoping the fix, since a shared ARN-parsing helper is an easy
place to fix one AWS-compatibility gap while introducing another (e.g.
hostedconfigurationversion, which the existing parts.length==6 branch
already over-accepts despite AWS not supporting tagging it at all - left
untouched here as a separate, pre-existing issue, out of scope for this fix).

* docs(appconfig): clarify no-op-tag javadoc, rename a misleadingly-named test

Review feedback on #2279 (Copilot):

- The class javadoc singled out hostedconfigurationversion as an
  example of something AWS doesn't support tagging for, but the
  existing parts.length==6 branch already accepts (and no-ops) that
  exact ARN shape - describing current behavior generally instead
  (application persisted, everything else recognized-but-no-op) rather
  than calling out one type as if it were rejected.
- Renamed tagExtensionAndExtensionAssociationArnsAreAcceptedNotRejected
  to listTagsForExtensionAndExtensionAssociationArnsIsAcceptedNotRejected
  - the test only ever calls GET (ListTagsForResource), never POST
    (TagResource), so the old name would mislead anyone reading a
    failure.

AppConfigIntegrationTest: 25/25 passed.
2026-08-15 13:06:26 -04:00
Dixit R Jain b45de1bb7d feat(s3tables): emulate metadata service (#2322)
* feat(s3tables): emulate metadata service

* fix(s3tables): serialize metadata updates
2026-08-15 12:48:27 -04:00
Kenshin Okinaka ff0201a13a feat(ses): add DKIM actions with domain-inherited email DKIM (#1904)
* feat(ses): add DKIM actions with domain-inherited email DKIM

Adds three DKIM actions and aligns DKIM status with AWS:

- v1 SetIdentityDkimEnabled: toggles the signing flag only (unknown identity ->
  InvalidParameterValue).
- v1 VerifyDomainDkim: returns a domain's three DKIM CNAME tokens (stable across
  calls), registering the domain as pending if absent.
- v2 PutEmailIdentityDkimSigningAttributes (PUT .../dkim/signing): sets the
  signing origin (AWS_SES Easy DKIM, regenerating tokens when the key length
  changes; EXTERNAL BYODKIM), returning DkimStatus + DkimTokens.

DkimVerificationStatus now tracks DNS record detection (via the Route53 lookup
in refreshIdentityState) rather than the enabled flag, so setDkimAttributes no
longer forces the status; the v1-native InvalidParameterValue is remapped to
BadRequestException on the v2 path. An email identity inherits its parent
domain's DKIM (SigningEnabled/Status/Tokens), matching AWS. Adds the
SigningAttributesOrigin / signing key length / last-key-generation fields to the
DkimAttributes response (LastKeyGenerationTimestamp is emitted as epoch seconds,
matching the SES v2 wire format).

Includes an AWS Java SDK compatibility test that exercises all three actions and
the email-inherits-domain behavior end-to-end.

* fix(ses): decouple DKIM status from signing flag and reject DKIM signing on email identities

- refreshIdentityState no longer gates the DkimVerificationStatus -> Success
  transition on isDkimEnabled(), so a domain with the expected CNAMEs reaches
  Success even when DKIM signing is disabled (status tracks DNS detection).
- putDkimSigningAttributes now rejects an email-address identity with
  BadRequestException ("The EmailIdentity value must be a valid domain."),
  matching real AWS — previously it mutated state the email would just inherit
  back from its parent domain on every read.

* fix(ses): report domain DKIM as NotStarted on create, Pending on read

CreateEmailIdentity now returns DkimAttributes.Status=NOT_STARTED for a new
domain (SES has not begun tracking the CNAMEs yet); the first GetEmailIdentity
/ ListEmailIdentities refresh transitions it to PENDING, matching AWS. The
signing-enabled flag no longer gates the NotStarted->Pending transition, so a
disabled domain still reports PENDING on read.

* fix(ses): reject blank identity on PutEmailIdentityDkimSigningAttributes with a 400

A blank or whitespace EmailIdentity fell through to a NotFoundException (404) instead
of the validation error AWS returns. AWS rejects a missing/blank value with the same
400 "The EmailIdentity value must be a valid domain." as an email-shaped identity
(verified), so extend the guard to also cover null/blank.

* docs(ses): clarify DKIM inheritance is from the exact parent domain

An email inherits DKIM only from an exactly-matching registered parent domain, not from a
verified ancestor — a verified example.com does not cover user@mail.example.com unless
mail.example.com is itself registered (verified against AWS). Note this in the DKIM
paragraph so "parent domain identity when one is registered" isn't read as ancestor coverage.
2026-08-15 09:26:37 -04:00
JinHwanKim 3fe836aa16 fix(s3): verify SigV4 signature on presigned URLs when enforce-auth is enabled (#1842)
* fix(s3): verify SigV4 signature on presigned URLs when enforce-auth is enabled

* test(s3): use real SigV4 signatures in presigned URL auth enforcement tests

* test(s3): assert tampered presigned signature is rejected

* fix(s3): construct presigned canonical query per SigV4 encoding rules

* test(s3): cover presigned canonical query edge cases

Extract canonical query construction into a package-private buildCanonicalQueryString method and add unit tests for the SigV4 encoding, ordering, empty-value, duplicate-name, and signature-exclusion branches.

* test(s3): add SDK-signed presigned URL regression tests

Add integration tests that generate presigned URLs with the AWS SDK S3Presigner (an independent signer) under enforce-auth: both original URLs succeed, transplanting object A's path onto object B's query is rejected with 403 SignatureDoesNotMatch, reordered and special-character queries still verify, expired URLs and malformed credentials are rejected, and an IAM-issued access key verifies. Adds the aws-sdk s3 test dependency.

* fix(s3): collapse sequential spaces in signed header values per SigV4

Canonical values for non-host signed headers were only trimmed. SigV4 also collapses sequential spaces to a single space, so a valid presigned request carrying such a header could be rejected. Extract canonicalizeHeaderValue and add unit coverage.

* style(s3): log caught exception in presigned SigV4 verification

The catch block silently returned false. Log at debug per repo style so a swallowed exception can be diagnosed.

* test(s3): move SDK presigned URL tests to compatibility-tests

Move S3PresignedUrlSdkIntegrationTest from the main project to
compatibility-tests/sdk-test-java and remove the aws-sdk s3 test
dependency from the main pom.xml per CONTRIBUTING.md guidelines.

* fix(s3): read X-Amz-Content-Sha256 instead of hardcoding UNSIGNED-PAYLOAD

* fix(s3): reject presigned URLs with X-Amz-Expires outside 1-604800

* fix(s3): reject presigned URLs with unsupported X-Amz-Algorithm
2026-08-14 23:52:46 -05:00
Alex BannaandAlexander Banna e4010ec12f feat(rds): model DB proxies and their target groups (#1813)
* feat(rds): model DB proxies and their target groups

Add DB proxies as first-class RDS resources for both the RDS Query API
and CloudFormation:

- RdsService: two persisted stores plus the proxy lifecycle
  (create/register-targets/describe/delete). A proxy exposes a bare-host
  endpoint on the engine family's default port; in non-mock mode
  registering a target starts an auth relay (via RdsProxyManager) that
  forwards 1:1 to the target cluster/instance, re-armed on restart.
- RdsQueryHandler: CreateDBProxy, DeleteDBProxy, RegisterDBProxyTargets,
  DescribeDBProxyTargetGroups, DescribeDBProxyTargets, and a real
  DescribeDBProxies listing (2014-10-31 XML shapes).
- AwsQueryController: route the six DBProxy actions to RDS.
- CloudFormation: provision/delete AWS::RDS::DBProxy and
  AWS::RDS::DBProxyTargetGroup.

This models DB proxies for provisioning and discovery; it does not add
real connection pooling (the relay forwards 1:1), so it does not close
#1679.

* fix(rds): reserve DB proxy port so same-engine proxies get distinct ports

createDbProxy used the engine family's default port (5432/3306/1433)
directly without reserving it, so two proxies for the same engine got
the identical port and the second relay failed to bind in non-mock
mode. Reserve the default port via reserveOrAllocateProxyPort, falling
back to an allocated pool port when it is already taken — the first
proxy keeps the clean bare-host default port, later ones get a distinct
port, and the persisted port stays canonical across restarts.

* fix(rds): harden DB proxy lifecycle compatibility

* fix(rds): complete DB proxy compatibility hardening

* fix(rds): make DB proxy lifecycle rollback-safe

* fix(rds): default omitted proxy target group

* test(dynamodb): retain Quarkus port for cleanup

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-14 23:34:56 -05:00
lex00 42a79a7fd7 feat(ec2): DescribeVpcEndpointServices returns the common interface services with AZs (#2007)
* feat(ec2): DescribeVpcEndpointServices returns the common interface services with AZs

The empty service set aborted CDK InterfaceVpcEndpoint synthesis
(lookupSupportedAzs calls this at synth time). Now returns the standard
com.amazonaws.<region>.<service> interface services (ec2, ssm, logs,
sts, secretsmanager, kms, ecr, ecs, lambda, iot.data, ...) plus s3, each
with the region's AZs and serviceType, honoring a ServiceName filter.

Fixes #2004

* fix(ec2): DescribeVpcEndpointServices echoes an explicit ServiceName with all AZs

An explicit ServiceName filter (CDK InterfaceVpcEndpoint queries a
specific, often custom, service name) now returns exactly that service in
every AZ, instead of an empty AZ set when the name isn't in the built-in
list — which failed synth with 'lookupSupportedAzs returned <> but
subnets have AZs ...'.

* test(ec2): pin the s3-Gateway and ecr.api-Interface pairing in the endpoint-services test

* fix(ec2): report both endpoint types for S3 and update the SDK compatibility test

Two gaps flagged in review.

S3 is the one service with both a Gateway and an Interface offering, and AWS
reports both on its single service detail. The handler emitted Gateway only,
despite the comment above the loop saying otherwise, so an interface-endpoint
lookup for S3 found nothing.

The Java SDK compatibility suite still asserted that serviceNames and
serviceDetails come back empty, which the populated response violates. It now
asserts what the endpoint actually returns: the S3 detail carrying both types,
an interface-only service, and non-empty availability zones.
2026-08-14 22:59:47 -04:00
Kenshin Okinaka 80d1dc732e feat(ses): implement PutAccountVdmAttributes and return VdmAttributes from GetAccount (v2) (#2265)
* feat(ses): implement PutAccountVdmAttributes and return VdmAttributes from GetAccount (v2)

Add the SES v2 PutAccountVdmAttributes action (PUT /v2/email/account/vdm) and surface the
account's VDM settings in GetAccount under VdmAttributes. The settings (VdmEnabled,
DashboardAttributes.EngagementMetrics, GuardianAttributes.OptimizedSharedDelivery — each an
ENABLED/DISABLED FeatureStatus) are stored per region and round-trip through GetAccount. VDM
is opt-in, so each flag defaults to DISABLED. An invalid FeatureStatus value is a
BadRequestException, matching AWS; Floci stores the settings but does not run VDM analytics.

* fix(ses): reject non-string FeatureStatus values in PutAccountVdmAttributes

parseFeatureStatus coerced any JSON node via asText(), so a boolean or
object VdmEnabled produced a misleading enum error instead of being
rejected as a type mismatch. Guard on isTextual() before matching the
ENABLED/DISABLED enum, consistent with the other SES v2 parsers.

* fix(ses): match AWS GetAccount VdmAttributes shape

GetAccount always emitted VdmAttributes with the nested Dashboard/Guardian
objects. AWS instead omits VdmAttributes entirely until VDM has been
configured for the region, and once present adds the Dashboard/Guardian
sub-objects only while VdmEnabled is ENABLED. Return VdmAttributes only
when the region has stored VDM state, and gate the nested objects on the
stored VdmEnabled flag.

* test(ses): record live-AWS confirmation that unconfigured VDM omits VdmAttributes

eu-west-1 and ap-northeast-1 (never configured) omit the VdmAttributes key,
while a configured-then-disabled region reports VdmEnabled DISABLED.
2026-08-14 21:45:16 -04:00
Andre Kurait ecad6acf58 feat(swf): add Simple Workflow Service emulation (#2257)
* feat(swf): add Simple Workflow Service emulation

Implements all 39 SWF operations over the JSON 1.0 protocol
(X-Amz-Target: SimpleWorkflowService.*): domain and type registration,
the workflow execution state machine, and the decider/worker task
lifecycle.

Behaviour was derived from botocore's swf-2012-01-25 model and verified
against the live service, which drove several details that are easy to
get wrong from the model alone:

- Faults carry a namespaced __type (com.amazonaws.swf.base.model#Fault)
  in the body but the bare fault name in x-amzn-query-error. botocore
  prefers the header, so a namespaced value there makes the CLI print
  "com.amazonaws.swf.base.model#UnknownResourceFault" where SWF prints
  "UnknownResourceFault". SwfException keeps the two spellings apart.
- Timestamps are epoch-second numbers, not ISO strings.
- Void operations answer 200 with an empty body rather than {}.
- An idle poll returns taskToken "" rather than omitting the member;
  the SDKs read the empty token as "no task".
- ActivityTaskTimedOut reports startedEventId 0 for a task that never
  started, and WorkflowExecutionStarted reports parentInitiatedEventId 0
  on root executions, rather than omitting either member.

State machine:

- One decision task outstanding per execution. Events arriving while one
  is outstanding set a pending flag that is satisfied when it completes,
  so a signal cannot produce two concurrent decision tasks.
- Decisions apply in order; a decision after a closing decision is
  dropped. A decision that cannot be applied appends its *Failed event
  with the AWS cause and gives the decider a fresh task instead of
  failing the request.
- Closing with open activities, timers, or children appends
  UNHANDLED_DECISION and leaves the execution open.
- Timeouts (activity schedule-to-start, start-to-close,
  schedule-to-close, heartbeat; decision start-to-close; execution
  start-to-close; timers) expire from one background sweep rather than a
  timer per task, so a restart leaves nothing to reconcile.
- Child executions link to their parent and report their outcome back;
  the closing parent's childPolicy is applied to open children.

Tests: 29 unit tests drive timeout expiry through a controllable clock,
32 integration tests assert the wire shapes and fault strings captured
from the live service, and a compatibility suite exercises the same
flows through the AWS SDK v2 client so responses must deserialize into
the generated model and faults into typed exceptions.

Long polling, ScheduleLambdaFunction invocation, and retention-based
pruning are not implemented; docs/services/swf.md records each.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): report the child-started event id on ChildWorkflowExecution* events

A ChildWorkflowExecution* event carries two correlation ids, and they point at
different events in the parent's history: initiatedEventId is the
StartChildWorkflowExecutionInitiated id, startedEventId is the
ChildWorkflowExecutionStarted id. Both were reported as the initiated id, so a
decider correlating a child's outcome on startedEventId matched the wrong event.

Verified against the live service, where a parent that starts one child and sees
it complete produces:

  5 StartChildWorkflowExecutionInitiated
  6 ChildWorkflowExecutionStarted        {initiatedEventId: 5}
  8 ChildWorkflowExecutionCompleted      {initiatedEventId: 5, startedEventId: 6}

The child now records the parent's ChildWorkflowExecutionStarted id at start
time and reports it back on every ChildWorkflowExecution* event.

The integration test asserts both ids against the events they name rather than
against a "greater than zero" placeholder, and fails on the previous behaviour
with "startedEventId Expected: <6> Actual: <5>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): reject a decision batch whose closing decision is not last

RespondDecisionTaskCompleted accepted a batch with decisions after a closing
decision and silently dropped the remainder. The live service rejects the whole
batch instead:

  HTTP 400
  {"__type":"com.amazon.coral.validate#ValidationException",
   "message":"Close must be last decision in list"}

Silently accepting it hides a decider bug and diverges on both the status code
and the response body, so a decider that ships a malformed batch sees success
locally and a 400 against AWS.

The batch is now validated before any state is mutated, matching the live
service's behaviour of leaving the decision task outstanding so the decider can
retry with a corrected batch. Note this fault is namespaced
com.amazon.coral.validate rather than com.amazonaws.swf.base.model.

Tests assert the status code, both fault spellings, the message, that no
DecisionTaskCompleted event is appended, and that the same task token still
works afterwards. They fail on the previous behaviour with "Expected status code
<400> but was <200>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): name the scheduled event when an activity task has already closed

An activity task token that resolves to a task which is no longer open reported
"Unknown or expired task token". The live service distinguishes the two cases: a
genuine token whose task has closed names the scheduled event instead, because
the token itself was valid.

Captured from the live service, heartbeating a task that a cancel had already
closed:

  HTTP 400
  {"__type":"com.amazonaws.swf.base.model#UnknownResourceFault",
   "message":"Unknown activity, scheduledEventId = 5"}

Both cases are UnknownResourceFault, so SDK error typing was already correct and
only the message diverged — but a worker that logs or matches on the message sees
a different string locally than against AWS.

A token that never existed still reports the bad token; only a resolved token on
a closed task reports the scheduled event. This required keeping the token's map
entry when an activity closes, since removing it made both cases indistinguishable;
reuse is still refused by the existing open-state check.

Test asserts both branches and fails on the previous behaviour with "expected:
<Unknown activity, scheduledEventId = 5> but was: <Unknown or expired task token>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): serialize execution mutation per domain and guard the sweep interval

Addresses three review findings.

Concurrent StartWorkflowExecution calls for one workflowId all scanned for an
open run before any of them inserted, so each persisted its own run key. Eight
concurrent starts produced eight open runs where SWF admits one, and later
operations without a runId then selected an arbitrary run. The open-run check
and the insert are now one atomic step.

A closing execution mutates its parent (ChildWorkflowExecution* events) and its
children (childPolicy), but held only its own lock, so event-id allocation and
the history list raced. Six children closing against one parent reproduced
ConcurrentModificationException.

Both come from the same mismatch: the lock was per execution while the
invariants span an execution family. The lock is now per domain. A parent and a
child always share a domain, so one lock covers the family and never has to be
nested — nesting would deadlock, since a closing child takes its parent while a
closing parent takes its children. Per-domain granularity is sufficient here:
the emulator serves a single developer's workload, not production concurrency.

A zero or negative timeout-sweep interval reached scheduleWithFixedDelay, which
threw IllegalArgumentException out of the StartupEvent observer and stopped the
whole emulator becoming ready — one bad SWF setting taking down every other
service. A non-positive interval now falls back to 1s with a warning.

Tests fail on the previous behaviour with "expected: <1> but was: <8>",
ConcurrentModificationException, and IllegalArgumentException respectively.
Verified over the wire too: eight concurrent starts yield one success, seven
WorkflowExecutionAlreadyStartedFault, and one open run.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): report the live service's TypeNotDeprecatedFault message

DeleteWorkflowType/DeleteActivityType against a still-registered type
reported the type descriptor, e.g. "WorkflowType=[name=W, version=1]". The
live service answers with prose instead, and uses the same wording for both
type kinds:

  {"__type":"com.amazonaws.swf.base.model#TypeNotDeprecatedFault",
   "message":"The type is currently registered and cannot be deleted in its
              current state"}

Since both variants are identical, the two fault factories collapse into one.
The descriptor form is still correct for the other type faults
(TypeDeprecatedFault, TypeAlreadyExistsFault, UnknownResourceFault), which were
verified unchanged in the same probe.

Also adds integration coverage for the five actions that had none at either
test layer: DeprecateActivityType, UndeprecateActivityType, DeleteActivityType,
ListWorkflowTypes, and RespondActivityTaskFailed. Every assertion is taken from
a live-service capture, including that scheduling a deprecated activity type
appends ScheduleActivityTaskFailed with cause ACTIVITY_TYPE_DEPRECATED and
leaves the execution open, that ListWorkflowTypes filters by registration
status and name, and that a second RespondActivityTaskFailed on the same token
reports "Unknown activity, scheduledEventId = 5".

The message tests fail on the previous behaviour with "Expected: The type is
currently registered ... Actual: WorkflowType=[name=TestWf, version=1.0]".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* feat(swf): invoke real Lambda functions for ScheduleLambdaFunction

The decision was recorded as ScheduleLambdaFunctionFailed with cause
LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION rather than invoking anything. SWF is
otherwise a pure coordination service — deciders and activity workers are the
user's own processes, so there is no user code for the emulator to run — but
ScheduleLambdaFunction is the one decision where SWF itself executes something,
and Floci already runs Lambda functions in containers. A decider that fans work
out to Lambda could not be exercised locally at all.

Floci now invokes the function through its own Lambda service, the same way the
EventBridge and Scheduler invokers do, and records the outcome. Verified against
the live service:

  5 LambdaFunctionScheduled  {control, id, input, name, startToCloseTimeout}
  6 LambdaFunctionStarted    {scheduledEventId: 5}
  7 LambdaFunctionCompleted  {result, scheduledEventId: 5, startedEventId: 6}
  8 DecisionTaskScheduled

Four behaviours came from that capture and are easy to get wrong:

- A function that cannot be resolved is LambdaFunctionFailed with Lambda's own
  error code as reason (ResourceNotFoundException) — not
  ScheduleLambdaFunctionFailed — and it still reports Started first.
- An execution with no lambdaRole never starts the function at all: Scheduled is
  followed by StartLambdaFunctionFailed with cause ASSUME_ROLE_FAILED and the
  message "No IAM role is attached to the current workflow execution."
- lambdaRole resolves from StartWorkflowExecution's lambdaRole, falling back to
  the workflow type's defaultLambdaRole, and is echoed in the started event.
- An absent input reaches the handler as {}, and reusing an id is accepted —
  there is no ID_ALREADY_IN_USE for Lambda the way there is for activity ids.

SwfService takes a LambdaInvoker seam rather than LambdaService directly, so the
unit tests keep running without a Docker daemon while SwfLambdaInvoker wires the
real thing at runtime. The invocation is RequestResponse because the response
body is what gets recorded as result; the fire-and-forget invokers use Event for
the opposite reason.

The Lambda region comes from the execution's domain ARN, so a workflow in one
region does not invoke a function in another.

Tests: SwfServiceTest covers all four paths against a recording invoker and
fails on the previous behaviour with "the function must actually be invoked
==> expected: <1> but was: <0>". SwfLambdaIntegrationTest and the SDK
compatibility SwfLambdaTest deploy a real function and assert the recorded
result is what the container returned, so neither passes against a synthesised
event. Docker-backed cases live in their own class so a Docker-less run loses
only them rather than the whole SWF wire suite.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): scope state by region and paginate the registration lists

Addresses two AWS compatibility gaps from review.

SWF names are unique per region, but storage keys were the bare name, so
registering a domain in us-east-1 made the same name in eu-west-1 fail as a
duplicate, and describe/list could return the first region's domain and ARN.
Verified against the live service: the same name registers in both regions with
independent descriptions and retention periods, each ARN naming its own region;
a type registered in one region answers UnknownResourceFault in the other; and
executions, including their runIds, do not cross.

Keys are now region-qualified — `<region>:<domain>` for domains,
`<region>:<domain>/<name>/<version>` for types, and
`<region>:<domain>/<workflowId>/<runId>` for executions — and every store scan
is prefixed by region. The region reaches the service on each call and is stored
on the execution, which is also what task tokens resolve through, so a token
issued in one region cannot address another's execution. The per-domain
mutation lock is region-qualified too; leaving it bare would have let two
regions serialize against each other, and would have disagreed with the
sweeper's own lock derived from the storage key.

ListDomains, ListWorkflowTypes and ListActivityTypes ignored maximumPageSize and
nextPageToken and returned everything. They now share one paging helper with the
history and execution listings. Details taken from live captures rather than the
docs: nextPageToken is absent on the final page even when that page is exactly
full, a maximumPageSize of 0 or absent means "no caller limit", above 1000 is
rejected rather than clamped, and a corrupt token answers
`ValidationException: Invalid token` instead of silently restarting at the first
page — which would make a paging loop repeat forever.

Adds AWS SDK regression tests (SwfRegionPaginationTest) driving two clients at
different regions against the same emulator, plus wire-level integration
coverage. Against the previous implementation those SDK tests fail with
DomainAlreadyExists on the second region, "maximumPageSize must cap the page: 5",
and nothing thrown for an oversized page size.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): pin reverseOrder as applying before pagination

The registration lists reverse the whole result set and then page it, so with
maximumPageSize=3 and reverseOrder=true the first page is the tail of the
ascending order. That was already the behaviour but nothing asserted it, and the
shared paging helper makes "page first, then reverse the page" an easy
regression to introduce.

Measured against the live service: 5 types at page size 3 reversed returns
Paged4, Paged3, Paged2 and then Paged1, Paged0. Injecting the page-then-reverse
ordering fails the new test with
"Expected: <[Paged4, Paged3, Paged2]>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): cover region scoping at the wire level

The region-scoping tests went in at the service and SDK layers, but every
SwfIntegrationTest request omitted an Authorization header, so nothing asserted
that the region is read from the SigV4 credential scope — the step that decides
which region's state a call addresses.

Adds a wire test that sends a credential scope naming the region, covering the
same name registering in two regions with independent descriptions, retentions
and ARNs, a type being unknown in the other region, and a same-region
re-registration still faulting.

Against 7cc6c0f2 the test fails with
DomainAlreadyExistsFault / "Expected status code <200> but was <400>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): correct four decision, polling and locking cases from review

An invalid decision anywhere in a batch could still mutate the execution.
respondDecisionTaskCompleted appended DecisionTaskCompleted, dropped the token
and applied earlier decisions before applyDecision's default arm rejected an
unknown decisionType mid-loop, so [RecordMarker, NotARealDecision] grew the
history from 3 to 5 events and burned the token. A try/catch cannot undo that —
decisionTokens is a separate map and the history lands on the in-memory
execution — so the whole batch is now validated up front, extending the shape
requireCloseIsLastDecision already used. Both rules live in one requireValidBatch,
and the accepted types come from SwfConstants.DECISION_TYPES so the check and the
message quoting the enum set cannot drift.

PollForDecisionTask with a nextPageToken claimed a new task instead of paging the
original. AWS states that "calling PollForDecisionTask with a nextPageToken
doesn't return a new decision task", and the live service answers a continuation
with the same startedEventId, previousStartedEventId and workflowExecution, plus
the next contiguous history page. The continuation token now names the task it
belongs to, so a continuation resolves that task rather than polling again.
startAtPreviousStartedEvent was modeled but read nowhere; it now trims the window
to events from previousStartedEventId onward, which the live service treats as
inclusive.

A child that continued as new lost its parent. The successor was built from a
StartWorkflowExecutionRequest, which carries no parent fields, so its parent was
null and the parent kept tracking the closed run — never learning the successor's
outcome and never applying child policy to it. carryParentTo moves the parent
identifiers and repoints the parent's childExecutions entry before the successor's
WorkflowExecutionStarted is appended, so that event names the parent as it does
on the live service.

The Lambda invocation held the domain lock. That lock deliberately covers a whole
domain family, so a cold start stalled every unrelated execution in the domain.
A decision now queues the invocation, records LambdaFunctionScheduled and
LambdaFunctionStarted under the lock, and the invocation runs after the lock is
released; the outcome is recorded under the lock again, so the state transition
around the result stays atomic.

Guards, each failing on the code before it: the batch case with
"a rejected batch must not grow the history ==> expected: <3> but was: <5>", the
continue-as-new case with "the successor of a child must keep its parent ==>
expected: <wf-cn-parent> but was: <null>", the two polling cases on an empty
continuation response, and the liveness case by blocking inside the invoker and
signalling an unrelated execution in the same domain.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* refactor(swf): collapse the paging helpers into one, and cap every operation

Three page-token codecs and three copies of the same offset/limit/token block had
accumulated across the history, execution and registration listings, plus a
fourth for the PollForDecisionTask continuation. There is now one Page record
with one encode/decode pair — the task token is an optional field, which is the
only thing the poll needed — and one pagedList helper the history and execution
listings reuse. Net 62 fewer lines in the service and handler.

Collapsing the two page-size methods surfaced a real divergence rather than just
shortening code: historyPageSize clamped an oversized maximumPageSize while the
registration lists rejected it. The live service rejects it everywhere, measured
on GetWorkflowExecutionHistory, ListOpenWorkflowExecutions and
PollForDecisionTask, and rejects a negative value with its own message
("greater than or equal to 0"). One pageSize method now serves all of them.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* docs(swf): document batch atomicity, poll continuation and the page-size cap

The three behaviours the last two commits changed were only visible in the code: a decision batch is all-or-nothing, a PollForDecisionTask continuation pages the same task rather than claiming a new one (and startAtPreviousStartedEvent is inclusive), and the 1000 page-size cap applies to every paginated operation rather than only the registration lists.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): render the decisionType enum set in the service's own order

The rejection message for an unknown decisionType listed the enum members in the
API model's order. The live service uses a different order, stable across
repeated calls, so a client comparing the message byte-for-byte saw a mismatch:

  service: [CompleteWorkflowExecution, StartTimer, RequestCancelExternal...
  model:   [ScheduleActivityTask, RequestCancelActivityTask, CompleteWork...

Taken from four live responses rather than from the model. The guard now asserts
the whole message instead of a substring, and fails on the previous order with
the two strings diffed in full.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): scope queued Lambda work to the request, not the thread

The queue of deferred invocations was a ThreadLocal drained after the domain lock
was released. On a pooled request thread that outlives the request: if anything
threw between queueing an invocation and draining, the work stayed on the thread
and the next decision response ran it — invoking a real function for a request
that had already failed, and recording the outcome against whatever state that
later execution was in.

The queue is now a local list created per call and threaded through
applyDecisions, so the drain is reachable only after the batch has been applied
and stored. A request that throws leaves the list unreferenced; there is no
cross-request carrier left to leak through.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): guard that a failed batch leaves no queued Lambda work

Reaches the leak window by failing the execution store after a Lambda has been queued and the history mutated, then issuing a second request on the same thread.

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
2026-08-14 11:16:21 -04:00
Alex Banna 5657e35007 feat(cloudfront): enforce signed private content (#1831)
* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): enforce signed private content

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

* fix(cloudfront): wildcard aliases match exactly one subdomain level

wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched
a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the
wildcard at that level only:

  "you can't add alternate domain names that are at levels higher or lower than the
   wildcard. For example, you can't add the alternate domain names example.com or
   marketing.product.example.com."

  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

Practical effect: a distribution owning "*.example.com" would answer for
a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to
nobody. Require the label standing in for the wildcard to contain no dot.

wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour
(a.b.example.test resolving to the *.example.test distribution); it now asserts no
match, plus the same for a deeper wildcard.

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix(cloudfront): match wildcards in signed policy queries
2026-08-13 23:32:24 -04:00
Alex Banna 97ac3cabb5 feat(stepfunctions): add UpdateStateMachine and update in place on stack updates (#1867)
* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): preserve log group on failed rename

* fix(cloudformation): scope update rollback to attempted resources

* fix(cloudformation): delete resources after stack updates

* test(cloudformation): wire cloudfront fixture dependency

* fix: include Step Functions update date in describe response

* fix: preserve Step Functions describe response shape

* fix: preserve generated Step Functions names
2026-08-13 22:36:15 -04:00
Saatvik Arya 4215006fe2 feat(logs): support log group deletion protection (#2256)
* fix(logs): accept log group deletion protection lifecycle

* feat(logs): support log group deletion protection
2026-08-12 22:39:39 -04:00
Alex BannaandAlexander Banna a29464abc7 feat(dynamodb): global-table v2 replicas (UpdateTable ReplicaUpdates + Custom::DynamoDBReplica) (#1811)
* feat(dynamodb): support global table replicas

* fix(dynamodb): validate replica updates before mutation

* fix(dynamodb): align replica compatibility behavior

* chore: rerun CI after download outage

* fix(dynamodb): document replica update semantics

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 20:18:42 -04:00
Alex BannaandAlexander Banna d9e4447aeb feat(cloudformation): resolve dynamic references in RDS credentials (#1809)
* feat(cloudformation): resolve dynamic references in RDS credentials

* test(cloudformation): pin secret resolution failures

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 19:38:51 -04:00
Alex BannaandAlexander Banna bc21367cc4 feat(cloudformation): provision AWS::Events::EventBus as a real custom bus (#1807)
* feat(cloudformation): provision EventBridge event buses

* fix(cloudformation): restore main's provisioner changes lost in the EventBus merge

The previous conflict resolution took this branch's whole
CloudFormationResourceProvisioner, which silently reverted five commits main had
landed on that file since the merge base — including the DynamoDB/Lambda delete
idempotency from #1803 and AWS::EC2::LaunchTemplate from #1973.

Re-resolve from main's file and apply only this branch's EventBus additions on
top: the ownership-tracking provisioner, its validation helpers, and the typed
rethrow in deleteEventBridgeRuleSafe. main's provisionEventBusPolicy and inline
Policy support are kept, with Policy added to EVENT_BUS_SUPPORTED_PROPERTIES so
the inline form is no longer rejected.

* fix(cloudformation): delete EventBus resources created before ownership tracking

deleteEventBusSafe(StackResource) refused to delete whenever the
FlociEventBusCreatedTime attribute was absent, treating "ownership not tracked"
the same as "ownership changed". Stacks provisioned by an earlier Floci build are
restored from cloudformation-stacks.json without that attribute, so the first
DeleteStack after upgrading left them permanently in DELETE_FAILED.

Only refuse when a recorded created-time actually disagrees with the live bus.
A missing attribute falls back to the pre-tracking behaviour of deleting what the
stack recorded it created.

* fix(cloudformation): adopt untracked EventBus on update and record identity before the policy call

Two provision-side defects, both surfaced in review:

UpdateStack broke for stacks provisioned before FlociEventBusCreatedTime existed.
Those resources are restored without the attribute, so the adoption guard's
'existingCreatedTime == null' arm re-threw ResourceAlreadyExists on every update,
including no-ops. Same inverted guard the delete path already uses: only a recorded
time that actually disagrees means the bus was recreated out of band.

The bus also leaked when Policy application failed. r.setPhysicalId ran after
putPermission, and rollbackCreatedResources skips resources whose physicalId is
null, so a malformed policy left a live bus rollback could not find. Identity and
ROLLBACK_OWNED_ATTR are now recorded before the policy call, matching how
provisionIamRole marks a freshly created role. The attribute is cleared on the
adoption path so rollback never deletes a bus this stack did not create.

* chore: re-run CI

Build and Test failed on RuntimeApiServerTest's extension/stop race, a pre-existing
flake unrelated to this change (no CloudFormation test failed). Root-caused separately:
test-timing half in #2141, server-side shutdown-ordering half filed as an issue.

* fix(cloudformation): adopt tagged pre-tracking event buses

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): reject unsafe EventBus policy updates

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:38:17 -04:00
Alex BannaandAlexander Banna e1f389f61b feat(lambda): support EFS file system configs (#2053)
* feat(lambda): support EFS file system configs

* fix(lambda): prevent stale and shared EFS mounts

* fix(lambda): isolate warm pools by version

* test(dynamodb): retain Quarkus port for cleanup

* fix(lambda): scope warm pool invalidation by environment

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:12:39 -04:00
Aniket Shukla 2f5bc39680 fix(s3vectors): return cosine distance from queries (#2175)
* fix(s3vectors): return cosine distance from queries

Convert cosine similarity to the AWS-compatible distance value and sort query results nearest-first.

* fix(s3vectors): honor query distance response flag

* test(s3vectors): request query distances explicitly
2026-08-12 13:51:45 -04:00
Kenshin Okinaka cd3588b517 feat(ses): honor ConfigurationSetName on CreateEmailIdentity (v2) (#1812)
* feat(ses): honor ConfigurationSetName on CreateEmailIdentity (v2)

CreateEmailIdentity now reads the optional ConfigurationSetName and sets it as
the identity's default configuration set, surfaced by GetEmailIdentity. Verified
against AWS: a non-existent configuration set fails with NotFoundException before
the identity is created (atomic), matching the deleted-default send behavior.

* fix(ses): treat only an empty ConfigurationSetName as absent on CreateEmailIdentity

A whitespace-only ConfigurationSetName was silently ignored (isBlank),
diverging from the PutEmailIdentityConfigurationSetAttributes path, which
routes such a name through name validation. Switch to isEmpty so both paths
reject a whitespace-only name as invalid input (400), and add coverage for
the empty (no default) and whitespace (400) cases.

* test(ses): clarify that empty-string ConfigurationSetName handling deviates from AWS

The comment on the empty-string CreateEmailIdentity test mentioned that AWS stores ""
verbatim without stating that Floci deliberately diverges (treating "" as "no default"),
which could read as if the assertion matched AWS. Reword to make the deviation and its
rationale explicit.

* docs(ses): correct the non-string ConfigurationSetName comment to match the actual response

The comment claimed AWS returns a 400 with an empty body, but the code throws a
SerializationException that AwsExceptionMapper renders as a JSON error body. Reword the
comment to describe the actual response shape.

* fix(ses): reject a non-string EmailIdentity on CreateEmailIdentity

CreateEmailIdentity read EmailIdentity via asText, which coerces a non-string JSON value
(e.g. 123 -> "123") and would silently create an identity named "123". Reject a non-string
EmailIdentity with a 400 SerializationException, matching the ConfigurationSetName handling
in the same method.

* fix(ses): validate Tags before creating the identity on CreateEmailIdentity

parseTagsArray ran after verifyEmailIdentity/verifyDomainIdentity, so a non-array Tags
value (e.g. "Tags":"oops") returned 400 but left the identity created — a half-created
state. parseTagsArray is pure, so hoist it above the create; the identity is now
persisted only after both the ConfigurationSetName and the Tags shape have been
validated, matching AWS.
2026-08-12 00:12:16 -04:00
Mihai BlidaruandMihai Blidaru a79e04e4ec fix(firehose): build S3 object keys with AWS prefix expressions and name suffix (#1858)
* fix(firehose): build S3 object keys with AWS prefix expressions and name suffix

Delivered objects now follow the AWS key format
<evaluated prefix><stream>-<version>-<yyyy-MM-dd-HH-mm-ss>-<uuid> observed on
real AWS: default prefix yyyy/MM/dd/HH/ when no Prefix is set, literal
concatenation of the time prefix for expression-free prefixes,
!{timestamp:<pattern>} and !{firehose:random-string} evaluation, no .json
extension, and CustomTimeZone support. The non-AWS {year}/{month}/{day}/{hour}
placeholders are gone.

See floci-io/floci#1857 for the behavior captured against a real AWS account.

* refactor(firehose): cache the default time-prefix DateTimeFormatter

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-08-11 21:40:24 -04:00
Maciej 0cfffbea00 fix(kms): reject mismatched keys in decryption requests (#1893)
* fix(kms): reject mismatched keys in decryption requests

* fix(kms): reject mismatched keys in reencryption requests

* fix(kms): verify if key is usable for cryptographic operations
2026-08-10 23:49:31 -04:00
Kenshin Okinaka bd01c1a70b feat(ses): implement SendCustomVerificationEmail for v1 and v2 (#2191)
* feat(ses): implement SendCustomVerificationEmail for v1 and v2

Add the SendCustomVerificationEmail action on both the v1 Query API and the v2 REST
JSON API (POST /v2/email/outbound-custom-verification-emails). The service renders the
stored custom-verification-email template into the inspection mailbox and the SMTP
relay, returns a MessageId, and registers the recipient as a pending-verification
identity, matching AWS. A missing template is the v1-native
CustomVerificationEmailTemplateDoesNotExist (remapped to NotFoundException on v2), with
the v1 send message ("Template <name> does not exist") verified against AWS.

* test(ses): log custom-verification compat cleanup failures instead of swallowing them

The @AfterAll cleanup deleted templates and identities in best-effort try/catch
blocks that swallowed every exception, so a real deletion failure would leave
state behind with no diagnostic. Log the affected template/identity and the
exception message, per AGENTS.md's rule against silently discarding exceptions.
2026-08-10 20:34:09 -04:00
Dmitriy Polomoshnov a2b20cc085 fix(dynamodb): compare Value when legacy Expected supplies Exists (#2125)
* fix(dynamodb): compare Value when legacy Expected supplies Exists

A legacy Expected entry that supplies both Exists:true and a Value was
evaluated as an existence check only — the supplied Value was silently
discarded, so any stale value passed the condition.

This is the wire form emitted by version-guarded writes, where the caller
pairs Exists:true with the version it last read:

    "Expected": {"version": {"Exists": true, "Value": {"N": "5"}}}

Because the guard was present on every request and ignored on every
request, conflicting writes were accepted with no visible symptom.

Per the documented ExpectedAttributeValue semantics, Exists:true always
carries a Value and means the attribute must exist AND equal it, which is
the same check as a bare Value. Only Exists:false is a pure absence check.
The three combinations DynamoDB documents as invalid now raise
ValidationException instead of being silently accepted:

  - Exists:true with no Value
  - Exists:false alongside a Value
  - Exists combined with ComparisonOperator / AttributeValueList

Validation runs over the whole Expected map before any condition is
evaluated. PutItem, DeleteItem and UpdateItem all route through
evaluateLegacyExpected, so the change applies to all three.

* fix(dynamodb): compare collection values in legacy EQ conditions

The EQ comparison used by legacy Expected, QueryFilter and ScanFilter
reduced a non-scalar attribute value to an empty string, so any two
values of the same collection type compared as equal. A stale
expectation on an SS, NS, BS, L or M value was therefore always
satisfied and the guarded write was applied.

EQ now delegates to the existing attributeValuesEqual helper — the same
one the ConditionExpression path uses. It is type-strict, compares
numbers via BigDecimal, recurses into M and L, and treats set types as
unordered.

* fix(dynamodb): compare number set members numerically in equality

Number set equality put the members in a HashSet<BigDecimal>, so
membership went through BigDecimal.equals, which is scale-sensitive: 1
and 1.0 were treated as different members. Because NS elements are
normalized on write while a supplied condition value is not, an
otherwise valid condition on a numerically equivalent set was rejected
and the guarded write blocked.

Membership now goes through a TreeSet, whose contains uses compareTo, so
members compare numerically. Applies to both the legacy Expected /
QueryFilter / ScanFilter EQ path and ConditionExpression, which share
this helper.

* fix(dynamodb): compare collection values in legacy NE conditions

NE had the inverse of the collapse the previous commit fixed for EQ: it
compared the scalar projections of both values, which are empty strings
for non-scalar types, so any two collections of the same type looked
equal and NE was always false. A condition asserting an attribute
differs from a set it genuinely differs from blocked the write.

NE now negates attributeValuesEqual, mirroring EQ. Null handling is
unchanged: a missing attribute or a missing comparison value still
satisfies NE.

* test(dynamodb): pin type-strict equality in legacy conditions

EQ and NE compare attribute types as well as values, so a string "5"
does not match a stored number 5. Nothing pinned that, which left room
for a refactor to reintroduce equality via scalar string projections
without any test failing.

* fix(dynamodb): match DynamoDB validation for legacy Expected entries

Verified the legacy Expected rules against DynamoDB itself and aligned
the validation with what the service actually returns.

Error messages now carry the "1 validation error detected: " prefix and
the exact wording, including "Exists and ComparisonOperator cannot be
used together", which differed from the message used before.

Two rules were missing:

  - AttributeValueList without a ComparisonOperator is rejected, and
    that check takes precedence over the Exists rules. It applies
    whether or not Exists is present.
  - An entry with neither Exists nor Value is rejected as well,
    reported as "Value must be provided when Exists is null".

DynamoDB reports only the first offending entry even when several are
invalid, so validation still stops at the first error.
2026-08-09 19:03:42 -04:00
Priamo Germosen d78520d5cb feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2) (#1914)
* feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2)

Adds the kinesisanalyticsv2 service (X-Amz-Target KinesisAnalytics_20180523.*):
a control-plane state machine plus a real Apache Flink JobManager container spun up
as a sidecar on StartApplication, modeled on the AmazonMQ->RabbitMQ pattern.

- CreateApplication -> READY, StartApplication -> STARTING -> RUNNING via a readiness
  poller, StopApplication -> READY, DeleteApplication -> removed
- Container image chosen from the requested RuntimeEnvironment (FLINK-1_15..1_20 ->
  apache/flink:1.x) via KinesisAnalyticsRuntimes, with an optional operator override;
  unsupported runtimes (SQL / Zeppelin) rejected with InvalidArgumentException
- Container naming via ContainerStorageHelper.resourceName (floci-kinesisanalytics-<name>)
- Registered in ResolvedServiceCatalog, dispatched by AwsJson11Controller; container
  teardown wired into EmulatorLifecycle.onStop
- Tests: service + handler unit tests, @QuarkusTest integration, Java SDK compatibility test
- Docs: service page, services index, README, environment-variable reference

* fix(kinesisanalytics): enforce delete/update state and version/timestamp guards

Addresses review feedback (self-review + Greptile) on the Managed Flink service:

- DeleteApplication rejects a non-READY (RUNNING/STARTING) application with
  ResourceInUseException; the caller must StopApplication first (Greptile P1)
- DeleteApplication validates the required CreateTimestamp against the stored value
- UpdateApplication validates CurrentApplicationVersionId (ConcurrentModificationException
  on mismatch, InvalidArgumentException when absent)
- StopApplication error message reads 'RUNNING or STARTING' to match the guard
- Readiness poller @PreDestroy awaits termination (bounded) before returning so a
  mid-flight write cannot race the shutdown storage flush
- Drop the unused Tags field from FlinkApplication (full tag support tracked as a follow-up)
- Compat test @AfterAll logs tolerated teardown failures (AGENTS.md) and stops before delete

Tests updated accordingly and verified live against the packaged jar.

* feat(kinesisanalytics): deploy and run the application JAR on the Flink cluster

Implements real job submission for Managed Service for Apache Flink, so the AWS
'deploy a JAR' flow actually runs the job (previously only a bare JobManager reached RUNNING):

- CreateApplication parses and stores ApplicationConfiguration (ApplicationCodeConfiguration
  S3ContentLocation + ParallelismConfiguration); DescribeApplication echoes it back as
  ApplicationConfigurationDescription
- StartApplication reads the JAR from Floci's local S3 (via S3Service), starts a JobManager plus a
  TaskManager (sharing the JobManager network namespace for localhost RPC), then uploads and runs the
  JAR via the Flink REST API (new FlinkRestClient); the app reaches RUNNING when the Flink job is RUNNING
- StopApplication cancels the job and tears down both containers
- Applications created without code still come up as a bare cluster
- Docs + README updated; unit tests for config round-trip; verified live end-to-end against the
  packaged jar (S3 JAR -> RUNNING Flink job -> stop/delete cleanup)

Not yet emulated: EnvironmentProperties injection, snapshots/savepoints, in-place code updates.

* fix(kinesisanalytics): align Flink runtimes with AWS and add the 2.x line

The runtime map now mirrors the runtimes AWS Managed Service for Apache Flink actually offers:

- Add FLINK-2_0 / 2_1 / 2_2 / 2_3 -> apache/flink:2.0/2.1/2.2/2.3 (the Flink 2.x line; FLINK-2_2 is in
  the AWS SDK RuntimeEnvironment enum and the whole 2.x line has published apache/flink images)
- Remove FLINK-1_16 / FLINK-1_17 -> AWS does not offer these runtimes, so Floci should reject them too
  rather than accept versions real AWS refuses

Supported set: FLINK-1_15, 1_18, 1_19, 1_20, 2_0, 2_1, 2_2, 2_3. Tests + docs + README updated.

* test(kinesisanalytics): cover both Flink 1.18 and 2.3 in the SDK compat test

Refactor the single-runtime compat test into an abstract ordered lifecycle run against two
runtimes, so the suite guards both the Flink 1.x and 2.x lines (Flink 2.0 changed the config
system and boots slower):

- AbstractKinesisAnalyticsV2LifecycleTest: PER_CLASS instance state + the create->start->RUNNING->
  list->stop->unsupported->delete lifecycle, parameterized on an abstract runtime()
- KinesisAnalyticsV2Flink118Test (FLINK-1_18) and KinesisAnalyticsV2Flink23Test (FLINK-2_3)
- FLINK-2_3 is passed as a string (newer than the pinned SDK 2.44.14 enum) and asserted via
  runtimeEnvironmentAsString(); RUNNING wait bumped to 300s for Flink 2.x's slower boot

Verified live: both subclasses boot real apache/flink:1.18 and :2.3 clusters and reach RUNNING
(0 skipped). CI now exercises two clusters; both skip gracefully when Docker is unavailable.

* fix(kinesisanalytics): preserve AwsException from a bad application-code S3 location

StartApplication's catch(RuntimeException) wrapped every failure from startCluster into
InternalFailureException (HTTP 500) — including the AwsException that readJar throws when the
application-code S3 object is missing/empty/unreadable. A client's bad S3 code location therefore
surfaced as a 500 server error instead of the intended InvalidArgumentException (400).

Now AwsException propagates as-is (preserving its error code and message); only unexpected
RuntimeExceptions (e.g. Docker unavailable) become InternalFailureException. Addresses Greptile P1.

* feat(kinesisanalytics): add resource tagging (TagResource/UntagResource/ListTagsForResource)

Adds Tags support to CreateApplication plus TagResource, UntagResource, and
ListTagsForResource, dispatched as regular JSON1.1 actions under the same
KinesisAnalytics_20180523 target prefix as every other action — verified
against the real botocore kinesisanalyticsv2 model that this API has no
separate REST tagging endpoint (protocol is pure "json"/1.1 with all
operations on POST /), unlike REST-JSON services (EKS, MWAA) that use the
shared /tags/{arn} controller.

Tags is a list of {Key, Value} objects on the wire (not a map), same shape
MemoryDB's handler already uses for its own tagging actions; mirrored that
parse/build pattern rather than the map-shaped TagHandler interface. Tags
are stored on FlinkApplication but, matching the real API, never echoed in
ApplicationDetail (CreateApplication/DescribeApplication) — only
ListTagsForResource returns them. TagResource enforces AWS's 50
user-defined-tag ceiling (TooManyTagsException) on both CreateApplication
and TagResource.

docs/services/kinesisanalytics.md's action table is auto-generated from the
handler source (tools/docs/regen_action_docs.py) — regenerated it and filled
in the three new rows' hand-written descriptions.

* feat(kinesisanalytics): inject EnvironmentProperties into the Flink cluster

CreateApplication now accepts ApplicationConfiguration.EnvironmentProperties
.PropertyGroups and writes them to /etc/flink/application_properties.json in
both the JobManager and TaskManager containers before the job runs — the
same well-known path and JSON shape (a list of {PropertyGroupId, PropertyMap}
objects, matching the AWS API's own PropertyGroups shape) real Managed
Service for Apache Flink uses, so a JAR written against
KinesisAnalyticsRuntime.getApplicationProperties() picks them up unmodified
against Floci. DescribeApplication echoes them back under
ApplicationConfigurationDescription.EnvironmentPropertyDescriptions
.PropertyGroupDescriptions.

/etc/flink does not exist in the stock apache/flink image, and the
container's non-root "flink" user (uid 9999) can't create it directly under
/etc (confirmed live: mkdir -p /etc/flink fails with permission denied as
that user). The fix, also verified live: name the tar entry
"flink/application_properties.json" and extract into the existing /etc
rather than targeting /etc/flink directly — the daemon-level copy API can
create the missing subdirectory as part of unpacking the archive even
though the in-container user couldn't, landing as root:root 775 (so it's
still world-readable by the flink user). A real apache/flink:1.18 container
was used to verify both the failure mode and the fix before writing the
Java implementation.

* feat(kinesisanalytics): add application snapshot (savepoint) support

Adds CreateApplicationSnapshot/DescribeApplicationSnapshot/ListApplicationSnapshots/
DeleteApplicationSnapshot. Triggers a real Flink savepoint of the running job and
polls it to completion the same way StartApplication polls job readiness. Snapshot
files land on a persistent named Docker volume mounted at /opt/flink/savepoints in
the JobManager container, so they survive a Stop/Start cycle; the volume is only
removed on DeleteApplication.

* feat(kinesisanalytics): support in-place application code updates

UpdateApplication with a new ApplicationCodeConfigurationUpdate (or
ParallelismConfigurationUpdate) now redeploys onto an already-running application
without tearing down its JobManager/TaskManager containers: the current job is
cancelled and the new JAR is uploaded and run on the same cluster, transitioning
RUNNING -> STARTING -> RUNNING the same way StartApplication submits a fresh job.
Updating a READY application just stores the new code location for the next
StartApplication. Attaching code to a running bare cluster for the first time is
not yet supported and is rejected with InvalidRequestException.

* fix(kinesisanalytics): use AWS's documented generic InternalFailure code

startApplication and updateApplication's redeploy-code path threw an invented
"InternalFailureException" for unexpected Docker provisioning failures — not a
shape kinesisanalyticsv2's model declares (no operation in this API declares any
5xx shape at all). AWS documents "InternalFailure" (no "Exception" suffix, HTTP
500) as the generic error common to every service's API; it's also already the
default used elsewhere in this codebase (JsonErrorResponseUtils, KMS, Pricing,
SES, CloudControl, EventBridge, and others).

* feat(kinesisanalytics): add CreateApplicationPresignedUrl and SnapshotsEnabled

CreateApplicationPresignedUrl returns a URL to the running application's Flink
Dashboard (UrlType: FLINK_DASHBOARD_URL only; Zeppelin/Studio isn't supported).
Floci has no real session/proxy layer for this, so it returns the JobManager
container's own REST/dashboard URL directly, while still validating UrlType and
SessionExpirationDurationInSeconds against AWS's documented constraints.

ApplicationSnapshotConfiguration.SnapshotsEnabled (default true, matching real
AWS) is now honored on CreateApplication and toggleable via UpdateApplication's
ApplicationSnapshotConfigurationUpdate; CreateApplicationSnapshot rejects the
request with InvalidRequestException while disabled.

* fix(kinesisanalytics): persist flinkJobId as soon as the job is submitted

The readiness poller only called putApplication when advanceToRunning reported
RUNNING, not when it merely assigned flinkJobId after submitting the job (which
returns false until the job state catches up). pendingJars — a separate,
in-process-only cache — is already cleared by that point, so an emulator
restart between job submission and reaching RUNNING would leave the
application stuck: no persisted flinkJobId to resume polling, and no cached
JAR left to resubmit.
2026-08-09 15:01:30 -04:00
Oliver Andrews 02288abc11 fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe* (#1740)
* fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe*

DescribeDBInstances/DescribeDBClusters returned an empty 200 when the
identifier parameter matched nothing; real AWS faults for the parameter
form and returns an empty list only for the Filters form. Track whether
the identifier came from the parameter and fault when it matched nothing,
with error codes, messages, and 404 status matching live AWS.

* fix(rds,docdb,neptune): ARN identifiers and Filters-form parity for Describe*

Review follow-ups:

- RDS, DocDB, and Neptune list methods accept an ARN (the identifier
  parameter and the db-instance-id/db-cluster-id filters both allow ARNs
  per the AWS model). The ARN is matched against each resource's stored
  ARN, so a cross-account or cross-region ARN does not resolve a
  same-named local resource.
- DocDbQueryHandler and NeptuneQueryHandler fault only for the identifier
  parameter, not the Filters form, which returns an empty list (mirror of
  the RDS fix).

* test(rds): expect NotFound faults after delete in SDK compat tests

The Go and Java compat suites asserted the old emulator behavior — an
empty 200 when describing a deleted instance/cluster by identifier. Real
AWS faults DBInstanceNotFound/DBClusterNotFoundFault there, which is what
the deletion waiters key on, and the emulator now does the same.
2026-08-08 21:48:17 -05:00
Hector Ventura 8b8f837728 fix(ecs): report service deployments and MISSING failures on DescribeServices (#2176)
* fix(ecs): report service deployments and MISSING failures on DescribeServices

DescribeServices omitted services[].deployments entirely and always returned an
empty failures list. Both are read by AWS's own ServicesStable waiter, which
accepts on

  length(services[?!(length(deployments) == `1` && runningCount == desiredCount)]) == `0`

and fails fast on failures[].reason == "MISSING" (botocore
ecs/2014-11-13/waiters-2.json). Because that file is codegen'd into every SDK,
`aws ecs wait services-stable` and every SDK waiter polled for the full
40 x 15s before giving up, and Terraform's aws_ecs_service never converged
(terraform-provider-aws internal/service/ecs/service.go:2206 applies the same
len(Deployments) == 1 test). Evaluating the acceptor against the old payload
raises JMESPathTypeError, so it could not even be evaluated.

An ACTIVE service now reports exactly one PRIMARY deployment derived from its
current state, with rolloutState COMPLETED once runningCount reaches
desiredCount. The deployment id is derived from the service ARN and task
definition rather than generated per request, so it is stable across calls and
restarts and rolls over when the task definition changes. An unresolvable
service reference is returned as a MISSING failure carrying the ARN it would
have had, instead of being dropped.

Known deviations are documented in docs/services/ecs.md: a single deployment
with no draining ACTIVE alongside it, no deploymentController gating, and
pendingCount always 0.

Closes #2174

* fix(ecs): stamp a deployment with its own start time, not the service's

A task-definition change mints a new deployment id, but both deployment
timestamps were still taken from the service's creation time, so the payload
contradicted itself: a new deployment claiming to have been created when the
service was. botocore documents Deployment.createdAt as "the time when the
service deployment was created", and moto stamps it at deployment construction
(moto/ecs/models.py:540) rather than reusing the service's.

Track when the current deployment began on the service model, set at creation
and on every task-definition change, and report that. Services persisted before
this field existed fall back to the service creation time.

Raised in review on #2176.
2026-08-08 21:37:59 -05:00
Kenshin Okinaka aed50cc2b2 feat(ses): implement custom verification email templates for v1 and v2 (#1840)
* feat(ses): implement custom verification email templates for v1 and v2

Add the SES custom-verification-email-template CRUD APIs across both protocols,
backed by one shared StorageFactory store (key cvet::<region>::<name>):

- v1 Query: Create/Get/List/Update/DeleteCustomVerificationEmailTemplate.
- v2 REST JSON: the same five operations under
  /v2/email/custom-verification-email-templates.

Behaviour and error shapes were verified against real AWS: duplicate create is
AlreadyExistsException, missing is NotFoundException, the FromEmailAddress must
be a verified identity (NotFoundException otherwise), an invalid redirection URL
is BadRequestException, the template body is not content-validated, List omits
TemplateContent, and the store is shared between v1 and v2. SendCustomVerification-
Email is left as a follow-up.

* fix(ses): serialize custom-verification-template mutations under one lock

Guard the check-then-write of updateCustomVerificationEmailTemplate and
deleteCustomVerificationEmailTemplate on the same lock as create (renamed
cvetCreateLock -> cvetMutationLock) so a concurrent delete can't slip between
an update's existence check and its put and resurrect the just-deleted
template. Also clean up the shared template left by the v1 integration test.

* fix(ses): validate custom-verification-template fields before the existence check on update

UpdateCustomVerificationEmailTemplate ran the existence check before validating
required fields, so omitting TemplateName (possible on the v1 Query API) returned
NotFoundException instead of the required-field InvalidParameterValue (v2
BadRequestException). Validate first, matching CreateCustomVerificationEmailTemplate.
Also drop an unused Hamcrest import in the v2 integration test.

* test(ses): give the custom-verification-template cleanup a unique last order

update_missingTemplateName and cleanup_deleteSharedTemplate both used @Order(8);
with OrderAnnotation equal values have no guaranteed order and the suite is stateful.
Move the cleanup to @Order(9) so it runs last deterministically.

* fix(ses): throw v1 error codes for custom-verification-template not-found/duplicate

The CVET service methods threw the v2 codes (NotFoundException/404, AlreadyExistsException/400)
directly, so remapV1Exception was a no-op and the v1 Query path returned the wrong codes: the
v1 SDK's typed CustomVerificationEmailTemplate* exceptions never fired, and not-found used 404
instead of AWS's 400. Throw the v1-native codes (CustomVerificationEmailTemplateDoesNotExist /
CustomVerificationEmailTemplateAlreadyExists, both 400, verified against AWS) and map them in
remapV1Exception, so v1 is correct while v2 still returns NotFoundException/404 and
AlreadyExistsException/400. Also wrap the get/delete CVET endpoints in remapV1Exception (the
only two that lacked it) and pin the v1 codes with integration assertions.

* fix(ses): throw the v1 code for an unverified custom-verification-template sender

An unverified FromEmailAddress threw NotFoundException/404 from the shared CVET validator, so
the v1 Query wire carried a v2 code. AWS classic SES returns FromEmailAddressNotVerified/400
(verified); throw that v1-native code and map it in remapV1Exception, so v1 is correct while
v2 still returns NotFoundException/404. Pin the v1 code with an integration assertion.
2026-08-08 21:36:21 -05:00
Kenshin Okinaka fa9ed9100e feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2) (#1875)
* feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2)

SendEmail now honors ListManagementOptions (ContactListName / TopicName):

Opt-out suppression — recipients opted out of the named contact list are
suppressed as a Bounce, reusing the existing relay-exclusion and Bounce-event
path. A contact is opted out when UnsubscribeAll is set; with a TopicName, an
explicit OPT_OUT preference (or the topic's OPT_OUT DefaultSubscriptionStatus
when no explicit preference) suppresses; without a TopicName, only
UnsubscribeAll contacts are suppressed. A recipient that is not yet a contact
is created on the list automatically; an unknown contact list fails the send.

Unsubscribe handling — a single-recipient list-managed send gets a functional
unsubscribe link: the {{amazonSESUnsubscribeUrl}} body placeholder is replaced
and List-Unsubscribe / List-Unsubscribe-Post headers are added. The link points
at Floci's own /_aws/ses/unsubscribe endpoint (GET/POST), which applies the
opt-out (topic -> OPT_OUT, no topic -> UnsubscribeAll), auto-creating the
contact if needed. The link uses readable query parameters rather than AWS's
opaque token, and its scheme follows Floci's base URL. Raw sends do not get
link injection yet.

* fix(ses): apply list-management unsubscribe headers to relay + inspection, override duplicates, preserve placeholder in templates

Addresses three review findings on the unsubscribe handling:

- The List-Unsubscribe / List-Unsubscribe-Post headers now reach the SMTP relay
  message (relay() takes the additional headers and applies them) and are stored
  on SentEmail so GET /_aws/ses surfaces them under Headers — previously they
  only appeared in published events.
- withUnsubscribeHeaders now overrides a caller-supplied List-Unsubscribe /
  List-Unsubscribe-Post rather than appending a duplicate, matching AWS.
- applyTemplateData leaves the reserved {{amazonSESUnsubscribeUrl}} placeholder
  intact instead of failing with MissingRenderingAttribute, so a templated body
  can carry it (replacement still happens post-render in the send path).

* fix(ses): sanitize relayed headers against SMTP injection and avoid double-slash unsubscribe URLs

User-supplied SendEmail Headers reach the SMTP relay, where a name or value containing
CR/LF could inject extra headers (e.g. Bcc) into the delivered message. Skip any header
with a blank name or CR/LF in its name/value before adding it to the relay message, and
log the drop. Also trim a trailing slash from the configured base URL when building the
List-Unsubscribe URL so a base-url ending in "/" no longer yields "//_aws/...".

* fix(ses): make the unsubscribe GET a no-mutation confirmation page

The unsubscribe endpoint applied the opt-out on both GET and POST. A GET is a browser
click that AWS answers with a landing page, and treating it as a mutation is the RFC 8058
prefetch hazard: mail clients, scanners and link-preview bots that fetch the URL would
silently unsubscribe the contact. GET now renders a confirmation form that POSTs back;
only the POST (the RFC 8058 one-click request) applies the opt-out. Adds GET test
coverage and updates the docs.

* test(ses): add an SDK compat test for SendEmail with ListManagementOptions

Send with ListManagementOptions through the SES v2 SDK client to prove the nested structure
(ContactListName + optional TopicName) marshals as a real client sends it, and that Floci
actually applies it — an absent recipient is auto-created as a contact on the list. Also note
in the docs that {{amazonSESUnsubscribeUrl}} is left verbatim on a send without
ListManagementOptions (Floci behavior, not verified against real SES).

* fix(ses): harden the unsubscribe confirmation page and document its trust model

Escape '&' as '&amp;' in the confirmation form's action attribute (valid HTML), and add the
RFC 8058 one-click hidden field so the form's POST body matches the advertised
List-Unsubscribe-Post header. Also document — in the controller Javadoc and the SES docs — that
the endpoint carries the target in readable query parameters and, like the rest of Floci, is
unauthenticated, so it is only safe on a trusted dev/test network.

* fix(ses): filter unsafe headers once so all send surfaces stay consistent

The SMTP relay dropped user-supplied headers with a blank name or CR/LF, but the stored
SentEmail (GET /_aws/ses) and published events kept the raw list — so inspection and events
could show headers the relay dropped and retain CR/LF injection payloads. Move the safety
check to MessageHeader.isSafe(), filter the headers once in the send path, and use that
sanitized list for storage, relay, and event publishing alike.

* fix(ses): reject SES v2 message headers that omit a required Name or Value

Content.Simple.Headers / Content.Template.Headers entries declare Name and
Value as required members. A header object missing either member was parsed
leniently and later silently dropped, which is surprising when the request is
otherwise accepted. Reject it at parse time the way AWS does — BadRequestException
with the Smithy "Member must not be null" constraint message anchored at the
offending header path and 1-based index.
2026-08-08 21:33:35 -05:00
Kenshin Okinaka ff8d6efdf3 feat(ses): implement v1 receipt rule set actions (stored-but-inert) (#2128)
* feat(ses): implement v1 receipt rule set actions (stored-but-inert)

Add the SES v1 receipt-rule-set management actions: CreateReceiptRuleSet,
DescribeReceiptRuleSet, ListReceiptRuleSets, DeleteReceiptRuleSet,
SetActiveReceiptRuleSet, and DescribeActiveReceiptRuleSet. Floci has no inbound-mail
endpoint, so rule sets are stored inertly — a set never holds any receipt rules and
routes no mail — but the management API round-trips so tools like Terraform can declare
a rule set during bootstrap without hitting UnsupportedOperation.

Behavior matches AWS (verified): RuleSetDoesNotExist for a missing set, AlreadyExists
for a duplicate name, idempotent DeleteReceiptRuleSet, and an empty
DescribeActiveReceiptRuleSet when no rule set is active. Individual receipt rules and
receipt filters are out of scope.

* fix(ses): reject deleting the active receipt rule set and read active state under lock

DeleteReceiptRuleSet removed the active rule set unconditionally; AWS rejects it with
CannotDelete/400 (verified), so reject it and preserve the set. DescribeActiveReceiptRuleSet
read without the lock, so a concurrent set-active replacement (clear-then-set) could expose
its intermediate no-active state; read under receiptRuleSetLock so the reader sees the old or
new active set, never the gap.

* fix(ses): validate the receipt rule set name against AWS's constraints

RuleSetName was only checked for non-blank, so Floci accepted names AWS rejects. Validate
it as AWS does (verified): a character outside ^[a-zA-Z0-9_.-]+$ is a ValidationError, and a
name over 64 characters or that does not start and end with an alphanumeric is an
InvalidParameterValue ("Not a valid ruleSetName"). Applied on create/describe/delete and on
set-active when a name is given.

* chore(ses): tidy receipt rule set import order and record the RuleSetName probe provenance

Address review nits: move the ReceiptRuleSet import into alphabetical position in
SesQueryHandler, and expand the RuleSetName validation comment to record that the
constraints come from probing live SES (the botocore model has no pattern), so the
next reader can re-verify rather than treat them as settled.
2026-08-07 23:23:01 -04:00
Alex Banna 78ba5b3457 feat(iam): list entities attached to managed policies (#1808) 2026-08-01 16:36:11 -05:00
Alex Bannaandabanna aadc93e306 feat(rum): add CloudWatch RUM app-monitor service (#1797)
* 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>
2026-08-01 15:28:54 -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
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
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
Jason van Zyl aa77d4ce46 fix(elbv2): expose target health reason parity (#1743) 2026-07-14 22:57:45 -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
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
David Phillips a3e8bf5a8b fix: Support S3 auth enforcement (#1689) 2026-07-10 22:41:03 -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
Maciej bf53ff71d8 fix(secrets-manager): return partial result for missing secrets in batch (#1591)
* fix(secrets-manager): return partial result for missing secrets in batch

* fix(secrets-manager): remove hardcoded errorCode mapping

* fix(secrets-manager): report deleted and missing current version secrets in BatchGetSecretValue errors
2026-07-10 20:44:37 -05:00
kotov228 97b64a1d3b feat: add AWS Lightsail emulation (#1583)
* feat(lightsail): add AWS Lightsail emulation

* fix(lightsail): align error responses with AWS

* fix(lightsail): address review edge cases

* fix(lightsail): reject attached disk reattach

* fix(lightsail): reject static ip reattach

* fix: register lightsail docs handler
2026-07-10 20:43:42 -05:00
TiM 13772fb5f8 feat(ecs): resolve containerDefinitions[].secrets at task launch (#1687)
RegisterTaskDefinition now parses and stores containerDefinitions[].secrets
(name + valueFrom) and round-trips them on register/describe as references,
matching AWS (the resolved values are never returned).

At RunTask launch, EcsContainerManager resolves each secret to an environment
variable through the in-process SsmService / SecretsManagerService (the same
local resolution CodeBuildRunner already uses, no extra HTTP hops):

- SSM parameter by name or full ARN -> Parameter.value
- Secrets Manager full ARN -> SecretString
- a full ARN's own region is used, so cross-region references resolve correctly
- env precedence: task-def environment < resolved secrets < RunTask container
  override environment (override still wins on a name collision)

When a referenced secret/parameter cannot be resolved the launch fails the way
AWS does: no container is started and the task goes STOPPED with a
ResourceInitializationError stoppedReason, rather than silently starting the
container without the variable.

Deferred (noted in floci-io/floci#1624): the Secrets Manager valueFrom selector
suffix (:json-key:version-stage:version-id) is not yet parsed; such a valueFrom
is resolved as the plain secret.

Adds handler round-trip tests, container-manager resolution / override /
cross-region unit tests, a stopped-task failure test, and Java SDK
compatibility coverage.
2026-07-10 20:41:43 -05:00
Kenshin Okinaka efc9453fd7 fix(ses): populate VerificationStatus in v2 ListEmailIdentities (#1722)
* fix(ses): populate VerificationStatus in v2 ListEmailIdentities

ListEmailIdentities built each item with only IdentityType / IdentityName /
SendingEnabled, so VerificationStatus always serialized as null and clients had
to call GetEmailIdentity per identity. Populate it from the identity's stored
status (mapped to the v2 enum via toV2Status), and refresh each identity's
state the same way GetEmailIdentity does so the list stays consistent (e.g. a
domain that transitioned to SUCCESS via its DKIM records).

* fix(ses): derive SendingEnabled from verification status in v2 ListEmailIdentities

SendingEnabled was hard-coded to true, so a not-yet-verified identity was
reported as sendable, which is inconsistent now that VerificationStatus is
populated. AWS returns SendingEnabled=true only when the identity is verified
(VerificationStatus SUCCESS) and false otherwise (PENDING/FAILED), matching the
VerifiedForSendingStatus logic already used by GetEmailIdentity. Derive it the
same way here.
2026-07-09 23:54:43 -05:00