Commit Graph
1233 Commits
Author SHA1 Message Date
Allen Sanborn 41b5148824 fix(ec2): report a reachable EIP address, and run gzipped user-data (#2621)
* fix(ec2): report an address that actually answers, and run gzipped user-data

Two independent bugs, both of which end a Terratest suite the moment it tries
to SSH into an instance.

1. The address the API reports was never an address that works. Launch set
   PublicIpAddress to 127.0.0.1 on the strength of a comment calling it
   "host-reachable", but Docker publishes the guest's SSH on a high host port,
   so :22 there is nothing. AllocateAddress then invents a 54.x.x.x that routes
   nowhere, and that is the value Terraform surfaces as aws_eip.x.public_ip and
   test suites dial. The invariant now is that whatever DescribeInstances and
   DescribeAddresses report accepts a connection on the service's real port.

   Where the container network is routable from Floci's API clients — native
   Linux Docker, OrbStack — that address is the container's own IP: port 22 is
   really port 22 there, with no published mapping to translate, and so is every
   other port the guest listens on. Where it is not — Docker Desktop, whose
   containers sit behind a VM — nothing changes and 127.0.0.1 plus published
   ports remains. Which case applies is detected, never assumed, by a throwaway
   TCP connect towards the container network: a refusal is proof of a route,
   since only the container's network stack could have sent the RST. The one
   case a probe cannot settle is Floci running inside a container itself, where
   it measures container-to-container reachability while the clients that will
   use the answer are on the host; there the Docker backend arbitrates and
   FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE overrides either way.

   AssociateAddress re-points the EIP at that reachable address rather than
   leaving the fictional one. Aliasing instead would need Floci to own routing
   or DNS on the client's machine, and clients that read the address out of the
   API and dial it — Terratest does exactly this — would still get something
   dead. Association is also the first moment the answer is knowable. The cost
   is one deliberate deviation from AWS, an EIP whose public IP changes when it
   is associated; the AllocationId, AssociationId and domain are untouched, and
   disassociation restores the allocated address.

2. Gzipped cloud-init user-data was skipped in silence. The launch path
   recognised a literal "#!" or a plaintext MIME boundary and nothing else, so
   data.cloudinit_config { gzip = true } — the documented way to pass multipart
   user-data — was dropped whole. The instance booted fine and was simply
   missing everything it was supposed to install, which is what made this
   expensive to find. UserData is now unwrapped through gzip, base64, and
   base64-of-gzip before the existing shellscript/MIME handling, and the "no
   executable parts" line is a WARN that says what the consequence is.

* fix(ec2): re-resolve an associated EIP's address on DescribeAddresses

Association can happen before the instance has a container, and Docker hands out
a different bridge IP after a stop/start; either leaves the association naming an
address that no longer answers. DescribeAddresses is the call Terraform refreshes
public_ip from, so it is the last chance to be right.

* test(ec2): cover EIP re-pointing on associate, describe and disassociate

The address rewrite had no test of its own: reverting pointAddressAtInstance
left every existing test green, so nothing was holding the behaviour in place.
These three assert the claim directly — association reports the reachable
address rather than the invented 54.x.x.x one, DescribeAddresses re-resolves it
after the container IP moves, and disassociation hands the allocation back.

* docs(ec2): document container-IP routability and the EIP address rewrite

FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE was undocumented, and the IMDS table
still promised public-ipv4 always returns 127.0.0.1. The Elastic IP section now
states the one deliberate deviation from AWS — an associated EIP's public IP is
rewritten to something reachable — so it is not discovered by surprise.

* fix(ec2): bound gzipped UserData decompression to stop a heap-exhaustion DoS

GZIPInputStream#readAllBytes() materialized the full decompressed
UserData with no size limit, so a caller-controlled gzip stream (e.g.
via CreateLaunchConfiguration) could expand to gigabytes in the shared
emulator JVM. Bounds it the same way AwsJsonCborController.decodeBody
already does: read in chunks, discard and warn past 10 MB decompressed.

Also documents the container-ips-routable override in both the main
and test application.yml templates, alongside the other ec2 keys.

* fix(ec2): bound aggregate concurrent UserData gzip decompression

The per-payload 10MB decompression cap runs independently per launch
on the unbounded cached launch executor, so it only bounds what a
single launch can allocate. N concurrent RunInstances/
CreateLaunchConfiguration calls, each smuggling a near-cap gzip
payload, could together decompress N * 10MB at once with no aggregate
ceiling.

Add a shared Semaphore(4) that gunzip must acquire before
decompressing and release afterward, budgeting ~40MB of decompressed
UserData in flight at a time - a few multiples of the per-payload cap
rather than 1, so an ordinary burst of legitimate concurrent launches
isn't serialized to one at a time. A launch that can't acquire the
budget blocks briefly rather than failing, mirroring the existing
ContainerLauncher.POPULATE_SEMAPHORE pattern for capping concurrent
code-volume populates.

Adds a concurrency test that drives 12 real concurrent launches with
near-cap gzip UserData through a fixed thread pool and asserts, via a
test-only hook, that peak concurrent decompressions never exceeds 4.
Verified the test fails (peak of 12) when the budget is disabled.
2026-08-28 11:35:06 -04:00
Sam Fakhreddine c96dc98065 feat(s3): opt-in global bucket namespace and replication config (#2640)
* feat(s3): bucket replication configuration round-trip

PUT/GET/DELETE ?replication store the replication configuration verbatim
(validated for a Role and at least one Rule with a Destination/Bucket)
instead of falling through to CreateBucket. Storage-only fidelity — floci
performs no actual replication. Split from a cross-service commit; the IAM
password-policy and CloudFormation SSM-parameter changes ship separately.

* fix(s3): resolve buckets cross-account under a global bucket namespace

S3 bucket names are globally unique in AWS: a bucket lives in one account but is
legitimately reachable cross-account. floci's per-account isolation broke LZA,
which has member accounts read/write a management-owned shared assets bucket and
runs cross-account custom resources (e.g. Custom::S3PutBucketReplication) whose
Lambda calls back under a different account context than the bucket's owner.

Add an opt-in globalBucketNamespace mode (default off, preserving isolation):
bucket/object existence RESOLUTION spans every account's partition while LISTING
stays owner-scoped. Reads route through resolveBucket/resolveObject; bucket-config
MUTATIONS route through a new owner-aware mutateBucket helper that resolves the
owning account via AccountAwareStorageBackend.findAnyAccountEntry and writes back
to the owner's partition (putForAccount) rather than forking a phantom bucket into
the caller's partition. Applied to put/deleteBucketReplication — the path LZA's
Logging stage exercises cross-account.

* test(s3): guard getObject against torn reads under concurrent overwrite

LZA's Bootstrap stage fans out ~15 CodeBuild actions that redundantly re-upload
the same artifact keys (Source.zip/Config.zip) while other builds concurrently
download them. A non-atomic truncate-then-write would let a reader observe an
empty/partial object — which surfaced as an empty src-Config secondary source and
ENOENT: global-config.yaml. Add a stress test (4 writers / 4 readers) asserting
getObject never returns a torn view of a constant-size key.

* docs(s3): document the global bucket namespace flag

Describe FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE in s3.md, the
multi-account isolation exception, and the environment-variable reference.

* feat(s3): account-level Block Public Access (s3control PublicAccessBlock)

Add account-scoped PUT/GET/DELETE PublicAccessBlock to the s3control
controller, keyed by the x-amz-account-id header and stored separately
from the bucket-level configuration. LZA's Custom::PutPublicAccessBlock
custom resource calls this account-level op while building the
LoggingStack; without a route the resource reported FAILED and the
stack rolled back (NoStack on CDK readback).

(cherry picked from commit a1cdf186ac7909647350ced455c4e0ba5d2d26a0)

* fix(s3): persist account-level Block Public Access

The account-level (s3control) PublicAccessBlock configuration was held in a
plain ConcurrentHashMap, bypassing StorageFactory while every other piece of
S3 state goes through it. Block Public Access is a security control, and LZA's
Custom::PutPublicAccessBlock runs once per governed account during the
LoggingStack deploy — it does not re-run on a resumed pipeline. A restart
therefore dropped the control silently and every governed account started
reporting NoSuchPublicAccessBlockConfiguration.

Move it to a StorageFactory-backed store (s3-account-public-access-block.json)
addressed through the explicit *ForAccount overloads, so the account comes from
the validated x-amz-account-id header and globalBucketNamespace never widens it.
The s3 descriptor already declares storageKey/storageMode, so no catalog change
is needed and PersistentPathValidator now covers this state.

clear() no longer wipes the config: like the bucket and object stores, its
lifecycle belongs to StorageFactory.clearAll().

* fix(s3): check x-amz-account-id against the caller on Block Public Access

The account-level PublicAccessBlock operations took the account solely from the
x-amz-account-id header, which was only checked for being non-blank. Any caller
could read, overwrite or delete any account's Block Public Access configuration
by setting one header — and Block Public Access is a security control.

AWS s3control answers AccessDenied when the header does not name the caller's
own account: there a cross-account call carries credentials assumed into the
target account, so header and caller always agree. Compare the header against
the caller's resolved account and return the same AWS-shaped AccessDenied (403)
on a mismatch, resolving the caller exactly as AccountAwareStorageBackend does
so the check and the storage partition can never disagree.

One exception is kept deliberately: the configured default (management) account
may act on any account, because Floci's launched Lambdas run on placeholder
credentials that resolve to the management account instead of assuming a role in
the target account. Without it LZA's Custom::PutPublicAccessBlock — the reason
these operations exist — would be denied for every governed account. This is the
same allowance S3Service.mutateBucket already makes for
Custom::S3PutBucketReplication.

Enforcement is scoped to the three PublicAccessBlock routes; the tag routes on
this controller accept and ignore the header as before.

* docs(s3): state the global bucket namespace trade-off explicitly

No behaviour change. The flag widens bucket resolution across accounts, which
reads as an account-isolation violation to a reviewer working from a checklist.
Say the intent in place, on the config option and in the S3 guide: S3 bucket
names are globally unique in AWS, a bucket lives in one owning account, and
cross-account access is a policy decision — so a hard per-account partition
models a state AWS cannot reach and fails legitimate cross-account calls with
NoSuchBucket. Record what it costs too: with the flag on, only IAM and bucket
policy stand between a caller and another account's object. Mutations still
write back to the owning account and listing stays owner-scoped, and the flag
is off by default.

* fix(s3): keep the account-aware bucket replication over the upstream #2519 duplicate

Upstream landed its own Put/Get/DeleteBucketReplication (ce4f6d1c4), which
duplicated the branch implementation. The branch copy stays because it goes
through mutateBucket (the caller-scoped mutation the LZA
Custom::S3PutBucketReplication path requires) and validates Role, Rule and
Destination/Bucket; upstream's root-element MalformedXML check is folded
into it so nothing upstream tested is lost. Duplicate Bucket field and
accessors removed.

* fix(s3): enforce the modeled AccountId pattern and ReplicationRule status enum

Account-level Block Public Access took x-amz-account-id as its storage
partition key after only a blank check, so a value outside the s3control
AccountId shape (^\d{12}$) filed a security configuration under a partition
no account could address again.

PutBucketReplication stored the document after checking only that a Role, a
Rule and a Destination/Bucket were present, so a rule with a missing or
out-of-enum Status round-tripped through GetBucketReplication as a document
AWS would have rejected. Both now answer the error the operation already
uses for its other input guards.

* fix(s3): resolve GetBucketReplication cross-account under the global bucket namespace

putBucketReplication and every other bucket-config mutation resolve cross-account
through mutateBucket/resolveBucket when globalBucketNamespace is enabled, but
getBucketReplication still called bucketStore.get(bucketName) directly. A
management-account caller could write a bucket's replication configuration
cross-account (mirroring LZA's Custom::S3PutBucketReplication path) but a
follow-up GetBucketReplication under the same caller saw NoSuchBucket instead of
the configuration it just stored.

RED test: getBucketReplicationResolvesCrossAccount in
S3GlobalBucketNamespaceTest failed with NoSuchBucket before this change.

* fix(s3): validate each replication rule's own destination bucket

PutBucketReplication checked that at least one Bucket appeared anywhere in the
document, then validated only Status per rule. A multi-rule document where only
one rule carried a Destination/Bucket satisfied that document-wide check and
round-tripped through GetBucketReplication as a configuration AWS would have
rejected as MalformedXML.

Destination elements appear in the same document order as their owning Rule
(extractGroupsMulti can't see nested Destination/Bucket as a Rule leaf), so
pairing the Destination list position-for-position with the Rule list and
requiring an equal count plus a non-blank Bucket in each enforces that every
rule carries its own destination.

RED test: putReplicationRejectsARuleWithoutItsOwnDestinationBucket in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): remove unreachable duplicate ?replication dispatch

The PUT and GET handlers each had two identical `if (hasQueryParam(uriInfo,
"replication"))` branches — a rebase artifact. The earlier branch in each
method always returns first, so the second was dead code that risked a future
routing change updating only one copy.

* docs(s3): expose global-bucket-namespace in the canonical application.yml

globalBucketNamespace() was documented in EmulatorConfig and in
docs/services/s3.md but absent from the s3 block in both application.yml
files, leaving the runtime configuration surface out of sync with what the
code and docs describe.

* test(s3): assert torn-read stress threads actually finish

The writer/reader threads were joined with a 30s timeout but never checked for
liveness afterward. A thread still running past the timeout could leak past
the test (hanging the suite) or let the assertions pass vacuously without that
thread's reads or writes having completed.

* fix(s3): reject malformed PutPublicAccessBlock bodies

s3control's PutPublicAccessBlockRequest requires PublicAccessBlockConfiguration,
but the controller normalized any body — null, empty, unparseable, or a
different root element entirely — into a valid configuration with every flag
defaulted to false via canonicalPublicAccessBlockXml. For an account-level
Block Public Access control, that silently disabled every protection on a bad
request instead of failing it.

Reject a body whose root element is not PublicAccessBlockConfiguration with
the same MalformedXML the bucket-level replication path already uses for this
class of error, before normalization runs.

RED test: putRejectsAMalformedOrWrongRootBody in
S3ControlAccountIdEnforcementTest got 200 instead of 400 before this change.

* fix(s3): validate replication destinations against their own rule, not the document total

Counting Rule and Destination elements document-wide and requiring the totals to match let a
rule with two Destinations balance a rule with none, satisfying the check while storing a
configuration AWS would reject as MalformedXML. Destination is Required: Yes directly on Rule, so
PutBucketReplication now walks the parsed element tree and requires each Rule to have exactly one
Destination of its own with a non-blank Bucket, instead of comparing counts across the whole
document.

* fix(s3): reject a replication destination with multiple Bucket elements

Destination.Bucket is a required scalar member (botocore
s3/2006-03-01/service-2.json: "Bucket":{"shape":"BucketName"}), not a list.
child("Bucket") returns only the first match, so a Destination with two Bucket
children silently accepted the first and stored a document AWS would reject
as MalformedXML.

Count the Bucket children explicitly and require exactly one, instead of
taking child("Bucket")'s single match unconditionally.

RED test: putReplicationRejectsADestinationWithMultipleBucketElements in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): wire bucket-policy operations through cross-account resolution

getBucketPolicy/putBucketPolicy/deleteBucketPolicy still resolved via
bucketStore directly, unlike object read/write and replication, so a
management-account caller got NoSuchBucket on a member-owned bucket's
policy even with the global bucket namespace enabled. Route them
through resolveBucket/mutateBucket like the rest of the cross-account
paths, and document the IAM-enforcement dependency and the same-name
non-determinism case in the trade-off writeup.

* docs(s3): name the flag that actually gates bucket-policy evaluation

The trade-off write-up said global-bucket-namespace's IAM/bucket-policy
protection depends on FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED, but that flag
only gates identity-policy checks in IamEnforcementFilter before a request
reaches S3 — bucket-policy evaluation itself (S3Service.authorizeS3Read/
authorizeS3Write, which reads the stored bucket policy) is gated separately
by FLOCI_SERVICES_S3_ENFORCE_AUTH, which also defaults false. Name both
flags and make explicit that the S3-specific one is what actually turns
bucket-policy evaluation on or off.
2026-08-28 11:24:47 -04:00
Allen Sanborn f1ad306599 fix(ec2): round-trip launch template data instead of discarding it (#2595)
* fix(ec2): round-trip launch template data instead of discarding it

CreateLaunchTemplate returned 200 and kept only ImageId, InstanceType,
KeyName, UserData, IamInstanceProfile, SecurityGroupIds and
TagSpecifications. Every other member of RequestLaunchTemplateData was
dropped without a word, so Terraform read back its own input missing and
reported "Provider produced inconsistent result after apply", or diffed
forever. MetadataOptions with HttpTokens=required (IMDSv2) and
BlockDeviceMappings appear in most Gruntwork ASG and ECS modules.

The AWS EC2 service model is the reference for what is stored and for the
element names it is read back under: request parameter names are the ones
botocore's EC2 serializer emits (note the singular BlockDeviceMapping.N
and NetworkInterface.N list prefixes, taken from each list member's
locationName), and response elements use ResponseLaunchTemplateData's
locationNames.

Stored and read back unchanged: ImageId, InstanceType, KeyName, UserData,
KernelId, RamDiskId, SecurityGroupIds, IamInstanceProfile,
BlockDeviceMappings, NetworkInterfaces, TagSpecifications, MetadataOptions,
Monitoring, Placement, CpuOptions, CreditSpecification, EnclaveOptions,
HibernationOptions, MaintenanceOptions, PrivateDnsNameOptions,
CapacityReservationSpecification, EbsOptimized, DisableApiTermination,
DisableApiStop, InstanceInitiatedShutdownBehavior.

Two further contradictions in the same call, both fixed:

- IamInstanceProfile keeps the form it was given. A profile submitted as
  Name reads back as Name rather than being rewritten to an Arn, so
  aws_launch_template.iam_instance_profile.name converges. The
  instance-profile ARN is derived at launch time instead.
- NetworkInterfaces survives as a NetworkInterfaces block. Its Groups are
  no longer hoisted into top-level SecurityGroupIds; on AWS the two are
  mutually exclusive, and the promotion made the block vanish from state.
  A launch resolves security groups from whichever of the two is set.

Deliberately out of scope, accepted and ignored rather than rejected:
InstanceMarketOptions, InstanceRequirements, LicenseSpecifications,
ElasticGpuSpecifications, ElasticInferenceAccelerators,
NetworkPerformanceOptions, Operator, SecondaryInterfaces, and
SecurityGroups (groups by name). Within NetworkInterfaces the IPv4/IPv6
address and prefix lists, EnaSrdSpecification,
ConnectionTrackingSpecification, PrimaryIpv6 and EnaQueueCount are also
ignored. A focused subset that round-trips beats a broad partial one.

LaunchTemplate no longer mirrors launch data in flat fields alongside its
version map; it holds one LaunchTemplateData, which removes the
dataFrom/applyData sync and collapses two 11-argument service methods into
a parameter object with explicit merge semantics for version creation.

Fixes a compatibility defect this collapse introduced (flagged by review):
a template persisted before this change stored the IAM instance profile as
a bare iamInstanceProfileArn string and instance tags as a flat
instanceTags list, both directly on LaunchTemplate and, separately, inside
each entry of its versions map. Neither key exists on the new model, so
ignoreUnknown silently dropped both on load - an upgrade would launch from
an existing template with no IAM profile and no instance tags, with
nothing in the logs to say so.

Legacy @JsonSetters on LaunchTemplateData and LaunchTemplate map both old
keys onto the new shape at load time, covering the versions-map entry (the
path DescribeLaunchTemplateVersions and AutoScaling actually read) and the
top-level fields (the path a template with no versions map falls back to).
Deserialize-only, so a file saved by the current code never regains the
old shape. Ec2ServicePersistenceTest#legacyIamProfileAndInstanceTagsSurviveRestart
seeds a hand-built pre-migration ec2-launch-templates.json and asserts both
paths survive a restart; reverting the two model changes alone fails it.

* fix(ec2): correct SourceVersion inheritance and round-trip VersionDescription

Addresses review feedback on the prior commit:

- CreateLaunchTemplateVersion with SourceVersion omitted merged onto the
  latest version instead of following the AWS-documented "no source
  specified, no inheritance" behavior. A version created without
  SourceVersion now starts from an empty LaunchTemplateData, populated
  only by whatever fields the request itself supplies.
- VersionDescription was accepted and silently dropped. It is a
  version-level field on LaunchTemplateVersion, not a member of
  RequestLaunchTemplateData, so it is tracked in a parallel per-version
  map on LaunchTemplate (alongside VersionNumber, CreateTime) rather than
  inside LaunchTemplateData, and round-trips through
  DescribeLaunchTemplateVersions. CreateLaunchTemplate accepts the same
  field for the initial version.
- SecurityGroups (security groups by name) stays out of scope: resolving
  names to IDs would need lookup machinery - store scan, not-found
  handling, ambiguity across VPCs - that no other EC2 action here has
  either (RunInstances itself only accepts SecurityGroupId). Documented
  the reasoning in both the code and docs/services/ec2.md so the ignored
  list stays accurate now that SourceVersion and VersionDescription are
  handled correctly.
2026-08-28 11:08:52 -04:00
Kenshin Okinaka 2963601f69 feat(ses): support v2 tenant CRUD (CreateTenant/GetTenant/ListTenants/DeleteTenant) (#2644)
* feat(ses): support v2 tenant CRUD (CreateTenant/GetTenant/ListTenants/DeleteTenant)

Add the first phase of SES v2 multi-tenancy: tenant create/get/list/delete via the
RPC-style POST routes under /v2/email/tenants. A new SesTenantService owns the tenant
store, id/ARN generation (tn-<hex>, arn:aws:ses:<region>:<account>:tenant/<name>/<id>),
the ENABLED sending status, and the TenantName validation (1-64 chars [A-Za-z0-9_-],
duplicate -> AlreadyExistsException, unknown -> NotFoundException); the facade delegates
and the controller only parses/renders. Resource associations, tenant suppression, and
tenant-scoped sending are follow-ups.

* docs(ses): correct account-scoping description in SesTenantService Javadoc
2026-08-28 11:03:12 -04:00
Sam Fakhreddine c90c5adfcb feat(lambda): code-signing endpoints and account settings (#2646)
* feat(lambda): GetAccountSettings with usage-derived account limits

Adds the Lambda GetAccountSettings operation. AccountUsage (total code
size and function count) is derived from the caller's stored $LATEST
functions in the region; AccountLimit reports the configured regional
concurrency limit and its unreserved share after per-function reserved
concurrency.

* fix(lambda): widen the default Runtime API port pool to 12000-12499

One Runtime API port is held for the lifetime of each running Lambda
container, so the width of the range is a hard ceiling on concurrent
Lambda executions. The old default of 9200-9299 gave 100, which a
multi-account AWS Landing Zone Accelerator deployment exhausts: it fans
out several custom-resource Lambdas per account and can want well over
a hundred at once.

Exhaustion did not announce itself as a capacity limit either. The
custom resource reported FAILED and CloudFormation rolled the stack
back, so an operator saw an apparently unrelated CloudFormation error
with no hint that a port pool was the cause.

12000 rather than a widened 9200 because the old range's tail collides
with ports floci and its sidecars already use: 9200 is OpenSearch's own
REST port, 9400-9499 is the OpenSearch host-binding pool, 9092 is Kafka
and 9644 Redpanda's admin port.

Both application.yml and the @WithDefault annotation are updated.
application.yml is a config source, not a set of defaults, so a value
set there wins over the annotation; changing only the annotation would
have been a silent no-op (issue #2225). The new test asserts the two
agree, so they cannot drift apart again.

Refs #2206

* fix(lambda): make the Runtime API port-pool exhaustion error self-describing

The old message did not name the pool, its width, or the property that
widens it. It also rarely reaches an operator directly: the Lambda
failure surfaces as a custom resource reporting FAILED and
CloudFormation rolling the stack back, so this text is buried in
floci's own log alongside a CloudFormation error that looks unrelated.

The message now carries its own diagnosis — which pool ran dry, how
many ports it had, that one port is held per running container so this
is the concurrent-execution ceiling, and the two properties that widen
it. Previously the only way to learn those knobs existed was to find
this class in the source.

Refs #2206

* feat(lambda): add ListFunctionsByCodeSigningConfig

Net-new endpoint, GET /2020-04-22/code-signing-configs/{arn}/functions,
always returns an empty FunctionArns list since this codebase has no
CodeSigningConfig management (no Create/PutFunctionCodeSigningConfig),
so no function can ever actually have one attached.

Implemented as its own controller class with its own class-level
@Path("/2020-04-22") rather than folding it into the existing
LambdaCodeSigningController (/2020-06-30): a JAX-RS class-level @Path
is load-bearing for route-matching priority, and stripping it to share
one class across two API-version prefixes causes both endpoints to
fall through to a more general catch-all route elsewhere in the app.

* fix(lambda): scope code storage, publish-version counters, and S3 sync-reload to the owning account

CodeStore resolved extracted code to baseDir/<functionName> with no account
segment, so two accounts' same-named functions in one region shared a single
on-disk directory and overwrote each other's package -- while codeObjectKey
already wrote the same package to an account-prefixed S3 key. Cross-account
invoke resolves a function by the ARN's own account, so a collision here
silently serves one account's code under the other's ARN.

The PublishVersion counter was keyed region+"::"+functionName and the delete
path removed that same unscoped key; both now key on the owning account, via
the shared ownerAccount() helper the S3 key already used.

onS3ObjectUpdated runs on the CDI event thread with no RequestContext, so its
ambient scan only ever saw the default account's partition and its save wrote
back into that partition. It now lists across every account (keeping the region
and $LATEST filters) and saves into the function's own account. listAll(), whose
only caller is the startup concurrency rehydration, is broadened the same way so
a restart no longer drops non-default accounts' reserved concurrency.

Recovered from 613db7bd1, re-derived onto upstream's current shape: CodeStore's
methods are re-signed rather than overloaded (the unscoped forms had no
remaining consumer), and the sync-reload uses a new region-filtered
listAllAccounts() instead of widening listAll() at that call site.

* fix(lambda): carry persisted version counters across the account-scoped key change

The counter map is persisted precisely so a restart cannot re-issue a version
number that already names a snapshot. Re-keying it on the owning account made
every pre-existing entry unreachable, so the next PublishVersion on an upgraded
deployment would have started again at 1 and overwritten the live :1 snapshot.
The counter now adopts and clears the pre-account key on a miss, and deleting a
function clears both forms.

Also covers the widened listAll(): the reserved-concurrency pool is per region
and shared across accounts, so the startup rehydration that feeds it has to see
every account or a restart silently frees capacity that steady-state
PutFunctionConcurrency had already accounted for.

* fix(lambda): validate CodeSigningConfigArn on ListFunctionsByCodeSigningConfig

The handler took @PathParam("codeSigningConfigArn") and never read it, so any
input — including "not-an-arn" — got a 200 with an empty FunctionArns array.
It also dropped the modeled Marker/MaxItems query parameters.

Botocore models InvalidParameterValueException (400) and
ResourceNotFoundException (404) for this operation, and carries a pattern on the
CodeSigningConfigArn shape:

  arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}((-gov)|(-iso(b?)))?-[a-z]+-\d{1}
  :\d{12}:code-signing-config:csc-[a-z0-9]{17}

(max 200 chars). That pattern is now applied verbatim, whole-string.

The 404 for a well-formed ARN is a derivation, not an observation against real
AWS: ResourceNotFoundException is modeled for this operation, the only resource
the path parameter can name is a code-signing config, and Floci implements no
CreateCodeSigningConfig / PutFunctionCodeSigningConfig — therefore every
well-formed ARN necessarily names a config that does not exist. The previous
always-empty 200 asserted the opposite (config exists, has no functions), which
is the stronger and false claim.

Validation order matches AWS: ARN shape, then MaxItems range (botocore
MaxListItems: min 1, max 10000), then resource resolution — so a bad MaxItems is
reported as such instead of being masked by the not-found. Marker is accepted
and stateless: the result set is always empty, so no NextMarker is ever emitted.

The pre-existing test asserted the 200-empty behaviour using an ARN whose csc-
suffix was 9 characters, which the model's pattern rejects; it is replaced by six
cases covering the two error classes and both MaxItems bounds.

docs/services/lambda.md's two "always empty" claims are corrected to match.

* docs(lambda): derive the operation count from the routed operations

The branch adds two operations (GetAccountSettings and
ListFunctionsByCodeSigningConfig) but bumped docs/services/index.md by one,
30 -> 31. Rather than hand-correcting to 32, the count was re-derived from the
routes, because 30 could not be reconstructed from anything in the tree.

index.md's own preamble states the rule for REST services: "the count reflects
distinct AWS SDK operations, collapsing routes where one JAX-RS handler fans out
via query-string or header markers". Counting JAX-RS methods across the Lambda
controllers on upstream/main gives:

  LambdaController              24
  LambdaConcurrencyController    3
  LambdaEventInvokeController    5
  LambdaLayerController          5
  LambdaTagController            3
  LambdaUrlController            4
                                --
                                44

Two collapses applied. LambdaCodeSigningController's /2020-06-30 route and
LambdaController's /2015-03-31 route are the same SDK operation
(GetFunctionCodeSigningConfig) and count once. LambdaUrlInvocationController (5)
and the lambda-package ApiGatewayController (5) are data-plane proxies with
{proxy: .*} catch-alls, not Lambda SDK operations, so they are excluded.

44 + GetAccountSettings + ListFunctionsByCodeSigningConfig = 46.

Corroboration that 44 is the real base and 30 is drift: docs/services/lambda.md's
Supported Operations table lists 34 rows on upstream/main and omits exactly the
5 layer and 5 event-invoke operations — 34 + 10 = 44. Those 10 missing table rows
are pre-existing and left alone here; only the count is in scope.

* fix(lambda): match the current CodeSigningConfigArn pattern for isolated partitions

The inlined regex predated the model's (eusc-)? prefix and widened -iso(b?)
alternation, so a well-formed ARN in aws-iso-e/iso-f or the European sovereign
cloud was rejected as malformed instead of reaching the modeled 404.

* fix(lambda): validate FunctionName length, Role ARN, and Handler on config paths

botocore models FunctionName up to 256 chars with dots allowed in the name
segment; LambdaArnUtils rejected dots and never bounded length. Also close
the gap where UpdateFunctionConfiguration accepted a malformed Role ARN or a
whitespace-containing/oversized Handler and stored it verbatim.

* fix(lambda): close leaked directory-listing streams and block dot-segment traversal in CodeStore

Files.walk/Files.list returned streams that were never closed, leaking file
descriptors and making delete() flaky on platforms that refuse to remove an
open file. Separately, sanitizeName replaced disallowed characters but let a
segment consisting entirely of dots (".", "..") pass through untouched, so an
account or function name of exactly ".." resolved outside baseDir via
Path.resolve instead of being rejected.

* fix(lambda): reclaim pre-account-scoped code directories on delete and update

A function created before code storage was account-scoped left its extracted
code at <codePath>/<functionName>. DeleteFunction only ever targeted the new
<codePath>/<accountId>/<functionName> path, and UpdateFunctionCode re-extracted
to the new path without touching the old one, so the legacy directory (and its
disk usage) lingered indefinitely after either operation. CodeStore now also
clears the legacy path on delete, and re-extraction reclaims it on success.

* fix(lambda): reject an explicit null Handler on UpdateFunctionConfiguration

validateHandler treated null as "clear the handler", matching how Description
is handled, but null is not a string at all -- and unlike Description, Handler
names the file AWS invokes. A request with "Handler": null silently cleared it
instead of failing with a 400, which would have broken every subsequent
invocation of the function instead of the one bad request that caused it.

* fix(lambda): do not reclaim a legacy code directory another account's function still uses

The pre-account-scoped layout gave every account's same-named function the
exact same on-disk directory. CodeStore.delete() and code re-extraction both
reclaimed that legacy directory unconditionally once a function migrated to
the account-scoped path, so a delete or code update in one account could
destroy the legacy directory while another account's never-migrated $LATEST
still served invocations from it -- its next cold start would then fail with
a missing code directory.

CodeStore.delete() no longer touches the legacy path at all; only
LambdaService calls deleteLegacy() explicitly, after checking every account's
$LATEST functions (via the existing cross-account listAllAccounts) for one
still pointing its codeLocalPath at that directory.

* fix(lambda): check published versions, not just $LATEST, before reclaiming a legacy code directory

publishVersion snapshots codeLocalPath verbatim (required so a version-qualified
invoke doesn't launch a container with no code, #1987), so a version published
while $LATEST was still on the pre-account-scoped legacy path keeps that
directory alive on its own after $LATEST migrates. The unused-check only
scanned $LATEST records via listAllAccounts(region), so a later delete or code
update reclaimed the directory out from under that published version's own
future invokes. Switched to functionStore.listAll(), which has no $LATEST or
region filter, matching the fact that the legacy path itself carries neither.

* fix(lambda): close a publish-vs-legacy-cleanup race on the code directory

publishVersion read codeLocalPath and persisted a snapshot of it with no
synchronization against extractZipCodeBytes's/deleteFunction's decision to
reclaim the pre-account-scoped legacy code directory (added in bede98fc1 and
f3837be32). A version could be published in the narrow window between that
decision (finding no live reference) and the actual delete, persisting a
snapshot whose codeLocalPath names a directory that is about to be removed --
its own future invocation would then fail with "Code directory not found".

publishVersion and the reclaim call in extractZipCodeBytes now both take the
same per-function lock deleteFunction already used for this. Proven with a
test that holds the lock externally and asserts publishVersion blocks until
it is released, rather than relying on timing to catch the race in the act.
2026-08-28 10:52:53 -04:00
takahiro 64c38c77b9 feat(s3): apply VersioningConfiguration in CloudFormation S3 bucket provisioning (#2626) 2026-08-28 10:36:25 -04:00
Matan Baruch 277809fb41 feat(aps): add Amazon Managed Service for Prometheus workspaces (#2604)
* feat(aps): add Amazon Managed Service for Prometheus workspaces

Implements the AMP workspace lifecycle (CreateWorkspace,
DescribeWorkspace, ListWorkspaces, UpdateWorkspaceAlias,
DeleteWorkspace) plus tagging through the shared /tags/{resourceArn}
dispatcher via a TagHandler with service key aps. Previously the aps
service did not exist, so aws_prometheus_workspace could not be created
through Terraform or Pulumi at all.

Workspaces are ACTIVE from birth so the provider's create waiter
(CREATING to ACTIVE) completes on its first DescribeWorkspace poll, and
a deleted workspace answers DescribeWorkspace with the typed
ResourceNotFoundException its delete waiter matches. createdAt is
serialized as restJson1 epoch-seconds; the ListWorkspaces alias
parameter is a prefix filter, matching the provider's alias_prefix.

clientToken is accepted and ignored, kmsKeyArn is stored and echoed,
and no alertmanager/rulegroups/scraper/logging operations are included.

* refactor(aps): build ARNs via RegionResolver and parse tag ARNs with AwsArnUtils

Replaces the inlined AwsArnUtils.Arn.of + config.defaultRegion pair with
regionResolver.getRegion()/buildArn so a request signed for another
region gets an ARN and endpoint in that region, and drops the
EmulatorConfig dependency that existed only for that getter. The tag
dispatcher path now parses ARNs with AwsArnUtils.parse plus an explicit
workspace/ prefix check (the SchedulerTagHandler idiom), so a
non-workspace aps ARN fails with ValidationException instead of a
misleading workspace ResourceNotFoundException. Also makes the delete
and alias mutators void (their returns were unused) and removes a dead
DELETING status mutation.

* docs(aps): map the aps service key to managed-prometheus.md in the service matrix

The docs-check gate matches ResolvedServiceCatalog external keys against
docs/services/index.md rows by filename; aps is documented at
managed-prometheus.md, so it needs the same alias treatment as
kafka -> msk.

* fix(aps): partition workspaces by request region and align minor wire details

Review follow-ups from #2604:

- Key the workspace store by region (region::workspaceId, like
  CloudWatchLogsService's groupKey), and thread the SigV4-resolved request
  region through every lifecycle and TagHandler operation, so workspaces
  created in one region are invisible to describe/list/delete/tag calls
  served in another. Covered by unit and HTTP region-isolation tests.
- Default ListWorkspaces to pages of 100 (AWS's documented default) while
  keeping the 1000 ceiling, via Pagination's seven-argument overload.
- Strip leading/trailing blanks from aliases at create, alias update, and
  the list prefix filter, per the documented normalisation.
- Return DeleteWorkspace's 202 with an empty body instead of {}.
- Reject tag keys beginning with the reserved aws: prefix in TagResource
  with a ValidationException.

* refactor(aps): align the reserved tag-key check with sibling services

- Match the aws: prefix case-insensitively as a plain loop, the same idiom
  as FisService and BatchService, instead of a case-sensitive stream chain.
- Derive key() from keyPrefix() so the :: separator lives in one place, and
  hoist the region prefix out of the scan predicate.
- Replace the two near-identical SigV4 Authorization literals in the
  integration test with an auth(region) helper.
2026-08-28 10:05:42 -04:00
武田隆志 29325006bb fix(appsync): use ApiKey.id as the API key value (#2645)
CreateApiKey returned a short random id and kept the value the execute
endpoint validates in a non-model apiKey field, which the AWS CLI and SDKs
drop. On AWS the id itself is the da2- key value sent as x-api-key, so make
id that value, validate against it, and drop the extra field. Keys persisted
by earlier builds keep their short id, stay listable and deletable, and never
authenticate (as before).
2026-08-28 09:59:42 -04:00
Michal SchreiberandPriamo Germosen 3b0e31b888 fix(rds,docdb): list DocumentDB clusters and instances in the RDS-family list form (#2623)
* fix(rds,docdb): list DocumentDB clusters and instances in the RDS-family list form

The list form of DescribeDBClusters and DescribeDBInstances answered from
one store: on the rds scope from RDS, on the docdb scope from DocumentDB,
so a DocumentDB cluster was invisible to every list while its identifier
form worked. A live account lists the whole family from either endpoint.
RdsQueryHandler now assembles the list from both stores, honouring the
db-cluster-id / db-instance-id filters in each and an engine filter across
them (case-insensitive, OR over values, refused for a name outside the
family's engine list as on AWS), and the controller sends the docdb-scope
list form there too. The identifier form keeps routing to the store that
owns the identifier. Both halves list the region the request is signed
for.

Closes #2613

* fix(rds): report and filter an Aurora member instance by its Aurora engine name

DbInstance collapsed aurora-postgresql and aurora-mysql onto the community
engine enum, so a cluster member reported Engine postgres and the engine
filter matched it as postgres, where a live account says and matches
aurora-postgresql. Keep the engine name the request gave (or the
cluster's, for a member created without one) on the instance, and read it
for both the Engine element and the filter; a record persisted before the
field existed falls back to the enum.

* fix(rds): give a persisted instance its engine name on restore

An instance written before engineIdentifier existed deserializes with it
null, and a runtime fallback to the enum would keep reporting an Aurora
member as postgres. Backfill it in restorePersistedRuntime from the state
that knows: the member's cluster for a member, the enum for a standalone
instance.

* fix(rds): never persist a guessed engine name for a member of a nameless cluster

A cluster persisted before its own engineIdentifier existed (#1829) has
none to hand down, and writing the member's enum in that case would store
postgres for what may be an Aurora member — a guess that outlives the
code able to tell. The backfill writes only what is certain: the
cluster's stored name for a member, the enum for a standalone instance;
a member of a nameless cluster is left unset.

* fix(rds,neptune): list Neptune clusters and instances in the RDS-family list form too

A live account lists a Neptune cluster from the rds, docdb and neptune
endpoints alike and selects it with engine=neptune. The list form now
merges Neptune rows the way it merges DocumentDB ones, and the neptune
scope's list form goes to the same assembly. The Neptune store is not
keyed by region, so its rows are scoped to the request's region by ARN.

* fix(rds): close the subnet-group tags test in rds.bats

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-28 09:37:29 -04:00
Sam Fakhreddine 7188b3ec9d feat(iam): enforce SCPs and populate aws:PrincipalArn during policy evaluation (#2637)
* feat(iam): enforce service control policies during policy evaluation

Service control policies from the caller's organization now gate IAM
policy evaluation. CallerContext carries an optional list of SCP levels
(root, each OU on the account's path, then the account); the evaluator
requires an explicit allow and no explicit deny at every level before
identity policies are consulted. SCPs never grant permissions on their
own.

The ceiling applies to evaluate() only. IamEnforcementFilter is the
single producer of SCP levels, so simulatePrincipalPolicy and the
AppSync GraphQL IAM-auth path (IamAuthValidator) evaluate without one.
Both are explicit non-goals rather than oversights: giving them a
ceiling would require IAM to resolve the principal's organization,
which is the dependency ScpProvider exists to avoid. The coarse AppSync
request is still bounded by the filter ahead of the resource; only the
field-level check runs outside it.

The new ScpProvider interface keeps the dependency direction clean:
OrganizationsService implements it and IamEnforcementFilter resolves it
lazily via Instance, so IAM never depends on Organizations while
Organizations keeps using IamService for role provisioning.

Enforcement is doubly opt-in — FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED
plus FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED — and the
management account is exempt, matching AWS.

* fix(iam): apply service control policies to the account-root principal

floci's account-root principal is a bare 12-digit account-id access key
(LocalStack multi-account convention). IamService.resolveCallerContext
returns null for it, so IamEnforcementFilter took the unknown-key bypass
and returned before SCP levels were ever consulted. Effect: a
DenyLeaveOrganization SCP attached to a workload OU did not stop a member
account from leaving — SCPs never applied to floci's primary
multi-account principal, unlike the AWS account root which is fully
bounded by SCPs.

Fix: when the caller has no registered identity but the account actually
has an effective SCP ceiling and the access key is the account root
(akid == accountId), synthesize an implicit full-access identity
(ROOT_ALLOW_ALL) and evaluate it against the SCP levels. Accounts with no
effective SCPs, and unknown AKIA keys, keep the historical bypass.

Strictly more enforcement, gated behind two opt-in flags
(iam.enforcement-enabled + organizations.scp-enforcement-enabled, both
default off), so the LZA campaign and existing bare-account behavior are
unaffected.

Known flag-flip caveats (both are correct SCP semantics, documented here
for operators enabling enforcement):
- A level that carries SCPs but no FullAWSAccess denies everything for
  the account root, since scpAllows requires an explicit allow at each
  non-empty level. Auto-attached FullAWSAccess covers the normal path.
- Condition-scoped guardrails keyed on aws:PrincipalArn (e.g. a
  DenyRootUser "Deny * when aws:PrincipalArn like *:root") are inert:
  IamConditionContextResolver never populates aws:PrincipalArn, so a
  plain StringLike on that absent key fails the condition block and the
  statement does not apply. A regression test locks this in.

Tests: unit coverage in IamEnforcementFilterTest (bare-account deny,
non-denied allow proven via arnBuilder invocation, and the realistic
two-statement workload-guardrails doc) plus an end-to-end
ScpEnforcementLeaveOrganizationIntegrationTest driving the Organizations
control plane over HTTP.

* feat(iam): populate aws:PrincipalArn for real identities in policy conditions

IamEnforcementFilter built the condition context only from
IamConditionContextResolver, which populates s3:prefix/delimiter/max-keys
and nothing else. aws:PrincipalArn was therefore never set, so every
policy condition keyed on it was inert across all policy layers (SCPs,
identity, session, permissions boundary): a principal-scoped Deny never
fired and a principal-scoped Allow never matched.

Fix: after resolving the condition context, look up the caller's ARN via
IamService.resolveCallerArn(akid) and, when present, set aws:PrincipalArn.
The lookup returns the user ARN for IAM-user access keys and the
assumed-role ARN for STS sessions, and Optional.empty() for the bare
account-id key (floci's account root) and unknown keys. So the key is
populated for real, identifiable principals and stays absent for the
account root — which is exactly why a DenyRootUser guardrail keyed on
aws:PrincipalArn continues not to fire against the account root, per the
account-root SCP change in the preceding commit.

Effect is bidirectional and applies to every policy layer that
evaluate() consults: a principal-scoped Deny can now deny, and a
principal-scoped Allow can now grant. Both remain gated behind the two
opt-in enforcement flags (iam.enforcement-enabled +
organizations.scp-enforcement-enabled, both default off).

IamEnforcementFilter is the sole caller of the condition-aware
IamPolicyEvaluator.evaluate overload and the sole user of
IamConditionContextResolver, so there is no second evaluation path where
the key would be absent and the same policy would behave differently.

Known caveat (pre-existing, surfaced here for operators): resolveCallerArn
hardcodes the assumed-role session name as "floci-session", so
aws:PrincipalArn for assumed-role callers will not match a condition that
pins a specific session name. This matches what STS GetCallerIdentity
already reports.

Tests: two conditional cases in IamEnforcementFilterTest exercise both
directions against a real IamPolicyEvaluator — a principal-scoped SCP
Deny that fires for an IAM user, and an identity-policy Allow gated on an
IAM-user principal that grants access. Both were confirmed RED with the
population disabled.

* docs(iam,organizations): document account-root SCP handling and condition keys

Clarify how SCP enforcement treats the bare account-id key (subject to the
SCP chain as the account root, but carrying no identity policy), the
condition keys floci populates (s3:prefix/delimiter/max-keys,
aws:PrincipalArn), and the absent-key rule that keeps aws:PrincipalArn
guardrails inert against the account root.

* feat(iam): organization support ops for LZA bootstrap

Add ListOrganizationsFeatures and the root-credentials-management and
root-sessions enable/disable pairs, backed by OrganizationRootFeatures.
LZA custom resources call these during the Prepare/Accounts stages
(EnableAllFeatures), alongside CreateServiceLinkedRole for the Access
Analyzer role, which the emulator already implements — the tests here
cover the service-linked role names those stages depend on.

* fix(iam): register OrganizationRootFeatures for reflection

PersistedModelReflectionTest asserts every type reachable from persisted
storage carries @RegisterForReflection -- without it, native-image
persistence breaks on restart. OrganizationRootFeatures was added in
e60e8abd (organization support ops) without the annotation, so the test
has been red since.

Adds @RegisterForReflection plus @JsonIgnoreProperties(ignoreUnknown =
true), matching the convention of every sibling model in the package
(InstanceProfile, IamPolicy, IamGroup).

* feat(iam): tag and untag instance profiles

Adds a tags map to InstanceProfile and wires TagInstanceProfile /
UntagInstanceProfile through the query handler, with an integration test
covering the tag round trip.

* feat(iam): add UpdateGroup

Net-new operation modeled on the existing updateUser: rename and/or
change a group's path, with the ARN and stored users moving with it.
Same EntityAlreadyExists/NoSuchEntity exception shape as updateUser.

* docs(iam): document SCP enforcement where it is implemented

The Organizations page described SCP participation in policy evaluation and
linked to iam.md#service-control-policies-scps and iam.md#bypass-rules, neither
of which existed anywhere. The behaviour belongs to the IAM enforcement layer —
IamEnforcementFilter resolves the chain via effectiveScpLevels — so document it
there, including the account-root and bypass cases, and restore the
cross-reference now that both anchors resolve.

* fix: use canonical IAM service-linked role names

* feat(iam): seed AWS Backup service-role managed policies

LZA's OperationsStack attaches AWSBackupServiceRolePolicyForBackup and
AWSBackupServiceRolePolicyForRestores to its backup service roles; without
catalog entries AttachRolePolicy fails with NoSuchEntity and the stack
rolls back.

* feat(iam): seed AWS Backup S3 service-role managed policies

LZA's OperationsStack backup role also references
AWSBackupServiceRolePolicyForS3Backup / ForS3Restore, which live at the
root path in real AWS rather than /service-role/. Without them the role
create fails with NoSuchEntity and the stack rolls back.

* fix(iam): deny when a service control policy fails to parse

The SCP ceiling skipped any document it could not parse and evaluated
whatever else the level held. Since FullAWSAccess is attached to every
target, a level almost always carries it alongside the customer's
guardrail: a malformed guardrail dropped out, FullAWSAccess supplied the
required explicit allow, and the restriction vanished with only a WARN
line to show for it. A security control must not fail open.

parseAll now reports whether any document failed, and a level holding an
unparseable document denies. Only SCP evaluation reads that signal —
identity, resource, session and boundary policies keep skipping bad
documents as before.

* perf(organizations): scan the policy store once per SCP resolution

effectiveScpLevels called policiesIn(organization) inside the loop over
the account's ancestry, and policiesIn scans every account's policy
store. A root -> OU -> account chain therefore did three full scans on
an authenticated request path. Hoist the scan above the loop and keep
the per-node target filter inside it.

Also record why the SCP levels are resolved before resolveCallerContext
in IamEnforcementFilter: the account-root branch needs to know whether a
ceiling exists before it can choose between enforcing and bypassing.

* test(organizations): cover each reason effectiveScpLevels returns null

The management-account exemption, the account-outside-any-organization
case, and the SCP-policy-type-disabled case were only asserted as three
lines inside the walk-the-chain test, where a name never says what broke
and an earlier failure hides them. Give each its own test, and assert a
member account does get a ceiling in the same setup so the exemption
cases cannot pass for the trivial reason that no SCPs exist at all.

* fix(iam): never reissue deleted policy version ids

CreatePolicyVersion derived the next version id from the version count,
so deleting a non-default version and creating a new one silently
rewrote the highest surviving version. AWS ids are monotonic; derive
the next id from the highest existing one and cap on the live count.

* fix(iam): resolve principal policies in the account the ARN names

collectUserPolicies, collectRolePolicies, resolveUserBoundaryDocument
and resolveRoleBoundaryDocument stripped a bare name out of the given
principal ARN and looked it up in ambient request-context storage. When
two accounts each hold a same-named user or role, presenting account
A's ARN resolved whichever account the request happened to run as — a
cross-account authorization bypass in either direction, and one that
also silently applied the wrong permissions boundary.

Each lookup now scopes to the account segment of the ARN it was given,
via the existing findRole(accountId, roleName) and a new symmetric
findUser(accountId, userName). resolvePrincipalContext passes the full
ARN to the user-side helpers instead of pre-stripping it to a name.

Callers that legitimately have no ARN — resolveCallerContext, reached
from a long-term access key — still resolve through the ambient account,
so account-routed access keys keep working.

* fix(iam): enforce the modeled password-policy bounds and instance-profile tag limits

UpdateAccountPasswordPolicy stored whatever numbers arrived, so a policy with
MinimumPasswordLength outside 6-128, MaxPasswordAge outside 1-1095 or
PasswordReusePrevention outside 1-24 persisted and was read straight back by
GetAccountPasswordPolicy as if AWS had accepted it. Reject with ValidationError,
the code the service already raises for shape-constraint failures.

TagInstanceProfile merged the tag map with no cardinality check and
UntagInstanceProfile accepted an unbounded TagKeys list, though both shapes are
max 50. Tagging past the quota now raises LimitExceeded, matching the other
per-resource quota guards; an over-long TagKeys request raises ValidationError.

* fix(iam): check the instance-profile tag list shape before resolving the profile

Separates the two constraints the previous commit conflated: a request carrying
more than 50 tags fails the tagListType shape and is now rejected with
ValidationError before the profile lookup, matching untagInstanceProfile's order
and AWS's; exceeding the 50-tag per-resource quota across requests stays
LimitExceeded.

* fix(iam): validate GroupName/NewPath and InstanceProfileName shape before mutation

UpdateGroup read GroupName and NewPath with getParam and passed them straight
into IamService.updateGroup with no pattern/length check, and TagInstanceProfile
did the same for InstanceProfileName before reaching IamService.tagInstanceProfile.
botocore's iam/2010-05-08 model constrains groupNameType/instanceProfileNameType
to [\w+=,.@-]{1,128} and pathType to 512 chars matching a bare slash or a
slash-delimited run of !-~; a malformed value previously surfaced as
NoSuchEntity/200 instead of the ValidationError AWS returns.

* fix(iam): never reissue a policy version id after deleting the highest surviving version

CreatePolicyVersion derived the next id from the max of the currently-live version keys, so
deleting the highest-numbered surviving version (as opposed to an older one) and creating a
new one silently reissued the deleted id — e.g. deleting v5 while v4 survives makes the next
version v5 again, violating IAM's monotonic version-id contract. IamPolicy now tracks a
persisted next-version high-water mark, taken as the max of itself and the live-key floor so a
policy rehydrated from before this field existed is never regressed below what it already has
on disk.

* fix(iam): defensively copy InstanceProfile tags and reject a null map

setTags assigned the incoming map directly and allowed null. A persisted "tags": null on
rehydration, or a caller mutating the map it passed in after the call, could NPE at
new LinkedHashMap<>(profile.getTags()) in tagInstanceProfile or silently mutate the profile's
stored tags out from under it. Now defensively copies into a fresh ConcurrentHashMap, or an
empty one for null, matching how getTags()/setTags() are used elsewhere on this model.

* fix(iam): validate UpdateGroup's NewGroupName and keep member policies resolving across a rename

NewGroupName reached storage with no pattern/length check (the same groupNameType gap already
closed on GroupName/NewPath), and UntagInstanceProfile's InstanceProfileName had the same gap
UpdateGroup's tag-sibling TagInstanceProfile already closed. Also: renaming a group rekeyed
only the group record, leaving each member's own groupNames list pointing at the deleted old
name, so ListGroupsForUser dropped the renamed group and collectUserPolicies silently stopped
resolving its inline/attached policies for those members. updateGroup now updates every
member's groupNames symmetrically with addUserToGroup/removeUserFromGroup.

* fix(iam): guard against reissuing a version id deleted before nextVersionNumber existed

nextVersionNumber previously defaulted to 2 in its field initializer, so a policy persisted by a
pre-migration Floci version rehydrated with the same value a genuinely fresh policy would have,
regardless of how many versions it actually held historically. If such a policy's then-highest
version had been deleted (e.g. v1-v4 live after a pre-migration DeletePolicyVersion("v5")), the
live-key floor alone could not reveal that v5 was already used, and CreatePolicyVersion reissued
it. The field is now left null (unset) unless a policy explicitly sets it, so Jackson leaves a
legacy record's value null instead of masquerading as fresh; CreatePolicyVersion treats null as
"true history unknown" and jumps the counter past the live-key max by 5 (a policy can never hold
more than 5 concurrent versions, so no more than 5 stacked deletions could sit above the live max
between two persists).

* fix(iam): populate aws:PrincipalArn as the account root for the synthesized root principal

Maintainer review on #2637 (pgermosen): SCPs already treat floci's bare account-id key as the
account root (enforced), but aws:PrincipalArn was left absent for it, so a common DenyRootUser
guardrail keyed on aws:PrincipalArn (StringLike arn:aws:iam::*:root) could never fire against it
even though the same principal is otherwise bounded as root — an internal inconsistency between
the two forms of root enforcement. IamEnforcementFilter now populates aws:PrincipalArn as
arn:aws:iam::<account>:root right where the root identity is synthesized, matching AWS's own
root ARN shape. Inverts the IamEnforcementFilterTest that pinned the old inert behavior (a
DenyRootUser guardrail now correctly denies the account root's other actions too, not just the
one an accompanying statement explicitly targets) and adds a direct assertion that the exact
root ARN is what's populated. Docs updated to match.
2026-08-28 08:55:50 -04:00
Ricky Rattlesnake 066e6c904b fix(s3): return x-amz-version-id from presigned POST (#2608)
A presigned POST to a versioning-enabled bucket creates a new version but the
response omits x-amz-version-id, so the caller cannot discover it. A browser
upload has no other channel — there is no SDK response to read — which breaks
the common direct-to-S3 pattern where the browser uploads, reads the version
from the response, and reports it back to the application.

The handler already has the S3Object returned by putObject; it simply never
read getVersionId(). Every other write path in S3Controller sets the header
behind the same null guard.

Fixes #2607
2026-08-28 08:55:07 -04:00
Sam Fakhreddine e471946f44 feat(route53): VPC association lifecycle actions (#2638)
* feat(route53): add VPC association lifecycle actions

Zone creation already persists VPC associations, but the lifecycle
operations that manage them afterwards were missing. Adds, on top of the
existing VpcAssociation model:

- AssociateVPCWithHostedZone   POST /hostedzone/{Id}/associatevpc
- DisassociateVPCFromHostedZone POST /hostedzone/{Id}/disassociatevpc
- CreateVPCAssociationAuthorization POST /hostedzone/{Id}/authorizevpcassociation
- DeleteVPCAssociationAuthorization POST /hostedzone/{Id}/deauthorizevpcassociation
- ListHostedZonesByVPC          GET  /hostedzonesbyvpc

Request paths, XML element names and response shapes follow the Route 53
2013-04-01 rest-xml model, including HostedZoneSummary's HostedZoneId and
Owner members, and ListHostedZonesByVPC honours maxitems/nexttoken.
Associate is idempotent; disassociate raises VPCAssociationNotFound for
an unknown VPC and LastVPCAssociation when it would remove the only
remaining association, and associating a public zone raises
PublicZoneVPCAssociation.

VpcAssociation has no value equality, so associations are matched on VPC
ID and region rather than object identity.

The two authorization endpoints are shape-only: hosted zones are not
account-scoped here, so an authorization cannot gate a later associate
call. They validate the request and echo the VPC back.

* fix(route53): enforce the VPCRegion enum on the VPC association actions

AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, the two
authorization actions and ListHostedZonesByVPC all read VPCRegion and
stored or matched on it verbatim. A region outside the modelled enum was
accepted, so the association was written under a region that could never
be matched again: the associate reported INSYNC while the later
disassociate answered VPCAssociationNotFound and ListHostedZonesByVPC
silently omitted the zone.

Reject an unmodelled VPCRegion with InvalidInput, which the model lists
for every one of these operations. The check carries the enum from the
model rather than reusing AwsRegions.KNOWN_IDS, because the enum admits
the ISO and European Sovereign partitions the emulator never advertises.

* fix(route53): reject unmodelled VPC regions on create and fix VPC-list pagination

CreateHostedZone stored a VPC association's region without checking it
against the modelled VPCRegion enum, so an association created that way
could never be found again by the later disassociate/list lifecycle
actions, which do check it. ListHostedZonesByVPC also silently restarted
pagination on an unrecognized NextToken and ignored a non-positive
MaxItems instead of rejecting both with InvalidInput.

* fix(route53): don't strand legacy VPC regions, and stabilize equal-name pagination

Two review findings from the latest re-review:
- ListHostedZonesByVPC and DisassociateVPCFromHostedZone rejected any VPCRegion outside the
  modelled enum before ever touching storage, so an association persisted under a region since
  retired from the enum (or from before this check existed) could never be listed or removed —
  only a full hosted-zone deletion could get rid of it. The enum check now applies only to the
  paths that create a new association (AssociateVPCWithHostedZone, CreateHostedZone,
  CreateVPCAssociationAuthorization); lookups and removal accept whatever region is on record.
- ListHostedZonesByVPC sorted matches by name only, so two zones with the same name were ordered
  however the backing store happened to iterate them, which can differ between the page-1 and
  page-2 scans and desync the id-based NextToken continuation point. The sort now tie-breaks by
  id so the total order is fixed regardless of iteration order.

* fix(route53): use the modeled InvalidPaginationToken and ConflictingDomainExists errors

ListHostedZonesByVPC returned the generic InvalidInput for an
unrecognized NextToken instead of the purpose-built
InvalidPaginationToken the model declares for exactly this operation.
AssociateVPCWithHostedZone also let the same VPC attach to two
different hosted zones sharing a name, something the model documents
as ConflictingDomainExists; the existing listHostedZonesByVpc lookup
now scans for that conflict before storing a new association.
2026-08-28 08:19:14 -04:00
Matheus Oliveira c4050936a8 feat(ecs): rewrite ECR image URIs on RunTask like Lambda already does (#2641)
Extracts the AWS-ECR-URI rewrite out of Lambda's ContainerLauncher into
EcrRegistryManager.rewriteImageUri(), now shared by Lambda and ECS so
RunTask images resolve through Floci's emulated registry instead of the
real amazonaws.com host.

Closes #2568

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-27 22:33:30 -04:00
Sam Fakhreddine 149ac635f2 fix(ssm): validate SettingValue and require an account list on ModifyDocumentPermission (#2635)
* fix(ssm): validate SettingValue and require an account list on ModifyDocumentPermission

UpdateServiceSetting.SettingValue was read with plain asText(), so an absent
or blank value silently stored an empty customized setting, and botocore's
ServiceSettingValue max (4096) was never enforced. ModifyDocumentPermission
accepted a request with neither AccountIdsToAdd nor AccountIdsToRemove and
returned success having shared/unshared nothing, when botocore documents at
least one of the two as required.

* fix(ssm): review comments — whitespace SettingValue, non-list AccountIds, message format

Greptile: isBlank() rejected a whitespace-only SettingValue even though
botocore's ServiceSettingValue constraint is length-only (min 1); switched to
isEmpty().

Copilot: a non-list AccountIdsToAdd/AccountIdsToRemove payload was silently
treated as an empty list because forEach() on a scalar/object node yields no
elements, so the new "neither list specified" guard could pass a malformed
request. Reject a present-but-non-array field explicitly, and reworded that
guard's message to match this file's "1 validation error detected:" prefix.
2026-08-27 22:26:30 -04:00
Sam Fakhreddine 5400204563 fix(kms): grant fidelity (#2639)
* fix: preserve KMS grant metadata

* fix(kms): reject GrantOperation values outside the modeled enum

CreateGrant stored the Operations list verbatim, so a grant could be
persisted and echoed back with an operation name AWS would have refused.
Validate each element against the GrantOperation enum and raise
ValidationException, matching the other CreateGrant input guards.

* fix(kms): validate CreateGrant Name against GrantNameType constraint

Real AWS enforces GrantNameType's pattern (^[a-zA-Z0-9:/_-]+$) and
256-char max length on CreateGrant's Name field. Add the same
validation so malformed names are rejected the way AWS rejects them.

* fix(kms): validate CreateGrant Constraints and fix name-length error message

Two review findings on CreateGrant:
- Constraints previously passed through unvalidated: an unknown member,
  a non-map EncryptionContextSubset/EncryptionContextEquals, or a
  malformed SourceArn would be persisted and echoed back on ListGrants
  even though real KMS rejects the request. Validate against the
  modeled GrantConstraints shape (kms/2014-11-01/service-2.json).
- Name's length check used the max-length message for both the empty
  and over-256 cases; an empty name now cites the min-length-1
  constraint instead.

* fix(kms): reject non-object CreateGrant Constraints instead of silently dropping it

The handler converted Constraints to null whenever it wasn't a JSON object, so a raw string or
array value was treated as absent and the grant was created without ever reaching
validateGrantConstraints, instead of rejecting the malformed request as real KMS does.
2026-08-27 21:35:32 -04:00
Stuart Lang bf6c7b001c fix(dynamodb): reject key attribute values whose type does not match the key schema (#2625)
* fix(dynamodb): reject key attribute values whose type does not match the key schema

PutItem/UpdateItem (and Get/Delete/BatchWrite/TransactWrite via the same
path) accepted a NULL-typed partition or sort key, which real DynamoDB
and LocalStack reject with a ValidationException. Worse, non-scalar key
values collapsed to an empty storage key, so all such items collided on
one slot.

buildItemKey now validates each key attribute value against the table's
AttributeDefinitions, using AWS's wording for both flavours: the Key
argument form ("The provided key element does not match the schema")
and the PutItem item form ("One or more parameter values were invalid:
Type mismatch for key <name> expected: <type> actual: <type>").

Fixes #2624

* test(dynamodb): cover NULL-typed key rejection at the HTTP layer

* fix(dynamodb): validate key value shapes and index key types on writes

Review follow-up for #2625, all behaviours verified against real DynamoDB:

- Key attribute values that are empty objects or carry multiple type
  members are rejected with AWS's "Supplied AttributeValue ..."
  messages; non-object values get a SerializationException like AWS's
  protocol layer, instead of aliasing onto another item's storage key.
- GSI/LSI key attributes present in a written item are validated
  against AttributeDefinitions on PutItem and UpdateItem (covering
  batch and transact paths, which reuse them), matching AWS's
  "Type mismatch for Index Key <name> Expected: <T> Actual: <T>
  IndexName: <idx>" wording. Absent attributes stay valid (sparse
  indexes).
- Brace the new single-line conditionals per AGENTS.md.

* fix(dynamodb): apply value shape and empty-string rules to index keys

Review follow-up for #2625. The malformed-shape checks added for base
keys skipped GSI/LSI key attributes: validateIndexKeySchema's guard
stepped over empty, multi-member, and non-object values instead of
rejecting them. The three checks now live in a shared
validateAttributeValueShape helper that both key paths run, so they
cannot drift again.

Empty-string index key values are also rejected now, verified against
real DynamoDB, which uses different wording per operation: PutItem
names the index ("... IndexName: gsi1, IndexKey: gsiKey") while
UpdateItem uses the update-expression form without it.

Number normalization no longer rebuilds a multi-member AttributeValue
around its N member — {"S":"x","N":"1"} was being laundered
into a well-formed {"N":"1"} before validation could see it, which
turned the AWS shape error into a type-mismatch error.
2026-08-27 21:05:52 -04:00
Sam Fakhreddine 7f6b875136 feat(ssm): document lifecycle, share permissions, and account-scoped service settings (#2629)
* feat(ssm): document share permissions for DescribeDocumentPermission and ModifyDocumentPermission

* feat(ssm): model documents with GetDocument, CreateDocument, and UpdateDocument

LZA's session-manager-settings custom resource reads SSM-SessionManagerRunShell
via GetDocument, creates it (DocumentType Session) when the InvalidDocument error
code comes back, and updates it otherwise, tolerating DuplicateDocumentContent.
Model documents region-scoped in a persistent store and serve all three ops with
those exact error codes so the AWS SDK maps them to its typed exceptions.

* feat(ssm): add DescribeDocument and DeleteDocument

Completes the document lifecycle alongside the existing Get/Create/Update
operations. DeleteDocument raises InvalidDocument for a name that was never
stored rather than succeeding silently.

* feat(ssm): account-scoped service settings (Get/Update/ResetServiceSetting)

LZA's ssm-block-public-document-sharing module assumes a role into every member account and reads/updates /ssm/documents/console/public-sharing-permission. Model the ServiceSetting API with per-account per-region state, account defaults (Enable for public sharing), and ServiceSettingNotFound for unknown ids, matching real AWS. Closes the gap reported upstream as floci-io/floci#2235.

* fix(ssm): raise InvalidDocument when a permission op names an unknown document

DescribeDocumentPermission returned an empty list and ModifyDocumentPermission
happily created share state for a document that does not exist. Botocore models
InvalidDocument on both operations, and this branch now has a real documentStore,
so the two halves of the service no longer need to disagree about whether a
document exists: both permission methods resolve the document first.

This also settles the ownership half. Only the document's owner may share a
document in AWS. Ownership here is the storage partition: documentStore is an
AccountAwareStorageBackend keyed by the caller's account from RequestContext,
the same resolution RegionResolver.getAccountId() performs, so getDocument can
only resolve a document in the caller's own partition and a non-owner gets
InvalidDocument. Deriving the guard from the partition rather than a second
stored owner field keeps check and storage scope from ever disagreeing.

* fix(ssm): validate Name and PermissionType on the document operations

Every new document handler read request.path("Name").asText(), which yields ""
— not null — for an absent field, so a request with Name omitted built the key
"<region>|" and surfaced "Document  does not exist." with a blank in the message.
Botocore constrains DocumentName to ^[a-zA-Z0-9_\-.]{3,128}$, making a blank name
a constraint violation, which AWS reports as ValidationException. No per-operation
error fits: InvalidDocument means "does not exist" rather than "malformed", and
CreateDocument does not model it at all — so unlike the ACM guards, a generic
ValidationException here is the modeled shape, not a substitute for one.

PermissionType was accepted and ignored on both document-permission operations.
Botocore models DocumentPermissionType as an enum whose only value is Share and
models InvalidPermissionType on both operations, so a present-but-unsupported
value now raises InvalidPermissionType. PermissionType is a required member, so
an absent one is treated as a missing required member (ValidationException), the
same as an absent Name.

Both guards run before the store lookup. The integration test for the permission
round-trip now creates the document it shares, and a two-account test asserts a
non-owner cannot share another account's document.

* fix(ssm): enforce the modelled DocumentType and AccountIds constraints

Two values the document operations read and store were never checked
against the model.

CreateDocument took DocumentType verbatim. Botocore models it as a
17-value enum; floci stored whatever arrived and echoed it back from
GetDocument, DescribeDocument and the create response, so a document
could sit in the store with a type neither AWS nor the emulator
recognises.

ModifyDocumentPermission wrote AccountIdsToAdd straight into the
document's share list. The model caps each list at 20 members and pins
the member pattern to (?i)all|[0-9]{12}; without either check a share
with "not-an-account" reported success and DescribeDocumentPermission
faithfully echoed it back.

Both are rejected with ValidationException, matching the treatment the
blank Name and the PermissionType enum already get.

* fix(ssm): enforce the DocumentName pattern instead of only rejecting blank names

requireDocumentName rejected an absent or blank Name but let any other
value through unvalidated, so a name violating botocore's
^[a-zA-Z0-9_\-.]{3,128}$ pattern (e.g. containing a slash) was accepted
and persisted instead of raising ValidationException. The lifecycle
integration test's document names started with "/", so they had to be
corrected to comply with the pattern now that it is actually enforced.

* fix(ssm): reject missing or non-string Content on CreateDocument/UpdateDocument

Content was read via JsonNode.asText(), which silently returns "" for
either an absent member or a non-textual node (e.g. a JSON object sent
instead of a JSON/YAML-encoded string). That let CreateDocument store
an empty document, and let UpdateDocument erase existing content while
still incrementing the version. Botocore models DocumentContent as a
required string with min length 1 on both operations, so this now
raises ValidationException before either service call is made.

* fix(ssm): clear share permissions when a document is deleted

deleteDocument removed only the document record, leaving its entry in
documentPermissionStore behind. A document recreated later under the
same account, region, and name inherited the deleted document's
account shares instead of starting unshared.

* fix(ssm): validate SettingId is present on service-setting operations

Get/Update/ResetServiceSetting read SettingId via JsonNode.asText(),
which yields "" for an absent member. That blank id was then treated
as an unknown setting (ServiceSettingNotFound) rather than a missing
required member (ValidationException) — the same distinction already
drawn for the document operations' Name field.

* fix(ssm): reject non-string document Name in CreateDocument

asText() silently coerces a numeric or boolean Name to its string form, so it can satisfy the DocumentName pattern and reach create/lookup instead of raising ValidationException for the wrong-typed member.

* fix(ssm): serialize document create/delete/share against each other

deleteDocument's trailing documentPermissionStore.delete ran unsynchronized against createDocument and modifyDocumentPermission, so a delete overlapping a same-name recreate-and-share could wipe out the recreated document's new shares.

* fix(ssm): widen GetDocument/DescribeDocument Name pattern for ARN reads

Botocore models a wider Name pattern (adds ':' and '/') on GetDocument
and DescribeDocument than on the other five document operations, since
DescribeDocument accepts the document's full ARN when reading a
document shared from another account. The shared DOCUMENT_NAME pattern
rejected that shape on both read operations, so an ARN naming a
caller's own document — an ordinary way to call GetDocument — failed
with ValidationException instead of resolving (or, for an unknown
document, InvalidDocument).
2026-08-27 17:20:56 -04:00
Sam Fakhreddine 9b9e7f56a2 feat(apigateway): API key import/usage-plan fidelity and update-operation fixes (#2631)
* feat(apigateway): complete the REST API resource lifecycle

Adds the missing delete and update operations across authorizers,
integrations, integration responses, methods, method responses, models,
request validators, resources, rest APIs, stages, deployments, domain names
and base path mappings, plus tag/untag, usage plan and usage plan key CRUD,
and ImportApiKeys backed by a new ApiKeyCsvParser.

Each operation has a wire-level integration test.

* feat(apigatewayv2): allow clearing an HTTP API CORS configuration

deleteCorsConfiguration unsets the optional CORS block on a stored API so
the response omits it rather than echoing a stale configuration.

* fix(apigateway): accept the AWS-native ImportApiKeys CSV format

The header validator required exactly `name,value,enabled` in lowercase and
read every row by fixed position. Real AWS ships `Name,Key,Description,
Enabled,UsagePlanIds`, so the CLI, SDKs and Terraform all took a 400 on their
first call. Columns are now resolved case-insensitively by name into an index
map, `value` is kept as an alias for `Key`, a missing or blank `Enabled`
defaults to true as AWS does, and rows shorter than the header no longer throw.

Imported keys are also created with generateDistinctId, because the CSV `Key`
column is the key VALUE and AWS generates the id separately — reusing the value
as the id let one row silently clobber an existing key and detach its usage
plan associations.

ImportApiKeys now reports warnings for real: a row whose key value duplicates an
earlier row in the same import raises one, and `failonwarnings=true` turns those
warnings into a BadRequestException instead of being ignored.

* fix(apigateway): honour the patchOperations envelope on UpdateModel and UpdateUsagePlan

Both handlers parsed the PATCH body as a flat map. Real AWS sends
`{"patchOperations":[{"op":"replace","path":"/description","value":"x"}]}`, so
the flat parse succeeded, matched nothing, and returned the untouched resource
with a 200 — a silent no-op. Both now walk the ops list the way the six sibling
endpoints in this controller already do.

UpdateModel supports /description, /schema and /contentType, and rejects /name
with a BadRequestException: AWS treats a model name as an immutable identifier.
That also removes the delete-then-put rename, which had no existence check on
the target key and so destroyed any model already using the new name.

UpdateUsagePlan supports /name, /description and add/remove of /apiStages as
"apiId:stage", covering what the flat handler could do. UsagePlan carries no
throttle or quota state, so those paths are left unsupported rather than faked.

UpdateAuthorizer now parses /authorizerResultTtlInSeconds before mutating
anything. A non-numeric value used to be written straight to the store, after
which serialisation threw on the PATCH and on every later GetAuthorizer and
GetAuthorizers for that resource — unrecoverable short of delete and recreate.

* fix(apigateway): reject duplicate sibling paths and bad parentId on resources

UpdateResource pointed at an unknown /parentId surfaced getResource's 404
"Invalid resource id specified", which reads as though the resource being
patched is missing; the `parent == null` guard beneath it was unreachable for
the same reason. AWS answers 400, so the lookup failure is now rethrown as a
BadRequestException naming the offending value.

Neither CreateResource nor UpdateResource checked for a sibling collision, so
two children of one parent could end up with the same path and request routing
became order-dependent. Both now go through a shared guard that raises
ConflictException (409) when another child of the effective parent already uses
that pathPart.

UpdateResource also stopped mutating as it goes. The store hands back live
objects, so applying ops in-place meant a later rejected op left the earlier
ones visible in memory; the patch is now resolved into pending parentId and
pathPart values, validated, and only then applied.

* style(apigateway): put HttpHeaders first in deleteAuthorizer

Every other handler in the controller takes @Context HttpHeaders as its first
parameter. No behaviour change.

* fix(apigateway): answer BadRequestException for a malformed patchOperations envelope

The PATCH handlers parsed the envelope with convertValue(node, List.class)
inside a catch that only covered IOException. convertValue throws
IllegalArgumentException, which no mapper handles, so a non-array
patchOperations returned 500 instead of the modelled BadRequestException.
The raw List.class conversion also deferred a structured operation value
into the service layer as a ClassCastException, a second 500.

Extract one parsePatchOperations helper that converts through a
TypeReference<List<Map<String, String>>> and widens the catch, so scalar
values coerce and structured ones are rejected at the boundary.

* fix(apigateway): dispatch ImportApiKeys on mode, not on media type

ImportApiKeys was annotated @Consumes("text/csv"), but botocore sends the
operation with no Content-Type header at all — only Accept: application/json.
A request with no Content-Type is application/octet-stream to JAX-RS, so it
never matched, and fell through to the sibling CreateApiKey handler, which
fed the CSV body to the JSON parser and answered a spurious
BadRequestException. Every existing test hid this by setting text/csv
explicitly, a header no client sends.

Fold both operations into one POST /apikeys handler that consumes any media
type and tells them apart by the mode query parameter, the way AWS does, and
cover it with a raw-client case that sends no Content-Type.

* docs(apigateway): document the operations this branch added

The branch added 13 v1 management operations and DeleteCorsConfiguration on
v2 without touching docs, and the Not Implemented list still named
UpdateAuthorizer, DeleteAuthorizer, ImportApiKeys, GetUsagePlan,
UpdateUsagePlan and UpdateModel as absent. GetDeployment and DeleteDeployment
were already implemented but had never been listed either.

api-gateway.md is hand-maintained — ApiGatewayController is a REST controller
and is not registered in tools/docs/services.yaml — so the tables are updated
by hand and the index counts follow the tables: v1 64 -> 79, v2 48 -> 49.
Also record how CreateApiKey and ImportApiKeys share POST /apikeys.

* fix(apigateway): extend the patchOperations boundary parse to the inherited handlers

Six PATCH handlers predate this branch and still parsed the envelope with
convertValue(node, List.class) inside an IOException-only catch, so
updateRestApi, updateResource, updateMethod, updateIntegration, updateStage
and updateApiKey kept answering 500 for a malformed envelope while the eight
handlers this branch added answered 400. A reviewer would rightly ask why
only some of the surface agrees with AWS.

This is a deliberate scope extension beyond the audit's finding: point all
six at the existing parsePatchOperations helper so every PATCH operation on
the service shares one boundary contract. updateAccount stays as it is — it
validates each operation itself and already raises a modelled 400.

* docs(apigatewayv2): correct the VPC Link operations, which are implemented

The v2 Not Implemented list named all five VPC Link operations as absent, but
CreateVpcLink, GetVpcLink, GetVpcLinks and DeleteVpcLink have been routed on
/v2/vpclinks and backed by ApiGatewayV2Service since before this branch. Only
UpdateVpcLink is genuinely missing — there is no PATCH route for it.

Verified each claimed route against ApiGatewayController before editing. Adds
the VPC Links row the v2 table never had and carries the four operations into
the index count: 49 -> 53.

* fix(apigateway): enforce the modelled op enum on patchOperations

Botocore models PatchOperation.op as an enum of add, remove, replace,
move, copy and test. The boundary parse read the envelope's shape but
never the op value, and the handlers behind it disagree about what to do
with an unrecognised one: UpdateModel throws, UpdateApiKey and UpdateStage
skip it. On the skipping handlers an unmodelled op was answered 200 with
the resource untouched, which reads to the caller as an applied patch.

Check op against the enum in parsePatchOperations, the boundary this
branch already made responsible for the envelope on every PATCH handler.
The set is the model's, not the intersection of what the handlers
implement: whether a handler supports move is its own business, but a
value outside the enum should never reach one.

* fix(apigateway): reject a null element in the patchOperations envelope

parsePatchOperations silently skipped a null element in the patchOperations
array instead of rejecting it. Several handlers that predate the shared
boundary parse (updateRestApi, updateStage, updateApiKey, updateMethod) have
no null guard of their own and call op.get("op") directly, so a null element
reached them as an unhandled NullPointerException -- a 500 instead of AWS's
modelled BadRequestException.

Reject the null at the boundary all handlers already share, the same place
that already validates the op enum.

* fix(apigateway): apply patchOperations atomically instead of partially

updateAuthorizer, updateUsagePlan, updateRequestValidator, updateModel,
updateDomainName and updateBasePathMapping mutated the live stored object as
each op was validated. The store hands back live objects (no defensive
copy), so a valid op followed by an invalid one left the valid op's change
visible even though the request answered 400 -- the same partial-apply bug
already fixed for updateResource in an earlier commit on this branch, which
established the fix: resolve every op into pending local values, validate
the whole list, and only mutate the stored object once the patch is known
to be entirely good.

Each handler also now rejects a null patchOperations element explicitly, on
top of the shared boundary's own rejection, matching the defensive style
already used by updateRequestValidator and updateModel before this change.

* fix(apigateway): translate a malformed ImportApiKeys CSV into BadRequestException

ApiKeyCsvParser.parse throws IllegalArgumentException on an unterminated
quoted field, but only AwsException is registered with an ExceptionMapper.
The unmapped exception escaped as a 500 instead of AWS's modelled 400,
letting a malformed import request past the error boundary entirely.

Catch the parser's IllegalArgumentException at the one call site and
translate it into the same BadRequestException every other CSV validation
failure in this method already raises.

* style(apigateway): brace the new conditionals this branch added

New single-line if statements in the domain-name serialization, CSV import
column/cell handling, and resource sibling-collision check violated the
repository's mandatory conditional-brace convention. No behaviour change.

* fix(apigateway): validate all UpdateIntegration patch ops before applying any

updateIntegration mutated the live stored integration inside the same loop that validated later operations, so a PATCH with a valid op followed by an unsupported path left the earlier op applied even though the request as a whole was rejected with 400.
2026-08-27 16:59:59 -04:00
Michal Schreiber 75f8f42d5f fix(elasticache): keep a replication group's encryption, snapshot settings, tags and ARN (#2632)
* fix(elasticache): keep a replication group's encryption, snapshot settings, tags and ARN

DescribeReplicationGroups wrote AtRestEncryptionEnabled and
SnapshotRetentionLimit as constants and never emitted KmsKeyId,
SnapshotWindow or ARN, so a group created with them drifted on the next
Terraform plan (kms_key_id forces replacement) and its tags, given at
create, could not even be asked for without an ARN. Store the four
settings and the tags on the group, resolve KmsKeyId through the KMS
store in the request's region to the key ARN a live account reports,
apply the snapshot settings from ModifyReplicationGroup, emit them with
the ARN, and answer ListTagsForResource for replicationgroup ARNs — for
the record the ARN names, since the store keys groups by id alone.
Delete and modify of a group now share one monitor, so a modify cannot
write the group back after a delete removed it. Validation and wording
follow a live account.

Closes #2615

* fix(elasticache): refuse a KMS key with encryption at rest omitted, and change nothing on a refused modify

An omitted AtRestEncryptionEnabled is false on a live account and a
KmsKeyId is refused with it the same way as with an explicit false.
ModifyReplicationGroup applied the snapshot settings to the store's own
object before validating the user ids, so a request refused for an
unknown user had already changed the group; every check now runs before
any change.

* fix(elasticache): read AtRestEncryptionEnabled as a live account does, and refuse an empty snapshot window

A live account reads any AtRestEncryptionEnabled value that is not
"false" as true — banana, yes and "TRUE " all created an encrypted
group — so the flag is read the same way rather than parsed strictly.
A snapshot window whose end equals its start was measured as a full day;
a live account refuses it as shorter than an hour.
2026-08-27 16:53:33 -04:00
Sam Fakhreddine 4affa05cea feat(firehose): add StartDeliveryStreamEncryption and StopDeliveryStreamEncryption (#2583)
* feat(firehose): add Start/StopDeliveryStreamEncryption

Models DeliveryStreamEncryptionConfiguration on the stream description so
the encryption state set by Start is visible to Describe and cleared by Stop.
Limitations documented in docs/services/firehose.md.

* fix(firehose): keep the key identity on StopDeliveryStreamEncryption and reject Start without an encryption input

- Stopping customer-managed encryption now preserves KeyType and KeyARN with
  Status DISABLED, matching what DescribeDeliveryStream reports on real AWS.
- Streams persisted before the encryption field existed deserialize to the
  AWS-shaped DISABLED default instead of null via a field-level initializer.
- StartDeliveryStreamEncryption without DeliveryStreamEncryptionConfigurationInput
  is now rejected with InvalidArgumentException instead of silently defaulting.

* fix(firehose): reject a KeyARN that is not a KMS key ARN

StartDeliveryStreamEncryption stored DeliveryStreamEncryptionConfigurationInput's
KeyARN verbatim, so a bare key id or an alias ARN was accepted and then reported
back by DescribeDeliveryStream as the stream's encryption key. botocore pins
AWSKMSKeyARNForSSE to arn:.*:kms:<region>:<12-digit account>:key/<id> with a
512-character cap; anything else is an InvalidArgumentException on real AWS.

* fix(firehose): enforce the modeled input constraints on the pre-existing operations

DeliveryStreamType is now checked against the modeled enum, and Tags,
Records and TagKeys against their modeled list bounds (1-50, 1-500,
1-50), all answering InvalidArgumentException as the operations model.
Previously all four were accepted verbatim. Included here because this
PR already carries wire-shape hardening for the same handler; found by
a model-grounded constraint sweep.

* fix(firehose): treat StartDeliveryStreamEncryption input as optional

DeliveryStreamEncryptionConfigurationInput is Required: No in the model; omitting
it is the documented way to enable SSE with the service-owned key and defaults
KeyType to AWS_OWNED_CMK. The prior null-input rejection regressed that path -
inverted the pinning test to assert the 200/AWS_OWNED_CMK behavior.
2026-08-27 16:48:12 -04:00
Michal Schreiber 20ecb89155 fix(rds): keep the tags given to CreateDBSubnetGroup (#2627)
The handler never read Tags.Tag.N, so a group created with tags answered
an empty list to ListTagsForResource — which terraform-provider-aws calls
right after the create — although the model already carried a tag map
and AddTagsToResource on the group's ARN worked. Store the tags with the
group in the same write. DocumentDB subnet groups are the same records
through the same scope.

Closes #2612
2026-08-27 16:40:27 -04:00
Matheus Oliveira b1d7286444 feat(rds): match proxy TLS cert SAN to the advertised endpoint (#2603)
Persists a shared self-signed CA whose SAN list grows to cover every
advertised RDS host, enabling sslmode=verify-full / VERIFY_IDENTITY for
both Postgres and MySQL proxy connections.

Reissuing the CA for a new host now reuses its existing key pair
instead of minting a new one, so a client that already trusts a prior
copy keeps validating connections as the SAN list grows. The MySQL TLS
upgrade path also renumbers every packet through the rest of the
connection phase (not just the first), since the backend's sequence
counter stays one behind the client's for as long as that phase lasts.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-27 16:25:24 -04:00
Allen Sanborn 8f76e13dd6 fix(ec2): canonicalize IPv4 route destinations at the API boundary (#2620)
* feat(core): add IPv4/IPv6 CIDR canonicalisation utility

AWS canonicalises CIDR blocks on write (zeroing host bits, e.g.
100.68.0.18/18 -> 100.68.0.0/18) but Floci currently stores them
verbatim. Add CidrCanonicalizer as a shared, pure-function utility in
core.common so EC2 routes and other CIDR-bearing resources can adopt
it without duplicating parsing logic.

Handles both IPv4 and IPv6 (commons-net's SubnetUtils is IPv4-only
and was deliberately not used), parses the address half as a literal
via InetAddress.ofLiteral to avoid ever falling through to a DNS
lookup on malformed input, and renders IPv6 in RFC 5952 compressed
form to match what AWS itself returns. canonicalize() and
isCanonical() give callers a real, distinguishable signal between
"malformed" and "valid but non-canonical" rather than overloading one
outcome for both.

No caller is wired up yet; this is foundation-only for floci-1dn.

* fix(ec2): canonicalize IPv4 route destinations at the API boundary

AWS documents that a DestinationCidrBlock is reduced to its canonical
form on input (e.g. 100.68.0.18/18 becomes 100.68.0.0/18). Without
that step, CreateRoute, ReplaceRoute and DeleteRoute could each be
handed a differently-spelled but equivalent CIDR for the same network
and silently disagree about which route it named - two spellings of
one /18 could coexist as distinct routes, or a ReplaceRoute/DeleteRoute
using an equivalent spelling could miss the stored route entirely.

Canonicalize DestinationCidrBlock once, in all three verbs, before it
is matched against existing routes or stored, delegating the actual
bit-twiddling to CidrCanonicalizer rather than reimplementing it here.
DescribeRouteTables then echoes the canonical form for free, since the
stored Route never holds anything else.

DestinationIpv6CidrBlock has no equivalent canonical-form sentence in
the CreateRoute/ReplaceRoute model, so it is deliberately left out of
scope even though CidrCanonicalizer itself supports IPv6: a value that
parses as an IPv6 literal is passed through untouched, the same as any
other malformed-for-this-field input. DestinationPrefixListId is an
opaque ID rather than a CIDR and is likewise untouched.

Follow-up to the RouteAlreadyExists duplicate-destination rejection.

* fix(ec2): canonicalize a route's DestinationCidrBlock on load too

Greptile flagged a gap in the API-boundary canonicalization: a route
persisted before that fix keeps its original, non-canonical spelling
(e.g. 100.68.0.18/18) on disk. Reloading it after a restart never
re-canonicalizes that value, so it can no longer be matched by a
freshly-canonicalized incoming destination under strict string
comparison - CreateRoute could create a duplicate of the legacy route,
ReplaceRoute against its original spelling could wrongly 404, and
DeleteRoute could report success while leaving it in place.

Move the canonicalization into Route.setDestinationCidrBlock() itself,
scoped to IPv4 the same way as the API boundary (a value containing
':' is left untouched). PersistentStorage reconstructs a Route via
Jackson, which calls this setter, so a legacy on-disk route is
normalized the moment it is read back into memory and every later
in-memory comparison is apples-to-apples again. The constructor now
routes through the same setter instead of assigning the field
directly, which is a no-op for callers in Ec2Service that already
canonicalize before constructing a Route.

Ec2ServicePersistenceTest#legacyNonCanonicalRouteDestinationCanonicalizesOnRestart
hand-writes a pre-fix-shaped ec2-route-tables.json, restarts a service
over it, and asserts the reloaded route reads back canonical and that
CreateRoute/ReplaceRoute/DeleteRoute against the legacy spelling all
correctly identify the same route. Reverting the setter change alone
fails this test.
2026-08-27 15:26:07 -04:00
Sam Fakhreddine 18521edf28 feat(organizations): add ListAccountsWithInvalidEffectivePolicy (#2628)
* feat(organizations): add ListAccountsWithInvalidEffectivePolicy

Effective-policy validation is not modeled, so the operation returns an
explicit empty Accounts list rather than fabricating data. Documented as
a limitation in docs/services/organizations.md.

* fix(organizations): validate PolicyType on ListAccountsWithInvalidEffectivePolicy

The operation takes a required PolicyType drawn from the EffectivePolicyType
enum, and the handler ignored it entirely: any string — NOT_A_POLICY,
SERVICE_CONTROL_POLICY — was answered 200 with an empty Accounts list, which
reads as "no account has an invalid effective policy" when AWS would have
rejected the request outright.

Route the operation through the service so it validates PolicyType the way
DescribeEffectivePolicy does, and lift that check into a shared helper.

EFFECTIVE_POLICY_TYPES is floci's rendering of the EffectivePolicyType shape
and had drifted five values behind the model (INSPECTOR_POLICY,
UPGRADE_ROLLOUT_POLICY, BEDROCK_POLICY, S3_POLICY,
NETWORK_SECURITY_DIRECTOR_POLICY); widened so the new validation enforces the
enum rather than a subset of it.

* fix(organizations): restrict ListAccountsWithInvalidEffectivePolicy to management/delegated admin

An ordinary member account could call this operation and get HTTP 200 with an
empty Accounts list, indistinguishable from "everything checked out fine".
The botocore model restricts it to the management account or a member account
registered as a delegated administrator - unlike DescribeEffectivePolicy, which
any account in the organization may call.

Add requireManagementOrDelegatedAdmin alongside the existing
requireOrganizationForCaller/requireManagementAccount pair and route this
operation through it.

* fix(organizations): tighten ListAccountsWithInvalidEffectivePolicy to management-only

requireManagementOrDelegatedAdmin (added in the prior commit) let a member
delegated as admin for any unrelated service - config.amazonaws.com in the
new test - through, since it only checked whether the account's
delegatedServices map was non-empty rather than which service.

The model names no service this operation's delegation should be scoped to,
and EffectivePolicyType maps to none, so there is nothing to check a
registration against. Collapse to requireManagementAccount instead, matching
every other operation gated on this same boilerplate phrase in this file
(attachPolicy, enablePolicyType, registerDelegatedAdministrator,
listDelegatedAdministrators) - stricter than the model text, consistently so.

Removes the now-unused requireManagementOrDelegatedAdmin helper.

* fix(organizations): echo PolicyType on ListAccountsWithInvalidEffectivePolicy

Accounts is always empty by design here, so PolicyType was the only field the
response could carry any information in, and it was being dropped by the
shared accountsResponse() helper (built for the two-member ListAccounts shape).
Builds the response inline instead, echoing the validated PolicyType back per
the modeled response shape. Also closes a stray blank line above
requireManagementAccount's javadoc, and expands the delegated-administrator
note on why management-only is correct today.
2026-08-27 15:21:10 -04:00
Sam Fakhreddine d60bd6ead2 feat(route53resolver): add Route 53 Resolver with DNS Firewall domain lists (#2582)
* feat(route53resolver): AWS-managed DNS Firewall domain lists

New JSON 1.1 service exposing ListFirewallDomainLists with the four
AWS-managed domain lists, deterministic ids stable across restarts.
LZA's NetworkPrepStack Custom::ResolverManagedDomainList Lambda resolves
managed list ids by name and previously failed with UnknownOperation.

* feat(route53resolver): full-parity build-out (16 ops)

Adds firewall domain list CRUD, resolver endpoint CRUD, resolver rule
CRUD, and rule-association management, backed by four new
StorageBackend stores. The pre-existing deterministic AWS-managed
domain list logic (AWS_MANAGED_DOMAIN_LIST_NAMES, managedList(),
FirewallDomainList) is untouched -- LZA's bootstrap Lambda depends on
those ids being stable across calls.

Also fixes the JSON-1.1 dispatch case in AwsJson11Controller to pass
the account id through to the handler, matching every other service's
dispatch signature (route53resolver was the one holdout still calling
handle() with the old 3-arg signature).

* fix(config): declare route53resolver enabled toggle in both application.yml files

Upstream's ServiceConfigYamlCoverageTest requires every service config with an
enabled() toggle to declare it explicitly in both files; this branch predates
that test and fails it without the declaration.

* docs(route53resolver): register the generated action table

* fix(route53resolver): declare storageKey and storageMode on the service descriptor

The service persists four stores through StorageFactory, but its catalog
descriptor left storageKey and storageMode null, so it was invisible to
PersistentPathValidator's boot check and to per-service storage config
resolution. Mirror the organizations descriptor.

* fix(route53resolver): make creates idempotent on CreatorRequestId

CreateFirewallDomainList, CreateResolverEndpoint and CreateResolverRule
allocated a new resource on every call, so an LZA/CloudFormation retry of
the same CreatorRequestId left duplicates behind. Real AWS returns the
resource the token originally created. Dedupe per store, after the
operation's own validation so a replayed token cannot excuse a malformed
body; a blank or absent token still allocates.

* fix(route53resolver): give outbound resolver endpoints rslvr-out ids

Every CreateResolverEndpoint allocated an inbound-style rslvr-in- id
regardless of Direction, so an outbound endpoint carried an id AWS would
never issue. Key the prefix off Direction (INBOUND/INBOUND_DELEGATION ->
rslvr-in, OUTBOUND -> rslvr-out) and reject values outside the
ResolverEndpointDirection enum instead of silently defaulting to inbound.

* test(route53resolver): assert managed domain lists by name, not by count

ListFirewallDomainLists returns the four managed lists plus whatever
custom lists other tests in the run have created, so size()==4 and the
[0] index extraction were both order-dependent. Assert the four managed
names are present and pick the id by name. Also drop the call-site counts
from the 404-convention comment, which would go stale on any refactor.

* docs(route53resolver): correct the scoping limitation

The limitation claimed resources are visible regardless of the caller's
account. They are not: all four stores are created through StorageFactory,
which wraps every backend in AccountAwareStorageBackend, so keys are
prefixed with the calling credential's account id and both scan() and
keys() filter on that prefix. Region and VPC are what go unenforced, and
the AWS-managed lists are region-derived and globally visible by design.

* fix(route53resolver): validate Direction before the CreatorRequestId replay check

endpointIdPrefix ran only on the allocation path, so replaying a known
CreatorRequestId with an unrecognised Direction returned 200 and the
original endpoint instead of InvalidParametersException. Bind the prefix
right after the Direction is read, so every request is validated whether
or not it turns out to be a replay.

* fix(route53resolver): enforce the RuleType and ResolverEndpointType enums

CreateResolverRule stored any RuleType string it was given and UpdateResolverEndpoint
copied any ResolverEndpointType through, so Get/ListResolverRules and
GetResolverEndpoint reported values outside botocore's RuleTypeOption
(FORWARD/SYSTEM/RECURSIVE/DELEGATE) and ResolverEndpointType (IPV6/IPV4/DUALSTACK).
Both now reject with the same InvalidParametersException the Direction check uses.

* fix(route53resolver): reject an empty TargetIps list

The model pins TargetIps to list min 1; a present-but-empty array was
stored verbatim. Absent stays allowed for SYSTEM rules. Found by the
botocore-grounded review pipeline; the hand audit missed it.

* fix(route53resolver): make the CreatorRequestId replay check atomic

Two overlapping create retries with the same token could both pass the
replay scan before either put, persisting two resources with different
ids. The three create methods are now synchronized, making the
scan-then-put pair atomic on this ApplicationScoped singleton.

* fix(route53resolver): scope the CreatorRequestId replay to the request's region

replayOf matched purely on CreatorRequestId content across the whole
account-partitioned store, which carries no region in its keys. The same
account replaying a token in a second region got the first region's
resource and ARN back instead of the regional resource it asked for.
Route 53 Resolver is regional, so a token identifies one resource per
region: match the candidate's region too, taken from the ARN this service
builds rather than a stored field, so nothing new reaches the wire.

Also folds the two stacked javadoc blocks above replayOf into one; the
second was shadowing the first, which left the idempotency contract out
of the generated docs.

* docs: correct service count to 79 after the #2579 merge

The upstream/main merge (ca772bc72) added two new services
(servicequotas, ram) on top of this branch's own route53resolver
addition. The merge-base count was 76; three disjoint new services
(1 ours + 2 upstream) makes 79, not 78 as the merge commit left it.

* fix(config): restore the controltower enabled toggle in both application.yml files

The route53resolver key was inserted between controltower: and the
enabled: true that belonged to it, so controltower: became a bare key
binding nothing and route53resolver adopted its child. Control Tower kept
running only because ControlTowerServiceConfig.enabled() carries
@WithDefault("true"), which masked the break; the explicit toggle was
gone. Caught by ServiceConfigYamlCoverageTest, which names controltower
rather than route53resolver and made the CI failure read as unrelated.

* fix(route53resolver): raise the error codes the model actually names

InvalidParametersException (plural) is a Service Catalog shape and does
not exist anywhere in route53resolver's model. Checked every throw site
against the per-operation error lists in botocore route53resolver
2018-04-01 rather than renaming globally, because the service carries two
vocabularies: the resolver endpoint, rule and association operations model
the singular InvalidParameterException, while the DNS Firewall operations
model ValidationException and do not list InvalidParameterException at all.

CreateFirewallDomainList therefore raises ValidationException; the other
eight sites raise InvalidParameterException. requireText and requireEnum
are shared across both families, so each caller now passes the code its
own operation models instead of the helper picking one. ResourceNotFound
usage was already correct and is untouched.

* fix(route53resolver): reject a CreatorRequestId replayed with different parameters

A replayed token was deduplicated on the token alone, so a retry carrying
different but individually valid parameters got a success response
describing the original resource rather than the one it asked for.

CreateResolverEndpoint and CreateResolverRule now compare the retry
against the stored resource and raise ResourceExistsException, which both
operations model. CreateFirewallDomainList is deliberately left lenient:
its modeled error list carries no conflict error at all, so reporting one
would mean inventing a shape real SDK clients cannot deserialize. That
divergence is pinned by a test and ledgered rather than guessed at.

* fix(route53resolver): compare IP request values, not just their count, on a replayed create

The conflict check compared IpAddressRequests by size, so a retry reusing
a CreatorRequestId with the same number of entries but a different subnet
or address was treated as an equivalent replay and returned the original
endpoint, dropping the configuration the caller actually asked for.

The modeled ResolverEndpoint shape carries IpAddressCount and no IP list,
and the handlers return the stored node verbatim, so the addresses are
recorded in a side store keyed by endpoint id rather than on the resource
itself; nothing new reaches the wire. Comparison is order-insensitive so a
reordered retry is still a replay, and endpoints created before this
record existed fall back to the count comparison instead of reporting a
conflict on every retry.

* fix(route53resolver): treat a missing IP-request record as a conflict, not a pass

The fallback for an endpoint with no recorded IpAddressRequests compared
IpAddressCount instead, which accepts a retry that keeps the count but
changes a subnet or address — exactly the case the record exists to catch.
That made it a silently wrong check rather than a lenient one.

With nothing to compare against, sameness cannot be established, so the
retry is now reported as ResourceExistsException. A spurious conflict is
loud and recoverable; a wrong success is neither. Nothing released can
reach this state: the endpoint store is new in the same change as the
record, so the only ways in are a write interrupted between the two stores
or state from an intermediate build of this branch.

Adds a package-private constructor so a hermetic test can create the
missing-record state the public API cannot, following the pattern in
Ec2IpamService. The cost of failing closed — an identical retry also
conflicting — is pinned as its own test rather than left implicit.

* fix(route53resolver): order IP requests by a member-order-independent key

The replay comparison sorted IpAddressRequests by JsonNode.toString, which
serialises members in insertion order. A retry carrying the same addresses
with the members written in a different order could sort the entries into a
different sequence, so an equivalent request was rejected as a conflict.

Sort by a canonical key that ignores member order instead. Both sides are
re-normalised at comparison time rather than trusting the stored order, so
a record written before this fix still compares as equal.
2026-08-27 14:16:38 -04:00
Allen Sanborn bd436eeea1 fix(msk): reject numberOfBrokerNodes values that only look whole after double rounding (#2571)
asBrokerCount validated the incoming JSON number by parsing it as a double and
comparing d == Math.rint(d), but a literal like 1.0000000000000001 has no exact
double representation and collapses to precisely 1.0 during that conversion -
so the check ran after the precision that would have caught it was already
gone, and malformed input was silently accepted as a valid integer.

Binding numberOfBrokerNodes straight to Integer isn't a fix either: Jackson's
default float-to-int coercion truncates a JSON float token the same way
intValue() would, reintroducing the exact bug this field's validation exists
to prevent.

BrokerCountDeserializer reads the token as an exact BigDecimal via
JsonParser#getDecimalValue(), which Jackson builds directly from the source
text rather than routing through a lossy double, so it can tell a genuinely
fractional literal from one that only looks fractional (or only looks whole)
after floating-point rounding.

It can't throw directly on malformed input, though: an exception raised while
Jackson is still reading the request body is caught by
ServerJacksonMessageBodyReader before the JAX-RS resource method - and this
service's AwsException/AwsExceptionMapper handling - ever run, producing a
bodyless 400 instead of MSK's usual {message, invalidParameter} shape.
BrokerCount carries "malformed" as a value instead, and
MskService#validateCreateRequest raises the proper error once binding has
finished successfully, the same way it already does for every other
CreateCluster validation failure.
2026-08-27 13:08:28 -04:00
Allen Sanborn f411a316a2 fix(iam): implement UpdateAccountPasswordPolicy, Get and Delete (#2616)
* fix(iam): implement UpdateAccountPasswordPolicy, Get and Delete

IAM's UpdateAccountPasswordPolicy returned UnsupportedOperation, blocking
the aws_iam_account_password_policy Terraform resource. Mirrors the
existing account-alias trio's storage shape: a single stored value per
account, replaced wholesale rather than merged on update, NoSuchEntity
from Get/Delete when nothing has ever been set.

floci-ge4

* fix(iam): reject malformed boolean values in UpdateAccountPasswordPolicy

Malformed booleans such as RequireSymbols=banana were silently coerced
to false and persisted instead of being rejected. Boolean parameters
now accept only true/false (case-insensitive) and return
ValidationError otherwise, matching the existing numeric-parameter
validation.

* fix(iam): default HardExpiry to false and reject malformed integers

HardExpiry now always appears in GetAccountPasswordPolicy and
UpdateAccountPasswordPolicy responses, defaulting to false when the
caller omits it, matching AWS's documented boolean default instead of
omitting the element entirely (a permanent Terraform diff otherwise).
MaxPasswordAge and PasswordReusePrevention keep their existing
absent-when-unset behavior.

MinimumPasswordLength now goes through a new strict integer parser
(getStrictIntParam) mirroring the existing strict boolean helper, so a
non-numeric value returns ValidationError instead of silently falling
back to the field's default and succeeding with 200.
MaxPasswordAge/PasswordReusePrevention already rejected malformed
values via getOptionalIntParam.
2026-08-27 13:01:05 -04:00
Sam Fakhreddine 4435c62848 feat(logs): add AssociateKmsKey and DisassociateKmsKey for log groups (#2584)
* feat(logs): AssociateKmsKey / DisassociateKmsKey for log groups

floci had no CloudWatch Logs KMS association at all, so LZA's
Custom::UpdateSubscriptionFilter Lambda got UnsupportedOperation, the
resource reported FAILED, AWSAccelerator-LoggingStack rolled back, and
CDK's readback surfaced the misleading "NoStack: CloudFormationStack
object does not hold a stack".

The Lambda reads logGroup.kmsKeyId from DescribeLogGroups and only calls
AssociateKmsKey when it differs from the target key ARN, so storing the
association is not enough -- DescribeLogGroups has to echo kmsKeyId back
or the association never converges and it re-associates every deploy.

- LogGroup: kmsKeyId field
- CloudWatchLogsService: associateKmsKey / disassociateKmsKey, both
  ResourceNotFoundException on an unknown group; associate rejects a
  blank kmsKeyId with InvalidParameterException
- CloudWatchLogsHandler: AssociateKmsKey / DisassociateKmsKey actions
  (name or ARN identifier), and kmsKeyId emitted by DescribeLogGroups
  only when a key is associated

(cherry picked from commit d548de18dc5c5dc8de96cb3b37a3935915be9da2)

* fix(logs): accept resourceIdentifier on Associate/DisassociateKmsKey and require an identifier

The ARN alternative for these two operations is resourceIdentifier on the
wire (unlike the query operations' logGroupIdentifier), so SDK requests
identifying the group by ARN previously failed with ResourceNotFoundException.
A request with neither identifier now returns InvalidParameterException
instead of resolving a null group name. Both actions documented in the
cloudwatch supported-actions table.

* fix(logs): reject KMS requests naming both logGroupName and resourceIdentifier

AWS models the two identifiers as mutually exclusive — exactly one is
required. Supplying both previously succeeded against the named group
while silently ignoring the ARN target.

* fix(logs): enforce the modeled input constraints on the pre-existing operations

logEvents (1-10000 on PutLogEvents), logStreamNames (1-100 on
FilterLogEvents) and the Random/ByLogStream distribution enum on
PutSubscriptionFilter now answer the modeled InvalidParameterException
instead of being accepted verbatim. Included here because this PR
already hardens the same handler; found by a model-grounded constraint
sweep.

* fix(logs): treat a present-but-blank KMS target identifier as present

A blank logGroupName beside a valid resourceIdentifier slipped past the
exclusivity check as "absent" and the mutation proceeded on the valid
field. Presence is now membership (non-null), and a blank chosen
identifier is rejected outright — the model pins both to min length 1.

* fix(logs): store kmsKeyId on CreateLogGroup, reject query-result identifiers, and treat null lists as absent

CreateLogGroup modeled kmsKeyId but the handler never read it, so an
encrypted-at-creation request was accepted, stored nowhere, and absent
from DescribeLogGroups. Both AssociateKmsKey and DisassociateKmsKey
resolve resourceIdentifier through extractLogGroupNameFromArn, which
only recognizes the :log-group: form; the modeled :query-result: form
(account-wide GetQueryResults encryption, a separate feature) fell
through unchanged and became a misleading ResourceNotFoundException
naming a log group the caller never specified. FilterLogEvents also
used request.has("logStreamNames"), which is true for an explicit
JSON null, tripping the min-1 bound the same way an empty array does;
AWS treats an explicit null on an optional member as absent.

Fixes all three: plumb kmsKeyId through a new createLogGroup overload
and store it when non-blank; recognize and reject the query-result
resourceIdentifier form as unsupported instead of mangling it;  switch
to hasNonNull for logStreamNames, matching the idiom already used in
resolveKmsTargetLogGroupName. Also fixes requireListSize's
fully-qualified JsonNode parameter and a stray blank line.
2026-08-27 10:50:05 -04:00
Aniket Shukla d8ef1c8d7b fix(s3): emit post events for browser uploads (#2577) 2026-08-27 09:49:51 -04:00
Sam Fakhreddine 715bab68e7 feat(networkfirewall): emulate AWS Network Firewall (#2580)
* feat: emulate AWS Network Firewall

* docs: register Network Firewall service

* feat(networkfirewall): add AssociateFirewallPolicy

Sets FirewallPolicyArn on the stored firewall, validating that both the
firewall and the policy exist. Round-trip covered by an integration test
(create -> associate -> describe shows the new policy ARN).

FirewallPolicyChangeProtection is not enforced; documented as a limitation.

* docs(networkfirewall): register the generated action table

* docs(networkfirewall): correct the service matrix protocol and action count

The Network Firewall row claimed JSON 1.1 with 25 actions; the service speaks
x-amz-json-1.0 and the generated action table lists 27.

* test(networkfirewall): assert list membership instead of positional indexes

hasSize(1) and [0] assertions coupled these tests to JUnit's method order and
to being the only resource in the store.

* fix(networkfirewall): declare the storage key and mode in the service catalog

The service persists four backends through StorageFactory, but its descriptor
left storageKey and storageMode null, so it was skipped by PersistentPathValidator
and by per-service storage configuration.

* fix(networkfirewall): reject DeleteFirewall when delete protection is enabled

AWS raises InvalidOperationException rather than deleting a protected firewall;
the emulator deleted it regardless of the flag it had already stored.

* fix(networkfirewall): give the subnet and AZ association ops real semantics

All four routed through updateFirewall, which copies request fields onto the
stored firewall wholesale. That ignored SubnetChangeProtection and
AvailabilityZoneChangeProtection, and a Disassociate call left the mappings it
was meant to remove in place. Associate now adds deduplicated mappings,
Disassociate removes the named ones, and either is rejected with
InvalidOperationException while the matching change protection is set.

DescribeFirewall only synthesises endpoints for a firewall created without
SubnetMappings, so draining every subnet now reports no sync states.

* fix(networkfirewall): name the resource kind in ResourceAlreadyExistsException

createNamed passed the response wrapper field, so a duplicate create reported
"RuleGroupResponse already exists" instead of "RuleGroup already exists".

* fix(networkfirewall): validate association requests before touching the firewall

mappingsOf() creates the mappings array on the live stored node, so it ran
before the request array was validated: a rejected DisassociateSubnets on a
firewall created without SubnetMappings left an empty array behind and
permanently suppressed the synthetic sync states in DescribeFirewall.

* fix(networkfirewall): name the resource kind in ResourceNotFoundException

describeNamed passed the response wrapper field as the kind, so a miss reported
"RuleGroupResponse not found". Same defect as the create path; the now-unused
responseField parameter goes with it.

* fix(networkfirewall): return the deleted firewall and its status from DeleteFirewall

AWS responds with {Firewall, FirewallStatus}; the emulator returned only the ARN
and name, so an SDK client parsed an empty response. The handler already had the
region in scope, so no controller change was needed.

* fix(networkfirewall): enforce modeled enums on rule group Type and logging config

Three modeled enums were read and stored without being checked.

CreateRuleGroup/UpdateRuleGroup Type: the model enumerates STATELESS, STATEFUL
and STATEFUL_DOMAIN. The prefix choice was a two-way branch, so every unmodelled
value (including a lowercase "stateful") silently fell through to the
stateful-rulegroup ARN and was persisted as a rule group AWS would have
rejected. The branch keeps its meaning deliberately: only STATELESS gets the
stateless prefix, and both stateful variants share stateful-rulegroup, matching
AWS. A test pins STATEFUL_DOMAIN to that prefix so the mapping is no longer
implicit.

UpdateLoggingConfiguration LogType (ALERT/FLOW/TLS) and LogDestinationType
(S3/CloudWatchLogs/KinesisDataFirehose): the LoggingConfiguration is stored
verbatim, so an unmodelled or wrongly-cased value was persisted and echoed back
by DescribeLoggingConfiguration. Enforced case-sensitively, as the model spells
them and as LZA's network-firewall construct sends them.

Rejections use InvalidRequestException, which both operations list.

* fix(networkfirewall): validate association requests before mutating stored mappings

mappingsOf handed back the live stored array (or installed one), so a
request with a valid mapping followed by an invalid one mutated the
firewall before the rejection. The mappings are now a detached copy,
validated in full, and attached only when storeAndRespond commits.

* fix(networkfirewall): whitelist mutable fields on the shared UpdateFirewall* path

The generic update loop copied every raw request field onto the stored
firewall, so an UpdateFirewallDescription request carrying SubnetMappings
or AvailabilityZoneMappings persisted them without the change-protection
checks the Associate/Disassociate ops enforce. The loop now copies only
the union of fields the six UpdateFirewall* operations actually model
(Description, the four protection flags, EnabledAnalysisTypes), matching
AWS dropping unmodeled request members.

* fix(networkfirewall): scope UpdateFirewall* to the invoked op's own field

The shared updateFirewall path copied any field present in the raw
request that appeared in the union of all UpdateFirewall* mutable
fields, regardless of which specific action was invoked. A plain
UpdateFirewallDescription request could therefore smuggle
DeleteProtection (or any other operation's field) past its own
dedicated operation and change-protection checks.

Each UpdateFirewall* operation models exactly one mutable field
(botocore 2020-11-12); replace the shared whitelist with a per-action
field map so a request only ever mutates the field its own action
models.

* fix(networkfirewall): default DeleteProtection/SubnetChangeProtection/FirewallPolicyChangeProtection to true

botocore's network-firewall 2020-11-12 model documents CreateFirewall as
initializing these three flags to TRUE when the caller omits them;
AvailabilityZoneChangeProtection is the lone exception, documented as
defaulting to FALSE (already correct). Floci defaulted all four to false,
so the enforcement code in firewallForChange/deleteFirewall was correct
but unreachable in the common case of an SDK/Terraform caller that omits
the flags entirely.

RED-first: createFirewall_withoutProtectionFlags_defaultsToProtected
failed against the old defaults (DeleteProtection false, expected true).
Existing tests that relied on the old false default to exercise
mutation paths now pass explicit false for the flags they don't intend
to test, matching how a real caller opts out of protection.
NetworkFirewallIntegrationTest: 27/27 green.

* fix(networkfirewall): flatten UpdateFirewall* response to the modelled shape

All six UpdateFirewall* operations shared updateFirewall(), which returned
firewallResponse()'s nested {Firewall, FirewallStatus} envelope -- the
CreateFirewall/DescribeFirewall shape. botocore 2020-11-12 models each
UpdateFirewall*Response as a flat {FirewallArn, FirewallName, <field>,
UpdateToken}, confirmed for all six ops (UpdateFirewallDescription,
UpdateFirewallDeleteProtection, UpdateSubnetChangeProtection,
UpdateFirewallPolicyChangeProtection, UpdateAvailabilityZoneChangeProtection,
UpdateFirewallAnalysisSettings). A typed SDK client got null back from every
modelled accessor.

RED-first: updateFirewallDeleteProtection_returnsTheFlatModelledShape failed
(FirewallArn/DeleteProtection/UpdateToken were all null at the top level;
present one level down inside Firewall). CreateFirewall/DescribeFirewall
still use firewallResponse() and are unaffected -- only the six Update*
callers changed. NetworkFirewallIntegrationTest: 28/28 green.

* fix(networkfirewall): omit optional update fields instead of echoing null

UpdateFirewallDescription and UpdateFirewallAnalysisSettings read the response
member back with path(), so a firewall created without Description or
EnabledAnalysisTypes serialised the resulting MissingNode as an explicit null.
Both members are optional on these ops (botocore 2020-11-12 marks no required
members on either), so the response now omits what was never set.

* docs: correct service count to 79 after the #2579 merge

The upstream/main merge (6bd7c9d3a) added two new services
(servicequotas, ram) on top of this branch's own network-firewall
addition. The merge-base count was 76; three disjoint new services
(1 ours + 2 upstream) makes 79, not 78 as the merge commit left it.

* docs: correct service count to 80 after the sso-admin merge

upstream/main reports 79 with sso-admin included; this branch adds one further
descriptor (network-firewall, 94 vs upstream's 93), so the hand-maintained count
is 80.

* fix(networkfirewall): honour change protection and clear-on-omit per the model

Two review findings, both verified against the botocore clone at
/Volumes/Extra/repos/botocore rather than the pip install.

AssociateFirewallPolicy (Greptile P1) persisted a replacement policy ARN even
with FirewallPolicyChangeProtection set. The flag is documented as protecting
'against a change to the firewall policy association' and InvalidOperationException
is in the op's modeled errors, so it now routes through firewallForChange like the
subnet and AZ association ops. An existing test created its firewall inline and so
inherited the now-default-true protection; it states the flag explicitly.

UpdateFirewallDescription (pgermosen) preserved and re-echoed a stale description
when the request omitted Description. The model is explicit: 'If you omit this
setting, Network Firewall removes the description for the firewall.' Omission now
clears the stored value.

Deliberately NOT symmetric: EnabledAnalysisTypes carries no equivalent statement
in the model, so UpdateFirewallAnalysisSettings still preserves an omitted value.
A test pins that difference so it reads as a decision rather than an oversight.

* fix(networkfirewall): serialise the association read-modify-write

mappingsOf hands out a deepCopy of the stored mapping array and storeAndRespond
replaces the whole field with it, so two overlapping association calls each start
from the same snapshot and the later write-back discards the earlier caller's
mapping. A 16-caller test loses 4 of 16 associations before this change, and
leaves survivors behind when every subnet is concurrently disassociated.

The four association operations are now synchronized. updateFirewall and
associateFirewallPolicy are deliberately untouched: they mutate a field on the
live shared node rather than replacing a detached copy, so a concurrent write to
a different field is not lost.

Reported by Greptile on #2580; the finding was initially disputed on the grounds
that the storage backends return live references, which is true but irrelevant —
the detachment is in mappingsOf, not in storage.
2026-08-27 09:23:52 -04:00
Sam Fakhreddine 9563b7ef08 feat(ec2): IPAM with real CIDR allocation, EBS encryption defaults, and transit gateway route export (#2596)
* feat(ec2): add IPAM model, CIDR math and Ec2IpamService

Emulates VPC IPAM: organization admin delegation, IPAMs with default scopes, hierarchical pools with provisioned CIDRs, and netmask/specific-CIDR allocations that skip space held by allocations and child pools. This is the surface LZA needs for Custom::EnableIpamOrganizationAdminAccount (Organization stage) and the get-ipam-subnet-cidr Lambda (Deploy stage).

* feat(ec2): wire IPAM actions into the EC2 query handler

Adds 13 dispatch arms and XML writers: enable/disable org admin, IPAM and pool CRUD, provisioned CIDR reads, and pool CIDR allocate/release/list.

* test(ec2): construct Ec2QueryHandler with the IPAM service

* feat(storage): add OwnedEntry/findAnyAccount helpers

Extracted from 9dfda3cb (fix(s3): resolve buckets cross-account under
a global bucket namespace) — that commit's storage-layer helpers are a
genuine prerequisite for the Route 53 VPC associations work that follows,
but its full diff also carries an unrelated S3 replication feature chain.
This isolates just the additive AccountAwareStorageBackend.OwnedEntry /
findAnyAccount / findAnyAccountEntry helpers those commits need.

* feat(ec2): add owner-account overload for createIpamPool

Adds a createIpamPool overload taking an explicit ownerId, with the 6-arg
form delegating to it using the ambient default account. Purely additive
delegation; existing callers are unaffected.

Provenance: extracted verbatim from 91b93aab ("fix(ec2): stamp IPAM and IPAM
pool ownerId with the resolved account"), which is otherwise CloudFormation
provisioning work and remains on hold. Only the Ec2IpamService method is taken
here — none of that commit's Cfn provisioner files are included. The overload
itself touches no CloudFormation code; it is needed because account-scoped IPAM
tests construct pools for an explicit owning account.

* feat(ec2): add IPAM ASN associations and discovery operations

* fix: preserve shared IPAM pool ownership

* feat(ec2): add ModifyIpamPool

Net-new operation, part of the deferred 16-op EC2 IPAM/TransitGateway
P0 block. IpamPool gains autoImport, allocationMinNetmaskLength,
allocationMaxNetmaskLength, and allocationDefaultNetmaskLength fields
(the CIDR allocation defaults real ModifyIpamPool controls); resource
tag add/remove is out of scope for this pass.

Persists through the existing requireOwnedPool/savePool account-scoped
helpers, matching every other pool mutation in this service.

* feat(ec2): EBS account-level encryption defaults

Adds Get/Enable/DisableEbsEncryptionByDefault and
Get/Modify/ResetEbsDefaultKmsKeyId, region-scoped with the AWS-managed
alias/aws/ebs fallback. LZA's SecurityStack
Custom::EnableEbsEncryptionByDefault Lambda calls these and previously
failed with UnsupportedOperation.

* test(ec2): construct Ec2QueryHandler with the EBS encryption service

* feat(ec2): add GetSecurityGroupsForVpc and ModifyVpcEndpoint

Two of the deferred 16-op EC2 IPAM/TransitGateway P0 block; grouped
together since neither has ties to IPAM or TransitGateway and there
was no existing feature branch for standalone VPC-endpoint/
security-group work.

GetSecurityGroupsForVpc filters the existing security group store by
vpcId, using the simplified SecurityGroupForVpc response shape (no
ipPermissions) per the real API. ModifyVpcEndpoint adds a
policyDocument field to VpcEndpoint plus add/remove-list handling for
route tables, subnets, and security groups; IpAddressType/DnsOptions/
SubnetConfigurations are out of scope for this pass.

New branch cut from main (both ops depend only on core SecurityGroup/
VpcEndpoint infra that already lives there, not on any in-flight
feature branch's work).

* feat(ec2): add ExportTransitGatewayRoutes

No real S3 write happens: the operation validates the route table and
bucket, then returns a deterministic s3:// location string matching the
real operation's export naming convention.

* fix(ec2): honour ClientToken on the IPAM pool creates and allocations

* fix(ec2): keep IPAM and IPAM-pool mutations owner-only

* fix(ec2): return MissingParameter for absent IPAM pool and scope ids

* fix(ec2): store the IPAM delegated administrator organization-wide

* test(ec2): cover IPAM ClientToken idempotency at the wire level

* docs(ec2): document the IPAM operations

* docs(ec2): document the EBS encryption defaults and the other branch-added operations

* fix(ec2): drop the ModifyVpcEndpoint copy superseded by upstream #2526

Upstream landed its own ModifyVpcEndpoint (2e8cbc13d), so the branch
copy became a duplicate case label, a duplicate handler and service
method, and a doubled policyDocument element in vpcEndpointXml. The
branch wire tests now exercise the upstream implementation and pass
unchanged. GetSecurityGroupsForVpc from the same original commit is
not upstream and stays.

* fix(ec2): enforce the modelled IPAM enums on create and modify

Tier, MeteredAccount and AddressFamily are all modelled enums, and all
three were stored verbatim. CreateIpam and ModifyIpam wrote whatever
arrived into the IPAM and DescribeIpams echoed it back; CreateIpamPool did
the same with AddressFamily, which is worse than cosmetic — it is what
decides how the pool's CIDRs are parsed and allocated, so a pool created
with a third address family is a pool whose CIDR math never made sense.

Reject an unmodelled value with InvalidParameterValue, the code the rest
of this service already answers for a bad parameter. An absent value still
falls through to the AWS default, since every one of these members is
optional.

* fix(ec2): report the calling account as IPAM owner and harden IPAM input parsing

- CreateIpam/CreateIpamPool recorded config.defaultAccountId() as owner
  while account-aware storage partitioned by the caller, so a non-default
  account got resources whose ownerId and ARN named the wrong account.
  The handler now passes null and the service resolves null-means-caller
  with the same fallback chain storage uses.
- The ContextNotActiveException fallback in callerAccountId() now logs at
  debug so an unexpected context loss is diagnosable.
- Netmask-length parameters on ModifyIpamPool and AllocateIpamPoolCidr go
  through parseOptionalInt, returning InvalidParameterValue instead of an
  unmapped NumberFormatException on non-integer input.
- ReleaseIpamPoolAllocation's not-found message names the CIDR when no
  allocation id was supplied instead of rendering 'Allocation null'.
- Reworded the ExportTransitGatewayRoutes Javadoc: the S3 location has a
  unique random suffix, it is not deterministic.

* fix(ec2): require management account for IPAM org-admin delegation

EnableIpamOrganizationAdminAccount and DisableIpamOrganizationAdminAccount
never checked the calling account, so any member account could change or
remove the org-wide IPAM delegated administrator. Real AWS restricts both
operations to the organization's management account.

This emulator has no cross-service organization membership to resolve the
true management account from, so the configured default account stands in
for it — the same account launched Lambdas resolve to when calling without
an assumed role, matching how LZA's Organization-stage custom resource
invokes these operations.

* test(ec2): verify the IPAM org-admin gate against the real query path

Confirms EnableIpamOrganizationAdminAccount/DisableIpamOrganizationAdminAccount
succeed over the actual query-protocol endpoint using the same non-12-digit
credential style every other test in this suite uses, which
AccountContextFilter/AccountResolver resolve to the configured default
account -- the same resolution LZA's Organization-stage custom resource
relies on. Verifies 79bc8e251's management-account gate does not regress
that path.

* docs: drop the ec2 docs-drift tracking file, filed as floci-io/floci#2605

pgermosen's review on #2596 correctly flagged this file as a parallel,
invisible issue tracker that introduces a new top-level directory main
doesn't have, cites internal workflow details a maintainer can't act
on, and references a stale commit SHA unreachable from this branch's
history. The underlying finding (ten operations Ec2QueryHandler
dispatches with no docs row, predating this branch) is real and now
tracked as a GitHub issue instead.

* fix(ec2): use UnauthorizedOperation for the IPAM org-admin denial
2026-08-26 23:24:56 -04:00
MAN$I VERMAandPriamo Germosen 0205e4ed7e fix(msk): persist CreateCluster broker node groups, encryption, client auth, logging, configuration and tags (#2366)
* fix(msk): persist CreateCluster broker node group, encryption, client auth, logging, configuration and tags

* fix(msk): return the v2 Provisioned envelope and keep internal cluster state persistable

Addresses the two review findings on #2366, plus adjacent parity gaps.

Persistence: MskCluster is the shape WalStorage/PersistentStorage/HybridStorage
serialize, all with a plain ObjectMapper. Marking bootstrapBrokers, containerId
and volumeId @JsonIgnore to keep them out of API responses also stripped them
from the store, so a restart on non-mock storage came back with no bootstrap
brokers (breaking GetBootstrapBrokers and the Pipes Kafka source) and no
container or volume ID (orphaning the Docker resources). Those fields are
serializable again - as is accountId, which putCluster needs to write back to
the right account partition - and the API-facing exclusion moved to explicit
response views in MskController, matching toConfigurationView.

V2 shape: DescribeClusterV2/ListClustersV2 returned the flat v1 ClusterInfo.
The real v2 Cluster nests broker node group, encryption, client auth, monitoring,
logging, broker count and kafka version under Provisioned, with a top-level
ClusterType. An AWS SDK v2 client - what terraform-provider-aws calls - reads
them only there, so the flat shape left them invisible to exactly the callers
this fix is for.

Also:
- configurationInfo is a request-only member; the configuration is now reported
  on currentBrokerSoftwareInfo as configurationArn/configurationRevision, where
  the Terraform provider reads it from. It has no top-level response member on
  either API version.
- Apply AWS's server-side defaults for enhancedMonitoring (DEFAULT) and
  encryptionInTransit (TLS_PLAINTEXT / inCluster true), so an omitted member
  does not read back as drift.
- Omit absent optional members instead of serializing them as null.
- Cover the v2 envelope through the real AWS SDK in the compatibility suite, and
  add a plain-ObjectMapper round-trip test guarding the persistence regression.

* test(msk): mirror the storage mapper's configuration in the round-trip test

* fix(msk): round-trip openMonitoring, storageMode and rebalancing too

Three more CreateCluster request members that were discarded the same way, and
that AWS echoes on DescribeCluster (flat) and DescribeClusterV2 (under
Provisioned). openMonitoring and storageMode both map to terraform-provider-aws
attributes on aws_msk_cluster, so dropping them left the same non-converging
plan this change set is about.

* feat(msk): add the tag API, serverless clusters and CreateCluster validation

Closes the four gaps left open by the metadata round-trip work.

Tags: MSK had no tag endpoints at all, so tags could be set at create time and
read back from Describe but never updated. AWS puts them on /v1/tags/{arn},
which AppSync already owned - and two JAX-RS resource methods cannot claim the
same path and method. Resolved the way /tags/{arn} already was: the dispatch and
wire-shape logic moved out of SharedTagsController into a shared TagDispatcher,
a V1TagsController serves /v1/tags/{arn} on top of it, and the two handler sets
are kept apart by a @V1Tags qualifier so each service stays reachable only on
the path AWS defines for it. AppSync's three controller methods became
AppSyncTagHandler with its wire shape unchanged; MskTagHandler is new. MSK tags
clusters and configurations, so MskConfiguration gained a persisted tags map.

Serverless: CreateClusterV2 silently flattened a serverless request into a
provisioned cluster, which then reported itself as provisioned and echoed broker
metadata the caller never sent. It is now a first-class shape - clusterType,
a serverless envelope on the v2 response, and exactly one of provisioned and
serverless per request. The v1 API predates serverless and its ClusterInfo
cannot represent one, so DescribeCluster rejects it the way AWS does and
ListClusters omits it.

Validation: a create with no clusterName built an ARN containing
cluster/null/<uuid> and stored a cluster unaddressable by name. clusterName is
now required and length-checked, and the members AWS documents a range or an
enum for are checked too. The presence of kafkaVersion, numberOfBrokerNodes and
brokerNodeGroupInfo is deliberately still not required - the emulator has always
defaulted those, and tightening it is a separate, deliberate break.

Also: MskConfiguration.accountId was @JsonIgnore, the same persistence bug the
cluster model had - an async write-back after a reload had no account to target.
ConnectivityInfo gained the networkType member it was missing on both shapes.

* test(msk): point the v2 kafkaVersion assertions at the provisioned envelope

These two predate the v2 shape fix and asserted
clusterInfo.currentBrokerSoftwareInfo.kafkaVersion - the flat v1 layout on a v2
response, which is exactly what that fix corrected. They were codifying the bug,
so they moved to clusterInfo.provisioned.currentBrokerSoftwareInfo.kafkaVersion
rather than the view changing back.

* fix(msk): drop the broker-count ceiling and name the invalid parameter

Applies the two findings from the #2571 review to the code that is actually
going to land.

The 1-15 range came from the SDK/CLI reference, which carries an
__integerMin1Max15 shape for numberOfBrokerNodes. Two other AWS sources
contradict it: the REST API reference documents no minimum or maximum for that
member - on a page that does give ranges for its neighbours, volumeSize 1-16384
and revision min 1 - and the quota page allows 30 brokers per ZooKeeper cluster
and 60 per KRaft cluster, both adjustable upward. Capping at 15 rejected
clusters real MSK creates, turning "converges on the wrong number" into an
outright apply failure for every count from 16 up. The floor stays: a zero or
negative broker count is nonsense and every source agrees.

MSK's Error schema is message plus invalidParameter, "the parameter that caused
the error". Every validation failure now names the member it rejected, via the
four-argument AwsException the mapper already splats into the body. The
pre-existing configuration validations are left as they are - that is merged
code, not this change's.

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-26 23:17:03 -04:00
Sam Fakhreddine 2e843e9f23 feat(servicecatalog): emulate AWS Service Catalog with Control Tower Account Factory (#2585)
* feat: emulate AWS Service Catalog

* docs: register Service Catalog service

* feat(servicecatalog): full API parity for 55 operations

Closes the entire botocore servicecatalog gap surface found by a full-manifest
scan (56 ops; 55 landed, DescribeServiceAction escalated because no store
exists for it and a single write op may not invent one).

Each operation is dispatch-reachable, covered by a wire-level test asserting
response values (not just status codes), and falsifiability-checked at method
granularity. Tests are one class per operation family so falsification isolates
per operation.

Nine previously-unshipped bugs surfaced and fixed along the way, recorded as
issues 0017-0025: wrong field names in describeConstraint, three incompatible
service-action association keys across the single-op and batch-op pairs, a
Type discriminator collision leaking phantom entries into ListServiceActions,
the provisioned-product-plan family having no persistence at all, five cases of
an operation returning a generated id (RecordId, CopyProductToken, plan ids)
that nothing ever persisted, a hardcoded-empty ListConstraintsForPortfolio, and
TerminateProvisionedProduct reporting the wrong RecordType.

Limitations documented in docs/services/service-catalog.md.

* chore: drop local-only bug-ledger files before upstream

issues/0017-0025 are this fork's internal tracking, not something
upstream has a convention for.

* fix(config): restore EmrServerless config body lost in rebase

The rebase onto upstream/main collided where both upstream and this branch
declare a new service config interface sharing a trailing body; the
EmrServerless interface was left open, so the file did not parse.

* docs: state a single correct service count

Collapse the duplicated claim left by the docs merge to one number matching the
74 services this branch registers.

* fix(servicecatalog): adapt to upstream's Organizations model (OrganizationAccount, 5-arg createAccount)

* docs(servicecatalog): register the generated action table

* docs(servicecatalog): correct action descriptions after audit

* docs(servicecatalog): name the real Control Tower catalog triggers

* fix(servicecatalog): reject missing identifiers instead of failing with 500

Store lookups passed the request's identifier straight through to the
backing map, so an operation called without its id parameter died on a
null key and surfaced as InternalFailure. Guard the lookup helpers and
name the missing parameter in an InvalidParametersException.

* fix(servicecatalog): report a plan's own identifiers in its plan details

DescribeProvisionedProductPlan and ListProvisionedProductPlans reused the
plan's own id and provisioned-product name for ProvisionProductId and
PlanName, so callers could never recover the product a plan targets or the
plan's name. Read the distinct fields the plan already stores.

* fix(servicecatalog): require ProvisionProduct to name a real product

ProvisionProduct ignored ProductId and ProductName, so every request took
the Control Tower Account Factory path: an unrecognised product id still
created an Organizations member account and recorded it under the seeded
Account Factory identifiers. Resolve the target product and its
provisioning artifact first, reject what the catalog does not hold, and
touch Organizations only when the request really names Account Factory.
Other stored products now provision a plain record.

Product and artifact resolution is shared with DescribeProvisioningParameters,
which already validated a request the same way.

* docs: state one service count and ProvisionProduct's validated behaviour

docs/index.md still claimed 74 services while docs/services/index.md, the
canonical matrix, listed 77. The Service Catalog page also described
ProvisionProduct taking the Account Factory path for every request, which
stopped being true once it started resolving the product it was given.

* fix(servicecatalog): resolve ProductId by product id only

requireProduct also matches provisioning-artifact ids, so ProvisionProduct
with ProductId set to the Account Factory artifact id resolved the owning
product and created an Organizations account. resolveProduct now does a
strict id lookup; artifact ids in ProductId get ResourceNotFoundException.

* fix(servicecatalog): enforce the modeled enums and AccountId format on stored values

Five request members were read and stored, or used as a filter, without the
constraint botocore pins on them:

- Create/Update/DeletePortfolioShare built the share's store key from AccountId
  and OrganizationNode.Type unchecked, so a short account id or a node type
  outside OrganizationNodeType became a share DescribePortfolioShares reported
  back verbatim.
- CreateProvisionedProductPlan accepted any PlanType and then described the plan
  as CLOUDFORMATION, the only member ProvisionedProductPlanType has.
- CreateServiceAction stored any DefinitionType, likewise a one-member enum.
- DescribePortfolioShares and ListOrganizationPortfolioAccess filtered on an
  unvalidated type, turning a typo into an empty result rather than an error.

* fix(servicecatalog): enforce the PrincipalType enum on principal association

The model pins PrincipalType to IAM or IAM_PATTERN; the value was stored
verbatim. Found by the botocore-grounded review pipeline on its first
sweep — the hand audit of the same service missed it.

* fix(servicecatalog): reject an ambiguous ProductName on ProvisionProduct

Product names are not unique keys, so first-match could resolve a
user-created product carrying the Account Factory name — or vice versa —
and either skip or wrongly enter the Organizations account workflow.
More than one match now raises the modeled DuplicateResourceException.

* fix(servicecatalog): keep a missing AccountEmail inside the Service Catalog model

ProvisionProduct passed AccountEmail straight to Organizations, so omitting it
surfaced Organizations' InvalidInputException — a shape absent from Service
Catalog's model — to a servicecatalog client, which cannot deserialize it into
a typed exception. Validate it on the Account Factory path and raise the
service's own InvalidParametersException, matching how the createAccount
failure a few lines below is already translated.

A plain stored product needs no email, so the guard sits inside
accountFactoryAccountId rather than at the top of provisionProduct; a test
pins that provisioning a non-Account-Factory product without AccountEmail
still succeeds.

* fix(servicecatalog): refuse to delete a portfolio or product that is in use

DeletePortfolio and DeleteProduct deleted the resource and then cascaded,
removing every association naming the portfolio and every share keyed to it.
AWS refuses the call instead — a portfolio with associated products, users,
constraints, or shared accounts, and a product associated with a portfolio,
are both ResourceInUseException — so what AWS makes a recoverable no-op was
here unrecoverable data loss reported as 200. The scans that drove the
cascade now detect the in-use condition.

Every row AWS lists for a portfolio carries PortfolioId, so one scan covers
products, principals and constraints alike; the portfolio cascade is gone
because it is now unreachable. Tag-option associations key off ResourceId,
are absent from AWS's list, and were never cleaned by the old cascade either,
so nothing is orphaned that was not orphaned before. For a product only the
portfolio association blocks, so its remaining associations are still cleaned
up on delete.
2026-08-26 23:04:29 -04:00
Sam Fakhreddine a2bd22d5f8 feat(ssoadmin): serve Identity Center ListInstances (#2581)
* feat(sso): serve Identity Center ListInstances under SWBExternalService

LZA's Custom::GetIdentityCenterInstanceMetadata Lambda calls SSO Admin
ListInstances (target prefix SWBExternalService., the service's AWS-internal
codename, cf. config's StarlingDoveService) and requires exactly one instance
with InstanceArn and IdentityStoreId. Previously no descriptor matched the
target, so the call died with UnknownOperationException. Identifiers are
fixed constants so they survive restarts — LZA persists them into SSM
parameters between stages.

* fix(config): declare ssoadmin enabled toggle in both application.yml files

Upstream's ServiceConfigYamlCoverageTest requires every service config with an
enabled() toggle to declare it explicitly in both files; this branch predates
that test and fails it without the declaration.

* docs(ssoadmin): defer the single-op handler from action-table generation

* docs(ssoadmin): alias the sso descriptor to the IAM page

* fix(ssoadmin): report the caller's account as OwnerAccountId and assert the unsupported-operation error type

* fix(ssoadmin): use UnknownOperationException for unrecognized actions

Matches this codebase's JSON 1.1 dispatch convention (ServiceQuotas, Network
Firewall, and others already use it) and is a real modelled shape unlike the
bare UnsupportedOperation string, which has no Exception suffix and isn't in
sso-admin's error model.

* docs: correct service count to 79 after the #2579 merge

The upstream/main merge (8a4d9bd1b) added two new services
(servicequotas, ram) on top of this branch's own sso-admin
addition. The merge-base count was 76; three disjoint new services
(1 ours + 2 upstream) makes 79, not 78 as the merge commit left it.
2026-08-26 22:06:16 -04:00
Kenshin Okinaka c7cd78e3b3 feat(ses): extend tag endpoints to contact lists, custom verification email templates, and dedicated IP pools (#2589)
* feat(ses): extend tag endpoints to contact lists, custom verification email templates, and dedicated IP pools

* feat(ses): accept inline Tags on v2 CreateCustomVerificationEmailTemplate

* fix(ses): match probed AWS behavior for empty Tags/TagKeys and avoid tag-list aliasing

* docs(ses): describe the actual ValidationException wire body
2026-08-26 21:15:09 -04:00
Sam Fakhreddine f912c3b717 feat(servicequotas,ram): add Service Quotas and AWS RAM resource sharing (#2579)
* feat(servicequotas,ram): add Service Quotas and RAM sharing stub

Two Landing Zone Accelerator pipeline prerequisites:
- servicequotas: ListServiceQuotas/GetServiceQuota (+ AWS-default
  variants) over JSON 1.1 with curated real quota codes for codebuild
  and lambda, deterministic generated quotas for other services, and
  offset-token pagination
- ram: EnableSharingWithAwsOrganization returning {returnValue: true}

* feat(ram): model resource shares with the reads LZA's TGW share flow needs

RamController previously registered only /enablesharingwithawsorganization;
every other restJson1 RAM path fell through to S3's /{bucket} template route
and returned an XML error the LZA Lambdas' JSON parser choked on
(SyntaxError: Unexpected token '<'). Adds CreateResourceShare,
GetResourceShares (SELF vs OTHER-ACCOUNTS visibility incl. org/OU
principals), GetResourceShareInvitations (always empty — organization
sharing auto-accepts, matching real AWS), and ListResources with RAM
resource-type derivation.

* fix(ram): show every non-owned share to OTHER-ACCOUNTS callers

Launched-container credentials resolve to the emulator default account,
so LZA's Custom::GetResourceShare Lambda never matches an account-ID
principal check for the account it actually runs in. Principal-based
visibility hid IPAM pool shares from the accepting NetworkVpcStack while
org-ARN shares (TGW) passed, failing Network_VPCs. The Lambda filters
client-side by owningAccountId + name, so returning all non-owned shares
is safe.

* feat(servicequotas): add RequestServiceQuotaIncrease

Persists the requested increase and returns a RequestedServiceQuotaChange
the subsequent Get/List operations can read back. Limitations documented in
docs/services/servicequotas.md.

* fix(config): restore EmrServerless config body lost in rebase

The rebase onto upstream/main collided where both upstream and this branch
declare a new service config interface sharing a trailing body; the
EmrServerless interface was left open, so the file did not parse.

* fix(ram): persist resource shares

* feat(ram): add principal associations and resource-share lifecycle

* fix(test): conform RAM storage test doubles to upstream StorageFactory API

e9826026 introduced SharedStorageFactory overriding StorageFactory.create with
the pre-upstream return type StorageBackend<String,V>; upstream now returns
AccountAwareStorageBackend<V>. Matches the template used by upstream's own
CodeBuildServicePersistenceTest.

* fix(ram): restrict resource-share mutations to the owning account

Every mutating RAM operation resolved the share ARN with a global
all-accounts scan, so any caller holding an ARN could rename, retag,
associate resources into, or delete another account's resource share.
Thread the caller's account into the mutation paths and resolve the
share only within it; a non-owner now gets the same
UnknownResourceException an unknown ARN gets, matching AWS, which
resolves share ARNs inside the caller's account. Read visibility under
OTHER-ACCOUNTS is unchanged.

* fix(ram): return 400 SerializationException for a malformed request body

An unparseable body left readTree throwing UncheckedIOException, which
escaped the controller and surfaced as a 500 InternalFailure. Reject it
with the modeled restJson1 client error instead.

* fix(config): restore the bedrock-agent-core-control enabled flag

A rebase left the key with a null body in both the main and test
application.yml, silently dropping the service's enabled flag.

* docs(servicequotas): fix the docs path in the consumer test javadoc

* docs: correct the service count and the Service Quotas and RAM matrix rows

docs/index.md still claimed 75 services and listed RAM under JSON 1.1;
the canonical count in docs/services/index.md is 78 and RAM speaks
restJson1. Bring the Service Quotas row up to its five handled actions
and the RAM row up to its twelve REST operations.

* docs(tooling): acknowledge the RAM controller in the docs registry

RAM's action table is hand-written and carries a method-and-path column
the generator does not emit, so register it as a deferred handler rather
than a rest-mode source.

* test(ram): cover owner mutation over HTTP and pin the non-owner error message

The ownership checks were asserted only against the service; nothing
exercised the caller account the controller now threads through, so a
mismatch between the identity stamped at create time and the one
resolved at delete time would have gone unnoticed. Select the existing
SELF assertion by share name, since the store is shared across the
class.

* docs(ram): generate the action table from the controller

The RAM table was hand-written and only acknowledged in the docs
registry, so the drift sentinel could never fire on it. Fold the method
and path into each description the way the FIS REST controller's doc
does, add the generator markers, and register the controller as a
rest-mode source. Also record that mutations are owner-only.

* fix(ram): enforce the modeled resourceOwner enum on the share read paths

GetResourceShares, ListPrincipals and ListResources all read resourceOwner and
fed it to a two-way visibility fork: "SELF" meant owned shares, and literally
anything else meant OTHER-ACCOUNTS. The model enumerates exactly SELF and
OTHER-ACCOUNTS, so a caller who sent "self" or "OTHER_ACCOUNTS" was silently
handed the inverse of what they asked for rather than the InvalidParameterException
AWS returns — an error all three operations list.

Validated at the three entry points rather than inside the per-share visibility
check, so the rejection does not depend on the store being non-empty.

* test(ram): cover the resourceOwner enum rejection on the HTTP path

The service-level test proved the check; this pins the wire behaviour LZA
actually exercises. RamController substitutes "SELF" via asText("SELF") only for
an absent or null resourceOwner, so a present-but-unmodelled value — including a
non-string that Jackson coerces — must still reach the service and surface as a
400 InvalidParameterException on all three read routes. The absent case is
asserted to still return 200, so the default is not silently changed.

* fix(ram): stop exposing the contents of a deleted resource share

ListResources and ListPrincipals reported a deleted share's resources
as AVAILABLE to non-owning consumers. Both now skip DELETED shares,
while GetResourceShares keeps returning the share with DELETED status,
matching the retention window real RAM applies.

* fix(ram): reject a malformed GetResourceShareInvitations body

The endpoint ignores its body semantically, but malformed JSON is a
client error: it now goes through readTree and answers the modeled 400
SerializationException instead of 200 with an empty list.

* fix(ram): reject mutations on DELETED resource shares

A deleted share stays readable via GetResourceShares for the retention
window, but real RAM treats it as terminal: update, associate,
disassociate, tag, untag, and a second delete all raise
UnknownResourceException. findOwnedShare now filters DELETED so every
mutation path resolves a deleted share the same as an unknown ARN.

* fix(ram): apply the GetResourceShares filters and advance lastUpdatedTime

Four response-fidelity gaps from the maintainer review, interleaved in
the same two files:

GetResourceShares read only resourceOwner, so name, resourceShareArns
and resourceShareStatus were silently dropped and a caller narrowing by
share name got every visible share back. All three are applied now, and
an unmodelled resourceShareStatus is rejected with
InvalidParameterException the way resourceOwner already is.

lastUpdatedTime never advanced: ResourceShare had no such field and
creationTime was echoed in its place, on the share node, on the
association rows, and on ListPrincipals. The field now exists and is
stamped in putForOwner, the single seam every create and mutation
already passes through. State written before the field existed reads
back with creationTime, which is correct for a share never mutated
since.

Shares also report the modeled featureSet (STANDARD — floci has no path
to produce a policy-derived share), and DeleteResourceShare echoes the
clientToken the caller sent, both of which the model carries.

* docs(ram): record the filter support and the unrouted-operation behavior

* fix(ram): require resourceOwner on the share read paths

GetResourceShares, ListPrincipals and ListResources all substituted
SELF for a missing resourceOwner, which the model marks required. That
answered a question the caller never asked, and answered it with the
caller's own shares rather than an error. All three now pass a missing
or null value to the validator that already rejected unmodelled ones,
so it surfaces as InvalidParameterException.

* docs(ram): name GetResourceShareAssociations in the fall-through note

Per review, the unrouted-operation note is more useful if it names the
operation Terraform's association resources read on every refresh, and
says the symptom is an S3 NoSuchBucket XML body rather than a
credentials problem.

* fix(ram): reject trailing tokens after a valid JSON body

Jackson's default readTree stops at the first complete value, so a body
like "{} not-json" parsed as an empty object and the request executed
instead of returning the modeled 400 SerializationException. Read with
FAIL_ON_TRAILING_TOKENS, the convention the JSON 1.0/1.1 controllers,
FIS, Signin and EventBridge already follow.

* fix(servicequotas): validate the ServiceCode shape

ServiceCode was only checked for emptiness. Because an unknown code
deliberately generates a quota catalog, that meant a caller typoing
"!!!" got three invented quotas back instead of an error. Validate
against the modeled [a-zA-Z][a-zA-Z0-9-]{1,63} and 63-character cap;
unknown-but-well-formed codes keep generating as before.
2026-08-26 21:04:30 -04:00
Allen Sanborn 94795dd67b fix(lambda): return VpcConfig, SnapStart and LoggingConfig from every read path (#2527)
* fix(lambda): return VpcConfig, SnapStart and LoggingConfig

CreateFunction and UpdateFunctionConfiguration accepted all three with a 200
and then omitted them from every read path, so a VPC-attached function read
back unattached. Terraform refreshes aws_lambda_function.vpc_config,
snap_start and logging_config on every plan, which made the resource
permanently non-converging rather than cosmetically incomplete.

VpcConfig was already stored but never serialised; SnapStart and LoggingConfig
were dropped on the floor entirely.

The response shapes are not the request shapes, per the AWS service model:

- VpcConfigResponse adds VpcId, which VpcConfig has no member for. Resolved
  from the first subnet through Ec2Service, and left off when EC2 does not
  know the subnet — Lambda still accepts unmanaged subnet ids.
- SnapStartResponse adds OptimizationStatus, which SnapStart has no member
  for. On only for a published version with ApplyOn=PublishedVersions.

SnapStart and LoggingConfig are always present in a response, as on AWS: unset
reads back as ApplyOn=None/OptimizationStatus=Off and LogFormat=Text with the
default /aws/lambda/<name> log group. LogFormat=JSON additionally returns both
log levels, defaulting to INFO. RuntimeVersionConfig is returned for managed
runtimes. All of it is carried into PublishVersion snapshots.

LoggingConfig is replaced wholesale on update rather than merged, matching AWS.
Both enums are validated against the model's enum sets before any field is
mutated, alongside the existing Layers and EFS pre-checks — updateFunction-
Configuration mutates the live store object, so a late throw would leave a
rejected update half-applied.

* fix(lambda): validate LogGroup and stop storing Text-format log levels

pgermosen's review on #2527 flagged two loose ends in LoggingConfig
handling. LogGroup accepted any non-blank string instead of AWS's
documented 1-512 character, [.\-_/#A-Za-z0-9]+ constraint. Separately,
ApplicationLogLevel and SystemLogLevel were stored regardless of
LogFormat but only ever surfaced by putLoggingConfig when the format
is JSON, so a Text-format function could accept a log level, persist
it, and never show it on any read path — the same accepted-then-
forgotten shape this PR exists to remove. applyLoggingConfig now only
keeps the levels when the resolved format is JSON, so nothing is
stored that isn't observable.

Also switches the two SnapStart integration tests off nodejs20.x,
which AWS's SnapStart guide does not support, onto java21, and adds
coverage for the LogGroup constraint, the JSON-only log level
validation errors, the VpcConfig detach path, and the parity error
wording pgermosen's review called out as unasserted.

docs/services/lambda.md is updated to describe the LogGroup
constraint and the Text-format no-op behavior.
2026-08-26 21:03:05 -04:00
Allen Sanborn 1be97c9333 fix(ec2): reject a duplicate route destination with RouteAlreadyExists (#2546)
CreateRoute accepted the same destination twice and persisted both copies,
for all three destination kinds. AWS rejects the second with
RouteAlreadyExists.

A destination identifies a route, so duplicates leave the two operations
that match on one disagreeing about which copy they mean: ReplaceRoute
updates only the first, so the stale copy survives the replace, and
DeleteRoute removes every copy, so deleting one of two loses both. A table
holding duplicates therefore has no defined behaviour for either verb,
which is what the check restores rather than only tidying the table.

The check reuses matchesDestination and destinationLabel, already used by
replaceRoute and deleteRoute, so all three verbs agree on what "the same
destination" means. requireExactlyOneDestination runs first, so exactly one
destination kind is set and no cross-kind match is possible.

The local route seeded by CreateRouteTable is covered too, and deliberately:
AWS reports the same error for it, which is the RouteAlreadyExists that
Terraform surfaces when a configuration tries to route over the VPC CIDR.

Follows the RouteAlreadyExists precedent already in this file for transit
gateway routes. Filed as #2524.
2026-08-26 19:17:37 -05:00
Allen Sanborn 009ac0b4a6 feat(firehose): deliver records from a Kinesis stream source (#2528)
* feat(firehose): deliver records from a Kinesis stream source

A delivery stream created with DeliveryStreamType=KinesisStreamAsSource
recorded its KinesisStreamSourceConfiguration and then ignored it. Nothing
read the source stream, so the only way records reached S3 was PutRecord on
the delivery stream itself -- which real AWS rejects for a sourced stream.
CreateDeliveryStream succeeded, DescribeDeliveryStream reported ACTIVE, and
the stream silently delivered nothing.

Found by terraform-aws-messaging's own TestKinesisFirehose, which puts one
record into the source stream and polls the destination bucket: every API
call succeeded and the test failed with "no objects found in the bucket"
after six 60s retries.

The flusher tick now polls each sourced delivery stream through the ordinary
shard-iterator API, so what it ingests is exactly what a GetRecords consumer
would see, and the iterator doubles as the checkpoint. The first iterator
starts at DeliveryStartTimestamp rather than TRIM_HORIZON: attaching Firehose
to a stream that already holds records does not backfill them on AWS. Records
are handed to putRecordBatch, so they buffer and trigger flushes on the same
terms as records delivered by PutRecord.

A source stream that does not exist is logged at debug and skipped, so one
broken delivery stream cannot stall polling for the others.

* fix(firehose): persist Kinesis source shard checkpoints across a restart

The shard iterator each source shard had been consumed to lived only in an
in-memory map, while the delivery stream itself and the source stream's
records both sit in persisted storage. On restart the checkpoint was the one
piece that did not come back, so polling rebuilt every iterator from
DeliveryStartTimestamp and delivered the source stream's entire retained
history to S3 a second time -- silently, and again on every subsequent
restart.

The checkpoint moves into a firehose/source-iterators.json store alongside
streams.json. A Kinesis shard iterator is safe to persist because it is a
self-describing token (streamName|shardId|type|sequenceNumber|index|timestamp,
base64) with no JVM-lifetime component, and KinesisService never trims a
shard's record list, so an index recorded before a restart still resolves to
the same position after one.

The checkpoint is written after the polled records are buffered, so a crash
between the two re-reads them rather than dropping them, and a graceful
shutdown loses nothing at all: onPreShutdown already drains the buffers to S3
before storage is flushed to disk. buffers and bufferSince stay in memory --
losing those loses only what was in flight, which is bounded, where losing the
checkpoint replays an unbounded history.

* fix(firehose): commit source checkpoints on delivery, not on buffering

Persisting the advanced shard iterator inside pollKinesisSource fixed an
unbounded replay on restart but introduced a worse failure in its place.
Polled records do not go to S3 from the poller; they go through
putRecordBatch into the in-memory buffer and reach S3 only when a flush
trips. Writing the checkpoint immediately after buffering let the durable
checkpoint outrun durable delivery: terminate in that window and the buffer
is gone while the persisted checkpoint already says those records were
consumed, so the restored poller resumes past them and they are never
delivered. Real Firehose is at-least-once, so a duplicate is
correct-if-untidy; a silent permanent skip is not.

The checkpoint now has two halves. pendingSourceIterators holds the
advanced position in memory, and only a flush whose S3 write actually
succeeded promotes it into the persisted source-iterators store. The poller
reads from pending-or-committed, so a second poll still does not re-read
what the first buffered, and the restart case the previous commit fixed
still holds: polling resumes from the last committed position, never from
DeliveryStartTimestamp.

Ordering and failure detail:

- The advance runs inside putRecordBatch under the buffer lock, alongside
  the records it covers, so no flush can observe one without the other, and
  a throw before buffering leaves the checkpoint alone.
- flush takes the pending checkpoint out under that same lock, and flush
  drains the whole buffer, so a successful write makes every record the
  checkpoint covers durable.
- A failed write neither commits nor restores the checkpoint: the durable
  position stays put and the next poll reads those records again, which
  repairs the failed delivery instead of silently dropping it.
- Each advance rebases on the current pending-or-committed map instead of
  one carried across the shard loop, so a discarded pending rolls the other
  shards back with it. Commits merge per shard, so two flushes completing
  out of order cost a duplicate rather than dropping a shard's progress.
- onPreShutdown is unchanged and now correct by construction: its drain
  commits each checkpoint it makes durable, before storage is written out.

The comment claiming a crash between the two "re-reads them rather than
dropping them" was simply wrong -- buffering is not durability -- and is
replaced. Records arriving through PutRecord share the buffer and are
unaffected: they carry no checkpoint advance, and a flush that mixes them
with sourced records still delivers both before anything is committed.

* fix(firehose): stamp DeliveryStartTimestamp at creation for a Kinesis source

CreateDeliveryStream's KinesisStreamSourceConfiguration carries only the
ARN and role -- DeliveryStartTimestamp exists only on the Description
shape, which AWS fills in at creation. FirehoseJsonHandler mapped the
source straight off the request, so through the API the field was
always null and the poller fell back to TRIM_HORIZON, backfilling a
pre-populated source stream's whole history into S3.

createDeliveryStream now stamps the field itself when a
KinesisStreamAsSource request omits it, matching how AWS behaves:
attaching Firehose to a stream that already holds records does not
replay them.

Adds a wire-level regression test that pre-loads a Kinesis stream,
creates the delivery stream through the real CreateDeliveryStream API
call, and asserts the pre-existing record is never delivered while one
added afterward is -- closing the gap where the existing unit test
covered this by calling FirehoseService.createDeliveryStream directly
and hand-setting the timestamp, stepping around the API path entirely.
2026-08-26 14:24:43 -04:00
William St John Bacon 054508df87 feat(organizations): add CloudFormation resource types (#2495)
* feat(organizations): add CloudFormation resource types

Adds OrganizationsCfnProvisioner covering AWS::Organizations::Organization,
OrganizationalUnit, Account, Policy and ResourcePolicy. Attribute names are
taken from the registry schemas' readOnlyProperties so Fn::GetAtt resolves
the keys AWS publishes.

CloudFormation's delete path hands over a physical id and a region but no
caller identity, and every Organizations mutation is management-account
scoped. Rather than injecting a second collaborator into the provisioner,
OrganizationsService gains findManagementAccountForResource, which recovers
the owning account from the resource id — so the provisioner keeps to the
one-injected-service convention the other provisioners follow.

provision serves create and update: an OU is renamed in place rather than
recreated (ParentId is create-only in the schema), a Policy's TargetIds are
reconciled in both directions, and an Account is moved to its ParentIds
entry after creation.

The integration test asserts through stack Outputs backed by Fn::GetAtt: an
unmapped attribute does not fail provisioning, it silently resolves to the
literal "LogicalId.Attr", so asserting CREATE_COMPLETE would pass with every
attribute unwired.

* fix(organizations): converge CFN provisioning on partial failure and tag drops

Set the physical id as soon as the create call succeeds in provisionAccount
and provisionPolicy, before moveAccount and reconcileTargets respectively.
Both can throw once the resource already exists — a ParentIds entry pointing
at a missing OU raises DestinationParentNotFoundException, and attachPolicy
can fail on a bad target — and without an id CloudFormation's rollback has
nothing to call delete() with, leaving the account or policy a real member of
the organization but unmanaged by the stack.

Make putResourcePolicy replace its tag map rather than merge into it, so a key
dropped from a template is removed on update instead of lingering. A resource
policy is not a TagResource target, so resolveTagOwner rejects rp- ids and the
provisioner cannot reach it through replaceTags the way the other types do;
Put is the only call that can converge those tags. Supplying Tags states the
full set, while omitting them leaves the existing ones untouched, matching how
an absent Tags property behaves for every other Organizations type.

* fix(organizations): mark created accounts and policies as rollback-owned

CloudFormationService.rollbackCreatedResources deletes a CREATE_FAILED
resource only when it carries both a physical id and the
CfnRollback.ROLLBACK_OWNED_ATTR marker. The provisioner set the id but not
the marker, so rollback walked straight past an account whose MoveAccount
failed after CreateAccount had already made it a member of the organization.
The account survived, the organization could not be deleted while it still
contained one, and the stack reported ROLLBACK_FAILED instead of unwinding.

Set the marker as soon as the create call returns, the way
IamRoleCfnProvisioner does, so the create and the ownership record cannot
drift apart. OrganizationsCfnRollbackIntegrationTest drives a real stack
whose ParentIds names an OU that does not exist and asserts the account id
reaches the stack events, that rollback emits DELETE_COMPLETE for it, and
that neither the account nor the organization is left behind.

* feat(organizations): map OU Path and Account State/Paths

The published registry schemas declare three readOnly properties the
provisioner did not map: OrganizationalUnit Path, and Account State and
Paths. An unmapped key does not fail provisioning — CloudFormationTemplateEngine
resolves it to the literal string "LogicalId.Attr" — so a template asking for
Fn::GetAtt Dev.State silently got back "Dev.State".

Path and Paths are the organization path, o-<org>/r-<root>[/ou-<ou>]*[/<id>]/,
which needs a walk from the resource up to the root. OrganizationsService owns
that hierarchy and already computes the chain for effective-policy merging, so
it exposes it as organizationPath rather than the provisioner rebuilding it.
The account path is read after the move: accounts are always created under the
root, so reading it earlier would publish a path the account no longer lives at.

State is the parameter AWS is retiring Status in favour of on 2026-09-09. Floci
only ever puts an account in ACTIVE or PENDING_CLOSURE, both of which are also
AccountState values, so the two agree; PENDING_ACTIVATION and CLOSED are phases
the emulator does not model. Paths is list-typed in the schema, but an account
has exactly one parent and so exactly one path, and the engine's Fn::Select
splits a comma-delimited scalar back into a list, so the string-valued attribute
map carries it without loss.

Adding the Path lookup to provisionOrganizationalUnit opens the same window that
stranded accounts before: a call that can throw once the OU is already a real
member of the organization. Mark the OU stack-owned as soon as the create
returns, matching the account and policy paths, so rollback can still delete it.

* fix(organizations): Ref on Organization returns the management account id

AWS documents Organization as the one Organizations type where bare Ref
returns the management account id rather than the resource's own id;
Fn::GetAtt Org.Id already returned the organization id correctly. Adds
an OrgRef stack output/assertion covering the case, since the existing
integration test only ever exercised Fn::GetAtt on Org.
2026-08-26 14:05:23 -04:00
Sam Fakhreddine 45240998ac feat(controltower): add AWS Control Tower with landing-zone and baseline lifecycle (#2578)
* feat: controltower models + service (TDD)

Adds LandingZone/EnabledBaseline models and ControlTowerService with a
lazy-seeded landing zone, UpdateLandingZone reconciliation sink, static
baseline catalog, and IdentityCenter auto-enable derivation. Unblocks
LZA's Prepare stage (controlTower.enable: true) which otherwise fails
with UnknownOperationException on POST /list-landingzones.

Landing zone version is pinned to "4.0" to satisfy LZA's
validateLandingZoneVersion check, and the seeded manifest always
includes securityRoles (dereferenced unguarded by LZA's
makeManifestDocument). Empty ListLandingZones is never observable
since that is LZA's create-path trigger, which floci does not
implement (see issues/controltower/01-gap-analysis.md).

12/12 unit tests (U1-U12) pass.

* feat: controltower REST-JSON controller + catalog wiring (TDD)

Adds the 8 Control Tower routes (list/get/update landing zone, landing
zone operation polling, list baselines, list/enable enabled baselines,
baseline operation polling) and wires the service into EmulatorConfig
and ResolvedServiceCatalog so it's health-checked and routed like any
other emulated service. Integration tests I1-I6 exercise the same
sequence LZA's Prepare stage drives: seed read, manifest reconcile via
UpdateLandingZone, register-OU baseline enable/poll, and per-account
isolation.

* docs: controltower service

Documents the pre-seed/reconciliation-sink model, the pinned 4.0
landing-zone version, the IdentityCenter baseline auto-enable rule,
and the explicit non-goals (create-landing-zone path, sso-admin,
identitystore, IAM/KMS/Organizations create-path prerequisites).

* feat(controltower): baseline update/reset operation groundwork

Cherry-picked from the ControlTower-scoped slice of 919285e6, which
bundled this alongside an unrelated ConfigService delivery-channel fix
directly on integration/all-features and never made it to this branch.

Adds EnabledBaseline.lastOperationIdentifier, a getEnabledBaseline
lookup helper, and a recordOperation helper that also tracks insertion
order -- the plumbing ResetEnabledBaseline/UpdateEnabledBaseline (next
commit) build on top of.

* feat(controltower): add landing zone lifecycle and operation tracking

(cherry picked from commit 3ddea8f3afd1aebe065b504fe877f21851809438)

* fix(controltower): correct CreateLandingZone route typo

@Path("/create-landing-zone") didn't match botocore's real wire route
/create-landingzone (no hyphen, matching every sibling ControlTower
route's convention) -- confirmed against gate.py, which flipped from
MISSING to SUPPORTED after the fix. The existing test had been
silently exercising the wrong path all along.

* chore: drop local-only bug-ledger file before upstream

issues/0026 is this fork's internal tracking, not something upstream
has a convention for.

* fix(config): declare controltower enabled toggle in both application.yml files

Upstream's ServiceConfigYamlCoverageTest requires every service config with an
enabled() toggle to declare it explicitly in both files; this branch predates
that test and fails it without the declaration.

* fix: reconcile Control Tower OU guardrails

* fix: seed Control Tower SNS prerequisite

* docs(controltower): add the service matrix row

* fix(controltower): validate landingZoneIdentifier on Get/UpdateLandingZone

GetLandingZone and UpdateLandingZone accepted any request body and answered
with the stored landing zone regardless of which one the caller named, so an
unknown ARN still returned the seeded landing zone instead of an error.

Both now require landingZoneIdentifier and return ResourceNotFoundException
when it does not match the stored ARN, matching real Control Tower.

The check seeds before comparing, unlike Delete/ResetLandingZone which must
report a missing landing zone rather than re-seed one. That keeps the lazy
seed intact: LZA reads ListLandingZones first and passes back the ARN it
returns, so the reconciliation-sink path is unaffected.

* fix(controltower): scope the operation ledger per account and region

The ledger backing GetLandingZoneOperation, ListLandingZoneOperations and
GetBaselineOperation was a single process-global map, so any caller could
enumerate every other account's operation identifiers, and it grew for the
lifetime of the process.

There is now one ledger per account+region, holding the most recent 250
operations and evicting the oldest. Read paths look the ledger up rather
than creating it, so an unknown scope cannot grow the map.

An identifier from another scope still answers with the default operation
type and SUCCEEDED rather than an error: that is the same restart-safe
behaviour an identifier issued before a restart gets, and LZA depends on it
when it polls an operation whose ledger entry is gone.

* docs(controltower): correct the CreateLandingZone path and the scope section

The operation table gave CreateLandingZone a hyphenated /create-landing-zone
path. The controller and the AWS Control Tower service model both spell it
/create-landingzone, one word, like every other landing-zone URI — the docs
were what was wrong, and both review bots flagged the controller because of
them.

The "deliberately not implemented" list also contradicted itself, describing
ResetLandingZone and ResetEnabledBaseline as implemented sinks under a
not-implemented heading. It is now split into operations that answer without
the underlying effect and operations nothing serves at all.

Also documents the identifier validation and the ledger scoping and cap added
in the preceding two commits, adds the missing ListLandingZoneOperations row,
and replaces the controller javadoc's stale operation count with a
description of the surface.

* fix(controltower): pin remediationTypes to its single modeled value

The current botocore Control Tower model constrains remediationTypes on
both CreateLandingZone and UpdateLandingZone to a list of exactly one
element (min 1 / max 1) whose only valid value is INHERITANCE_DRIFT.
The shared reader now rejects anything else with ValidationException
instead of silently storing it.

* fix(controltower): enforce modeled ARN and version constraints on EnableBaseline

EnableBaseline read baselineIdentifier, targetIdentifier and baselineVersion
and stored them verbatim. The botocore model pins all three: the two
identifiers to min 20 / ^arn:aws[0-9a-zA-Z_\-:\/]+$, and baselineVersion to
^\d+(?:\.\d+){0,2}$ with max length 10. UpdateEnabledBaseline right next to it
already validated the same shapes, so the two operations disagreed about what
they would accept.

targetIdentifier is the enabled-baseline storage key and feeds the
organizationalUnitId() substring parse, so a non-ARN value persisted a record
that no subsequent GetEnabledBaseline (which does check isArn) could reach.

Reject with ValidationException, the error the model lists for the operation,
and extract the version check into requireBaselineVersion so both operations
share one rule.
2026-08-26 13:44:31 -04:00
Alex Banna 17e77ba9d3 fix(iam): correct GetAccountSummary provider and access-key counts (#2426)
* fix(iam): align account summary with AWS quotas

* test(iam): use SDK summary key types

* fix(iam): preserve root access key summary semantics

* fix(iam): retain current account summary quotas

* docs(iam): correct account summary tracking note

* fix(iam): update managed policy role quota
2026-08-26 13:09:55 -04:00
Matan Baruch 8b23ed8f4a feat(secretsmanager): persist and return secret resource policies (#2587)
PutResourcePolicy and DeleteResourcePolicy were inert stubs returning an
empty object, and GetResourcePolicy never returned a policy, so
aws_secretsmanager_secret_policy could not be created through Terraform
or Pulumi: the provider uses the ARN echoed by PutResourcePolicy as the
resource id, and an empty response fails the create outright.

The policy is now stored on the secret and round-trips through the three
ops, which also share the existing recovery-window guard: real AWS
rejects all three on a secret marked for deletion with
InvalidRequestException, and the provider substring-matches that message
on GetResourcePolicy to treat the policy as gone.

BlockPublicPolicy is accepted but not enforced, and
MalformedPolicyDocumentException fires on JSON-parse failure only.
2026-08-26 11:41:55 -04:00
Alex Banna 09d7502b28 feat(signin): add secure branded consent flow (#2429) 2026-08-26 11:02:05 -04:00
Kumar Prabhat 1e443acd06 fix(secretsmanager): stop CreateSecret overwriting a secret inside its recovery window (#2555)
createSecret's "already exists" guard only fired when deletedDate was
null, so a name scheduled for deletion fell straight through and
overwrote the recoverable secret at the same storage key. That also
cleared deletedDate, so RestoreSecret then reported "was not deleted"
and the original value was unrecoverable with nothing surfacing the
loss. Real AWS refuses this with InvalidRequestException, which is
what makes the recovery window mean anything.

tagResource, untagResource, and a repeat non-force deleteSecret had
the same shape - no pending-deletion check at all, so all three
returned 200. The repeat delete silently moved DeletionDate forward,
quietly extending a window the caller believed was counting down.
All four reuse the throwIfPendingDeletion helper from #2514.

deleteSecret's guard sits after the force-delete branch on purpose:
force-deleting an already-scheduled secret is a legitimate "skip the
window" escape hatch and stays allowed. DescribeSecret and
ListSecretVersionIds are untouched - AWS doesn't declare
InvalidRequestException for them, and describing a scheduled secret
is how a caller reads its DeletedDate.

Fixes #2549
2026-08-26 10:35:55 -04:00
NAMAN JAIN ac6cb06af4 feat(lakeformation): lake formation (#2427)
* feat(lakeformation): implement Lake Formation emulator

* chore(docs): register LakeFormationJsonHandler in deferred_handlers

* fix(lakeformation): resolve code review comments

* fix(lakeformation): ensure wildcard exclusions generate distinct keys

* fix(lakeformation): include tableCatalogId in DataCellsFilter keys

* fix(lakeformation): include LF-tag values in permission identity key and add integration tests

* fix(lakeformation): configure Jackson for PascalCase and fix JSON-1.1 handler

* fix(lakeformation): escape tag values in permission key to prevent collision

* fix(lakeformation): include embedded CatalogId in permission key and fix tag value encoding collision

* fix(lakeformation): include embedded CatalogId in permission key and fix tag value encoding collision

* feat(lakeformation): migrate from JSON 1.1 dispatcher to REST JSON

- Remove LakeFormationJsonHandler and its routing in AwsJson11Controller
- Create standard JAX-RS LakeFormationController mapped to specific actions
- Update ResolvedServiceCatalog to correctly route Lake Formation requests via restProxyClasses
- Implement regional data isolation via keys prefixing region in MemoryLakeFormationStorage
- Add modeled AlreadyExistsException and EntityNotFoundException handling in LakeFormationService
- Update LakeFormationIntegrationTest to send standards-compliant HTTP POST calls to mapped endpoints

* fix(lakeformation): revoke grant options when base permission is revoked

When a permission exists in both permissions and permissionsWithGrantOption and a revoke names it only in permissions, the grant option is now properly revoked as well to prevent dangling grant options and inconsistent permission states returned to clients.

* fix(lakeformation): correct LF tag casing to match AWS wire protocol

The AWS Lake Formation API uses LFTags, LFTag, LFTagPolicy, and LFTagExpression on the wire. The Jackson PascalCase naming strategy incorrectly converted internal lfTags fields to LfTags, causing silent mapping failures (e.g. AddLFTagsToResourceRequest lost its tags, and TBAC Resource.LFTag lost its resource identity entirely).

Added explicit @JsonProperty annotations to ensure strict compliance with AWS specifications.

* fix(lakeformation): apply filters when listing resources and permissions

The list-resources and list-permissions endpoints were completely ignoring the provided filters and returning the entire in-memory storage, which violates AWS behavior and breaks Terraform synchronization (since it sees permissions of other principals).

Updated MemoryLakeFormationStorage to natively apply:
- listResources: EQUALS, NOT_EQUALS, and BEGINS_WITH for RESOURCE_ARN FilterConditions
- listPermissions: Principal identification checks and exact Resource matching

* fix(lakeformation): resolve multiple minor conformance issues

- Add @JsonInclude(NON_NULL) to all Lake Formation model classes to omit empty JSON fields from wire responses
- Validate that PermissionsWithGrantOption is a subset of Permissions in GrantPermissions
- Validate that ResourceArn starts with 'arn:' in RegisterResource
- Create AwsThrowableMapper to map generic service NPEs to standard AWS 500 InternalFailure responses
- Update index.md documentation to reflect Lake Formation's REST JSON protocol instead of JSON 1.1

* test(lakeformation): cover missing API operations and TBAC grant

Added explicit coverage for the remaining 8 Lake Formation operations to ensure all endpoints execute against the mock storage cleanly:
- RegisterResource, DescribeResource, ListResources, DeregisterResource (Resource lifecycle)
- ListLFTags, DeleteLFTag (Tag lifecycle extension)
- AddLFTagsToResource, RemoveLFTagsFromResource (Tag assignment)

Also added a dedicated TBAC round-trip test (grantAndListPermissionsTBAC) to assert that grants scoped to LFTag resources serialize correctly and are successfully retrievable via ListPermissions.

* fix(lakeformation): enforce AWS-compatible FilterCondition operators and logic

- MemoryLakeFormationStorage now correctly implements AWS's EQ and NE operator strings instead of EQUALS and NOT_EQUALS (which bots and SDKs never send).
- Unrecognized operators now throw an InvalidInputException instead of silently matching everything.
- LakeFormationService now correctly ANDs all filters in the FilterConditionList by passing the entire list to storage rather than arbitrarily dropping all but the first.
- Fixed a Quarkus JAX-RS deployment conflict where Resource Explorer 2 and Lake Formation both mapped to POST /ListResources. The conflict was resolved by rewriting Resource Explorer 2's ambiguous path at the pre-matching filter layer, allowing both services to co-exist securely.

* fix(lakeformation): enforce required inputs on GrantPermissions and handle malformed records

- Added explicit validation to GrantPermissions and RevokePermissions to ensure Principal, Resource, and Permissions are present, throwing an InvalidInputException if missing.
- Null-guarded principal and resource dereferencing in MemoryLakeFormationStorage's listPermissions filter. This prevents a malformed grant record from triggering a NullPointerException and causing a 500 InternalFailure for all subsequent list operations.

* chore(lakeformation): pin ListResources filter in tests and document intentional omissions

- Updated LakeFormationIntegrationTest.resourceLifecycle to register a second resource, strictly asserting that ListResources with an EQ filter correctly isolates and returns only the requested resource.
- Added code comments to MemoryLakeFormationStorage documenting the deliberate omission of pagination (MaxResults, NextToken) and specific optional list filters (ResourceType, IncludeRelated), clarifying the design choice for future maintainers.
- Reverted the repo-wide AwsThrowableMapper addition as it falls outside the scope of the Lake Formation protocol fixes and warrants its own dedicated review.

* chore(lakeformation): Reverted the repo-wide AwsThrowableMapper

- Reverted the repo-wide AwsThrowableMapper addition as it falls outside the scope of the Lake Formation protocol fixes and warrants its own dedicated review.

---------

Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in>
2026-08-26 10:29:31 -04:00
Kumar Prabhat e4b101d5da fix(dynamodb): tolerate whitespace before a function's own parenthesis (#2510)
applySetClause/evaluateSetExpr gated list_append and if_not_exists on a
literal startsWith(functionName + "("), so "list_append (x, y)" (space
before the parenthesis) fell through to the "plain attribute reference"
branch instead of being recognized as a function call. The SET then
silently resolved to no value and left the target attribute unchanged -
no exception, no error, just a dropped write.

Real AWS DynamoDB's UpdateExpression grammar is whitespace-insensitive
around function calls, and this is exactly the form PynamoDB (a widely
used Python DynamoDB ORM) always emits, so this reliably data-loses
every list_append done through PynamoDB.

#1640 already fixed whitespace normalization between clause keywords and
between a function's arguments; this closes the remaining gap between a
function's name and its own opening parenthesis, which sits in a
different code path (the per-clause value evaluator, not the top-level
tokenizer) and wasn't covered by that fix's tests.

Fixes #2509
2026-08-25 23:48:06 -05:00
Aniket Shukla 859db2f352 feat(cloudwatch-logs): add resource policy actions (#2574) 2026-08-25 23:41:09 -05:00
Matan Baruch 247bd590bc fix(msk): return BadRequestException when a configuration ARN does not exist (#2572)
* fix(msk): return BadRequestException when a configuration ARN does not exist

Real MSK reports an unknown or deleted configuration ARN as
BadRequestException (400) with a message containing "Configuration ARN
does not exist", not NotFoundException (404). terraform-provider-aws
(and the Pulumi provider bridging it) substring-matches exactly that
code and message to detect a deleted configuration, so with the 404 the
provider's post-delete waiter never recognizes the configuration as
gone and every terraform/pulumi destroy of aws_msk_configuration fails.

All configuration operations resolve ARNs through
MskService#describeConfiguration, so Describe/Update/Delete and the
revision actions now share the corrected error shape. Cluster APIs are
untouched: real MSK does use NotFoundException there.

* test(msk): assert status, message and error-type header on unknown-ARN update tests
2026-08-25 23:40:02 -05:00
Alex Banna 399bf20387 fix(signin): preserve AWS token error modes (#2554) 2026-08-25 23:38:18 -05:00