Commit Graph
1206 Commits
Author SHA1 Message Date
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
Alex Banna 4083d0667d fix(eventbridge): return 400 for missing resources (#2553) 2026-08-25 23:30:22 -05:00
soreavis df5581e5bd fix(kinesis): reject non-blob Data instead of coercing it with asText (#2551)
PutRecord and each PutRecords entry read the blob with
path("Data").asText(), which renders a missing or container Data as
"", and null, booleans and numbers as their literal text. Whether
such a request was rejected then came down to whether that text
happened to be legal base64: a missing Data was stored as a
successful empty record, JSON null, true or 1234 landed as a few
garbage bytes, while false or 12345 happened to fail. AWS models Data
as required base64-encoded binary on PutRecord and on each PutRecords
entry, so none of these shapes is a valid request.

Accept exactly the two shapes a real client can send — a base64 text
string on the JSON protocol, or a binary node on the CBOR transports,
where an unmodified AWS SDK for Java Kinesis client encodes Data as a
byte string that Jackson decodes to a binary node, not text — and
route anything else the way each path already handles undecodable
base64: a 400 SerializationException on PutRecord, a per-record
InternalFailure in the PutRecords write loop. The issue proposed
rejecting non-textual Data; a textual-only gate turns out to break
every CBOR-default SDK client, so the shipped rule is non-blob.

The batch pre-pass keeps a null data for the rejected shapes so the
request cap still counts them at the bytes the caller sent, and the
record-size check now runs for every entry, so a malformed entry no
longer skips partition-key accounting. A binary Data now decodes in
the pre-pass, so both caps see its real decoded size: an oversized
CBOR blob fails the whole request as an oversized JSON-encoded record
already did, and a batch of CBOR blobs counts toward the request cap
at decoded length rather than its base64 rendering. An explicit
"Data": "" remains legal and stores an empty payload as before.

Closes #2516
2026-08-25 23:27:42 -05:00
Leandro-ft 3bdcd5b84f fix(ec2): apply availability-zone filter in DescribeInstances (#2543)
Fixes #2542
2026-08-25 23:17:56 -05:00
Daniel Zwicker f8597bdef9 fix(cognito): reject self-managed verification status (#2532) 2026-08-25 23:05:29 -05:00
Allen Sanborn 2e8cbc13d7 feat(ec2): support ModifyVpcEndpoint and persist the endpoint policy (#2526)
* feat(ec2): implement ModifyVpcEndpoint and store the endpoint policy

ModifyVpcEndpoint returned UnsupportedOperation. In a survey that drove 183
Terraform roots against Floci it was the single largest blocker, with 205 recorded
occurrences -- roughly five times the next entry.

A gateway endpoint is normally declared with its route tables, subnets and policy
attached after the endpoint itself exists, so aws_vpc_endpoint reaches for this
action in the ordinary case rather than an exotic one. EC2 is otherwise well
supported, which makes the failure especially expensive: a configuration builds most
of its infrastructure and then loses all of it to one refused call.

    Error: modifying EC2 VPC Endpoint (vpce-...): operation error EC2:
    ModifyVpcEndpoint, https response error StatusCode: 400,
    api error UnsupportedOperation: Operation ModifyVpcEndpoint is not supported.

Nearly all the state was already modelled -- VpcEndpoint carries routeTableIds,
subnetIds, securityGroupIds and privateDnsEnabled -- so this adds the handler, the
add/remove set semantics, and the one missing field.

The update is taken under the endpoint's stripe lock, following the convention
already used for network ACL entries and prefix lists. Terraform declares each
aws_vpc_endpoint_route_table_association as its own resource and applies them in
parallel, so several ModifyVpcEndpoint calls land on one endpoint at once; an
unsynchronized read-modify-write loses all but the last, and the losers' waiters then
poll for an association that was silently dropped:

    Error: waiting for VPC Endpoint Route Table Association (vpce-.../rtb-...) to
    become available: couldn't find resource (21 retries)

PolicyDocument is the missing field. CreateVpcEndpoint accepted it and silently
dropped it, and DescribeVpcEndpoints reported no policy, so an endpoint declared
with a policy read back without one and showed as drift on every plan even when
ModifyVpcEndpoint was never called. It is now honoured on create, on modify, and
cleared by ResetPolicy, which AWS documents as returning the endpoint to the default
full-access policy (modelled here as carrying no document).

Add/remove are set operations. AWS accepts adding an id that is already associated,
or removing one that is not, so both directions are idempotent. Every referenced id
is validated before anything is mutated, so a request naming one bad id cannot leave
the endpoint half-modified -- covered by a test.

Reference: request parameters, their optionality, and the minimal
{return, requestId} response --
https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyVpcEndpoint.html

Not implemented, as nothing in the model backs them yet: DnsOptions, IpAddressType
and SubnetConfiguration.N. They are accepted and ignored rather than rejected, which
matches how the other unmodelled endpoint attributes already behave.

Verified end to end. A Terraform configuration with two
aws_vpc_endpoint_route_table_association resources previously failed with the
"couldn't find resource" wait above, leaving one of the two associations dropped; it
now applies 6 resources with both associated. 378 existing EC2 and CloudFormation
tests still pass.

The concurrency test drives the service directly rather than over HTTP: requests
through the test server are serialized enough that an HTTP-level test passes even
with the lock removed. Driven through the service it fails on every run without the
lock, which is what makes it worth having.

* fix(ec2): honour ModifyVpcEndpoint presence semantics and the CFN endpoint policy

Follow-up corrections to the ModifyVpcEndpoint implementation in the preceding
commit. Three behaviour changes, each with a test that fails without it.

PolicyDocument was treated as absent when blank. The EC2 model gives the member no
`min`, so the only test the request supports is whether it is present; an empty
string is a value the caller supplied, and discarding it is the same silent-drop bug
the previous commit fixed for the create path. Presence is now the test, on create,
on modify, and when rendering DescribeVpcEndpoints.

An omitted VpcEndpointId reported InvalidVpcEndpointId.NotFound for the id "null".
VpcEndpointId is the sole required member of ModifyVpcEndpointRequest, and an absent
required Query parameter is MissingParameter here, as it already is for CreateSubnet
and CreateVpc. A present-but-unknown id still reports NotFound.

Ec2VpcEndpointCfnProvisioner passed null for the new policy parameter, so an
AWS::EC2::VPCEndpoint declaring PolicyDocument still lost it -- the EC2 API path was
fixed while the CloudFormation path kept the original bug. The property is declared
as JSON in the template and so arrives as an object node; it is serialised the way
IamRoleCfnProvisioner already serialises AssumeRolePolicyDocument.

Also tightens two error assertions in Ec2ModifyVpcEndpointTest that checked only for
status 400. UnsupportedOperation is also a 400, so both passed unchanged with the
action unrouted -- they proved nothing about the fix. Asserting the error code takes
the class from 8 of 11 failing to 9 of 11 when ModifyVpcEndpoint is unrouted.

Documents the action in docs/services/ec2.md, including the members accepted and
ignored.

* fix(cfn): resolve intrinsics in the VPC endpoint PolicyDocument

The AWS::EC2::VPCEndpoint provisioner serialised PolicyDocument straight
off the raw template node, so a policy built with Ref, Fn::Sub or
Fn::Join was stored as literal template syntax and DescribeVpcEndpoints
reported it verbatim.

Route it through CloudFormationTemplateEngine.resolveJsonAttribute, the
helper added in #2317 for JSON-valued attributes. It resolves the tree
and then unwraps a textual result instead of re-serialising it, avoiding
the double-encoding a naive resolveNode(...).toString() produces. It
also returns null for a null or missing node, so the old has()/isNull()
guard is redundant and goes away.

The javadoc previously cited IamRoleCfnProvisioner's bare toString() of
AssumeRolePolicyDocument as precedent; that precedent predates #2317 and
is no longer the right one to follow, so it now cites the helper instead.
2026-08-25 22:54:44 -05:00
soreavis 7ef698c1f4 fix(rds): reject a duplicate create while provisioning is in flight (#2525)
CreateDBCluster registers the new cluster only after the backing
container is provisioned, and a cold-cache image pull holds that
window open for about ninety seconds in the issue's log — long enough
for the CLI's retry to pass the exists-check again and start a second
container for the same identifier. Both containers then serve one
cluster, with the cluster endpoint wired to one database and the
instance endpoint to the other, and no error anywhere.
CreateDBInstance has the identical check-then-provision-then-register
race.

Serialize creates per identifier with a provisioning sentinel: the
wrapper claims the identifier before the exists-check and releases it
after registration, so a duplicate arriving mid-provision fails fast
with the same fault a completed create produces
(DBClusterAlreadyExistsFault / DBInstanceAlreadyExists) instead of
provisioning again. A failed create releases the identifier on the
way out, so a clean retry still works — the failed path registers
nothing, so a retained sentinel would wedge the identifier with no
resource to delete. Cluster and instance identifiers stay
independent namespaces, as in the issue's own reproduction, which
provisions both under one name.

The reject arm of the issue's suggested fix is deliberate: joining
the in-flight create would park the retrying client's connection on
the remainder of the pull, and CreateDBCluster is not documented as
idempotent-return on AWS either.

Closes #2051
2026-08-25 22:53:28 -05:00
soreavis ce4f6d1c48 fix(s3): route the replication subresource instead of falling through (#2519)
PUT /{bucket}?replication fell through to CreateBucket: in the default
region the idempotent-create path answered 200 with a Location header
and stored no replication configuration, and elsewhere it failed with
BucketAlreadyOwnedByYou. GET fell through to ListObjects and returned
a ListBucketResult the SDK silently parsed as an empty replication
configuration. Only DELETE was routed, as a no-op.

Route PUT and GET alongside the existing DELETE case, per the issue's
suggested fix: the configuration is stored verbatim on the bucket and
echoed back — Floci does not model replication behavior, and neither
the SDK nor the Terraform provider needs it to. The PUT body's
ReplicationConfiguration root is validated (MalformedXML otherwise);
GET on a bucket with no stored configuration answers
ReplicationConfigurationNotFoundError (404), which is what the SDK and
aws_s3_bucket_replication_configuration treat as "not configured".

Now that PUT stores a configuration, DeleteBucketReplication clears it
instead of no-opping (still an unconditional 204, matching AWS), and a
DELETE on a missing bucket answers NoSuchBucket instead of the no-op's
204.

IamActionRegistry maps the three verbs to the documented actions:
s3:PutReplicationConfiguration for PUT and DELETE (AWS authorizes
DeleteBucketReplication with the put action) and
s3:GetReplicationConfiguration for GET. The mapping mirrors the
controller's per-method dispatch order: on PUT and GET accelerate is
dispatched ahead of replication, while the DELETE chain routes
replication and never routes accelerate to an operation.

Closes #2296
2026-08-25 22:51:56 -05:00
Kenshin Okinaka 60dd795703 fix(ses): reject non-string tag members with SerializationException (#2512)
* fix(ses): reject non-string tag members with SerializationException

SesController.parseTagsArray coerced tag Key/Value via asText(null), so a
non-string member (number, boolean, object, array) was silently turned
into a string (123 -> "123") and accepted, across all five SES tag entry
points that share the method (CreateEmailIdentity, CreateConfigurationSet,
CreateEmailTemplate, CreateContactList, TagResource).

AWS's restJson1 deserializer rejects a non-string tag member with
SerializationException / 400 (probe-confirmed). parseTagsArray now rejects
a present-but-non-string Key/Value the same way, leaving missing/null
members to the downstream service validation.

* fix(ses): reject non-object tag list elements with SerializationException

parseTagsArray validated Key/Value types but not that each Tags element is
a JSON object, so a scalar/array/null element fell through to service-layer
validation. Reject a non-object element with SerializationException,
matching AWS's restJson1 deserializer (AWS returns 500 for a null element,
a server-side bug, normalized to the same 400).
2026-08-25 22:50:49 -05:00
Kenshin Okinaka 29f6e7ac6b fix(ses): enforce full AWS tag validation across all SES resources (#2504)
* fix(ses): enforce full AWS tag validation across all SES resources

The shared SES tag validator only checked a single tag's key/value
length, so CreateConfigurationSet, CreateEmailTemplate,
CreateEmailIdentity, CreateContactList, TagResource, and tenant tagging
all silently accepted invalid tag sets.

Add SesTags.validate(List<Tag>) matching probe-confirmed AWS SES v2
behavior: at most 50 tags, unique keys, key 1-128 / value 0-256 code
points, both key and value restricted to letters, numbers, Unicode
whitespace, and _ . : / = + - @, and the aws: key prefix
(case-insensitive) reserved for system tags. Lengths are counted by
Unicode code point (Smithy semantics), not UTF-16 code units.
TagResource enforces the 50-tag limit on the merged (existing +
incoming) set, allowing updates to existing keys. Messages and
evaluation order mirror AWS; all violations are BadRequestException / 400.

Route every SES tag entry point through the validator, and validate
CreateEmailIdentity's tags before the identity is persisted so an
invalid tag set fails atomically instead of leaving the identity behind.
Update the integration tests that encoded the old non-AWS behavior (an
omitted tag value now returns 400 like real AWS).

* test(ses): cover CreateEmailTemplate invalid-tag rejection

Route-level coverage that CreateEmailTemplate rejects an invalid tag set
(duplicate keys) atomically without persisting the template. The
service-level SesTags call was otherwise only exercised through
SesTagsTest, so a regression removing it could pass unnoticed.
2026-08-25 22:47:58 -05:00
Tom Longhurst e4356def24 fix(dynamodb): enforce composite query order (#2471)
* fix(dynamodb): enforce composite query order

Closes #2462

* fix(dynamodb): validate legacy composite queries
2026-08-25 22:23:28 -05:00
d3871e1f25 feat(resourceexplorer2): add AWS Resource Explorer 2 with cross-service resource discovery (#2485)
* feat(resourceexplorer2): Add AWS Resource Explorer 2 with cross-service resource discovery

Resource Explorer 2 lets AWS SDK clients discover resources across
S3, RDS, DynamoDB, ElastiCache, and OpenSearch through a single
query interface — the same way real AWS Resource Explorer aggregates
resources from multiple services.

Architecture: a ResourceProvider CDI interface in core/resource/
decouples Resource Explorer from individual services. Each service
implements the interface to expose its resources. Resource Explorer
discovers all providers via CDI Instance<ResourceProvider> and
queries them live on every request — no intermediate store, no
eventual consistency. New services become discoverable by
implementing the interface; Resource Explorer never imports service
packages directly.

Query parsing: hand-written character-by-character tokenizer that
implements the full Resource Explorer filter syntax — all 10 filter
attributes (accountid, application, id, region, resourcetype,
resourcetype.supports, service, tag, tag.key, tag.value), comma-OR
within filters, negation (-), wildcard suffix (*), quoted strings,
backslash escaping, and free-form text keywords. ListResources
rejects free-form text (filter-only mode); Search accepts both.
Tokens are classified by splitting on the first unescaped colon and
looking the prefix up against the known attributes, matching the
documented grammar.

API surface: 20 REST JSON endpoints covering ListResources, Search,
ListSupportedResourceTypes, full Index CRUD (CreateIndex always
creates LOCAL — promote via UpdateIndexType, matching real AWS),
full View CRUD with Scope and FilterString, BatchGetView with
Errors for missing ARNs, default view association, and pagination
with NextToken on all list operations. Tag operations use the
existing SharedTagsController + TagHandler infrastructure. A
default AGGREGATOR index and default view with tags included are
auto-provisioned on startup so ListResources works without setup.

AWS behavioral fidelity (matched against the API reference, not
guessed): ListResources/Search with no view and no regional default
return UnauthorizedException (401), not 404; the default view is
scoped per region; CreateView requires a unique, regex-valid
ViewName (ConflictException 409 / ValidationException 400) and only
accepts "tags" as an included property; promoting a second aggregator
index returns ConflictException; ListResources suppresses NextToken
at MaxResults=1000; Search/ListResources cap results at the first
1000 matches; QueryString is required (empty string allowed) and
MaxResults is range-validated. Pagination offsets are clamped so a
stale NextToken against a shrunk live result set returns an empty
page instead of a 500.

All response JSON uses PascalCase field names built via Jackson
ObjectNode (never valueToTree on domain models) to match the AWS
SDK wire format exactly. Verified by decompiling every SDK model
class with javap and comparing field-by-field, then running 16
read-only SDK tests against production resource-explorer-2 in
us-east-1.

ElastiCache ReplicationGroup gains arn and region fields so
Resource Explorer can discover it. RDS resources get tags via
ResourceGroupsTaggingService (the cross-service tagging API)
since floci's RDS service doesn't implement AddTagsToResource.

Indexes and views are persisted (hybrid storage) in production;
tests pin the service to in-memory storage so runs stay isolated
and idempotent.

Testing:
- 50 query parser unit tests covering the full grammar
- 20 filter evaluation unit tests against synthetic resources
- 9 pagination unit tests for the offset clamp and 1000-result cap
- 73 integration tests (@QuarkusTest + RestAssured), grouped with
  @Nested by behavior class: conditional/stateful response fields,
  data provenance across services, edge/boundary pagination,
  cross-service data consistency, filter semantics, and AWS API
  fidelity (401 no-default-view, conflict on duplicate view name and
  second aggregator, view-name and included-property validation)
- 28 SDK compatibility tests using real AWS SDK v2
  ResourceExplorer2Client, asserting every field the SDK model
  exposes. Dual-mode: run against floci or real AWS via
  FLOCI_TARGET=aws (mutating tests skipped against real AWS).

* feat(lambda): expose functions to Resource Explorer 2

Implement ResourceProvider so Lambda functions surface via the
Resource Explorer 2 ListResources/Search APIs and lambda appears in
ListSupportedResourceTypes. Iterates $LATEST versions only so published
versions don't produce duplicate function entries.

* feat(sns): expose topics to Resource Explorer 2

* feat(kms): expose keys to Resource Explorer 2

* feat(sqs): expose queues to Resource Explorer 2

Queue ARNs aren't persisted on the model; reconstruct them from the
region (recovered from the storage key) plus the queue name via
regionResolver.buildArn.

* feat(ecr): expose repositories to Resource Explorer 2

* feat(stepfunctions): expose state machines to Resource Explorer 2

* feat(msk): expose clusters to Resource Explorer 2

* feat(pipes): expose pipes to Resource Explorer 2

* feat(acm): expose certificates to Resource Explorer 2

* feat(cognito): expose user pools to Resource Explorer 2

* feat(iam): expose users and roles to Resource Explorer 2

IAM is a global service: its ARNs carry no region, and Resource Explorer
reports global resources with the region "global" (not an empty string),
matching real AWS. Emit two resource types, iam:user and iam:role.

* test(resourceexplorer2): parameterize per-service ListResources coverage

The ten single-service resource tests were byte-for-byte identical
except for the service name and resource type — the same
service-filter/assert-no-foreign-service/assert-type-present shape
copied ten times. Fold them into one @ParameterizedTest whose CsvSource
carries the (service, resourceType) pairs, so adding a service is one
row instead of a new @Nested class. IAM stays separate: it reports the
global region and two resource types, which the shared shape can't express.

* feat(amazonmq): expose brokers to Resource Explorer 2

Amazon MQ arrived on main after this branch was cut. Implement
ResourceProvider so brokers surface via Search/ListResources and mq
appears in ListSupportedResourceTypes, matching the other services
already wired into Resource Explorer. Brokers carry an ARN and tags, so
the mapping is the same shape as the rest: one mq:broker resource per
stored broker.

* feat(lightsail): expose resources to Resource Explorer 2

Lightsail landed upstream (#1583) after this branch began and models
taggable, ARN-bearing resources (instances, disks, static IPs, key
pairs) that AWS Resource Explorer indexes. Without a ResourceProvider
its resources were invisible to Search/ListResources, unlike every
other resource-owning service on this branch.

LightsailService now implements ResourceProvider: getResources() maps
each stored resource node to an ExplorerResource, deriving region and
account from the ARN and resourceType as lightsail:<Type>;
getSupportedResourceTypes() advertises the four stored types (static
IPs flagged non-taggable, matching AWS).

Coverage: a focused unit test asserts the node->ExplorerResource
mapping (arn, type, region, account, tags) without Quarkus, plus the
parameterized RE2 integration test seeds a Lightsail instance and disk
and asserts both surface via ListResources.

* feat(rum): expose app monitors to Resource Explorer 2

CloudWatch RUM (added upstream in #1797) owns taggable, ARN-addressable
app monitors, so it fits the ResourceProvider extension point the rest of
this branch uses to surface resources to Resource Explorer 2 Search,
ListResources, and ListSupportedResourceTypes.

RUM is the first RE2 provider whose API model carries neither an ARN nor a
region (GetAppMonitor returns neither), so getResources() reconstructs the
ARN: the region comes from the storage key, and the owning account is
captured at creation time on the AppMonitor. That owner account is
@JsonIgnore'd so it never leaks into the RUM API body and is not persisted;
getResources() falls back to the default account for monitors reloaded from
disk. Resolving the account at creation rather than at query time is what
keeps a monitor's identity stable — an earlier draft read the account from
the request context inside getResources(), which stamped every resource
with the account of whoever called ListResources instead of its true owner.

Injecting RegionResolver into RumService (threaded through the existing unit
tests) and adding RegionResolver.getDefaultAccountId() support this.

Adds RumResourceProviderTest, including a regression test proving the owner
account is the creator's, not the querying caller's, plus a RumServiceTest
assertion that the owner account never appears in the serialized API body.
Extends ResourceExplorer2IntegrationTest to seed an app monitor and assert
rum:appmonitor surfaces via ListResources and ListSupportedResourceTypes.

* feat(resourceexplorer2): complete the API surface and close the AWS gaps

Follow-up to the Resource Explorer 2 branch, addressing the gaps found reviewing
it against the AWS API reference and search-syntax documentation.

Wire-level corrections:

- MaxResults ceilings are now per-operation, as AWS models them: 1000 for
  Search/ListResources/ListSupportedResourceTypes, 100 for indexes, 50 for views,
  10 for member indexes. ListSupportedResourceTypes previously rejected page sizes
  AWS accepts, and ListViews accepted ones it rejects.
- ListViews is scoped to the calling Region. AWS returns "the views available in
  the AWS Region in which you call this operation"; every Region's views were
  being listed.
- Free-form keywords are OR'd rather than AND'd, which is how AWS reads them. The
  remaining deviation — AWS ranks a non-matching resource lower instead of
  excluding it — is documented rather than emulated, since a keyword-only search
  returning the whole account is not a useful local answer.
- A tag filter against a view whose IncludedProperties omit `tags` is rejected
  with a ValidationException, as AWS documents for tag: / tag.key: / tag.value: /
  application:, instead of being evaluated on data the view may not expose.
- Backslash escaping is honoured throughout the query grammar: escapes now survive
  tokenization and are resolved only where the character's meaning is decided, so
  `\-`, `\:`, `\,` and `\*` are literal text and a quoted phrase neutralises every
  operator inside it.
- application: matches the application name as well as the resource-group ARN;
  resourcetype.supports:tags consults the provider's declared tag support instead
  of passing everything through; free-form keywords match tag keys and values.

The remaining 12 operations are implemented, taking the service to all 32:
the multi-Region setup lifecycle (CreateResourceExplorerSetup,
DeleteResourceExplorerSetup, GetResourceExplorerSetup) provisions real indexes and
views and records each Region's outcome independently, so one Region's failure is
reported through its ErrorDetails rather than abandoning the task. The
organization and trusted-service surfaces answer with the wire-accurate empty
result, since floci models neither.

Eleven more services expose their resources: EC2 (instances, VPCs, subnets,
security groups, volumes, internet and NAT gateways, route tables),
CloudFormation, CloudWatch Logs, EventBridge, Secrets Manager, SSM, ECS, EKS,
Kinesis, Firehose, and ELB v2 — thirty providers in total. API Gateway and
Route 53 stay out: RestApi carries no Region and Route53Service resolves no
account id, so each needs a field added to an unrelated service first.

Also documents the service, which a new service requires: docs/services/
resource-explorer.md with the generated action table, the deviations above, and
the routing note, plus the mkdocs nav, README, and environment-variable entries.

Seven existing tests asserted on the emulator's total resource count, which thirty
providers push past Search's 1000-result cap; they are scoped to a bounded slice
so their arithmetic stays meaningful. 24 tests added for the new behaviour.

* fix(rum): keep a monitor's owning account across updates

UpdateAppMonitor rebuilds the AppMonitor from its current state and never carried
ownerAccountId over, so an update silently reassigned the monitor to whichever
account next called ListResources. Resource Explorer then reported a wrong ARN and
OwningAccountId for any monitor not owned by that caller.

getResources' fallback for monitors reloaded from disk — where the transient owner
account did not survive — was the configured default account. monitorStore.keys()
is already scoped to the calling account by the account-aware backend, so a monitor
reachable there is owned by that caller by construction; the caller's account is
the correct fallback.

Also addresses review findings on the Resource Explorer branch: braces in the
compatibility test's cleanup, a synchronized override in the Lightsail provider
test's storage stub, and four unread locals in the integration test.

* chore: drop the stray local-dev Dockerfile

docker/Dockerfile.localdev was carried in with the Resource Explorer work
but is unrelated to it: nothing in the repo references it, and its header
points at a CI pipeline and dev cluster that do not exist in this org.

* fix(resourceexplorer2): order paginated results before slicing

NextToken is a bare offset, but the list it indexes into is rebuilt on
every call by iterating Instance<ResourceProvider> and StorageBackend.scan,
neither of which promises an order. Offset pagination is only well defined
over a stable order: page through Search or ListResources with MaxResults
smaller than the result set and the second page indexes into a differently
arranged list, silently dropping or repeating resources.

Sort on a unique key before every paginate call: ARN for resources and
indexes, the view ARN for ListViews, the resource type for
ListSupportedResourceTypes. The regression test drives a provider that
reshuffles its resources on each call, which is what an unordered
map-backed store is free to do; without the sort a 25-resource set pages
down to 16 distinct ARNs.

This also makes ResourceProvider#getResources()'s "ordering is not
significant" contract true rather than merely permitted.

* docs: add the Resource Explorer row to the service matrix

The downmerge picks up #2465's service-matrix gate, which fails
`make docs-check` for any service registered in ResolvedServiceCatalog
without a row in docs/services/index.md — resource-explorer-2 was one.

The descriptor's external key carries the API version suffix while the
page is resource-explorer.md, so it also needs an alias entry, the same
way apigatewayv2 and cognito-idp do.

* test(resourceexplorer2): scope the tag-provenance lookup to the caller's Region

dynamoDbTagResourceUpdatesResourceExplorer took Resources[0] from an
unfiltered ListResources and tagged it. ListResources spans every Region
the view covers while DynamoDB TagResource resolves the table in the
request's Region, so the ARN it picked only worked as long as the first
result happened to be local.

Deterministic ARN ordering makes that assumption fail reliably instead of
by luck: the first table is now eu-west-2's and TagResource reports it as
not found. Filter on region:us-east-1, the same way the region-scoping
tests in this class already do.

---------

Co-authored-by: Marius Volkhart <marius@volkhart.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
2026-08-25 21:05:52 -05:00
NAMAN JAIN 943b4c1b45 feat(efs): add Elastic File System (file systems, mount targets, access points) (#2371)
* chore(efs): initialize service structure

* feat: implement EFS service models for file system and mount target management

* feat(efs): implement EFS metadata service emulator

This introduces support for the AWS Elastic File System (EFS) service, handling the control plane operations across the 2015-02-01 REST API.

- Scaffolded and generated EFS DTO models with Jackson PascalCase mapping

Created EfsService with StorageBackend capabilities for File Systems, Mount Targets, Access Points, and Policies
Created EfsController for all mapped REST-JSON routes under /2015-02-01
Registered EFS in the global EmulatorConfig and ResolvedServiceCatalog
Added comprehensive EfsIntegrationTest verifying end-to-end API lifecycle
Created EFS service documentation in docs/services/efs.md

* feat(efs): implement EFS metadata service emulator

This introduces support for the AWS Elastic File System (EFS) service, handling the control plane operations across the 2015-02-01 REST API.

- Scaffolded and generated EFS DTO models with Jackson PascalCase mapping
- Created EfsService with StorageBackend capabilities for File Systems, Mount Targets, Access Points, and Policies
- Created EfsController for all mapped REST-JSON routes under /2015-02-01
- Registered EFS in the global EmulatorConfig and ResolvedServiceCatalog
- Added comprehensive EfsIntegrationTest verifying end-to-end API lifecycle
- Created EFS service documentation in docs/services/efs.md

* fix(efs): address code review comments

- Fixed describe listings to be appropriately region-scoped
- Ensured idempotency token caching for AccessPoint and FileSystem creations
- Altered creation timestamps to use standard epoch seconds

* fix(efs): register models for reflection to satisfy native-image requirements

* fix(efs): resolve remaining review comments and add documentation

- Prevented file system deletion when mount targets exist
- Cleaned up policies and access points upon file system deletion
- Validated parent file system exists during Access Point creation
- Added proper logging for tolerated exceptions during mount target deletion
- Created missing documentation page docs/services/efs.md

* fix(efs): prevent deletion races by locking on file system ID

Wraps all state-mutating operations on file systems and their dependent resources in synchronized blocks keyed by the file system ID. This guarantees that CreateMountTarget, CreateAccessPoint, and similar operations cannot race with DeleteFileSystem, satisfying the Greptile review for P1 Deletion races dependent creation.

* fix(efs): resolve additional concurrency bugs identified by Greptile

- Prevents duplicate access point creation when concurrent requests reuse the same ClientToken across different file systems by adding a dedicated token lock.
- Prevents resurrection of deleted mount targets by wrapping modifyMountTargetSecurityGroups and deleteMountTarget in target-specific locks.

* fix(efs): enforce idempotent parameter matching for access points

* fix(efs): enforce parameter matching for idempotent creation requests

- Compares all parameters in CreateFileSystem (PerformanceMode, ThroughputMode, Encrypted, KmsKeyId, ProvisionedThroughputInMibps) when CreationToken matches
- Compares all parameters in CreateAccessPoint (FileSystemId, PosixUser, RootDirectory) when ClientToken matches
- Throws IdempotentParameterMismatch if parameters differ on a retried token, satisfying Greptile bot review

* fix(efs): enforce idempotent parameter matching for nested access point fields

- Compares PosixUser.SecondaryGids
- Compares RootDirectory.CreationInfo (OwnerUid, OwnerGid, Permissions)
- Throws IdempotentParameterMismatch if nested parameters differ on a retried token, satisfying Greptile bot review

* fix(efs): enforce idempotent parameter matching for default field omission and tags

- Treats null PerformanceMode as 'generalPurpose' for equality checks
- Treats null ThroughputMode as 'bursting' for equality checks
- Treats null Encrypted as false for equality checks
- Strictly compares tag lists in both CreateFileSystem and CreateAccessPoint
- Throws IdempotentParameterMismatch if these differ on a retried token, satisfying Greptile bot review

* fix(efs): override equals and hashCode on Tag model to enable correct idempotency comparison

- Resolves issue where identical tag values on retries were evaluated as mismatched due to object identity comparison
- Satisfies Greptile bot review for Tag idempotency checks

* fix(efs): enforce idempotent parameter matching for AvailabilityZoneName and Backup settings

- Persists AvailabilityZoneName (and derived ID) on the FileSystem during creation if supplied
- Implicitly creates an ENABLED/DISABLED BackupPolicy during CreateFileSystem to match AWS default behavior
- Compares AvailabilityZoneName on retry
- Evaluates Backup request flag against stored BackupPolicy status
- Satisfies final Greptile bot review for missing idempotency parameters

* fix(efs): evaluate creation-time backup configuration rather than current mutable policy during retries

- Adds originalBackupParameter to FileSystem model to immutably capture the configuration at creation time
- Refactors idempotency check to evaluate this stored value rather than querying the potentially modified live BackupPolicy
- Addresses Greptile P1 defect where PutBackupPolicy broke CreateFileSystem retries

* fix(efs): resolve backup retry snapshot persistence across emulator restarts

- Replaces @JsonIgnore FileSystem property with a dedicated originalBackupStore
- Ensures the original backup parameter is properly persisted and reloaded from disk
- Maintains AWS API contract fidelity while preventing IdempotentParameterMismatch on restarts

* fix(config): resolve EmrServerless and EFS configuration syntax

* fix(efs): prevent stale mount targets by deleting them inside the file system lock

* fix(efs): correct file-system policy endpoint path to singular /policy

* fix(efs): apply query string filters correctly for describe operations

* fix: align EFS emulator with AWS specifications

- Fix idempotency matching logic for CreateFileSystem and CreateAccessPoint
- Implement modern TagResource, UntagResource, and ListTagsForResource APIs
- Dynamically resolve regions and ARNs via RegionResolver
- Detect mount target subnet conflicts and dynamically resolve AZs
- Remove unused obsolete EFS model classes
- Ensure UpdateFileSystem returns 202 Accepted status code

* docs: generate EFS action table from controller

Resolves 'make docs-check' failure by injecting the floci:actions sentinel markers so the automated docs tool can maintain the supported actions list.

* fix: align EFS emulator with AWS specifications

- Fix idempotency matching logic for CreateFileSystem and CreateAccessPoint
- Implement modern TagResource, UntagResource, and ListTagsForResource APIs
- Dynamically resolve regions and ARNs via RegionResolver
- Detect mount target subnet conflicts and dynamically resolve AZs
- Remove unused obsolete EFS model classes
- Ensure UpdateFileSystem returns 202 Accepted status code

* docs: generate EFS action table from controller

Resolves 'make docs-check' failure by injecting the floci:actions sentinel markers so the automated docs tool can maintain the supported actions list.

* fix: prevent stale count on mount target deletion failure

Removes the generic catch block in deleteMountTarget so that an unexpected exception during the file system update causes the entire operation to fail, leaving the mount target intact instead of silently deleting it and causing an inconsistent parent count.

* fix: store original creation requests to prevent false idempotency conflicts

When a file system or access point is updated or retagged, its mutable state changes. Retries using the original creation token were incorrectly compared against this mutated state, causing IdempotentParameterMismatch conflicts. This commit introduces dedicated storage backends to retain the original CreateFileSystemRequest and CreateAccessPointRequest, ensuring that idempotent retries correctly compare their parameters against the original request rather than the current mutated state.

* fix: store original creation requests to prevent false idempotency conflicts

When a file system or access point is updated or retagged, its mutable state changes. Retries using the original creation token were incorrectly compared against this mutated state, causing IdempotentParameterMismatch conflicts. This commit introduces dedicated storage backends to retain the original CreateFileSystemRequest and CreateAccessPointRequest, ensuring that idempotent retries correctly compare their parameters against the original request rather than the current mutated state.

* refactor: remove unused idempotent parameter stores in EFS

Dropping originalFileSystemRequestStore, originalAccessPointRequestStore, and originalBackupStore, as parameter matching is no longer performed by the EFS emulator. These stores were persistent and written to on every create but never read, unnecessarily keeping state files around.

* fix(efs): resolve compliance issues and reviewer feedback

- Populate AccessPointDescription.Name from tags during create and describe
- Return 404 FileSystemNotFound for unknown IDs or CreationTokens in DescribeFileSystems
- Implement Marker/MaxItems pagination for DescribeTags
- Refactor AZ-ID generation to match exact AWS shapes (e.g. usw2-az1)
- Clear ProvisionedThroughputInMibps on transition to elastic/bursting mode
- Reject update requests setting ProvisionedThroughputInMibps on non-provisioned filesystems
- Add trailing newline to ThroughputMode.java
- Expand integration tests for ThroughputMode transitions

---------

Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in>
2026-08-25 19:48:38 -05:00
Kumar Prabhat fd78ae4f4b fix(secretsmanager): raise InvalidRequestException, not ResourceNotFoundException, for pending-deletion secrets (#2514)
DeleteSecret without ForceDeleteWithoutRecovery keeps the secret in
store with deletedDate set to a future date (recoverable via
RestoreSecret) - it's only removed from store outright on a force
delete, so resolveSecret() already raises ResourceNotFoundException on
its own for a genuinely gone secret. Any getDeletedDate() != null
check reached past resolveSecret() therefore always means "still
present, scheduled for deletion", which real AWS reports as
InvalidRequestException.

getSecretValue, putSecretValue, updateSecret,
claimTargetAttachment, rotateSecret, and updateSecretVersionStage
all threw ResourceNotFoundException here instead, making a
recoverable, still-restorable secret indistinguishable from one
that's genuinely gone. batchGetSecretValue in the same file already
had this right (InvalidRequestException with the correct message) -
extracted that into a shared throwIfPendingDeletion(secret) helper
and applied it consistently at the six other sites.

Strengthened the existing deleteSecretWithRecoveryWindow test (it
only asserted AwsException.class, which passes regardless of error
code) to check the specific error code, and added a test covering
all six affected operations.

Fixes #2513
2026-08-25 10:00:38 -04:00
Anders Wasen a3044e065e feat(rds-data): adding data-api support for lable/name and batch (#2518)
* feat(rds-data): adding data-api support for lable/name and batch

* feat(rds-data): fixing PR robots comments

* feat(rds-data): fixing PR comments; adding tests
2026-08-25 09:40:33 -04:00
Tom Longhurst a57c6c8112 fix(dynamodb): validate query key types (#2469)
* fix(dynamodb): validate query key types

Closes #2467

* fix(dynamodb): harden query validation

* fix(dynamodb): validate query value payloads
2026-08-24 18:11:05 -04:00
Tom Longhurst e3df59ae1f fix(dynamodb): validate cursor key types (#2470)
* fix(dynamodb): validate cursor key types

Closes #2468

* fix(dynamodb): reject malformed cursors
2026-08-24 17:52:17 -04:00
Allen Sanborn 564dbf204f fix(kinesis): apply CreateStream's Tags instead of dropping them (#2494)
* fix(kinesis): apply CreateStream's Tags instead of dropping them

CreateStream parsed StreamName, ShardCount, StreamModeDetails and
MaxRecordSizeInKiB and silently ignored the optional Tags member, so a stream
created with tags came back untagged from ListTagsForStream. AddTagsToStream
already worked, so only the create path was affected.

A hand-written script would not notice. Terraform does: aws_kinesis_stream sets
tags at create time and then reads them back, so every plan after a successful
apply reports "tags will be updated in-place" on an unchanged configuration.
That is what fails terraform-aws-messaging's TestKinesis, whose four subtests all
assert `terraform plan` returns exit code 0 after apply -- every other assertion
in that test (shard count, encryption type, retention period) already passed.

* refactor(kinesis): parse CreateStream and AddTagsToStream tags with one helper

The create-time tag support added in the previous commit duplicated the three
lines AddTagsToStream already used to turn the request's Tags object into a
map. Two copies of the same parse is two things to keep in step, and this
service now has three tag operations, so extract parseTags() the way
CodeBuild's and SecretsManager's JSON handlers already do.

No behaviour change: a missing or non-object Tags member still yields an empty
map rather than an error, and CreateStream still skips the store write when
that map is empty. Greptile flagged that asText() coerces a non-string tag
value ("null", "3", "") instead of rejecting it. That is true, but it is
AddTagsToStream's pre-existing behaviour, not something this PR introduced --
sharing one parser is what keeps the two paths from answering the same
malformed request differently. Rejecting non-string tag values is a separate
input-validation fix that should land on its own, across every tag operation.

Adds handler-level unit tests, which the class had none of for tags: create
with tags, create without, create with an empty Tags object, and AddTagsToStream
applying the same map. Unlike the ordered integration tests these get a fresh
service per test.
2026-08-24 17:39:59 -04:00
kk feb669d58b fix(bedrock-agentcore): support memory tagging and dropped fields (#2501)
* fix(bedrock-agentcore): tag memory resources and honor dropped CreateMemory/UpdateMemory fields

Three divergences from AWS in the Memory control plane (#2316):

- Memory ARNs were not taggable: the shared /tags/{arn} handler dispatched
  only agent/ and gateway/ segments, returning ValidationException for
  memory/ ARNs even though AWS supports TagResource on memories.
- CreateMemory silently dropped tags, encryptionKeyArn, and
  memoryExecutionRoleArn: accepted with 202, never stored.
- UpdateMemory ignored eventExpiryDuration (and memoryExecutionRoleArn),
  applying only description.

Memory now persists all three fields, the tag handler dispatches three
ways (with the foreign-account 404 guard covering memories), and
UpdateMemory applies description, eventExpiryDuration (validated 3-365),
and memoryExecutionRoleArn. Matching AWS, the Memory response shape never
embeds tags; they surface only via ListTagsForResource.

* fix(bedrock-agentcore): validate UpdateMemory input before mutating stored state

A rejected update (out-of-range eventExpiryDuration) could leave the
description already applied, because get() returns the live stored object
and validation ran after the first setter. Validate all inputs up front,
and pin the no-partial-mutation behavior with unit and integration tests.

Also deduplicates the @Order(3) collision in BedrockAgentCoreMemoryIntegrationTest.

Addresses review feedback from pgermosen.
2026-08-24 17:32:28 -04:00
Tedd 72dfa634f7 fix(apigateway): support AWS type Lambda integration and fix duplicate Content-Type header (#2049)
* fix(apigateway): support AWS type Lambda integration and fix duplicate Content-Type header

Integration tests for AWS type lambda integration with apigateway and duplicate content-type headers

Addressing Greptile review the qualifier is now preserved end to end and covered by tests

* fix(apigateway): resolving review feedback, adding in comment to LambdaArnUtils re lastIndexOf fallback, and updating DOCs with Line re v1 execution plane integration type behaviour
2026-08-24 17:24:09 -04:00
Allen Sanborn fcd662fb62 fix(msk): accept an empty serverProperties on Create/UpdateConfiguration (#2491)
* fix(msk): accept an empty serverProperties on Create/UpdateConfiguration

CreateConfiguration and UpdateConfiguration both validated serverProperties
with `== null || isBlank()`, which conflates "member absent" with "member
present but empty". A zero-length blob is a legitimate value in MSK: it means
"no property overrides".

Terraform modules hit this routinely. Gruntwork's msk module builds
serverProperties by joining a map that defaults to {} and creates
aws_msk_configuration unconditionally, so an unconfigured module sends an
empty blob and the emulator answered BadRequestException "serverProperties is
required." Three terraform-aws-messaging roots failed on it.

Both call sites now reject only null. Absent and empty stay distinguishable at
the REST layer: MskController.asString returns null for a missing member and
decodeServerProperties turns the empty base64 string into "".

* test(msk): read back both revisions, and match the class's naming

The round-trip test read back only revision 1, so an update that stored "" and
one that silently carried the previous revision's properties forward would both
have passed. It now checks both revisions.

Renames createConfigurationRejectsAbsentServerProperties to
...RejectsMissingServerProperties, which is what every neighbouring
missing-member test in these two classes is already called.
2026-08-24 15:59:44 -04:00
Abhigya 1ca19c722a fix(cognito): AWS-accurate UsernameAttributes pools — UUID username, alias sign-in, and token/revocation parity (#1849)
* feat: mint UUID username with mutable email alias for UsernameAttributes pools

* fix(cognito): align token claims, alias-exists, read-attributes, and not-found status with AWS

* fix(cognito): align token claims, alias-exists, read-attributes, not-found status, and canonical-username revocation with AWS

* fix(cognito): accept canonical UUID on RESEND, harden migration sub-minting and email validation)

* fix(cognito): AliasExistsException guard check

* test(cloudformation): expect 400 for Cognito ResourceNotFoundException

Align the post-deletion DescribeUserPool/DescribeUserPoolClient assertions
with the AWS-accurate 400 status now returned for Cognito
ResourceNotFoundException.

* fix(cognito): bind CUSTOM_AUTH challenge USERNAME to the session user

RespondToAuthChallenge validated SECRET_HASH against the caller-supplied
USERNAME while resolving the user from the session, so the two were allowed
to disagree. That reduced SECRET_HASH from a per-user binding to a bare
proof-of-client-secret check, and let callers pass locally against requests
real Cognito rejects.

Resolve the supplied USERNAME the same way sign-in does and require it to
match the session user; aliases still work since the caller may legitimately
send the email while the session holds the UUID.

Also compare SECRET_HASH with MessageDigest.isEqual instead of String.equals
so the MAC comparison does not short-circuit on the first differing byte,
matching the SRP path in CognitoSrpHelper.
2026-08-24 14:43:49 -04:00
Davor Santic 5c45c146c7 fix(ecs): round-trip command and entryPoint on container definitions (#2446)
RegisterTaskDefinition already parsed containerDefinitions[].command and
.entryPoint, and EcsContainerManager honoured both when launching the
container — but containerDefinitionNode never rendered them, so
DescribeTaskDefinition silently omitted both keys.

The practical consequence is data loss on the describe -> register
round trip that tooling relies on to cut a new revision: the overrides
disappear from the JSON and the new revision falls back to the image's
default entrypoint. The container still starts, so nothing surfaces until
whatever the entrypoint was meant to do turns out not to have happened.

Serialize both sparsely, matching the surrounding portMappings /
mountPoints style, so definitions that set neither stay byte-identical.

Tests: a parse+serialize unit test in the EcsJsonHandlerVolumesTest style
(round trip plus an absent-stays-absent guard), and an end-to-end
register -> describe case in EcsIntegrationTest.

Refs #2445
2026-08-24 09:25:47 -04:00
Allen Sanborn e18a262261 fix(ec2): store and report a route's IPv6 destination, and stop DeleteRoute NPEing (#2492)
* fix(ec2): store and report a route's IPv6 destination

CreateRoute accepted DestinationIpv6CidrBlock and dropped it. Route had no
member to put it in, so an IPv6 route was stored with no destination at all,
serialized with no destination element, and could never be matched again.
The Terraform provider's create-waiter polls DescribeRouteTables for the
route it just made and never finds it, so every `aws_route` with an IPv6
destination fails the apply at its 5-minute deadline.

A second defect falls out of the same gap. The destination comparison in
deleteRoute and replaceRoute read the stored side —
`r.getDestinationCidrBlock().equals(dest)` — so once any IPv6 route existed
in a table, every DeleteRoute against that table threw InternalFailure,
IPv4 ones included. That breaks `terraform destroy` independently of the
apply failure, which is why the comparison is now made from the request
side through a shared matchesDestination helper.

Per https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Route.html
the Route type carries destinationCidrBlock, destinationIpv6CidrBlock and
egressOnlyInternetGatewayId as separate members, all optional. This adds
the latter two to the model, reads DestinationIpv6CidrBlock and
EgressOnlyInternetGatewayId in CreateRoute, emits both in the routeSet, and
accepts either destination in ReplaceRoute and DeleteRoute.
DescribeRouteTables also gains the route.destination-ipv6-cidr-block
filter, which previously fell through to the catch-all and so matched every
route table rather than the ones holding that route.

CreateRoute, ReplaceRoute and DeleteRoute now require exactly one
destination: neither is MissingParameter, both is
InvalidParameterCombination. This is a behaviour change for two requests
that used to be accepted — a CreateRoute with no destination (which stored
the unmatchable route this commit is about) and a DeleteRoute with no
destination (which silently removed nothing). A prefix-list destination is
still not modelled and now lands on MissingParameter rather than being
quietly dropped.

The egress-only internet gateway actions themselves
(CreateEgressOnlyInternetGateway and its Describe/Delete) remain
unimplemented; this only keeps the id a caller sends from being discarded,
so the route reports its target instead of appearing targetless. An
egress-only target is still rejected in ReplaceRoute, which is unchanged.

Not verified: that this clears the Terraform failures end to end. It was
developed against the reproduction in the report and the API reference, not
against a Terraform run, and a private-subnet IPv6 configuration will still
need the egress-only gateway actions before it reaches a route at all.
Whether real AWS answers MissingParameter or InvalidParameterCombination
when both destinations are given is inferred from the reference listing
them as separate optional members, not confirmed against AWS.

Tests: Ec2Ipv6RouteTest covers the IPv6 round trip, the IPv4 route beside
it, both coexisting, the IPv6 filter, ReplaceRoute on IPv6, the IPv4-delete
regression, the IPv6 delete, and the rejected destination combinations;
9 of its 11 fail without this change. Ec2ReplaceRouteIntegrationTest's
"no IPv4 destination is rejected" case now uses a prefix list, since an
IPv6 destination is no longer rejected there.

* fix(ec2): treat a prefix list as the third route destination, not as none

The previous commit rejected CreateRoute/DeleteRoute/ReplaceRoute with
DestinationPrefixListId as MissingParameter, and a test asserted that as AWS
behaviour. It is not. The CreateRoute reference says "You must specify either a
destination CIDR block or a prefix list ID", and DestinationPrefixListId is a
declared member of all three inputs and of the Route output shape in
ec2/service-2.json. A prefix-list route is a route with a destination.

So store and report it like the other two. It was hitting exactly the bug this
PR is about: persisted with no destination at all, unmatchable by DeleteRoute
or ReplaceRoute, and its null IPv4 destination made every DeleteRoute against
the same table throw. The removeIf null-safety now covers all three kinds.

Also reject EgressOnlyInternetGatewayId combined with GatewayId or NatGatewayId,
which would persist and report a route with two targets. Scoped to the parameter
this PR newly accepts: CreateRoute has never enforced exclusivity between
GatewayId and NatGatewayId, and starting to would be a behaviour change beyond
this fix. Raised by Greptile.

On the error code for a genuinely destination-less request: AWS declares no
operation-specific error for these three actions — the API reference Errors
section is empty and the service model carries no error shapes — so
MissingParameter is chosen from EC2's common client error codes, not confirmed
against the real service. Now documented as such rather than asserted.

Ec2Ipv6RouteTest: 11 -> 13 tests.
2026-08-24 00:05:34 -04:00
TATSUNO “Taz” Yasuhiro b6418dbfee feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG) (#2452)
* feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG)

StartExecution accepts a state machine ARN with a test case suffix in
the Step Functions Local format. The test case comes from the mock
configuration file named by SFN_MOCK_CONFIG. A mocked Task state
returns the configured Return payload or fails with the configured
Throw error instead of calling the integrated service. The mocked
error and cause reach Retry and Catch unchanged. States not named in
the test case still call their real integration, so mocked and real
calls combine in one execution. Behavior was verified against Step
Functions Local 2.0.0.

Closes #2283

* fix(sfn): never retry or catch States.Runtime even when named explicitly

* fix(sfn): keep a bare trailing '#' unstripped on StartSyncExecution
2026-08-24 00:04:17 -04:00
Allen Sanborn ea2b62fb95 fix(s3): resolve virtual-hosted buckets whose names contain dots (#2493)
* fix(s3): resolve virtual-hosted buckets whose names contain dots

S3VirtualHostFilter.extractBucket split the Host header at the FIRST dot
and required the remainder to equal the endpoint host. S3 bucket names may
legally contain dots -- naming a website/log bucket after a domain is the
conventional pattern -- so for

    Host: r5e817e.floci.example.com-logs.localhost

it read the bucket as "r5e817e" with remainder "floci.example.com-logs.
localhost", which matches no known endpoint host. extractBucket returned
null, the request silently degraded to a path-style request against "/",
and HEAD / answered 200 (the ListBuckets route).

User-visible symptom: the Terraform AWS provider calls HeadBucket before
CreateBucket, read that 200 as "bucket exists", and failed every dotted
bucket with BucketAlreadyExists for a bucket that had never existed.

Match the endpoint host as a SUFFIX instead: the bucket is everything in
front of ".<endpoint-host>", minus an optional trailing S3 qualifier
(s3, s3.<region>, s3.dualstack.<region>, s3-website-<region>). The same
correction is applied to every resolution path -- configured base hostname,
always-on localhost, configured DNS suffixes, and the AWS-domain fallback --
so bucket.<host>, bucket.s3.<host> and bucket.s3.<region>.<host> all keep
working with dotted names. Where several known suffixes match, the longest
wins, so bucket.localhost.floci.io is not read as "bucket.localhost".

Two things must not be swallowed by the wider matching:

* Service endpoints. The existing isS3ServiceEndpointHost guard still runs
  first, and a prefix that IS a qualifier (s3.localhost,
  s3.us-east-1.localhost, s3-website-us-east-1.localhost) resolves to no
  bucket rather than to a bucket named "s3".
* Other services' virtual hosts. execute-api, lambda-url and friends share
  the endpoint host, and <api-id>.execute-api.<host> would otherwise read as
  a dotted bucket and hijack API Gateway requests. Hostnames carrying a
  non-S3 service label are not buckets.

Path-style hosts, IPv4 authorities and port stripping are unchanged.

* fix(s3): stop suffix matching from swallowing other services' regional hosts

Suffix matching reads any multi-label host under a known endpoint host as a
dotted bucket. The label denylist added with it is not a sound guard: it has to
name every service, and the first one it misses is silently served as a bucket.

Measured against the previous commit, with baseHostname=localhost — every one of
these resolved to null on main:

  123456789012.dkr.ecr.us-east-1.localhost -> 123456789012.dkr.ecr.us-east-1
  search-mydomain-abc.us-east-1.es.localhost -> search-mydomain-abc.us-east-1.es
  abc.iot.us-east-1.localhost -> abc.iot.us-east-1
  myapp.appsync-api.us-east-1.localhost -> myapp.appsync-api.us-east-1

The first is the registry URI EcrRegistryManager hands out, so it is not
hypothetical.

Replace the enumeration with a structural rule: a hostname carrying a region
label in a non-leading position and no S3 qualifier is another service's
regional virtual host. A real S3 virtual host always carries s3, s3.<region> or
s3-website-<region>, and when it does the region is read from there instead — so
a bucket whose own name ends in a region stays addressable as
logs.us-east-1.s3.localhost.

Drop "elb" and "mwaa" from the denylist in the other direction. No filter in this
repository routes *.elb.<host> or *.mwaa.<host> by Host, and my.elb.logs is AWS's
own load-balancer access-log naming convention — a perfectly legal bucket the
guard was rejecting for nothing. The four remaining labels each name a filter
that does claim that hostname in a regionless form the region rule cannot catch.

S3VirtualHostFilterTest: 117 -> 131 tests.

* test(s3): pin what the remaining service-label denylist costs

An automated reviewer flagged that a bucket named my.execute-api.archive is
unreachable virtual-hosted. That is true, and it is the intended side of the
trade rather than an oversight, so assert it instead of leaving it implicit.

The remedy suggested — validate each service's hostname grammar and let anything
that does not match through — trades a recoverable failure for an unrecoverable
one. A bucket that must be addressed path-style still works, and worked no
better before this PR. An API Gateway request answered by S3 is a silent
cross-service hijack with no client-side remedy. Each of the four labels names a
filter in this repository that claims that hostname; the two that named nothing
were removed in the previous commit.

S3VirtualHostFilterTest: 131 -> 135 tests.

* fix(s3): treat an S3 qualifier as a complete tail, not any label

bucketFromPrefix scanned the labels in front of the endpoint host one at a
time and split the bucket at the LAST label matching s3 or s3-website*. An
"s3" label anywhere inside a dotted bucket name therefore truncated it:

    Host: my.s3.archive.localhost   ->  bucket "my"

A request for the bucket my.s3.archive silently read and wrote a different,
existing bucket. That is worse in kind than the wrong 200 this branch set out
to fix -- the client gets a plausible success against the wrong data, with no
signal that anything went wrong.

A qualifier is a complete tail, not a label. isS3QualifierTail requires the
labels from index i onwards to account for the WHOLE remainder of the prefix
and to spell one of the endpoint forms the AWS General Reference publishes:

    s3                        s3-fips.<region>            s3-accelerate
    s3.<region>               s3-fips.dualstack.<region>  s3-accelerate.dualstack
    s3.dualstack.<region>     s3-<region>      (legacy dash form)
    s3-website                s3-website.<region>  (newer regions)
                              s3-website-<region>  (older regions)

Nothing legal follows "s3" except a region, dualstack.<region>, or the end of
the name, so "s3.archive" is bucket text and my.s3.archive is the bucket. The
genuine forms still split, including for a bucket that contains an s3 label:
my.s3.archive.s3.us-east-1.localhost resolves to my.s3.archive.

Stating the grammar properly also widens what is recognised. s3-fips.<region>,
s3-accelerate, the legacy s3-<region> dash form and the newer s3-website.<region>
dot form were previously unrecognised; they resolve now. Note the website
endpoint spells its region with a dot in newer regions and a dash in older ones,
and both are in service.

Recognising s3-<region> needs to tell a region id from arbitrary text, so
AwsRegions gains KNOWN_IDS: every published AWS region id across the commercial,
GovCloud and China partitions. It is deliberately distinct from AwsRegions.ALL
and a superset of it -- ALL is what the emulator ADVERTISES through
DescribeRegions, KNOWN_IDS is what it RECOGNISES in a hostname. AwsRegionsTest
pins ALL as a subset of KNOWN_IDS.

The remaining ambiguity is narrower than before and is asserted: a bucket whose
own name IS a complete qualifier tail (foo.s3, foo.s3.us-east-1) is still read
as a qualified reference to foo. A bucket that merely contains s3 is not.

S3VirtualHostFilterTest: 135 -> 155 tests. AwsRegionsTest: new, 14 tests.

* fix(s3): match region IDs by name, not by a region-shaped pattern

The guard that keeps another service's regional virtual host from being served
as a dotted bucket tested each non-leading label against

    [a-z]{2}-[a-z-]+-\d+

That is the shape of an AWS region id. It is also the shape of perfectly
ordinary bucket labels. my-cd-1 matches it, so the legal bucket data.my-cd-1
was rejected, fell back to path-style, and answered HEAD / with 200 -- exactly
the false "bucket exists" this branch was opened to eliminate, reintroduced for
a different class of name. eu-team-2, us-west-9, ap-corp-1 and no-such-region-12
all match it too.

Test against AwsRegions.KNOWN_IDS instead: the finite list of region ids AWS
actually publishes. data.my-cd-1, reports.eu-team-2, assets.us-west-9 and
logs.ap-corp-1.archive now resolve as buckets, while
123456789012.dkr.ecr.us-east-1.localhost and search-x.eu-north-1.es.localhost
are still refused -- including for regions outside the set the emulator
advertises.

Position within the host was considered as an extra discriminator and rejected:
it does not separate the two cases. The region label is last in
<acct>.dkr.ecr.<region> but medial in <domain>.<region>.es, so no positional
rule covers both without also covering bucket names.

Two residual costs, both accepted deliberately and documented at the call site:

* A bucket carrying a REAL region id in a non-leading position (data.us-east-1)
  is still unreachable in the unqualified virtual-hosted form. It stays
  reachable qualified (data.us-east-1.s3.localhost) and path-style, and it was
  equally unreachable before this branch. Recoverable, and asserted.
* A regional service host in a region AWS launches after KNOWN_IDS was last
  updated would be read as a bucket. That is the maintenance cost of a list over
  a pattern, and the direction in which the pattern was safer. It is bounded:
  the failure is a wrong route rather than data loss, and the four
  NON_S3_SERVICE_LABELS entries still cover the services Floci routes by Host.

The list is preferred because the pattern's failure mode is the one this branch
exists to eliminate -- a legal bucket silently answering 200 from the service
root -- while the list's failure mode only appears for a region AWS has not
launched yet.

S3VirtualHostFilterTest: 155 -> 167 tests.
2026-08-23 22:49:06 -04:00
Kenshin Okinaka bd36b02728 fix(ses): report the sending account in send-event payloads (#2499)
The SES send-event payload's mail.sendingAccountId and mail.sourceArn were built
from the fixed default account, so under Floci's per-request multi-account support
they always showed 000000000000 regardless of the caller. Resolve the account per
request via RegionResolver.getAccountId() in publishSendEvents (falling back to the
default account outside a request, e.g. unit tests). Assert the account in the
delivery event payload.
2026-08-23 21:59:42 -04:00
Kenshin Okinaka 622ba0adbd feat(ses): support v2 PutAccountDetails and GetAccount Details (#2498)
* feat(ses): support v2 PutAccountDetails and GetAccount Details

Add the SES v2 PutAccountDetails operation and surface its data under GetAccount's
Details. Details are per-region and present-when-set (like VdmAttributes): GetAccount
omits the block until PutAccountDetails is called for the region. MailType and
WebsiteURL are required, and their null violations are reported together (aggregated),
matching AWS; MailType/ContactLanguage are enum-constrained. Floci has no sandbox and
runs no production-access review, so ReviewDetails.Status is reported as GRANTED.

Add unit and integration tests, and document the operation.

* test(ses): cover ProductionAccessEnabled in account details

ProductionAccessEnabled is a GetAccount top-level member (not an
AccountDetails field), and Floci has no sandbox so it stays true
regardless of the value sent to PutAccountDetails. Add an integration
case asserting the top-level flag stays true and never appears inside
Details, and assert at the service layer that the value is still stored
as given.
2026-08-23 20:48:31 -04:00