Commit Graph
1324 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 c163a8678c fix(cloudwatch): keep GetLogEvents paging inside the list bounds (#2355)
GetLogEvents ends a page at Math.min(pageStart + maxEvents, total), and
maxEvents is Math.min(limit > 0 ? limit : Integer.MAX_VALUE,
maxEventsPerQuery). A max-events cap configured near Integer.MAX_VALUE, the
natural way to express "no cap" since the setting has no upper bound, makes
pageStart + maxEvents overflow negative as soon as a forward token moves
pagination past the first page. subList then throws IllegalArgumentException
and the call fails with a 500.

The end of the stream is where a client meets this rather than some deep page:
GetLogEvents echoes its forward token when nothing is left, so a paginator
always spends one more call on the token it was just handed.

Take the window out of what remains instead of adding to the offset, which
keeps both operands within the list's own bounds. The backward and tail
branches already subtract and clamp, so they are unaffected, and behaviour at
the default cap of 10000 is unchanged.

The regression test drives the second paginator call under an unbounded cap,
and fails without the fix with fromIndex(3) > toIndex(-2147483646).
2026-08-17 13:40:15 -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
z9rtm 291a97473e fix(cloudformation): physically delete nested stacks and removed resources on update (#2345)
* fix: delete removed resources during CloudFormation stack update

* fix: physically delete nested stacks and removed resources on update

* fix(cloudformation): propagate nested stack deletion failures and expand cleanup tests

* test(cloudformation): cover RetainExceptOnCreate, multi-level nested cleanup, and rollback preservation on update

* fix(cloudformation): persist stack on delete failure and improve cleanup robustness
2026-08-17 00:32:37 -05:00
Feyikemi Ogunsanya 24cdabb257 feat(cognito): add GetUserAttributeVerificationCode support (#1898)
* feat(cognito): issue attribute verification codes in CognitoService

* feat(cognito): dispatch GetUserAttributeVerificationCode in CognitoJsonHandler

* test(cognito): add GetUserAttributeVerificationCode happy path

* test(cognito): cover invalid token and unverifiable attribute errors

* docs(cognito): document GetUserAttributeVerificationCode

* fix(cognito): key attribute verification codes per attribute

* fix(cognito): match AWS error messages for GetUserAttributeVerificationCode

Real Cognito returns "Invalid Access Token", "Invalid attribute name.
Only phone_number and email can be verified.", and attribute-specific
"User does not have a valid registered email address" / "...phone
number" messages, per AWS-parity comparison in PR #1898 review.

* fix(cognito): match AWS destination masking format for verification codes

Real Cognito masks as "z***@b***" for email (first char of local part
and domain, three asterisks, no TLD retained) and "+********8920" for
phone (leading "+", asterisks, last four digits kept), per AWS-parity
comparison in PR #1898 review. Applies to both attribute-verification
and forgot-password/account-recovery delivery masking, which share
these helpers.

* test(cognito): assert exact AWS-parity error messages and mask format

Tighten GetUserAttributeVerificationCode assertions from loose
containsString checks to the exact wording and masking AWS returns,
so a regression in either silently drifting from AWS again is caught.

* test(cognito): cover re-issuing verification code for a verified attribute

AWS permits requesting a fresh GetUserAttributeVerificationCode code
for an attribute that is already verified, as long as its value has
not changed. Nothing in the current issuance path checks the
*_verified flag, so this locks in that AWS-parity behavior.

* style(cognito): drop redundant comment in attribute verification test

The method name already conveys the AWS behavior being tested, per
AGENTS.md's guidance to prefer self-explanatory code over comments.
2026-08-17 00:27:15 -05:00
Priamo Germosen 25b46e28ad fix(core): extract shared pagination helper, reject maxResults=0 (#2343)
Closes #2339, #2340.

ListResult<T> and its paginate()/encode()/decode() helpers existed as
five near-identical private copies (BedrockAgentCoreGatewayService,
BedrockAgentCoreIdentityService, BedrockAgentCoreMemoryService,
BedrockAgentCoreControlService's three list methods, and MskService),
not the two originally scoped in #2340 - the ListResult<T> record was
already shared within bedrockagentcorecontrol, which is what earlier
scoping missed. Extracts core.common.Pagination + PaginatedResult<T>
and migrates every one of them, deleting both now-unused per-service
ListResult model classes.

Every duplicate collapsed "maxResults omitted" and "maxResults=0"
onto the same primitive int, defaulting both to the full page instead
of rejecting the explicit zero the way AWS's MaxResults min:1
constraint requires (confirmed against botocore's real kafka and
verified live: botocore itself refuses to send MaxResults=0
client-side). Pagination.paginate/parseMaxResults take a boxed
Integer so the two cases are distinguishable, and every migrated
service now rejects 0 with its own existing error code
(ValidationException for the bedrockagentcorecontrol services,
BadRequestException for MSK) - the fix lands once, not five times.

Also carries over the MskController fix from #2336: an
Integer-typed @QueryParam converts before the resource method runs,
so a non-numeric maxResults was a bare 404 instead of an AWS-shaped
400. Every migrated REST controller now binds maxResults as a String
and calls Pagination.parseMaxResults, closing the same gap in
BedrockAgentCoreGatewayController/ControlController/MemoryController
that MSK already had fixed.
2026-08-17 00:01:48 -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
lex00 cdb6811bbf feat(ec2): DescribeImages synthesizes an AMI for an unmatched wildcard name lookup (#2009)
* feat(ec2): DescribeImages synthesizes an AMI for an unmatched wildcard name lookup

CDK MachineImage.lookup is a synth-time context provider that queries by
a name wildcard and aborts cdk deploy on an empty response. When a
wildcard name filter matches no seeded AMI, synthesize a deterministic
one satisfying the name/owner/architecture filters so the lookup
resolves — the exact id is a runtime detail.

Fixes #2008

* fix(ec2): synthesized lookup AMI id must be 17 hex chars (was substring OOB)

* fix(ec2): a synthesized lookup AMI must satisfy the request that produced it

The synthesized name was built by truncating the pattern at its first wildcard,
so an infix pattern like ubuntu-*-20.04-* produced "ubuntu-20260101", which does
not satisfy it. Each wildcard is now substituted instead, and the scalar fields
a request can filter on (architecture, owner alias, state, root device,
virtualization type, hypervisor) take the requested value rather than a
hardcoded one.

Synthesis is also no longer unconditional: the result is checked against the
full filter set before being returned, and withheld when it cannot satisfy it.
An empty result is what the caller would otherwise have got, and it is better
than an AMI that contradicts the request without the caller being able to tell.

* fix(ec2): a name filter reads ? as the single-character wildcard AWS defines

AWS filter values take two wildcards, * for any run of characters and ? for
exactly one. wildcardMatches expanded only *, quoting everything else, so a
pattern like ubuntu-? matched nothing. wildcardToRegex further down the same
file already read both, so the two disagreed on the same syntax. That half is
not specific to lookup synthesis and affects any name filter.

Synthesis in turn substituted * and left ? in place, which handed back a name
carrying a literal ? that the requesting filter no longer matches once the
matcher reads ? properly. It now substitutes a single character for each one.

* fix(ec2): a synthesized lookup image resolves its owner and faces the owner scope

Owner.N takes aliases, and synthesizeLookupImage wrote the requested value
through verbatim, so Owner.1=self with no owner-id filter produced an image
owned by the literal "self". Ec2Service matches self by comparing the image
owner against the account id, so nothing resolves that. It now maps self to the
account id and passes anything else through.

The guard below it only re-checked Filter.N, so the image never faced the owner
scope that produced it and a foreign Owner.N still got an AMI back.
matchesImageOwners already existed privately on Ec2Service and is now exposed
next to imageMatchesFilters, rather than restating the rule in the handler.

Two tests, neither of which passed before, since nothing in the suite sent
Owner.N.

* fix(ec2): DescribeImages owner aliases resolve to the accounts they name

Resolving only self left amazon and aws-marketplace written through verbatim, so
a synthesized lookup image came back owned by the literal alias. The owner check
added alongside it then accepted that by string equality, which made the result
self-consistently wrong rather than merely unmatched.

Both aliases now resolve to their accounts in the synthesized image, and
matchesImageOwners resolves them too, so Owner.1=amazon matches an
Amazon-owned image rather than only one owned by the literal string.

* fix(ec2): the seeded Amazon Linux images carry their owner

matchesImageOwners learning the amazon alias only helped registered images. The
catalog matches on its own owner metadata, and five of the ten seeded entries
carry none, so Owner.1=amazon omitted Amazon Linux 2 and 2023 regardless.

Both now carry ownerId 137112412989 and the amazon alias, matching how the
Canonical entries are already seeded. Debian, Alpine and Windows Server are
still without owner metadata, which is the same pre-existing gap and needs their
real account ids rather than a guess.

* fix(ec2): lookup synthesis reads the wildcard value, not the first one

A filter's values are an OR, and the name pattern was taken with findFirst on the
list, so an exact value ahead of a wildcard meant the wildcard check failed and
synthesis never ran. The lookup then got an empty set that one of its own values
could have been satisfied by.

It now picks the first value carrying a wildcard. This predates the ? support,
which only widened which values qualify.

* fix(ec2): a synthesized image's owner id and alias agree with each other

The alias defaulted to amazon whatever the owner resolved to, so Owner.1=self
reported account 000000000000 beside imageOwnerAlias amazon. The alias is now
derived from the resolved account, and an account with no alias emits no element
at all, which is what AWS does.

The mirror was wrong too and is fixed with it. An owner-alias filter names an
account as much as Owner.N does, but was consulted by nothing, so filtering on
owner-alias alone left the id at the Amazon default and reported that account
beside someone else's alias. Owner resolution now reads the owner-id filter,
then Owner.N, then the owner-alias filter, then the default.

Asserted as a pair across all four owner scopes rather than per field. Each half
was confirmed by reverting the source change with the test in place and watching
it fail on the exact contradiction.
2026-08-16 20:47:15 -05:00
lex00 9280369b64 feat(cloudformation): provision ApiGateway::Account, AutoScaling::LifecycleHook, and EC2::FlowLog (#2003)
* feat(cloudformation): provision ApiGateway::Account, AutoScaling::LifecycleHook, and EC2::FlowLog

Three small provisioners over existing services: Account records
metadata (physical id only), LifecycleHook maps onto
AutoScalingService.putLifecycleHook, FlowLog onto
FlowLogService.createFlowLog (newly injected into the provisioner).

Fixes #2002

* feat(cloudformation): per-service provisioners for ApiGateway::Account, AutoScaling::LifecycleHook, and EC2::FlowLog

The three resource types land in the extracted provisioner structure rather
than the switch in CloudFormationResourceProvisioner, one class per service:

- ApiGatewayAccountCfnProvisioner writes CloudWatchRoleArn into the API
  Gateway account settings, so GET /account reflects what the template asked
  for instead of the resource being recorded as a bare physical id.
- AutoScalingLifecycleHookCfnProvisioner puts the hook on its group and
  removes it again when the stack is deleted.
- Ec2FlowLogCfnProvisioner creates the flow log and deletes it when the stack
  is deleted.

Both deletes close the cleanup gaps raised in review: flow logs and lifecycle
hooks no longer outlive their stack. The delete path only holds a physical id,
and a hook's physical id is its name, so AutoScalingService gains
deleteLifecycleHookByName to find the hook whichever group owns it, including
groups that outlive the stack. API Gateway has no DeleteAccount operation and
its account settings are regional rather than stack-owned, so that provisioner
keeps the default no-op delete.

CloudFormationResourceProvisioner is byte-identical to main again: no switch
arms, no FlowLogService injection, and the two constructor-arg test edits are
reverted.

Tests: three isolated provisioner unit tests (one mocked service each) plus
the integration test, extended to cover deletion of the hook and the flow log
against a group created outside the stack.

* fix(cloudformation): delete a lifecycle hook on its own group, not by name alone

A lifecycle hook name is unique within an Auto Scaling group, not within a
region, but the CloudFormation delete path only had the physical id — the hook
name — so it removed every hook with that name in the region. Two groups using
the same hook name meant deleting or rolling back either stack stopped the
other group's lifecycle action.

CfnResourceProvisioner gained a delete overload that receives the whole
StackResource, defaulting to the existing id-only form, and the dispatcher
calls it for extracted provisioners. It sits after the EKS Nodegroup and IAM
policy special cases so extracting one of those later cannot bypass them.

The hook provisioner records its AutoScalingGroupName at create time and
deletes through the group-scoped API. Resources provisioned before that still
fall back to the by-name form: leaving the hook behind is worse, since it can
sit on a group that outlives the stack.

* fix(cloudformation): a stack update reuses its flow log and lifecycle hook

Ec2FlowLogCfnProvisioner called createFlowLog unconditionally, so every
UpdateStack created a second flow log and orphaned the first. The orphan then
outlived the stack, since delete only knows the id recorded last. It now reuses
the log this stack already made and creates only when that one is absent, on a
first execution or after removal out of band.

AutoScalingLifecycleHookCfnProvisioner had the same shape, but only when
LifecycleHookName is omitted: a freshly generated name each update left the
previous hook on the group, still firing, with nothing referencing it. An
unnamed hook now keeps the name its first execution generated. A declared name
needed no change, since putLifecycleHook is idempotent on it.

Both follow EcsCapacityCfnProvisioner. Neither surfaced in CI because no test
here ran an UpdateStack, so each provisioner now has one that does.

* fix(cloudformation): a createOnly change on a flow log or lifecycle hook is reported

Both provisioners reuse the resource the stack already made, so a change to a
property AWS treats as createOnly was being absorbed instead of surfaced.

The flow log reported the stack complete while DescribeFlowLogs kept serving the
previous ResourceId, TrafficType, LogDestination, LogFormat or aggregation
interval. The lifecycle hook was worse, since changing LifecycleHookName or
AutoScalingGroupName created the new hook and overwrote the id delete uses,
leaving the previous hook on its group and still firing.

Both now report an unsupported replacement, matching how EcsCapacityCfnProvisioner
treats a changed Name. A property the template stops declaring, or one the stored
record never captured, is left alone rather than read as a change.

* docs(cloudformation): list ApiGateway Account, LifecycleHook and FlowLog in the resource-type table

* fix(cloudformation): dropping a flow log's createOnly property is a change

rejectIfChanged returned early whenever the template supplied no value, so
removing a previously explicit LogFormat or MaxAggregationInterval skipped
validation entirely and the stack reported complete while DescribeFlowLogs kept
serving the old one.

An absent stored value still means leave it alone, since that is not evidence of
a different one, but an absent requested value is now compared rather than
skipped. MaxAggregationInterval compares against its documented default of 600
when the template omits it, which is the value a create would have used.

* fix(cloudformation): a flow log's createOnly comparison uses effective values

Removing the early return on a blank request fixed the dropped-property case and
broke two others. createFlowLog defaults ResourceType, TrafficType and
LogDestinationType, so re-applying an unchanged template compared null against a
stored default and failed a no-op update, while adding a property to a log that
never had one still returned early on the stored null and was ignored.

Both sides are now the effective value, defaulting the requested side exactly as
createFlowLog does, so add, drop and change all read as changes and a re-apply
stays a no-op. The test helper stamps the same three defaults, since a stub
without them is not a flow log this provisioner could have created.
2026-08-16 20:41:41 -05:00
Christian Franzen c194bffe30 fix(ec2): sshd can only be started from an absolute path since OpenSSH v3.9 (#2351) 2026-08-16 10:49:54 -04:00
Hector Ventura d819c00dbf fix(docker): label containers and volumes per emulator (#2341)
Every container and volume the emulator creates now carries `floci=true`,
`floci_emulator=floci-aws`, and `floci_namespace=<value>` when
`docker.resource-namespace` is configured.

Previously only volumes were labelled, with a bare `floci=true`. That key is
shared by floci-aws, floci-gcp and floci-az, so
`docker volume prune --filter label=floci=true` destroyed volumes belonging to
all three emulators at once. `floci_emulator` discriminates between them, while
`floci=true` still prunes everything when that is what you want.

Labels are applied at the single `createContainerCmd` choke point in
`ContainerLifecycleManager`, with per-spec labels layered over the defaults via
`ContainerBuilder.withLabel`/`withLabels` (a spec label wins on key conflict),
so every service is covered by construction rather than per call site. Volume
prefix renames and persisted volume names are deliberately out of scope.
2026-08-15 21:17:33 -05:00
Matheus Oliveira 16a8f042e7 fix(s3): enforce auth on object write paths when enforce-auth is enabled (#2326)
PutObject/DeleteObject and their subresources (tagging, retention,
legal-hold, acl, multipart, copy, batch delete, restore) accepted
anonymous requests even with enforce-auth enabled, unlike GetObject.

Also fixes: batch delete failing whole on a bad access key instead of
masking it per-key; explicit policy Deny taking precedence over ACL
grants; public-read-write ACL scoped to creating a new key only, per
AWS's ACL docs, never overwrite/delete; DeleteObject vs
DeleteObjectVersion as distinct actions; and BypassGovernanceRetention
required separately from DeleteObject/PutObjectRetention.

Fixes #2318

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-15 22:11:09 -04:00
TiM 573d4bdaff fix(lambda,iam): assume execution role for in-function SDK calls (#1909)
* fix(lambda,iam): assume execution role for in-function SDK calls

- Run Lambda SDK calls as known execution roles so IAM policies and caller identity match AWS behavior.
- Preserve unknown-role and mounted-credential fallbacks while leaving ECS behavior unchanged.
- Revoke container-bound sessions on cleanup and sweep orphaned sessions after restart.
- Resolve the session account from the function ARN when the model carries no account, so a
  published version enforces its execution role instead of dropping to the placeholder
  credentials, and revokes under the account it registered with. PublishVersion builds its
  snapshot field by field and leaves accountId unset (#2040), so the account has to come off
  the version ARN; routing every read through one helper keeps register and revoke in step.
- Add unit, enforcement, lifecycle, and real Docker coverage, plus updated documentation.

* fix(lambda): mint execution-role sessions from a CSPRNG and flag credential passthrough

The session key and secret are what IamEnforcementFilter authorizes a caller
against, so mint them from SecureRandom rather than ThreadLocalRandom, matching
how CertificateGenerator already sources security-relevant values. Register the
class for native-image run-time initialization so the static instance is not
captured, frozen-seed, into the image heap.

Credential passthrough (Floci's own AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/
AWS_SESSION_TOKEN forwarded into a launched container) applies whenever those
variables are set, so a Floci started from a shell that exports real credentials
hands them to every workload whose role it cannot resolve. Log a WARN carrying
the access-key prefix the first time the fallback forwards host credentials, and
say so in the docs, so the accidental case is visible instead of looking
identical to the deliberate one.
2026-08-15 20:59:05 -05:00
Priamo Germosen 4c510e576c feat(msk): add configuration CRUD (Create/List/Describe/Delete) (#2336)
* feat(msk): add configuration CRUD (Create/List/Describe/Delete)

MskController only served /v1/clusters and /api/v2/clusters, so every
configuration action 404s. An MSK configuration is the only supported
way to set broker-level server_properties, and aws_msk_configuration /
aws_msk_domain_policy are first-class Terraform resources - any stack
setting broker properties failed before the cluster was even attempted.

Adds a second StorageBackend on MskService (msk-configurations.json,
mirroring msk-clusters.json), a new MskConfiguration model, and four
endpoints on MskController mirroring the existing cluster handlers.
serverProperties is base64 on the wire; decoded and kept internal
(@JsonIgnore) since AWS only returns it via DescribeConfigurationRevision,
which is a separate follow-up issue - this stays plain CRUD.

Field names verified against botocore's actual kafka service model
rather than trusting the API reference docs verbatim: every field is
lowerCamelCase, including DeleteConfigurationResponse's `arn` (the
public API reference page shows "Arn" capitalized, which does not
match the real wire format).

* fix(msk): validate request field types and persist serverProperties

CreateConfiguration cast request fields directly (String)/(List<String>),
so a wrong-typed field threw ClassCastException instead of an AWS-shaped
BadRequestException, surfacing as an internal server error.

serverProperties was @JsonIgnore, which excludes it from Jackson
serialization entirely - not just REST responses, but also the
persistent/hybrid/wal StorageBackend serialization that uses the same
model. A configuration would silently lose its broker properties on
reload under any non-memory storage mode. The field now serializes
normally; the controller instead builds explicit response views for
Describe/List/Create so serverProperties still never appears on the
wire outside CreateConfiguration's own request, matching AWS (which
only returns it via the out-of-scope DescribeConfigurationRevision).

* fix(msk): default kafkaVersions to an empty array when omitted

kafkaVersions is optional on CreateConfigurationRequest, but
asStringList returns null when it's absent, and toConfigurationView
put that null straight into the response - AWS's Configuration shape
always populates it as an array. Default it the same way description
already is. No existing test created a configuration without the
field, which is why it slipped through.

* feat(msk): support maxResults/nextToken pagination on ListConfigurations

ListConfigurations previously returned every configuration in one
response, ignoring the maxResults/nextToken query parameters the
model declares. Mirrors the existing pagination pattern from
BedrockAgentCoreGatewayService (ListResult<T> + a private paginate()
helper): the cursor is the last returned item's ARN, base64
URL-encoded, resumed by scanning the ARN-sorted list past that value.
maxResults is bounded to [1, 100] and an undecodable token both throw
BadRequestException, matching CreateConfiguration's existing error
family for this service.
2026-08-15 21:50:20 -04:00
Bill DeMossandPriamo 42022fe937 fix(lambda): give published versions their code location (#2012)
* test(lambda): cover invoking a published version

LambdaVersionIntegrationTest covered publish, list and delete against a
function with no code at all, so nothing ever invoked a version. Adds
that case, plus a $LATEST baseline on a separate function so a failure
is attributable to versioning rather than to the harness.

Currently fails, reproducing #1987: the version invoke returns HTTP 200
with X-Amz-Function-Error: Unhandled and no result body, after the
container logs Runtime.ImportModuleError ("Cannot find module 'index'")
and the invoke times out at the 5s function timeout.

The baseline is a separate function on purpose. Invoking $LATEST on the
function under test leaves a warm container that the version-qualified
invoke then reuses -- the warm pool is keyed by function name alone
(#1988) -- so the version runs $LATEST's code and the assertion passes
while the version path is still broken. An earlier draft of this test
did exactly that and reported #1987 as fixed.

* fix(lambda): give published versions their code

publishVersion built the version snapshot by copying fields one at a
time and copied no code location at all -- not just codeLocalPath but
s3Bucket, s3Key, imageUri and codeSha256. A numeric qualifier resolves
straight to that snapshot, so a version-qualified invoke launched a
container for a function with no code.

It timed out rather than failing because ContainerLauncher.launch only
validated the code path when it was non-null, making the one state that
always means "no code" the one state never checked. The container came
up empty, the runtime logged Runtime.ImportModuleError where nobody saw
it, and the caller waited out the whole function timeout before getting
a 200 with X-Amz-Function-Error: Unhandled and no result body.

Copy the fields that determine what runs -- code location for every
package type, plus layers, architectures and ephemeral storage -- and
make a missing code location an error for non-hot-reload Zip functions.
The guard is what keeps the next dropped field from surfacing as a
timeout somewhere else instead of an error at its cause.

LambdaImageConfigTest.zipFunctionStillUsesHandlerAsCmd built a bare Zip
function with no code path as a fixture shortcut; it now gets a @TempDir.
The test covers cmd construction, not code validation.

Closes #1987

* fix(lambda): copy remaining config fields and fix @Order collision

Two follow-ups from review after the code-location fix:

- publishVersion now also copies tracingMode, deadLetterTargetArn and
  kmsKeyArn onto the version snapshot. These are surfaced by every
  config-serializing endpoint the same as the code-location fields,
  and were dropped by the same hand-enumerated field copy. Verified
  through ListVersionsByFunction rather than GetFunction/
  GetFunctionConfiguration with a :1 qualifier: those two resolve
  through LambdaService.getFunction(region, functionName), which
  hardcodes "$LATEST" in its storage lookup and never reads the
  qualifier, so they can't distinguish a version's stored config from
  $LATEST's — a separate, pre-existing gap, not fixed here.

- LambdaVersionIntegrationTest had two methods at @Order(6) after
  merging main, which independently added a test at the same value.
  Renumbered to keep execution order deterministic; both tests use
  independent function fixtures so this was never a functional bug.

Verified against a revert of each change: both new/moved assertions
fail without their fix and pass with it restored.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-08-15 21:41:09 -04:00
Hector Ventura 7a2dc53b96 fix(cognito): restore the SecureRandom import (#2337)
#2139 introduced `new SecureRandom()` in `ensureRefreshTokenSecret`, which
compiled under the file's wildcard `import java.security.*`. #1881 expanded
that wildcard into explicit imports without `SecureRandom`. Both PRs were
green on their own branches; the merged result does not compile, so main has
been failing at `CognitoService.java:2242 cannot find symbol: class
SecureRandom` since #1881 landed.
2026-08-15 19:53:30 -04:00
lex00 33d35b2079 feat(ec2): config toggle to report the AWS-faithful private IP (#2024)
* feat(ec2): config toggle to report the AWS-faithful private IP (#1983)

DescribeInstances reported the Docker container's bridge IP as PrivateIpAddress,
disagreeing with CloudFormation's subnet-allocated IP. Rather than force a
fidelity-vs-reachability tradeoff, this adds an opt-in:

  ec2.aws-faithful-private-ip (default false)

Default (false) is unchanged: the reported private IP is the reachable container
bridge IP, so instances can reach each other at that address on the shared
Docker network. When true, the CFN/subnet-allocated private IP set at launch is
reported instead (AWS-faithful); routing and IMDS always use the container
bridge IP (tracked separately as containerBridgeIp) regardless of the flag.

Wired via a new awsFaithful overload of exposeReachablePrivateAddress; the three
call sites pass the config flag. Test covers both modes.

Fixes #1983.

* docs(ec2): list aws-faithful-private-ip in application.yml and the config table

Every other floci.services.ec2 knob appears in both application.yml files and
the docs configuration table; this one was declared only on EmulatorConfig, so a
user-facing flag was undiscoverable.
2026-08-15 18:48:49 -05:00
lex00 5e01c07b33 feat(cloudformation): provision the network ACL family (#2001)
* feat(cloudformation): provision the network ACL family

AWS::EC2::NetworkAcl, NetworkAclEntry (rule number, protocol, action,
egress flag, CIDR, port range), and SubnetNetworkAclAssociation (CFN
semantics: find the subnet's live association and replace it onto the
target ACL) — all mapped onto existing Ec2Service APIs.

Fixes #2000

* refactor(cloudformation): move the network ACL family to a per-service provisioner

Ec2NetworkAclCfnProvisioner serves AWS::EC2::NetworkAcl,
AWS::EC2::NetworkAclEntry and AWS::EC2::SubnetNetworkAclAssociation
through the CfnResourceProvisioner seam, so the three types leave the
switch in CloudFormationResourceProvisioner along with their private
provision methods. The class is CDI-discovered by
CloudFormationResourceRegistry, needs no registration, and injects only
Ec2Service.

delete() now covers all three types, so stack deletion cleans them up
instead of leaking them. The ACL and the entry delegate to Ec2Service;
the subnet association reverts the subnet to its VPC's default ACL,
matching CloudFormation. NotFound is treated as already-deleted so a
retried delete does not fail the stack.

Entry properties resolve through the template engine rather than being
read raw off the JSON, so RuleNumber, Egress and the PortRange bounds
accept intrinsics such as Ref and Fn::Sub like the other properties
already did.

The integration test now deletes the stack and asserts the custom ACL
is gone. A unit test covers the family in isolation with one mocked
service.

* fix(cloudformation): a stack update reuses its network ACL and upserts entries

provisionNetworkAcl called createNetworkAcl unconditionally. CloudFormationService
re-invokes provision with the prior physicalId on UpdateStack, so every update
minted a second ACL, overwrote the id, and orphaned the previous one permanently.
It now reuses the ACL this stack already made, creating only when that one is
absent, and reports an unsupported replacement when VpcId changes, since VpcId is
createOnly. Same shape as EcsCapacityCfnProvisioner.

Fixing that alone broke the entry path: createNetworkAclEntry ran with
replace=false, which raises NetworkAclEntryAlreadyExists for a rule that already
exists. RuleNumber, Egress and NetworkAclId are the createOnly key, so
re-provisioning the same key is an update, and replace=true is correct.

Neither showed up in CI, since no test here ran an UpdateStack. Three now do.

* docs(cloudformation): list the network ACL family in the resource-type table
2026-08-15 18:24:50 -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
Feyikemi Ogunsanya 6c4d63b0a9 fix(s3vectors): route ListVectors instead of falling through to S3 (#2285)
* fix(s3vectors): add listVectors service method with cursor pagination

ListVectors had no backing service method. Add one modeled on
listCertificates' cursor-based pagination (base64 JSON cursor over the
last returned key), sorted by vector key for stable ordering across
pages.

* fix(s3vectors): route ListVectors instead of falling through to S3

S3VectorsController declared routes for twelve S3 Vectors operations
but not ListVectors, so requests fell through to the S3 REST-XML
controller and came back as a misleading S3 InvalidArgument XML error
instead of a ListVectors response.

Add the route, request/response records (modeled on GetVectors'
returnData/returnMetadata shape), and wire it to the new
S3VectorsService.listVectors.

Fixes #2161

* test(s3vectors): add regression tests for ListVectors

Reproduces #2161: before the route existed, ListVectors fell through
to the S3 controller and returned an XML InvalidArgument error instead
of a JSON ListVectors response. Covers the basic list (with
returnData/returnMetadata) and cursor pagination via maxResults +
nextToken across two pages.

* fix(s3vectors): resolve ListVectors by indexArn and fix cursor encoding

Two issues flagged in review on #2285:

- listVectors ignored indexArn and passed it through as an unused
  request field, so an ARN-only ListVectors call (a form the input
  contract explicitly allows) resolved a null bucket name and 404'd.
  Add resolveIndex to parse "<bucketArn>/index/<indexName>" and fall
  back to it when indexName is absent.
- encodeToken/decodeToken hand-built a JSON string around the cursor
  key without escaping, so a vector key containing a double quote
  truncated the cursor and repeated or skipped pages. Drop the JSON
  wrapping entirely — the cursor only ever holds one opaque value, so
  base64-encoding the raw key round-trips any key correctly.

* fix(s3vectors): pass indexArn through to listVectors

Wire ListVectorsRequest.indexArn() into the new
S3VectorsService.listVectors(bucketName, indexName, indexArn, ...)
signature so ARN-only requests actually resolve the index instead of
being silently dropped.

* test(s3vectors): add regression tests for indexArn and quoted keys

Reproduces both issues flagged in review on #2285: confirmed
listVectorsByIndexArnOnly failed with 404 and
listVectorsPaginationRoundTripsKeysWithQuotes returned the wrong page
against the prior code, before the resolveIndex and cursor-encoding
fixes.

* fix(s3vectors): resolve indexArn using its own region, not the request's

Flagged in review on #2285: resolveIndex parsed the bucket/index names
out of indexArn with manual substring slicing but discarded the ARN's
region entirely, doing the lookup in whatever region the ListVectors
request itself was signed for. A valid cross-region indexArn (or any
request not signed for the same region as the index) silently 404'd or
could resolve a same-named index in the wrong region.

Use AwsArnUtils.parse instead of manual slicing, validate the ARN is
an s3vectors ARN, and look up the index in the region encoded in the
ARN itself.

* test(s3vectors): add regression test for cross-region indexArn lookup

Reproduces the issue flagged in review on #2285: confirmed this test
failed with 404 against the prior region-ignoring resolveIndex, using
an index created under a us-west-2 credential scope and a ListVectors
request with no Authorization header (default region).
2026-08-15 19:09:13 -04:00
Priamo Germosen 78ad357eb8 feat(opensearch): parse, store, and return AccessPolicies (#2327)
* feat(opensearch): parse, store, and return AccessPolicies

AccessPolicies was never parsed on CreateDomain/UpdateDomainConfig,
stored on the domain, or returned by DescribeDomain(s)/
DescribeDomainConfig, so aws_opensearch_domain.access_policies and
aws_opensearch_domain_policy were unsupported and any inline policy
was silently discarded. Threaded through as a plain string alongside
engineVersion, following the same pattern: bare string in
DomainStatus, Options+Status wrapper in DomainConfig (mirroring the
existing EngineVersion field there).

* fix(opensearch): drop unused region parameter from updateDomainConfig

Domain.region is baked into the ARN at CreateDomain time and never
recomputed on update, so the parameter had no effect. Its own local
variable in the controller was correspondingly dead too.

* test(opensearch): cover clearing AccessPolicies with an empty string

The empty-string-clears-the-policy behavior was implemented but not
exercised by any test.
2026-08-15 18:31:50 -04:00
soreavis 833de25c08 fix(s3): route the accelerate subresource instead of falling through (#2330)
* fix(s3): route the accelerate subresource instead of falling through

PUT /{bucket}?accelerate fell through to CreateBucket: outside the
default region it failed with BucketAlreadyOwnedByYou, and inside it
the idempotent-create path returned a silent 200 without storing
anything, so PutBucketAccelerateConfiguration could not be applied
either way. GET /{bucket}?accelerate fell through to ListObjects and
returned a ListBucketResult, which the SDK silently parses as "not
configured". DELETE /{bucket}?accelerate fell through to DeleteBucket
and deleted an empty bucket outright.

Store the Transfer Acceleration status on the bucket, following the
requestPayment pair as the closest-shaped precedent: PUT requires the
body to parse to the AccelerateConfiguration root (checked with a new
XmlParser.rootElementName primitive, so an absent, truncated, non-XML
or wrong-root body is MalformedXML on every branch) and validates
Enabled/Suspended, while a configuration without the optional Status
element is accepted and leaves the stored state unchanged; GET
returns the stored status, or an AccelerateConfiguration with no
Status element for a bucket that has never been configured; DELETE,
which AWS does not define for this subresource, returns
MethodNotAllowed instead of falling through.

Closes #2295

* fix(s3): resolve accelerate requests to their own IAM actions

The subresource override in IamActionRegistry covered only acl and
tagging, so with auth enforcement enabled a PUT /{bucket}?accelerate
resolved to s3:CreateBucket through the generic bucket rule - a
principal allowed only to create buckets could reconfigure
acceleration on an existing bucket. Map bucket-level GET and PUT to
their own actions instead.

The mapping applies only when the path is bucket-level and no acl or
tagging parameter is present: the object routes ignore ?accelerate,
so an object request keeps resolving to its object action, and a
stricter acl or tagging resolution can never be downgraded by
appending an inert parameter. A bare DELETE stays on the rule table,
since AWS defines no delete action for this subresource.

* fix(s3): yield the accelerate IAM mapping to earlier subresources

A request carrying ?accelerate plus a subresource the controller
dispatches earlier - ?requestPayment, say - executes that other
operation while resolving to the accelerate action, so a principal
holding only the accelerate permission could read or change an
unrelated configuration. Wire-probed: PUT with both parameters
stores the request-payment payer, not an acceleration state.

The accelerate mapping now yields whenever such a subresource rides
along, falling back to the standard rule table - exactly what a
plain ?requestPayment request resolves to today. The yield lists
are method-aware because the dispatch chains are: ?uploads blocks
accelerate on GET but is inert on PUT, where accelerate still
executes and keeps its own action.
2026-08-15 18:25:05 -04: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
Michal Schreiber 20470b7f4a feat(ec2): support transit gateways (#2329)
* feat(ec2): support transit gateways

CreateTransitGateway, DescribeTransitGateways, ModifyTransitGateway and
DeleteTransitGateway, as EC2 Query actions alongside the existing VPC and
route table ones. Metadata only: nothing routes packets, and the value is
in ids later resources can reference and describes that round-trip so
plans converge.

Option defaults come from a live AWS account rather than the reference:
amazonSideAsn 64512, dnsSupport, vpnEcmpSupport and both default route
table options enabled, autoAcceptSharedAttachments,
securityGroupReferencingSupport and multicastSupport disabled. The last
of those is the one worth stating, since disable is easy to assume the
other way round. transitGatewayCidrBlocks is omitted entirely when unset
rather than sent empty.

Creating a gateway with either default route table option enabled also
mints the route table AWS mints, and reports its id as both
associationDefaultRouteTableId and propagationDefaultRouteTableId. Both
name the same table, and it is already on the create response rather than
appearing later, so a caller reading either id sees what AWS shows. The
actions that operate on route tables directly are not implemented; nor
are attachments.

State is reported settled rather than transitional. AWS returns a new
gateway as pending and reaches available in about 50 seconds, and reports
deleting for about a minute before deleted; nothing here is slow, so the
settled state is what the caller sees, matching how
createManagedPrefixList already compresses create-in-progress.

Modify and delete echo the gateway without its tagSet while create and
describe include it, which is what the live API does.

Part one of #2308.

* fix(ec2): keep a transit gateway's default route table options coherent

ModifyTransitGateway changed the DefaultRouteTableAssociation and
DefaultRouteTablePropagation flags without touching their route table
ids, so a gateway created with both disabled could be modified into
reporting an option enabled while carrying no id for it.

AWS does not create a route table on that request; it rejects it unless
an existing table is named, and rejects an id supplied alongside a
disable. An unknown table comes back as InvalidRouteTableID.NotFound
rather than a transit-gateway-specific code. Checked on a live account:

  enable DefaultRouteTableAssociation conflicts with
  AssociationDefaultRouteTableId null

  disable DefaultRouteTableAssociation conflicts with
  AssociationDefaultRouteTableId tgw-rtb-0123456789abcdef0

  Transit Gateway Route Table tgw-rtb-0123456789abcdef0 was deleted or
  does not exist.

Validate instead: the flag and its id have to move together in both
directions, and a named table has to exist. The divergent state is now
unreachable and a rejected call leaves the gateway untouched.

* fix(ec2): carry a default route table change through to what it governs

Disabling DefaultRouteTableAssociation or DefaultRouteTablePropagation
changed the flag alone, leaving the id it governs on the gateway and the
matching marker on the route table. A describe then reported the option
disabled while still naming a table, and the table still claimed to be
the default for it.

Checked on a live account. Disabling association on a gateway created
with both defaults enabled drops AssociationDefaultRouteTableId from the
options entirely rather than blanking it, clears DefaultAssociationRouteTable
on the table, and leaves the table itself in place with its propagation
marker and the gateway's PropagationDefaultRouteTableId untouched:

  DefaultRouteTableAssociation  disable      (no AssociationDefaultRouteTableId)
  DefaultRouteTablePropagation  enable       PropagationDefaultRouteTableId tgw-rtb-…
  tgw-rtb-…  available  defAssoc False  defProp True

Apply the same: the id follows its flag, the table's marker follows with
it, and the table survives. Enabling with a named table marks that table
instead.

* fix(ec2): require a default route table to belong to the gateway naming it

The route table named on a ModifyTransitGateway request was only checked
for existence in the region, so a gateway could take another gateway's
table as its default. Worse than a bad reference: applying the change
then rewrote the foreign table's own default marker, leaving the gateway
that actually owns it describing a table that no longer claims to be its
default.

AWS rejects this, under the same code as a table that exists nowhere but
with the gateway named in the message. Checked on a live account, gateway
A naming gateway B's default table:

  Transit Gateway Route Table tgw-rtb-0381f… was deleted or does not
  exist in Transit Gateway tgw-0438f…

Both wordings are now reproduced: unqualified when the table exists
nowhere, gateway-qualified when it exists but belongs elsewhere.

The three rules governing these options - flag and id agreeing in both
directions, and the named table existing and belonging to the gateway -
now sit in one validation block rather than accumulating as separate
guards.

* fix(ec2): judge a default route table change against the stored gateway

Validation looked only at the request, so a route table id arriving
without its flag skipped the coherence check entirely: the id was stored
while the table's default marker was left alone, and a disabled option
could end up naming a table.

AWS judges the pair against the gateway as it stands. Probed the whole
combination surface on a live account rather than the one case reported:

  id alone, option enabled     accepted
  id alone, option disabled    InvalidParameterCombination, and the
                               message quotes the stored flag, not the request
  enable alone, table named    accepted, keeps that table
  enable alone, no table       InvalidParameterCombination
  disable with an id           InvalidParameterCombination
  disable with an unknown id   the combination is reported, not the lookup

So the flag defaults to the stored one when the request omits it, enabling
without an id keeps the table already named rather than dropping it, and an
id on its own marks its table. The lookup still runs after the combination
check, which is the order AWS reports them in.

Two other behaviours from the same pass, both already correct and now
covered: removals apply before additions, so a CIDR added and removed in
one call survives, and removing a CIDR that is not present is accepted.

* fix(ec2): serialize transit gateway CIDR blocks as the string list they are

transitGatewayCidrBlocks is a plain string list, so each item carries the
CIDR as its own text. The items wrapped it in a cidrBlock element
instead, which the AWS CLI parsed as an empty string: a caller that added
a block got it back as "" from create, describe and modify alike.

Caught by the CLI compatibility suite, not by the integration test, which
asserted the same wrong shape the handler produced and so agreed with it.
The bats case now reads the list back through describe as well as modify,
since one helper serializes all three responses.

* fix(ec2): apply tag changes to a transit gateway, not just to the tag store

CreateTags and DeleteTags on a tgw- id updated the tag store but left the
gateway object alone, because updateResourceTags had no branch for it.
DescribeTags saw the change and DescribeTransitGateways did not, so a
gateway kept serving whatever tags its TagSpecification carried at
creation.

That is the path a Terraform tag update takes: the provider sends
CreateTags, then re-reads with DescribeTransitGateways and compares. With
the two disagreeing, aws_ec2_transit_gateway would never converge.

Route tables get the same branch, so their tags behave once part three
can create them.

The AWS CLI cases now cover the tag round trip and CIDR blocks supplied
at creation, both of which were only asserted against shapes this branch
produced itself.
2026-08-15 18:11:24 -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
Michal SchreiberandMichal Schreiber dfcd492198 feat(ec2): allow a security group rule to take a prefix list as its source (#2271)
* feat(ec2): allow a security group rule to take a prefix list as its source

AuthorizeSecurityGroupIngress and AuthorizeSecurityGroupEgress now read
IpPermissions.N.PrefixListIds.M, so a rule can name a managed prefix list
instead of a CIDR. The rule carries prefixListId in place of cidrIpv4 and
DescribeSecurityGroups nests the reference under the permission, matching the
shapes AWS returns.

AWS emits one rule per source, so createRules expands a permission across its
CIDRs and its prefix lists rather than treating the two as alternatives; a
permission naming neither still yields the single bare rule it did before. An
unknown list is rejected with InvalidPrefixListID.NotFound before the rule is
stored, so a typo cannot leave a rule pointing at nothing.

Closes #2269

* fix(ec2): resolve every prefix list before writing any security group rule

createRules stored the CIDR rules of a permission before validating its prefix
lists, so a permission naming a valid CIDR alongside an unknown list returned
InvalidPrefixListID.NotFound while leaving the CIDR rule behind. AWS persists
neither, checked against a live account, and rejects the call as a whole rather
than per permission.

Resolve every reference a request names before the first write, across all of
its permissions, so a later bad permission cannot leave an earlier good one
applied. Also brace the new parsing conditional, as AGENTS.md requires.

* style(ec2): brace the conditionals in parseIpPermissions

AGENTS.md is unconditional about braces, and the method held five unbraced
conditionals around the line this branch added. Bracing the whole method rather
than only the new line keeps it internally consistent.

* fix(ec2): scope security group revocation to the sources it names

Revocation compared only protocol and ports, so revoking one source removed
every permission sharing that tuple: revoking a prefix list also dropped a CIDR
rule on the same port. AWS scopes it to the source, verified against a live
account, and leaves the others in place.

Subtract the named sources instead, dropping a permission only once it had
sources and has lost them all. A request naming no source at all still removes
the whole matching permission, which is how a bare protocol and port revoke
behaves.

The permission a revoke names can be the very object authorize stored on the
group, so the source values are snapshotted before either list is mutated.

* fix(ec2): validate prefix lists once per request rather than per permission

Resolving the prefix lists again inside createRules reopened the window the
request-wide check had closed: a list can be deleted between the two, since the
group lock and the prefix list lock are different monitors, so a later
permission could fail after earlier ones had already stored their rules.

Authorize resolves every reference before the first write, so the repeat is
removed. createRules keeps no validation of its own; its other callers pass the
CIDR-only default egress permission.

* fix(ec2): resolve group references when revoking too

Scoped revocation compares the sources a request names against the ones
stored on the permission. Authorize resolves a reference made by group
name to its group id before storing it, so a revoke naming the same
source by name alone carried no id and matched nothing: the rule
survived the revoke that named it.

Resolve on the revoke path as well, mirroring authorize.

This only surfaces once both source-scoped revocation and group
references as a source exist, so the gap is between this branch and
#2266 rather than in either alone.

---------

Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
2026-08-15 13:11:53 -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
Priamo Germosen 984886f697 feat(kms): implement UpdateAlias (#2324)
* feat(kms): implement UpdateAlias

Repoints an existing alias at a different KMS key, following the
existing createAlias/deleteAlias/resolveKey patterns. Required by the
Terraform AWS provider, which treats a target_key_id change on
aws_kms_alias as an in-place update.

* fix(kms): reject invalid replacement keys in UpdateAlias

UpdateAlias accepted any existing key as a replacement target,
including keys pending deletion or with a different key usage/spec
than the alias's current target. Real AWS KMS rejects both: the
replacement key must be in a compatible state and match the current
target's key usage and key spec.

* fix(kms): compare key type instead of exact key spec in UpdateAlias

The exact KeySpec comparison rejected valid updates between same-type
keys with different specs (e.g. RSA_2048 to RSA_3072), which AWS KMS
accepts as long as both keys share the same key type and usage.

* test(kms): add Terraform compatibility test for UpdateAlias

Verifies the exact scenario from #2291: the Terraform AWS provider
treats target_key_id on aws_kms_alias as an in-place update, so
re-applying with a different target must call UpdateAlias and update
the alias without a destroy/recreate. Self-contained config, mirroring
the eni-destroy-tf pattern, since it needs a second apply with a
different var rather than the shared single-apply main.tf.

* fix(kms): compare key family instead of KeyType in UpdateAlias

Comparing the fine-grained KeyType enum rejected valid cross-family
asymmetric updates (e.g. RSA_2048 to ECC_NIST_P256) that AWS KMS
accepts. AWS only requires the current and new key to be "the same
type (both symmetric or both asymmetric or both HMAC)" - a coarser
three-way split - so compare on that instead.
2026-08-15 12:54:39 -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
Priamo Germosen b71bfc46b6 fix(iam,lambda): return resource tags in Get and Create responses (#2262)
* fix(iam,lambda): return resource tags in Get and Create responses

IAM stored role, policy and user tags and served them through
ListRoleTags/ListPolicyTags/ListUserTags, but never serialized them into
the Create/Get responses. Lambda did the same with GetFunction. The AWS
SDKs and the Terraform provider read tags off those responses rather than
by calling List*Tags, so every tagged role, policy, user and function read
back untagged: apply succeeds and then plan never converges.

The inclusion is asymmetric, and getting that wrong deviates from AWS in
the opposite direction. IAM's resource-listing operations deliberately
return a subset of attributes:

  ListRoles    "does not return the following attributes, even though they
                are an attribute of the returned object: PermissionsBoundary,
                RoleLastUsed, Tags"
  ListUsers    same, for PermissionsBoundary and Tags
  ListPolicies "this operation does not return tags"

roleXml, userXml and policyXml therefore take a detailed flag, following
the pattern #2155 established for the policy Description. Description on a
role stays unconditional: it is absent from the ListRoles exclusion list.
For policies one flag governs both Description and Tags, since ListPolicies
excludes them on identical grounds.

Detail call sites are CreateRole, GetRole, CreateServiceLinkedRole,
CreateUser, GetUser, CreatePolicy and GetPolicy. Listing call sites are
ListRoles, ListUsers, ListPolicies and GetGroup, plus the roles embedded in
an instance profile — GetInstanceProfile's own example response shows those
as a subset.

tagsElement emits nothing rather than an empty <Tags/> for an untagged
resource, which would otherwise read back as a tag set the caller never
configured.

Lambda needs no such gate: ListFunctions returns FunctionConfiguration,
which has no Tags field at all.

Closes #2199

* test(iam,lambda): cover the tag round trip and the listing-subset rule

Adds a GetFunction case to the Lambda tag test, ordered after the untag so
it also pins that a removed tag is reflected rather than served stale.

Adds a tagged role and a tagged policy to the Terraform compatibility
config, with cases for the positive round trip, the ListRoles/ListPolicies
subset negatives, and a clean second plan. The re-plan assertion is the one
that catches this drift class: tags that do not survive the round trip
apply cleanly and only show up later as perpetual drift.
2026-08-15 12:26:51 -04:00
MAN$I VERMA c12f3fae7d fix(cloudformation): don't double-encode string-form SNS RedrivePolicy and FilterPolicy (#2325)
CDK emits AWS::SNS::Subscription RedrivePolicy/FilterPolicy and Step Functions
definitions as an already-serialized JSON string via Fn::Join. resolveNode
collapses the Fn::Join to a TextNode, and toString() on that node re-quotes and
re-escapes the JSON a second time, so the stored policy is double-encoded and
SNS can no longer parse it (dead-lettering silently fails).

Add CloudFormationTemplateEngine#resolveJsonAttribute, which unwraps textual
results while keeping normal serialization for plain object/array nodes, and
use it at every site that stores a resolved node as a JSON document:
SNS FilterPolicy/RedrivePolicy, Step Functions Definition, IAM inline policy
documents, and the SQS RedrivePolicy already fixed in #1939.

Verified: GetSubscriptionAttributes returns the literal policy JSON and
regression tests mirror the SQS pattern from #1939.
2026-08-15 12:17:06 -04:00
Dixit R Jain 3cfa983479 fix(apigateway): honor configured execute-api hostname (#2286)
* fix(apigateway): honor configured execute-api hostname

* refactor(apigateway): cache execute-api hostname
2026-08-15 11:02:52 -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
soreavis 5afb60d0f5 fix(kinesis): reject records over the 1 MiB size limit (#1896)
* fix(kinesis): reject records over the 1 MiB size limit

PutRecord and PutRecords accepted records of any size; real Kinesis
rejects a record whose data blob plus partition key exceeds the
stream's maximum record size (1 MiB by default). Floci doesn't
implement UpdateMaxRecordSize, so every stream sits at the default.

Validate in putRecordWithShardId, covering both operations. An
oversized record in PutRecords fails the whole request up front,
before anything is written: the per-record ErrorCode field is
reserved for ProvisionedThroughputExceededException and
InternalFailure, so a size violation cannot be reported per record.

Closes #1755

* refactor(kinesis): decode batch entries once and resolve stream first

Review round: cache successful Data decodes for the write loop
(malformed entries keep their per-record failure), resolve the
stream before the size check so a missing stream reports
ResourceNotFoundException, and add a wire-level PutRecords
over-limit test.

* test(kinesis): cover PutRecords per-record failure and unknown stream

Two paths the size-limit change touched had no coverage: no test produced
a non-zero FailedRecordCount for Kinesis, and none covered PutRecords
against a missing stream.

Malformed per-record Data must stay a per-record InternalFailure rather
than a whole-batch failure. Collapsing the decode fallback to
entry.data() drops FailedRecordCount to 0 and stores a record with a null
blob, since validateRecordSize only counts the partition key; the next
GetRecords then fails on the encode.

Resolving the stream up front turns PutRecords against a missing stream
into ResourceNotFoundException instead of a per-record InternalFailure.
2026-08-15 09:22:20 -04:00
z9rtm 8ef71d6930 fix(cloudformation): honor resource-level conditions (#2255)
* fix(cloudformation): honor resource-level conditions

* fix: handle condition deletion failures

* fix(cloudformation): fail on unresolved condition dependencies instead of skipping

A resource that will be created must not depend on a resource excluded by a
false condition. Real CloudFormation rejects such a template synchronously at
CreateStack/UpdateStack with "Template format error: Unresolved resource
dependencies [X]" and provisions nothing, rather than silently skipping the
dependent (verified against AWS for DependsOn and Ref/Fn::Sub).

Validate the condition dependency graph in createChangeSet before any stack
state is created, and throw the same ValidationError from topologicalSort as a
safety net for nested/direct executions. Fn::If-guarded references remain valid
because dependency collection only walks the selected branch.

Tests cover: DependsOn and Ref/Fn::Sub unresolved dependencies fail; an
Fn::If-guarded false-branch reference is created; and a false->true condition
update creates the previously-skipped resource.

* fix: evaluate stackset conditions in target account

* fix(cloudformation): retain failed cleanup resources
2026-08-15 09:11:49 -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
Michal SchreiberandMichal Schreiber 4058dfae00 fix(ec2): type a security group rule's tags as security-group-rule (#2272)
* fix(ec2): type a security group rule's tags as security-group-rule

inferResourceType had no sgr- case, so DescribeTags reported a rule's tags as
resourceType "unknown" and a resource-type filter never matched them. The tags
themselves were already correct: createTags stores them and updateResourceTags
mirrors them onto the rule, so only the aggregation surface was wrong.

Closes #2270

* fix(ec2): brace inferResourceType and tag the group in its test

Bracing only the new arm would have left it the single braced line among
thirteen, so the whole method is braced rather than just the addition.

The test tagged only the rule, so the security-group assertion read an empty
result and fell back to the expected value through orElse, passing without
exercising the sg- classification at all. Tag the group too and assert on the
result directly; removing the sg- arm now fails the test.

---------

Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
2026-08-14 22:50:03 -04:00
Jay 58129108bf fix(cloudformation): expand AWS::Serverless::HttpApi via SAM transform (#2146)
* fix(cloudformation): expand AWS::Serverless::HttpApi via SAM transform

SamTransformProcessor's switch on SAM resource types only handled
AWS::Serverless::Function, AWS::Serverless::SimpleTable, and
AWS::Serverless::Api (REST, v1) — AWS::Serverless::HttpApi fell into the
default branch and was silently dropped from the expanded template, along
with any Auth.Authorizers/DefaultAuthorizer config and any HttpApi-typed
Events on a sibling Function. A stack using AWS::Serverless::HttpApi
reported CREATE_COMPLETE with a synthesized physical id for the resource,
but no AWS::ApiGatewayV2::Api ever existed.

Adds expandServerlessHttpApi, mirroring the existing explicit-API pattern
(expandServerlessApi for REST v1) rather than the implicit-API path
(generateImplicitApi/collectApiRoutes), scoped to the explicit
AWS::Serverless::HttpApi + Function Events ApiId: {Ref: ...} form. For
each explicit HttpApi resource this synthesizes a real
AWS::ApiGatewayV2::Api, a $default auto-deploy Stage, one
AWS::ApiGatewayV2::Authorizer per Auth.Authorizers entry (mapping SAM's
mixed-case JwtConfiguration.issuer/audience onto the PascalCase
Issuer/Audience the raw CFN resource expects), and — for every Function
event bound to that API — an AWS_PROXY Integration, a Route wired to
Auth.DefaultAuthorizer when present, and a Lambda::Permission.

Implicit HttpApi (a Function's HttpApi event with no ApiId, where SAM
auto-creates the API) is intentionally out of scope here, matching how
this file already keeps generateImplicitApi/collectApiRoutes as a separate
concern from expandServerlessApi's explicit-resource handling.

Full JWT-authorizer enforcement additionally requires #1758
(AWS::ApiGatewayV2::Authorizer CloudFormation provisioning) — without it,
the Authorizer resource this transform synthesizes is itself dropped by
the provisioner's default branch, the same way it is for a raw (non-SAM)
template. Verified locally with both fixes applied together; #1758 is a
separate PR since the bugs are independent (raw-CFN provisioning vs. SAM
transform expansion) even though a SAM+JWT-authorizer template needs both.

Fixes #1759.

* fix(cloudformation): honor per-event Auth: {Authorizer: NONE} on HttpApi events

expandServerlessHttpApi applied the HttpApi's Auth.DefaultAuthorizer to every
route uniformly, ignoring SAM's documented per-event override
(Events.<Name>.Properties.Auth.Authorizer: NONE) that lets a specific route
opt out of the default authorizer — e.g. a route whose auth is handled
inside the application itself and needs a missing/invalid token to still
reach the handler rather than being rejected by the gateway.

HttpApiRoute now carries whether its event declared Auth.Authorizer: NONE,
collected in collectHttpApiRoutes alongside the existing path/method
fields, and expandHttpApiRoute skips wiring the default authorizer for
routes that opted out.

Found while validating #1759's fix against a template with this exact
pattern (one route using the default JWT authorizer, a second explicitly
set to Authorizer: NONE) — the original fix would have silently applied
the default authorizer to both.

* fix(cloudformation): forward SAM authorizer IdentitySource for HttpApi JWT authorizers

expandServerlessHttpApi's buildHttpApiAuthorizer hardcoded IdentitySource to
$request.header.Authorization regardless of what the SAM template's
Authorizers.<Name>.IdentitySource declared, silently overriding any
non-default source (e.g. $request.querystring.token) with the header form.

CloudFormationResourceProvisioner.resolveIdentitySource and
ApiGatewayExecuteController already support arbitrary identity sources,
including querystring, for raw (non-SAM) AWS::ApiGatewayV2::Authorizer
resources — this closes the same gap for the SAM transform, accepting either
the documented array form or a scalar string, matching the raw provisioner's
leniency.

Verified by reverting the fix and confirming
createStack_samHttpApiAuthorizerHonorsCustomIdentitySource fails.

* fix(cloudformation): reject SAM JWT authorizer with no IdentitySource

Real sam deploy rejects a JWT authorizer that omits IdentitySource
(_validate_jwt_authorizer in samtranslator/model/apigatewayv2.py) rather
than defaulting it. This transform was silently defaulting to
$request.header.Authorization instead, so a template real SAM refuses
would pass here quietly.

* fix(cloudformation): reject SAM HttpApi authorizer with no JwtConfiguration, honor case-insensitive Issuer/Audience

SAM's _validate_jwt_authorizer checks JwtConfiguration before IdentitySource,
rejecting a template that omits it. buildHttpApiAuthorizer treated it as
optional, silently producing an authorizer that would never validate a token
for real sam deploy. It now rejects in the same order SAM does.

SAM's _get_jwt_configuration also lower-cases every JwtConfiguration key
before reading it, so any casing of issuer/audience is accepted, not just the
two spellings the docs happen to show. Only the lowercase form was read here,
so a template using another casing silently produced an authorizer with an
empty JwtConfiguration instead of an error.
2026-08-14 22:03:23 -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
lex00 a985fa4640 feat(cloudformation): provision AWS::EC2::VPCEndpoint (#1995)
* feat(cloudformation): provision AWS::EC2::VPCEndpoint

Maps VpcId/ServiceName/VpcEndpointType and the RouteTableIds/SubnetIds/
SecurityGroupIds reference lists onto the existing
Ec2Service.createVpcEndpoint; DeleteStack removes the endpoint.

Fixes #1994

* refactor(cloudformation): move VPCEndpoint into the per-service provisioner structure

Ec2VpcEndpointCfnProvisioner implements CfnResourceProvisioner for
AWS::EC2::VPCEndpoint and injects only Ec2Service. The registry discovers it
via CDI, so the provision and delete switch arms plus the resolveIdList helper
come out of CloudFormationResourceProvisioner.

Two review fixes carried in with the move:

- PrivateDnsEnabled now resolves through the template engine instead of
  props.path(...).asBoolean(false), so a Ref or parameter no longer collapses
  to false. An absent property passes null and Ec2Service applies the AWS
  default (true for Interface endpoints).
- An update deletes the endpoint it replaced, so re-deploys no longer leave
  orphaned endpoints behind. A missing prior endpoint is tolerated.

Adds an isolated unit test for the new provisioner; the existing
CloudFormationVpcEndpointIntegrationTest still covers the end-to-end path.

* feat(cloudformation): VPCEndpoint sets the CreationTimestamp attribute

The registry schema lists Id, CreationTimestamp, NetworkInterfaceIds and
DnsEntries as Fn::GetAtt attributes, and only Id was set. An unset attribute
resolves to the literal "LogicalId.CreationTimestamp" rather than failing, so a
template asking for it got a wrong value with nothing to signal it.

Ec2Service already stamps the timestamp at create, so the provisioner renders it
with the same format DescribeVpcEndpoints uses. NetworkInterfaceIds and
DnsEntries are not modelled yet and stay unset.
2026-08-14 21:03:56 -04:00
lex00 105a8eeb7e feat(cloudformation): provision AWS::Lambda::Permission and fix Version and Alias updates (#1997)
* feat(cloudformation): provision AWS::Lambda::Permission, Version, and Alias

Maps the three Lambda addressing resources onto the existing
LambdaService APIs: Permission -> addPermission (statement id = logical
id, SourceArn/SourceAccount carried), Version -> publishVersion (Ref =
version-qualified ARN, Version/FunctionArn attributes), Alias ->
createAlias (Ref = alias ARN).

Fixes #1996

* refactor(cloudformation): move Lambda addressing into a per-service provisioner

Moves AWS::Lambda::Permission, Version and Alias out of the
CloudFormationResourceProvisioner switch into LambdaAddressingCfnProvisioner,
following the SqsCfnProvisioner pattern. CloudFormationResourceProvisioner is
now byte-identical to main again.

The provisioner implements delete(), so the three resource types no longer
survive stack deletion. Physical ids double as delete handles: a Permission
stores <functionName>|<statementId>, a Version its version-qualified function
ARN, an Alias its alias ARN.

Also fixes two behaviors the switch arms did not cover:

- Alias RoutingConfig.AdditionalVersionWeights is now parsed and passed to
  LambdaService instead of being discarded.
- Stack updates no longer recreate these resources. A Permission replaces its
  previous statement rather than colliding on the duplicate Sid, a Version
  keeps the version it already published, and an Alias updates in place,
  deleting the old alias when a rename retargets it.

Adds LambdaService#deleteVersion (and the matching store method) so a single
published version can be removed without taking $LATEST with it.

* fix(lambda): a rejected permission replacement puts the previous statement back

A stack update re-provisions every resource, and AddPermission rejects a
duplicate Sid, so the provisioner removed the previous statement before adding
its replacement. When the replacement was then rejected the function was left
with neither: CloudFormation reported UPDATE_ROLLBACK_COMPLETE while every
service that could invoke the function before the update had lost access.

The statement is now captured before it is removed and put back if AddPermission
fails, with the restore failure attached as suppressed so the stack still
reports the original error. LambdaService gained restorePermissionStatement for
this, which takes the stored statement shape rather than an AddPermission
request so what goes back is exactly what came out.

* fix(cloudformation): narrow the provisioner to AWS::Lambda::Permission

upstream #1961 added LambdaVersionAliasCfnProvisioner, which claims
AWS::Lambda::Version and AWS::Lambda::Alias. This provisioner claimed the same
two, and the registry rejects a duplicate claim, so every stack rolled back with
"Duplicate CloudFormation provisioner for AWS::Lambda::Version".

Version and Alias provisioning is dropped here in favour of that one, which sets
the same physical id and attributes. What is left is AWS::Lambda::Permission,
which nothing else provisions.

Delete now tolerates a statement or function that is already gone, so a
DeleteStack retry does not fail a resource for work already done.

* fix(cloudformation): a stack update keeps its Lambda version and applies alias routing

Two gaps in LambdaVersionAliasCfnProvisioner, both reachable from a plain
UpdateStack.

provisionVersion called publishVersion unconditionally, so every update minted a
new version and repointed every Ref to it. Version resources are immutable in
CloudFormation, so the version this resource already published is kept while it
still exists, and a new one is published only when it is gone or the
FunctionName property moved to a different function.

RoutingConfig was not carried over, on the grounds that nothing emitted it. The
CloudFormation path does, so AdditionalVersionWeights is parsed and passed to
create and update. A template that declares no RoutingConfig clears the weights
rather than keeping them, which is why the existing alias test now expects an
empty map instead of null.
2026-08-14 20:41:12 -04:00
lex00 30a61646ac feat(ec2): support CreateImage (create AMI from instance) (#1979)
* feat(ec2): support CreateImage from an instance

Validates the source instance exists, then registers an image the same
way RegisterImage does. Unblocks AMI-baking flows (e.g. CDK
AwsCustomResource calling ec2:CreateImage on a stack-created instance).

Fixes #1978

* fix(ec2): CreateImage reboots the source and produces a launchable AMI

Two review findings.

CreateImage ignored the default reboot. AWS reboots the source instance unless
NoReboot=true so the image is captured from a quiesced file system; the action
only checked that the instance existed. NoReboot is now parsed and the reboot
runs by default.

The resulting AMI kept nothing of what it was captured from. registerImage was
called with null architecture, root device and block device mappings, so
DescribeImages reported a generic x86_64 /dev/sda1 image with no devices, and
RunInstances on the new id fell through to the catalog default guest because a
generated ami-* is not in the catalog. The image now inherits architecture,
root device name and block device mappings from the source instance's image,
and records the launchable ancestor so RunInstances starts the same guest.
CreateImage on an instance launched from a created AMI follows the chain back.

Tests: unit coverage for the reboot default and its NoReboot opt-out, and for
chained images resolving to the catalog ancestor rather than the generated id;
integration coverage that an arm64 source yields an arm64 AMI that launches.

* fix(ec2): a capture of a catalog AMI reports its root device

CreateImage inherits the source image's block device mappings, but a catalog
entry describes only its root device name and carries no mappings, so an AMI
captured from a catalog-launched instance was registered with no devices and
DescribeImages reported none.

The root device is now rebuilt from the catalog entry, with a snapshot
registered through the existing RegisterImage path.

* fix(ec2): a capture takes its own snapshot of each device

CreateImage handed the source AMI's mappings straight to RegisterImage, so the
captured image reported the source's snapshot ids and the two images shared one
snapshot. The mappings are now copied with fresh snapshot ids, keeping the
device name, size, type and encryption.

* fix(ec2): a capture includes the volumes attached after launch

CreateImage read only the mappings of the AMI the instance was launched from, so
a data volume attached afterwards was missing from the captured image. AWS
records block device mapping information for those volumes as well.

The instance's attached volumes are now added to the capture, each with its
device name, size, type and a fresh snapshot. The root volume is skipped because
the source AMI already describes that device.

Also lists CreateImage and RegisterImage in the AMIs action table. That table is
hand-maintained because Ec2QueryHandler is a deferred handler.

* fix(ec2): a capture reports the root volume type the source actually has

The catalog-source fallback in sourceImageMappings recorded the rebuilt root
device as gp2, while RunInstances creates the source instance's root volume as
gp3. DescribeImages therefore reported a type the instance never had.

Both sites now read one DEFAULT_ROOT_VOLUME_TYPE constant, alongside the
existing DEFAULT_ROOT_VOLUME_SIZE_GIB, so the two cannot drift apart again.
2026-08-14 18:33:46 -04:00
Feyikemi OgunsanyaandPriamo Germosen 58112b1f3b fix(cloudformation): map FIFO and redrive attributes for AWS::SQS::Queue (#1939)
* test(cloudformation): reproduce dropped DeduplicationScope and FifoThroughputLimit in SqsCfnProvisioner

* test(cloudformation): reproduce dropped RedrivePolicy in SqsCfnProvisioner

* fix(cloudformation): pass DeduplicationScope and FifoThroughputLimit to CreateQueue

* fix(cloudformation): serialize RedrivePolicy with resolved DLQ ARN for CreateQueue

* test(cloudformation): cover FifoQueue mapping for queues without an explicit QueueName

* fix(cloudformation): map FifoQueue and suffix generated FIFO queue names with .fifo

* test(cloudformation): verify CFN FIFO queue attributes end-to-end via CreateStack

* refactor(cloudformation): resolve FifoQueue once in SqsCfnProvisioner

* fix(cloudformation): unwrap already-serialized RedrivePolicy strings

RedrivePolicy in a template is usually a JSON object, but CDK commonly
emits it as an already-serialized JSON string via Fn::Join. resolveNode
collapses that to a TextNode, and calling toString() on it re-encodes
(quotes/escapes) the string a second time, so SqsService.createQueue
receives an unparseable value and the redrive silently doesn't work.

Reported on #1939.

* test(cloudformation): add regression test for string-form RedrivePolicy

Reproduces the double-encoding bug reported on #1939: when RedrivePolicy
is supplied as an already-serialized JSON string (CDK's common Fn::Join
form), resolveNode collapses it to a TextNode and TextNode#toString()
re-quotes/escapes it, so SqsService receives an unparseable value.

* chore: retrigger CI (transient base-image layer pull failure)

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-14 17:10:26 -04:00
thejrose1984andPriamo Germosen 0971cf6f64 fix(cloudformation): resolve ASG launch templates by id and MixedInstancesPolicy (#2005) (#2019)
An AWS::AutoScaling::AutoScalingGroup that pointed at its launch template
any way other than by LaunchTemplateName failed with "The specified
launch template does not exist."

provisionAutoScalingGroup collapsed LaunchTemplateId into the launch
template name argument, and Auto Scaling matches names exactly, so a
valid lt- id — including one that a Ref to an in-stack
AWS::EC2::LaunchTemplate resolves to — never matched. The id and name are
now passed to createAutoScalingGroup separately.

MixedInstancesPolicy was never read from template properties, so a
mixed-instances group reached Auto Scaling with no launch source and
failed validation. It is now built in the same shape the Query API parser
produces, including Overrides[].InstanceType and InstancesDistribution; a
non-integer distribution value fails the stack rather than being silently
dropped.

CloudFormationAsgLaunchTemplateIntegrationTest covers resolution by name,
by id, through a Ref to an in-stack launch template, and through
MixedInstancesPolicy.

Closes #2005

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-14 16:17:47 -04:00
Bill DeMoss 7d66bf087a fix(cloudformation): expand SAM AutoPublishAlias into Version + Alias (#1961)
* fix(cloudformation): expand SAM AutoPublishAlias

AutoPublishAlias was read nowhere in the codebase, so the SAM transform
silently dropped it: the stack reached CREATE_COMPLETE, the function
deployed with only $LATEST, and an alias-qualified invoke then failed
with "Alias not found" far from the deploy that caused it. The
"Unsupported SAM resource type" debug arm only covers unknown resource
types, not unknown properties, so nothing was logged either.

Expand it into the AWS::Lambda::Version + AWS::Lambda::Alias pair real
SAM generates, and provision those two types. Both halves are needed:
the transform alone emits resources the provisioner ignores, and the
provisioner alone is unreachable from a SAM template.

The Lambda service already implements publishVersion and the alias APIs,
so this is plumbing rather than new service behavior. The new types go
through CfnResourceProvisioner rather than the legacy switch, following
the registry migration. Ref/GetAtt on the emitted properties give the
function -> version -> alias ordering that topologicalSort already
follows, so no explicit DependsOn is needed.

An intrinsic alias name (e.g. !Ref StageName) is passed through to Name
for the engine to resolve at provision time; only the generated logical
id needs a literal and drops the suffix in that case.

* test(cloudformation): cover Version/Alias provisioner directly

The SAM integration test drives provisioning end to end but cannot reach
two paths: the already-exists fallback (createAlias conflicting with an
alias that outlived a stack delete) and delete(), which its @AfterEach
invokes but never asserts on — a broken delete was silent.

Add LambdaVersionAliasCfnProvisionerTest alongside the existing Sqs and
Rds provisioner tests: attribute wiring for both types, the conflict
fallback, non-conflict failures still propagating, alias delete parsed
out of the ARN, delete idempotency when the alias is already gone,
version delete as a no-op, and a physical id that is not an alias ARN
(the generic fallback's shape on stacks predating this provisioner).

Also stop pinning the alias's FunctionVersion to a literal "1" in the
integration test: assert it is a number and not $LATEST, which is what
the assertion is actually for. Pinning the first version fails
confusingly when an earlier run leaks the function and its counter.

* fix(cloudformation): point the SAM alias at $LATEST

Real SAM points AutoPublishAlias at the published version, and the first
revision of this change did the same. Floci cannot invoke a published
version: the snapshot carries no code path, so a version-qualified
invoke times out on a cold start (#1987), and silently runs $LATEST's
code when a warm container happens to exist (#1988). Emitting the
faithful form therefore broke the alias-qualified invoke this expansion
exists to enable — strictly worse than not expanding the property.

Point the alias at $LATEST instead. The Version resource is still
emitted, so the resource set and GetAtt still match SAM; only the
alias target differs, and it flips back to the version in one line once
#1987 lands.

The integration test asserted the alias record existed with a numeric
FunctionVersion, which the broken form satisfied — so it passed while
the behavior was broken. It now invokes through the alias and asserts
the function actually runs, which fails against the version-pointing
form (verified by reverting it with the record assertion relaxed).

* fix(cloudformation): point the SAM alias at $LATEST

Restores the change d753187e was supposed to carry. That commit landed
only its unit-test half — the main-code change and the integration
test's invoke assertion were lost to a `git checkout --` used to undo a
verification experiment, leaving a test asserting $LATEST against code
still emitting the version pointer.

Real SAM points AutoPublishAlias at the published version. Floci cannot
invoke a published version: the snapshot carries no code path, so a
version-qualified invoke times out on a cold start (#1987) and silently
runs $LATEST's code when a warm container happens to exist (#1988).
Emitting the faithful form broke the alias-qualified invoke this
expansion exists to enable.

The Version resource is still emitted, so the resource set and GetAtt
match SAM; only the alias target differs, and it flips back in one line
once #1987 lands.

The integration test now invokes through the alias instead of only
asserting the alias record exists — the record assertion was satisfied
by the broken form. Verified load-bearing by re-applying the version
pointer with the record assertion relaxed: the invoke fails at the
function timeout.

* fix(cloudformation): sanitize the generated alias logical id

The AutoPublishAlias expansion built the alias resource's logical id by
concatenating the alias name raw. Lambda alias names may contain '-' and
'_', neither of which is valid in a CloudFormation logical id, so
`AutoPublishAlias: blue-green` emitted `MyFuncAliasblue-green`.

Route the suffix through the sanitize() helper this file already uses
for every other derived logical id. The alias name sent to Lambda is
untouched -- only the logical id changes.

Also corrects the expandAutoPublishAlias javadoc: with FunctionVersion a
literal $LATEST there is no version -> alias ordering edge, only
function -> version and function -> alias. None is needed, since the
alias does not reference the version; the edge returns with the GetAtt
form once #1987 lands.
2026-08-14 14:43:42 -04:00
Olamide KosileandPriamo Germosen 0cbfba82dd fix(cloudformation): infer Lambda FunctionName mode for pre-fix persisted stacks (#2177)
* fix(cloudformation): infer Lambda FunctionName mode for pre-fix persisted stacks

Fixes #2163

A Lambda function persisted before FlociLambdaFunctionNameMode was
tracked has no recorded mode, so removing an explicit FunctionName
from the template silently kept reconciling under the old explicit
name instead of triggering the replacement AWS requires - the same
bug already fixed for AWS::Logs::LogGroup in #1965/#2152.

Generalizes the LogGroup fix's isGeneratedLogGroupName into a shared
isGeneratedName(physicalId, stackName, logicalId, maxLength), reused
by both resource types instead of duplicated. Made it properly
truncation-aware in the process: at Lambda's 64-character limit,
generatePhysicalName's truncation path is actually reachable (unlike
LogGroup's 512, where CloudFormation's 128+255 character stack
name/logical id limits make it provably unreachable), so the shared
helper now reconstructs the exact expected prefix generatePhysicalName
would produce, truncation included, rather than only matching the
untruncated shape.

* docs(cloudformation): document isGeneratedName's lowercase and maxLength assumptions

Found while re-verifying #2163: several other generatePhysicalName
callers use lowercase=true (S3 bucket, some IAM resources, ECR repo)
or could theoretically use a very small maxLength, neither of which
isGeneratedName accounts for. Not a live bug since both current
callers (LogGroup at 512, Lambda at 64) use lowercase=false and a
maxLength comfortably above the point where the truncated prefix could
go empty, but worth spelling out for whoever reuses this next.

* fix(cloudformation): warn when legacy Lambda name inference is ambiguous

greptile flagged a real gap in the legacy FunctionName mode backfill:
isGeneratedName() can't distinguish a legacy explicit name that
deliberately matches the generated-name shape (e.g. a name copied from
an earlier auto-generated deploy and then pinned) from one that really
was auto-generated all along. If Floci gets it wrong, removing
FunctionName from the template silently keeps the old name instead of
triggering the replacement AWS would perform.

Checked whether this is actually closeable: LAMBDA_NAME_MODE_ATTR is
already written on every successful provision based on that deploy's
real hasExplicitName, so from a resource's second update onward the
mode is exact, no heuristic involved. The heuristic only ever runs
once, on a legacy resource's first update after this attribute was
introduced - and for that one-time backfill, there's no stored history
of the previous template's actual FunctionName property to consult;
Floci never persisted it. No additional data captured now can recover
what was never recorded then, so this can't be made more accurate.

What it can be is observable. Adds a warning logged specifically when
the inference is consequential - a legacy resource, no recorded mode,
the physical ID matches the generated shape, and the current template
also has no FunctionName - so an operator relying on that removal to
trigger a replacement has a chance to notice it silently didn't,
instead of this being an invisible guess. The other inference
direction (name doesn't match the generated shape) isn't ambiguous -
an auto-generated name always has the deterministic shape, so anything
else genuinely was explicit - and correctly doesn't warn.

Verified: two new tests confirm the warning fires for the ambiguous
case and stays silent for the unambiguous one. Confirmed the positive
test fails with the warning temporarily disabled and passes with it
restored. Full cloudformation package regression is green (one
pre-existing, unrelated ECR/Docker-dependent failure, confirmed
against a clean upstream/main baseline earlier this session).

* fix(test): pass the CloudFront service argument in the legacy name mode test

CloudFormationLambdaLegacyNameModeTest calls the CloudFormationResourceProvisioner
constructor with the parameter list it had before #1831 added the CloudFrontService
store, so the merge with current main does not compile. The call goes straight from
the trailing nulls to CloudFormationResourceRegistry, missing CloudFrontService
between them.

This branch predates #1831 (merged as 5657e350) and its CI last ran on 2026-08-08,
so the failure only appears against current main. Same shape as #2261 and #2288.

Verified: full test-compile clean, and 1090 tests pass across the cloudformation,
lambda and cloudwatch.logs packages.

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-14 14:35:25 -04:00