Commit Graph
50 Commits
Author SHA1 Message Date
Franklin G. Mendoza 4944764fa3 feat(inspector2): add organization configuration operations (#3162)
* feat(inspector2): add organization configuration operations

* fix(inspector2): complete organization contracts

* fix(inspector2): scope organization account state

* test(inspector2): log tolerated organization state

* test(inspector2): isolate organization cleanup
2026-09-07 22:54:52 -05:00
Franklin G. Mendoza d99675a512 feat(controlcatalog): add control lookup operations (#3130)
* feat(controlcatalog): add control lookup operations

* fix(controlcatalog): complete control lookup contracts

* test(controlcatalog): verify pagination continuation

* fix(controlcatalog): move control model to package

* fix(controlcatalog): integrate service storage lifecycle
2026-09-07 21:49:39 -05:00
Vũ Thế Huy b9039fef1d feat(redshift-data): emulate the Amazon Redshift Data API (#3186)
* feat(redshift-data): resource resolver, connection factory, statement store, service registration

* feat(redshift-data): field mapper, column metadata, SQL parameter binding

* feat(redshift-data): execute, describe, and paged result retrieval

* feat(redshift-data): batch execution, list statements, cancel

* feat(redshift-data): schema introspection operations

* test(redshift-data): end-to-end Data API over a real cluster plus SDK compatibility test

* docs(redshift-data): document the Redshift Data API surface

* fix(redshift-data): address code review findings

- rejectMultiStatement now reuses the SQL tokenizer so a semicolon inside a
  comment, string literal, or dollar-quoted block no longer rejects a valid
  single statement
- GetStatementResultV2 gains unit coverage for the typed and CSV envelopes
- CSV output is RFC 4180 quoted (embedded comma, quote, CR, LF)
- batch rollback is asserted transactionally in the integration test
- RedshiftDataFieldMapper logs a swallowed blob-read SQLException
- RedshiftPid/RedshiftQueryId use a non-negative hash
- NextToken that decodes to a negative offset is rejected
- CancelStatement leaves a FAILED statement FAILED
- DescribeTable paginates ColumnList and emits NextToken
- DbUser is echoed on the SecretArn path
- the statement store no longer builds its sweeper executor in the test constructor

* fix(redshift-data): address PR #3186 review findings

- SQL scanner handles PostgreSQL escape strings (E'...'): a backslash-escaped
  quote no longer ends the literal and mis-detects a following :name as a bind
  marker; plain '...' literals still treat backslash as an ordinary character
- ListStatements clamps MaxResults to 1..100 so MaxResults=0 no longer emits the
  same NextToken forever
- DescribeTable matches Table / Schema exactly (=) instead of LIKE, so a name
  containing _ or % cannot merge other tables' columns into ColumnList
- register the service in the README category table
- drop a stray em dash from the neighbouring services.yaml comment

* fix(redshift-data): bind string parameters untyped so real PostgreSQL infers the column type

CI ran the integration test against a real Redshift (PostgreSQL 15) cluster and
parameterisedStatement failed: a string bound to an int column via setString
raised "operator does not exist: integer = character varying". H2 in PostgreSQL
mode coerces it, so the unit test missed it.

- RedshiftDataConnectionFactory adds stringtype=unspecified to the JDBC URL, so
  setString sends the value untyped and the server infers the target type,
  matching how AWS binds Redshift Data API parameters
- ListStatements now rejects MaxResults above 100 with ValidationException
  instead of silently clamping (PR #3186 re-review)
- RedshiftDataOperationsTest uses JBoss Logging, not java.util.logging (PR #3186 re-review)

* fix(redshift-data): back the statement store with StorageFactory

The store held a bare ConcurrentHashMap outside the configured storage and
lifecycle model. It now obtains an account-aware backend through StorageFactory
("redshift-data", statements.json), the same as Athena's query store, resolved to
the global storage mode via the catalog descriptor. Default mode stays memory, so
statements are still lost on restart as documented; the 24h TTL sweep now walks
every account partition and deletes per account since the sweep thread has no
request context. StoredStatement is annotated for reflection and field-visible
serialization so persistent modes round-trip it.

* test(redshift-data): cover StoredStatement serialization round-trip and values()

The StorageFactory-backed store serializes StoredStatement in persistent modes.
Adds a round-trip test through the exact mapper PersistentStorage builds,
covering the ArrayNode, enum, Instant, and nested sub-statement fields plus the
field-visibility annotation, and a values() test.

* fix(redshift-data): register the nested Status enum for reflection

PersistedModelReflectionTest walks every type reachable from a StorageFactory
persistence root; StoredStatement.status pointed at an unregistered enum, so
native-image deserialization of a persisted statement would fail on restart.
2026-09-07 20:18:22 -04:00
Franklin G. Mendoza 5864b013d2 feat(detective): add organization member operations (#3190)
* feat(detective): add organization member operations

* fix(detective): align organization operations with AWS

* docs(detective): clarify member listing

* fix(detective): enforce organization administration contracts
2026-09-07 18:31:48 -04:00
Franklin G. Mendoza 7a5ae965e5 feat(budgets): add full service emulation (#3165)
* feat(budgets): add budget and notification operations

* feat(budgets): complete service emulation

* fix(budgets): enforce account and action contracts
2026-09-06 23:54:37 -04:00
Hector Ventura 0321ae0ac8 refactor(cloudformation): move Cognito UserPool and UserPoolClient to CognitoCfnProvisioner (#3164)
* refactor(cloudformation): move Cognito UserPool and UserPoolClient to CognitoCfnProvisioner

Batch 3 of the CloudFormationResourceProvisioner split. AWS::Cognito::UserPool and
AWS::Cognito::UserPoolClient join the provisioner that already owns UserPoolDomain;
the two arms, their switch cases, the type-list entries, the Cognito-only
resolveStringMapOrNull helper and the CognitoService dependency leave the monolith.

Behaviour is preserved except for what the split's conventions require:

- the create/update branch reads ctx.isUpdate() instead of the resource's physical
  id, which provision overwrites as it runs
- deletes go through CfnDeletes.safeDelete tolerating only ResourceNotFoundException;
  a pool that still has a domain keeps failing the stack delete with
  InvalidParameterException, as on AWS
- the client also exposes Name, the read-only attribute the registry schema declares
  (ClientName stays for now), so CfnSchemaCoverageTest needs no gaps row
- the ReplacementCleanup hooks are wired for both types; nothing replaces yet, so
  they are inert until create-only properties are honoured

The unit test covers both types with a mocked service: request map and generated
names, update carrying the prior id, the exact attribute sets, positional client
arguments, and delete tolerance. The domain delete path now branches on type first,
since a pool resource also carries a UserPoolId attribute.

* fix(cloudformation): replace a Cognito user pool client when its create-only properties change

UserPoolId and GenerateSecret are createOnlyProperties in the AWS::Cognito::UserPoolClient
registry schema: on AWS a change to either creates a new client and deletes the old one
after the update commits. The provisioner passed the new pool id to UpdateUserPoolClient,
which fails with ResourceNotFoundException because a client is only found through the
pool that owns it, and a changed GenerateSecret was silently ignored since the update
call has no such parameter.

The provisioner now looks the prior client up by id, updates in place only when both
create-only properties are unchanged, and otherwise creates the replacement; the
ReplacementCleanup record deletes the displaced client once the update completes or
restores it on rollback. A prior client that is already gone is created anew. The by-id
describeUserPoolClient overload is new on CognitoService, mirroring its delete pair.

* fix(cloudformation): resolve Cognito UserPoolTags as the map the schema declares

AWS::Cognito::UserPool.UserPoolTags is an object (the type's tagProperty), not the
[{Key, Value}] list most types carry. The provisioner parsed it with the list helper,
which yields nothing for a map, so the tags only reached the service through the raw
property map, where a non-string tag value arrives as a number. The tags are now
resolved as a string map and put explicitly, on create and on update.

* fix(cloudformation): give Fn::GetAtt ProviderName on a Cognito user pool AWS's shape

The attribute returned the pool name. On AWS it is cognito-idp.<region>.amazonaws.com/<pool id>,
the value templates feed into an identity pool's CognitoIdentityProviders (CDK derives the
same string in UserPool.fromUserPoolArn). ProviderURL deliberately stays Floci's local
issuer, <base-url>/<pool id>, since that is the iss of the tokens Floci mints and a template
wiring it into a JWT authorizer must validate locally; the generated resource-type table
now says so.

* fix(cognito): apply PoolName on UpdateUserPool so a CloudFormation rename takes effect

UpdateUserPoolRequest carries PoolName in the service model and AWS::Cognito::UserPool
lists UserPoolName as updatable in place, but updateUserPool only ran populateUserPool,
which never sets the name, so a renamed pool kept its old name through both the API and
a stack update. The service now applies a non-blank PoolName.

The provisioner sends PoolName on update only when the template names the pool: an
unnamed pool keeps the name its first execution generated instead of being renamed to a
freshly generated one on every update.

* fix(cloudformation): expose only the schema's attributes on a Cognito user pool client

The AWS::Cognito::UserPoolClient registry schema declares ClientId, Name and ClientSecret
as its read-only properties. ClientName is a request property, not an attribute; on AWS
Fn::GetAtt Client.ClientName fails template validation, so no working template depends on
it. It is dropped in favour of Name.

* fix(cloudformation): validate Cognito user pool client properties instead of dropping them

A non-integer AccessTokenValidity, IdTokenValidity or RefreshTokenValidity was parsed to
null and silently ignored, so the template's intent was lost without a word. The
provisioner now fails the resource with ValidationError "Value of property X must be an
integer.", as the ECS provisioner does for DesiredCount. UserPoolId, the schema's one
required property, is likewise rejected when missing rather than passed through as null.

* test(cloudformation): cover Cognito user pool client replacement end to end

Through the CloudFormation API: a client moved to another pool and one whose
GenerateSecret flips are each replaced, with the displaced client gone once the update
completes; a rename updates the client in place; Fn::GetAtt Name and the pool's
ProviderName carry their AWS shapes; deleting the stack removes client and pools.

* fix(cloudformation): drop a stale ClientSecret attribute when a replacement client has none

The engine hands an update the prior attributes, and the provisioner only wrote
ClientSecret when the new client had one, so replacing a secret-bearing client with
GenerateSecret: false left the displaced client's secret readable through Fn::GetAtt.
The attribute is now removed when the client has no secret; rollback still restores it
from the cleanup record's snapshot.

* fix(cloudformation): refuse a Cognito client replacement that would reuse the prior client id

AWS client ids are random, so a replacement never collides with the client it replaces.
Under Floci's floci:override-cognito-client-id tag the id follows the client name, and a
replacement that kept the name (a GenerateSecret flip, or a move to a pool with the same
override) was created under the prior id: the store overwrote the prior client, the cleanup
record saw an unchanged id and recorded nothing, and the update could not be rolled back.
Neither overwriting nor delete-then-create can preserve the prior client, so the update is
now refused with ValidationError before anything changes and the stack rolls back intact.

CognitoService gains deterministicClientIdFor(userPoolId, clientName), sharing the id rule
with createUserPoolClient; the provisioner compares it with the prior id in the replacement
branch only.

* fix(cloudformation): refuse a Cognito client whose derived id another client already holds

The round-1 guard compared the derived id only with the client being replaced. Under
floci:override-cognito-client-id the store is keyed by client id alone, so a name whose
derived id belongs to any other client, in this pool or another, would overwrite that client
on create, and neither the cleanup record nor rollback knows about it. The guard now refuses
whenever an existing client holds the derived id, on a fresh create as well as a replacement.

* fix(cloudformation): make the deterministic Cognito client-id guard atomic and ignore orphaned records

Two gaps in the round-2 guard. CloudFormationService runs stack operations on a cached
thread pool and CognitoService's client store write is unconditional, so two stacks could
both find a derived id free and the later create overwrote the earlier stack's client; the
existence check and the create now run under one lock whenever the id is derived from the
name. And deleting a user pool does not remove its clients yet (#2949 adds that), so a client
of a deleted pool kept its derived id and the guard refused a legitimate create in another
pool; a holder whose pool no longer exists is now treated as a stale record the create may
take over. Random ids take neither path.
2026-09-06 22:51:50 -05:00
lex00 631df1dc01 feat(cloudformation): provision AWS::Backup::BackupVault (#3125)
Per-service provisioner over BackupService. Ref and Fn::GetAtt
BackupVaultName are the vault name and Fn::GetAtt BackupVaultArn its ARN. The
name is the physical id and createOnly, so an unnamed vault keeps its
generated name across updates instead of getting a second vault, and a rename
is refused as a replacement. EncryptionKeyArn is createOnly as well.
BackupVaultTags are driven to the template's set on update, untagging dropped
keys since TagResource only adds. Stack deletion deletes the vault and leaves
the non-empty-vault refusal to surface as on AWS.

The docs generator gains a label and row position for the new AWS::Backup
namespace.

Ported from lex00/floci#118. Tracked in lex00/floci#192.
2026-09-06 22:18:18 -05:00
Franklin G. Mendoza 6264b09a28 feat(identitystore): add full service emulation (#3159)
* feat(identitystore): add groups users and memberships

* feat(identitystore): add full service emulation

* fix(identitystore): validate update attribute paths
2026-09-06 21:51:19 -04:00
Franklin G. Mendoza d80734e6de feat(account): add alternate contact operations (#3118)
* feat(account): add alternate contact operations

* fix(account): complete alternate contact contracts
2026-09-06 15:49:12 -05:00
Franklin G. Mendoza aebed6e15c feat(accessanalyzer): add analyzer lifecycle (#3117)
* feat(accessanalyzer): add analyzer lifecycle

* fix(accessanalyzer): complete service contracts

* test(accessanalyzer): make SDK cleanup best effort

* test(accessanalyzer): use project logging for cleanup
2026-09-06 10:55:17 -04:00
Franklin G. Mendoza 162211de0c feat(route53): support cross-account VPC associations (#3116)
* feat(route53): support cross-account VPC associations

* test(route53): add SDK cross-account compatibility coverage

* fix(route53): harden cross-account VPC ownership

* fix(ec2): scope default resources by account
2026-09-06 00:05:31 -04:00
Franklin G. Mendoza 3927c66040 feat(macie2): add organization administration operations (#3105)
* feat(macie2): add organization administration operations

* test(macie2): validate organization administration with sdk

* fix(macie2): harden delegated administration routing
2026-09-05 23:49:52 -04:00
Franklin G. Mendoza 1bf7494e99 feat(ssoadmin): add permission sets and assignments (#3103)
* feat(ssoadmin): add permission sets and assignments

* test(ssoadmin): validate account assignments with sdk

* fix(ssoadmin): complete pagination and lifecycle contracts
2026-09-05 21:46:20 -04:00
Mario Toffia 6be9c1ee26 docs(cloudformation): note that a stack detaches an IoT policy before deleting it (#3042)
The generated resource-type table will say that a stack deletes an IoT policy after detaching it from its principals, while on AWS the delete fails with DeleteConflictException as long as the policy is attached. One notes entry in tools/docs/cfn_resource_types.yaml; the generator renders it once the type has an inventory row, which #3014 adds.
2026-09-05 18:04:52 -05:00
Mario Toffia c3d977a3e3 feat(apigateway): provision AWS::ApiGateway::DomainName and BasePathMapping (#3040)
* feat(apigateway): provision AWS::ApiGateway::DomainName and BasePathMapping

Both types were stubs: the stack turned green while no domain or mapping
existed, Fn::GetAtt on the domain resolved to the literal attribute name, and
a request sent to the custom domain was not routed. The new provisioner calls
the existing CreateDomainName and CreateBasePathMapping. Ref and every
Fn::GetAtt attribute return what GetDomainName reports, a changed DomainName
or BasePath replaces the resource (created before the prior one is deleted),
and everything else is patched in place.

The physical id of a mapping is the compound identifier CloudFormation uses
for the type, <DomainName>|<BasePath>, with (none) for an empty base path.

Service fixes needed so the provisioned values can be read back through the
API: CreateDomainName keeps regionalCertificateArn and regionalCertificateName
(both were dropped), an EDGE domain gets a distributionDomainName and the fixed
CloudFront hosted zone, GetDomainName returns domainNameArn,
endpointConfiguration.types and tags, UpdateDomainName accepts the
/endpointConfiguration/types/EDGE patch path, domain tags are managed through
the tag API on the domain ARN, and CreateDomainName checks the name and stores
the domain under one lock so two concurrent creates cannot both succeed.

* fix(apigateway): keep the distribution in step with a domain's endpoint type

A move to EDGE through UpdateDomainName left the domain without a
distributionDomainName, and a move back to REGIONAL kept the old one, so
GetDomainName and Fn::GetAtt reported CloudFront fields that did not match the
endpoint type. Both create and update now go through one helper that puts a
distribution in front of an EDGE domain and drops it for a REGIONAL one.

* fix(apigateway): serialize domain and mapping changes, refuse a taken base path, validate the endpoint patch path

The stores hand out live objects, so a domain patch, a tag write and a
mapping patch were read-modify-write steps that concurrent calls could lose
or corrupt: eight concurrent tag writes on one domain kept four tags. Every
change to a custom domain or a base path mapping now runs under one lock, and
a tag write replaces the tag map instead of changing the one a reader may be
iterating.

CreateBasePathMapping on a base path that already has a mapping answers
ConflictException as AWS does; before, the new mapping silently replaced the
old one, so eight concurrent creates of one base path all succeeded.

UpdateDomainName accepted any /endpointConfiguration/types/<x> path; the path
must now name the type the domain has, as on AWS.

The provisioner sends the PATCH before it reconciles the tags, so a rejected
update leaves the tags as they were. Tests cover every case above, the
remaining cells of the update matrix (a prior resource gone under a new name),
and the REGIONAL to EDGE move end to end through a stack.

* fix(apigateway): refuse an endpoint type other than REGIONAL or EDGE on CreateDomainName

UpdateDomainName already rejected any other value, but CreateDomainName stored
whatever string the request carried, so a PRIVATE or misspelled type produced a
domain that was neither regional nor edge-optimized and that nothing could
route or describe. Private custom domains are not emulated, so the create now
answers BadRequestException with the same message as the update, and nothing
is stored. Adds the two remaining provisioner matrix cells as tests: a taken
domain name fails the resource without deleting anything, and a resource
without Properties is rejected.
2026-09-04 22:45:24 -04:00
lex00 dd9cdc1207 feat(cognitoidentity): identity pool management plane (CRUD, roles, principal-tag maps, tags) (#2977)
* feat(cognitoidentity): identity pool management plane (CRUD, roles, principal-tag maps, tags)

Emulates the Cognito Identity (federated identity pools) management API:
CreateIdentityPool through DeleteIdentityPool, ListIdentityPools with
pagination, SetIdentityPoolRoles/GetIdentityPoolRoles including role
mappings, Set/GetPrincipalTagAttributeMap, and resource tagging. JSON 1.1
under the AWSCognitoIdentityService target prefix, signing name
cognito-identity.

* fix(cognitoidentity): require AllowUnauthenticatedIdentities and key tag writes by pool region

An omitted AllowUnauthenticatedIdentities returned success with false persisted. It now fails with ValidationException. TagResource and UntagResource wrote the pool back under the signing region rather than the region in its ARN.

* fix(cognitoidentity): reject a non-boolean AllowUnauthenticatedIdentities

Jackson coerced strings and numbers to a boolean instead of failing the request.
2026-09-04 12:16:18 -04:00
Mario Toffia 9220c057b7 feat(iot): domain configurations (#3008)
* feat(iot): add the domain configuration model and service

Stores AWS IoT Core domain configurations the way the API reports them:
a new configuration is ENABLED and CUSTOMER_MANAGED (ENDPOINT without a
domain name), carries one VALID server certificate, the default TLS
policy and an ARN with the short id AWS appends. Update changes the
status, authorizer, TLS, certificate and protocol settings; delete
refuses an ENABLED configuration, as AWS does; list filters by service
type and pages with marker and pageSize. Tags work on the ARN.

* feat(iot): serve the domain configuration API

Adds the REST-JSON routes CreateDomainConfiguration,
DescribeDomainConfiguration, UpdateDomainConfiguration,
DeleteDomainConfiguration and ListDomainConfigurations under
/domainConfigurations, registered with the IoT service so the
X-Amzn-Errortype header is set for unsigned callers too. Tags on a
configuration ARN go through IotTagHandler; the IoT /untag route now
uses the same handler as /tags instead of calling IotService directly.
DescribeEndpoint accepts iot:CredentialProvider, the endpoint type
that pairs with the CREDENTIAL_PROVIDER service type.

* feat(iot): provision AWS::IoT::DomainConfiguration

Adds IotDomainConfigurationCfnProvisioner over the domain configuration
service. Ref is the configuration name; Fn::GetAtt Arn, DomainType and
ServerCertificates resolve to what DescribeDomainConfiguration reports
(ServerCertificates as a JSON string, since attributes are strings).

Like the CloudFormation handler, a configuration is created ENABLED and
a DomainConfigurationStatus of DISABLED is applied with a follow-up
update; tags go through TagResource and are reconciled on update; a
delete disables the configuration first because the API refuses to
delete an ENABLED one. UpdateStack keeps the configuration when the
createOnly properties (DomainName, ServiceType, ValidationCertificateArn,
ServerCertificateArns) are unchanged and replaces it otherwise, with a
fresh generated name when the template names none.

Inventory TSV, fixture wiring and the generated resource-type table
updated.

* docs(iot): describe domain configurations and add the stack integration test

IotDomainConfigurationCfnIntegrationTest provisions the type through a
stack and asserts Ref and every Fn::GetAtt attribute against
DescribeDomainConfiguration, the in-place status update, and that
DeleteStack removes the configuration.

* test(iot): cover domain configurations in the Java and Go SDK suites

Both cases create, describe, list, update and delete a configuration
through the real SDK clients and check the AWS error types on the
duplicate create, the refused delete of an ENABLED configuration and
the describe after deletion.

* fix(iot): remove a renamed domain configuration and keep the status when the template omits it

A template that changes DomainConfigurationName creates the new
configuration and now removes the previous one, as the generated-name
replacement already did; before, the old configuration outlived the
stack. An update without DomainConfigurationStatus no longer forces
ENABLED: the field is omitted and the current status stays, as the AWS
handler does.

The service rejects a structured JSON value where a string, boolean,
list or object is expected instead of turning it into an empty string
or silently clearing the authorizer, and validates the whole update
before touching the stored record.

* fix(iot): let stack rollback remove a domain configuration and make same-name creates atomic

A configuration created by a stack is recorded, with the owned marker,
before the follow-up status update, so a failure there still lets the
create rollback delete it. A replacement that fails after the new
configuration exists removes it again, re-enables the previous one if
it had been disabled on the way out, and marks the resource restored,
as the other provisioners do.

CreateDomainConfiguration checks and stores the name in one step, so
two overlapping creates of the same name cannot both succeed. A tags
value that is not a list is rejected. The Java SDK compatibility case
looks for a leftover configuration instead of swallowing every cleanup
exception.

* fix(iot): point the resource back at the prior domain configuration after a failed replacement

After the unwind removes the replacement and re-enables the previous
configuration, the resource now carries the previous name and
attributes again, without the owned marker, so it describes the
configuration that is still there rather than the one just removed.

* feat(iot): serve the AWS-managed domain configurations

Every AWS account has iot:Data-ATS, iot:Data, iot:CredentialProvider
and iot:Jobs without creating them. They now exist in every region on
first use: AWS_MANAGED, ENABLED, no server certificate, and the address
DescribeEndpoint returns as their domain name. They can be updated and
tagged like any other configuration, but not deleted, as on AWS. A
client that starts by describing iot:Data-ATS gets an answer instead of
a 404.

* fix(iot): report a failed replacement cleanup as a rollback failure

When the unwind of a failed replacement cannot remove the new domain
configuration, the resource now carries the rollback-failure marker
with the reason, so the stack ends in UPDATE_ROLLBACK_FAILED instead of
reporting a clean rollback while the configuration is still there. The
marker moves next to the restored one in CfnRollback so extracted
provisioners can set it; the legacy provisioner keeps its alias.

* fix(iot): serialise every read-modify-write on a domain configuration

Update, delete, tag and untag read a record, change it and write it
back. Two overlapping writers lost each other's changes: sixteen tag
writers on one configuration left seven keys. All of them now run under
the lock the create already used, and a test pins the invariant. A JSON
round trip with the mapper setup persistent storage uses pins that the
model reloads intact.

* fix(iot): keep the prior status the unwind compares against and never delete a same-name replacement

The store hands out its live record, so disabling the prior on the way
to deleting it changed the very object the unwind later compared
against, and a prior whose delete failed half way was left DISABLED
while the stack reported a clean rollback. The status seen at the start
is now kept and used. The test reproduces the aliasing instead of
handing the provisioner a fresh copy per call.

A replacement under the same explicit name normally fails on the
create; if it goes through because the prior vanished in between, the
prior is no longer deleted, which would have removed the configuration
just created.

* fix(iot): tolerate a domain configuration that vanishes while a stack delete disables it

The disable that precedes the delete now treats ResourceNotFoundException
as already deleted, the way the delete itself does. The SDK cases also
enable an already ENABLED configuration, the call a client makes when
it only wants to be sure the configuration is on.
2026-09-04 01:05:21 -05:00
Mario Toffia 38176b9e05 feat(acm): provision AWS::CertificateManager::Certificate (#3003)
* feat(acm): provision AWS::CertificateManager::Certificate

Adds AcmCfnProvisioner over the existing AcmService. Ref and
Fn::GetAtt CertificateArn both resolve to the certificate ARN instead
of the stub's literal "LogicalId.CertificateArn". Maps DomainName,
SubjectAlternativeNames, ValidationMethod (default DNS), KeyAlgorithm
and Tags; DomainValidationOptions is accepted and ignored because the
certificate is ISSUED at once, there is nothing to validate locally.

UpdateStack: a change to a createOnly property (DomainName,
SubjectAlternativeNames, KeyAlgorithm) requests a new certificate and
deletes the previous one; otherwise tags are reconciled in place.
Delete tolerates an already removed certificate and lets
ResourceInUseException propagate.

Tests: AcmCfnProvisionerTest (attribute keys, update paths, delete),
AcmCfnIntegrationTest (stack output is an ARN DescribeCertificate
finds, gone after DeleteStack). Inventory TSV, fixture wiring and the
generated resource-type table updated.

* fix(acm): remove the replacement certificate when the prior one cannot be deleted

On a replacing update, a failure deleting the previous certificate
(ResourceInUseException, for one) made the update fail after the new
certificate existed. CloudFormationService restores the previous
StackResource on a failed update and never learns the new ARN, which
orphaned that certificate. Delete it and mark the resource restored
for the rollback walker, as Route53CfnProvisioner does for zones.

Also pins that a ValidationMethod-only update keeps the certificate:
the property is writeOnly in the registry schema and "No interruption"
in the AWS docs, and ACM has no call to change it on an issued
certificate.
2026-09-03 23:46:03 -04:00
Matheus André df0e7bc79c feat(route53): update supported operations and add VPC association actions (#2959) 2026-09-03 17:15:41 -04:00
Hector Ventura eb0472fccc docs: fix stale image tags, release model, service nav and contributor checklists (#2980)
The getting-started and contributor docs had drifted from what the workflows and the
code actually do:

- quick-start and CONTRIBUTING pointed users at a `latest-jvm` image that the release
  pipeline never publishes; both now name the `-compat` image, and `make docs-check`
  greps the docs for any `-jvm` tag
- the CONTRIBUTING branching model now matches the workflows: `main` is published as
  the nightly channel, a maintainer runs the Release Cut workflow to tag a release, and
  the tag triggers the publish; PR builds produce compat images but never publish them
- README and the docs landing page carried a hand-maintained service count and a
  second copy of the service table, both stale; they now link to the Services Overview
- the Service Matrix gains the ELB Classic row it was missing, with an `elb` alias so
  the check no longer resolves the Classic key to the v2 page, and
  check_service_matrix.py now also fails on a docs/services page that has no row
- the README category table lists 16 documented services it omitted
- mkdocs nav gains 11 service pages that were unreachable from the site, drops a
  duplicate CloudTrail entry, and the docs job now runs `mkdocs build --strict` with nav
  and link validation so a page without a nav entry fails CI
- AGENTS.md, CONTRIBUTING.md and docs/contributing.md told contributors to register a
  service in ServiceRegistry, which has no registration API; all three now point at
  ResolvedServiceCatalog and list the config, storage, native-image, docs, tooling and
  compat-suite touchpoints a new service needs
2026-09-02 22:10:46 -04:00
Olamide Kosile 961d82dda9 fix(cloudformation): provision AWS::Scheduler::ScheduleGroup (#2796) 2026-09-01 21:26:02 -05:00
Vũ Thế Huy 10192f05d5 feat(translate): add Amazon Translate mock service (#2879)
* feat(translate): add Amazon Translate mock service

JSON 1.1 stub for Amazon Translate covering the three self-contained sync
operations: TranslateText, TranslateDocument, ListLanguages. Follows the
existing Comprehend/Textract stub pattern (stateless, echoes input,
AI_MOCK_CONFIG override for TranslateText).

- TranslateText echoes Text, enforces the 10,000-byte limit, allows any
  language pair; an auto source is reported back as en.
- TranslateDocument echoes the base64 Content and enforces the English-pivot
  rule, the ContentType allow-list, valid base64, and the 100 KB cap
  (InvalidRequestException, matching the operation's error model). The
  encoded length is checked before decoding so an oversized payload cannot
  force a large allocation.
- ListLanguages returns a fixed ~35-language catalog; DisplayLanguageCode is
  validated, pagination inputs are accepted but ignored.

Untrusted request values are truncated before being echoed into error
messages.

* chore(translate): remove em-dashes per AGENTS.md style guide

Replace em-dashes in the Translate doc page and Java comments with colons,
commas, or periods, and the ellipsis in the error-message preview helper
with "...". Addresses the Greptile review note on PR #2879.
2026-09-01 14:47:33 -04:00
Allen Sanborn afe26c6ad1 fix(elb): route Classic (v1) requests to a dedicated handler instead of ELBv2 (#2619)
* feat(elb): implement Classic (v1) Elastic Load Balancing

Classic ELB (2012-06-01) and ELBv2 (2015-12-01) share an endpoint host and
an `elasticloadbalancing` credential scope, but they are different APIs. Every
Classic request was reaching the ELBv2 handler, which rejected a well-formed
one with `ValidationError: Name is required for load balancer.` — because the
name arrived as `LoadBalancerName`, the Classic parameter — and answered a
request that guessed `Name` with an ALB object in the 2015-12-01 namespace, a
shape Classic has no concept of.

Route on the API version. Every Query-protocol request carries the version it
speaks as the `Version` form parameter, and both service models declare it, so
that is the discriminator: 2012-06-01 to the new Classic handler, 2015-12-01 to
ELBv2. This is the same in-case split the `rds` scope already uses to separate
RDS, Neptune and DocumentDB. Requests that omit `Version` fall back to their
parameter shape — an action unique to one API, else `LoadBalancerName` /
`LoadBalancerNames` selecting Classic, else ELBv2 as before.

Classic state is its own model, not the v2 one: keyed by name, no ARN, listeners
inline, and one structured attribute record. Responses follow the 2012-06-01
model's wrapper and element names — `CreateLoadBalancerResult` carries `DNSName`
and nothing else.

Scope is what the AWS provider drives for `aws_elb` and for an Auto Scaling
group attached to one: Create/Delete/DescribeLoadBalancers, the listener
operations, ConfigureHealthCheck, Register/DeregisterInstances,
DescribeInstanceHealth, Modify/DescribeLoadBalancerAttributes, the subnet,
availability-zone and security-group operations, and tagging. The stickiness
and backend-server policy operations, and SetLoadBalancerListenerSSLCertificate,
answer `UnsupportedOperation` in the 2012-06-01 namespace rather than a
fabricated result. There is no Classic data plane: listener ports are recorded
but no socket is opened.

Health is checked per instance from the single `HealthCheck.Target` string —
`HTTP:`/`HTTPS:` probed with a request, `TCP:`/`SSL:` by connecting — with the
same counters and thresholds ElbV2HealthChecker uses. An ASG naming Classic load
balancers in `LoadBalancerNames` now registers and deregisters its instances
with them, so a `min_elb_capacity` wait can be satisfied.

* docs(elb): register ElbClassicQueryHandler in services.yaml

Unblocks 'make docs-check', which fails on rebase without this — the
handler was never registered when the Classic ELB feature landed.

* fix(elb): register ElbClassicService for native init, deregister stale ASG instances from Classic ELBs

ElbClassicService's SecureRandom field wasn't declared under
--initialize-at-run-time, which fails GraalVM native image builds
(image-heap Random instances have cached seeds). Registers it
alongside the other services/*.Service entries in application.yml.

Also closes a gap Greptile flagged: removeStaleInstances() pruned an
ASG's dead instance references without deregistering them from target
groups or named Classic load balancers first, unlike the terminating-
and scale-in paths, leaving orphaned registrations visible through
DescribeLoadBalancers/DescribeInstanceHealth.

* fix(elb): return the documented 409 for a Classic multi-VPC subnet set

CreateLoadBalancer's own Errors table puts InvalidConfigurationRequest at HTTP
409; the Classic path raised it at 400. The error code was already right, so a
client that retries on 409 but fails hard on 400 got the wrong signal from the
one place the two can be told apart. Covered by a unit test that asserts the
status, not just the code.

Also from review: the empty-Listeners ValidationError carried a message copied
from an unrelated subnet/AZ check, and the new cross-reference to the Classic
docs page split elb.md's opening sentence mid-paragraph instead of following it.
2026-08-31 19:05:07 -04:00
lex00 0b46d804c0 feat(codegurureviewer): repository association lifecycle with tagging (#2741)
* feat(codegurureviewer): repository association lifecycle with tagging

AssociateRepository, DescribeRepositoryAssociation, DisassociateRepository and
ListRepositoryAssociations over CodeGuru Reviewer's REST JSON protocol, with
TagResource/UntagResource/ListTagsForResource served on the shared /tags path.
The Repository union is validated as AWS validates it (exactly one provider,
Owner/ConnectionArn for third-party providers, KMSKeyId required for
CUSTOMER_MANAGED_CMK), duplicate associations report ConflictException, and an
association is Associated from the first read so provider waiters complete
immediately.

* fix(codegurureviewer): paginate ListRepositoryAssociations, register the model for reflection, generate the action table

ListRepositoryAssociations now honours MaxResults and NextToken with real
pagination (the filter query keys stay singular - ProviderType, State, Name,
Owner - matching the wire mapping the API reference documents for the plural
request fields). RepositoryAssociation carries @RegisterForReflection so
native-image persistence survives a restart. The docs page now uses the
generated action-table markers, has its service-matrix row, and maps the
hyphenated codeguru-reviewer signing name to its doc slug.

* fix(codegurureviewer): reject a malformed MaxResults with ValidationException, not 404

A JAX-RS Integer binding fails during parameter conversion, so
MaxResults=abc surfaced as 404 before the handler ran. The parameter is
now bound as a String and parsed in the controller, routing bad values
through the modeled 400 ValidationException.
2026-08-30 14:44:08 -05:00
lex00 7b6266e902 feat(connect): instance management (CreateInstance family, attributes, storage configs, tags) (#2740)
* feat(connect): instance management (CreateInstance family, attributes, storage configs, tags)

Amazon Connect control plane: CreateInstance/DescribeInstance/ListInstances/
DeleteInstance, instance attributes, instance storage configs, and resource
tagging over REST JSON, registered under the connect signing name. Instances
report ACTIVE from the first read so the Terraform provider's status poll
completes immediately.

17 integration tests cover the lifecycle, attribute validation against the
AWS InstanceAttributeType/DirectoryType/InstanceStorageResourceType enums,
storage-config association, and tag round-trips.

* docs(connect): register connect in the action-table catalog

The Action-tables CI gate requires every service registered in
ResolvedServiceCatalog to have an index row and a generated action table;
connect's page was hand-written and unregistered.

* fix(connect): validate boolean instance attribute values

UpdateInstanceAttribute stored any nonblank string while the inbound/outbound
flags coerced it to boolean, so an invalid value read back inconsistently
across DescribeInstanceAttribute and DescribeInstance. Reject anything but
true/false with InvalidParameterException and store the canonical lowercase
form.
2026-08-30 15:15:49 -04:00
Hector Ventura b76eadc98e docs(cloudformation): generate the supported resource-type table (#2739)
The "Supported Resource Types" table was hand-maintained, and had drifted:
ten provisioned types were undocumented, including the whole CloudFront
row, Lambda's Permission/MicrovmImage/NetworkConnector, RDS DBProxy and
DBProxyTargetGroup, ECS capacity providers, EC2 VPCEndpoint and
ApiGatewayV2 Authorizer.

Generate it from the provisioner inventory TSV that CfnResourceInventoryTest
already pins to the CDI-resolved registry, so the table cannot drift from
what Floci actually provisions. Wired into docs-sync and docs-check, with
the inventory path added to the workflow filters: it lives under
src/test/resources, which src/main/** did not cover, so a slice that moved
a type between owners would have skipped the gate.

The table is prose as much as data, so presentation stays configurable in
cfn_resource_types.yaml: service labels, curated type order (types not
listed there are appended alphabetically, so a new type still appears),
per-type notes, and extra_types for capabilities that are real but are not
provisioner types, each needing a stated reason. Nested Stack and the
Custom::* wildcard are the two such entries; the wildcard cannot be an
inventory type because the registry is keyed by exact type.

The generator reads the TSV rather than the Java because several
provisioners return Set.of(CONSTANT, CONSTANT) from resourceTypes(), which
a source regex only partly sees.

Also flags two things cheaply, before anyone waits on a Quarkus boot: a
provisioner missing @ApplicationScoped, and a type claimed by both the
legacy switch and a provisioner.
2026-08-30 13:04:29 -05:00
Vũ Thế Huy a1383fdd3d feat(redshift): implement Redshift emulation with snapshot and parameter group support (#2472)
* feat: add redshift domain models

* feat: add redshift service and test

* feat: add redshift query handler and routing

* feat(redshift): implement data plane container manager and wire storage

This commit implements Redshift Container Manager, wires the StorageFactory into RedshiftService, uses AwsException for error handling, implements Describe/Delete Clusters, and adds integration tests with AWS SDK in the compatibility tests project.

* feat: add redshift operations models and service logic

* fix: correct yaml indentation for redshift storage config

* fix: remove invalid redshift storage properties

* feat: implement pg_dump and psql for redshift snapshots

* feat: add redshift core operations query actions

* test: add redshift operations integration test

* fix(redshift): Write snapshot SQL dumps to file storage and add Parameter model

* docs: add redshift implementation plan, design spec, and PR description

* chore: remove superpowers working files

* fix(redshift): scope snapshots and cluster recovery per account, restore original password

- Scope snapshot SQL dump files under redshift-dumps/{accountId}/ so
  same-identifier snapshots from different accounts no longer collide,
  overwrite, or delete each other's data.
- Restore uses the source cluster's real master password instead of a
  hardcoded value, falling back to "admin" only when the source cluster
  no longer exists.
- Recreate Docker containers for all persisted "available" clusters on
  startup, across every account (not just the default), fixing clusters
  that were reloaded with stale endpoints but no running container.
- Add AccountAwareStorageBackend.accountId() accessor needed for the
  account-scoped dump path.

* fix(redshift): add logging for cleanup failures in RedshiftOperationsTest

* fix(redshift): scope container identity per account, persist snapshot password

- RedshiftContainerManager now keys its in-memory container map and Docker
  container name by accountId + clusterIdentifier, instead of just the
  cluster identifier. Previously two accounts creating a cluster with the
  same identifier would share (and clobber) the same Docker container,
  so startup recovery for the second account silently skipped its own
  cluster and left it advertised with a stale endpoint.
- Snapshot now captures masterPassword at snapshot-creation time, so
  restoreFromClusterSnapshot can recover the original credential even
  after the source cluster has been deleted, instead of falling back to
  "admin".
- Clean up fully-qualified java.nio.file / commons-compress references in
  RedshiftContainerManager in favor of imports.

* feat(redshift): implement adoptOrStart method to reuse existing containers

* chore: gitignore subagent-driven-development scratch workspace

* feat(redshift): add tagging support to RedshiftService

- Add tags field to Cluster, Snapshot, and ClusterParameterGroup models
- Inject RegionResolver into RedshiftService constructor
- Implement tag CRUD methods: createTags, deleteTags, describeTags, listTagsForResource
- Add resolveTagHandle ARN resolver for tagging operations
- Add 6 new unit tests covering tag operations and error cases

* feat(redshift): wire CreateTags/DeleteTags/DescribeTags into the query handler

* feat(redshift): store real parameter values on ClusterParameterGroup

* fix(redshift): use proper imports and preserve parameter metadata on modify

* feat(redshift): wire ModifyClusterParameterGroup, return real DescribeClusterParameters values

* feat(redshift): add ClusterSubnetGroup model and CRUD

* feat(redshift): wire ClusterSubnetGroup CRUD into the query handler

* feat(redshift): add ClusterSubnetGroupName/VpcSecurityGroupIds metadata to Cluster

* feat(redshift): add RedshiftContainerManager.alterUserPassword

* fix(redshift): prevent SQL injection in alterUserPassword via username validation

* feat(redshift): add RedshiftService.modifyCluster

* feat(redshift): add RedshiftService.rebootCluster (dump/restore based, no data loss)

* feat(redshift): wire ModifyCluster/RebootCluster into the query handler

* test(redshift): add compatibility coverage for tagging, subnet groups, modify/reboot

* fix(redshift): use imports and unique names in compatibility test

Follow this file's established conventions: proper imports instead of
fully-qualified SDK types, and TestFixtures.uniqueName() instead of
hardcoded resource names, matching the pattern used by the sibling
test methods.

* fix(redshift): address final whole-branch review findings

* fix(redshift): address PR review feedback and green the CI

Review comments:
- Translate three Vietnamese comments in RedshiftContainerManager and
  RedshiftService to English (repo is English-only).
- alterUserPassword: reword the single-quote guard to cite the AWS
  ModifyCluster MasterUserPassword constraint rather than the psql SQL
  literal, and enforce the full documented set for parity — reject
  ' " \ / @, require length 8-64 and at least one upper/lower/digit.
- adoptOrStart: LOG.warnv on the container-gone branch so a fresh empty
  cluster after a lost container is a searchable line, not a silent one.
- Move the .superpowers/ scratch ignore from the shared .gitignore to
  .git/info/exclude (local tooling, not project output).

CI failures:
- Register redshift.model.Parameter for reflection so
  PersistedModelReflectionTest passes and native-image persistence works
  (fixes CI shard 3 and the native sdk-test-java compat run).
- Convert RedshiftQueryHandler.handle() from an if/else chain to
  switch (action) so the docs action-table generator can extract the
  action list, matching every other Query handler. Bodies unchanged.
- Register redshift in tools/docs/services.yaml, add docs/services/redshift.md
  with the generated action table, and add the Service Matrix row in
  docs/services/index.md (fixes Docs Action Tables / Action tables in sync).

* fix(redshift): reject path traversal in SnapshotIdentifier

createSnapshot spliced the request's SnapshotIdentifier straight into a
host path (<persistentPath>/redshift-dumps/<accountId>/<id>.sql). A value
with traversal segments or an absolute prefix escaped the account dump
directory: snapshot creation would write pg_dump output over an arbitrary
host file, and the resulting absolute path was persisted so a later
restore (arbitrary read into an attacker-controlled DB) or delete
(arbitrary unlink) trusted it.

- validateSnapshotIdentifier: enforce AWS's format (1-255 chars, leading
  letter, letters/digits/non-consecutive hyphens) — rejects '.', '/', '\'
  so no separator can appear.
- Keep a normalise + startsWith(dumpDir) containment check as defence in
  depth.
- restore/delete now verify the stored sqlDump path still resolves inside
  the account dump dir before touching it, so a path written by the
  pre-fix code can't be acted on.

Also replace inline java.* fully-qualified names in RedshiftService and
RedshiftQueryHandler with top-of-file imports.

* fix(redshift): validate snapshot dump path before restore provisioning

The trusted-dump-path check added in the previous commit ran inside the
try block, after restoreFromClusterSnapshot had already persisted the
target cluster as "creating" and started its container. Rejecting an
untrusted path then left the container running and a "failed" cluster
record behind, blocking a retry with the same identifier
(ClusterAlreadyExists).

Move the check ahead of all provisioning — right after the snapshot is
loaded, before clusters.put and containerManager.start — so a rejected
restore creates no resources.

---------

Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
2026-08-29 15:25:02 -04:00
Matheus Oliveira 2a7c94b04d feat(applicationautoscaling): evaluate target-tracking and step-scaling policies against ECS (#2692)
Adds a generic CloudWatch alarm evaluator plus an ECS CapacityAdjuster,
so a firing policy calls UpdateService to change desiredCount instead
of sitting inert. Adds DescribeScalingActivities to observe the result.

Closes #2565

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-29 14:23:13 -04:00
Ahmed khaled cf6fede453 feat(rekognition): add Amazon Rekognition sync image-analysis actions (#2706)
* feat(rekognition): add Amazon Rekognition sync image-analysis actions

Implements DetectLabels, DetectFaces, DetectText, CompareFaces, and
DetectModerationLabels as fixed AWS-shaped stub responses over the
real JSON 1.1 wire protocol (X-Amz-Target: RekognitionService.*).
Image/SourceImage/TargetImage input is required and validated (must
specify Bytes or S3Object) but never decoded, matching the pattern
already used for Textract's Document input.

Content-listing operations (DetectLabels, DetectText) always return
one canned entry, matching TextractService's stub precedent. Face and
moderation operations (DetectFaces, CompareFaces,
DetectModerationLabels) return empty results by default rather than
fabricating biometric attributes or a moderation flag for content
that was never analyzed, matching ComprehendService's PII-detection
precedent.

Face-collection persistence, custom-model training, live video
(StreamProcessor), async video jobs, and Face Liveness sessions are
out of scope for this PR.

Closes #2705

* fix(rekognition): reject wrong-typed Bytes/S3Object as SerializationException

requireImage() only checked field presence via hasNonNull(), so a
wrong-typed Bytes (e.g. a number) or S3Object (e.g. a string) was
silently accepted instead of rejected, same class of bug as the
Comprehend Text/LanguageCode type-coercion fix. Bytes must now be
textual and S3Object must be an object when present, both rejected
as SerializationException (a shape/marshalling mismatch) otherwise.

Content-level validation (well-formed base64 in Bytes, S3Object's
Bucket/Name presence, rejecting both Bytes and S3Object together) is
intentionally not added: S3Object has no required members in AWS's
own model, and nothing in the model declares supplying both fields
invalid — documented as intentional deviations.

Addresses review feedback on #2706.
2026-08-29 14:15:52 -04:00
Ahmed khaled 5c1b69c45f feat(comprehend): add Amazon Comprehend sync text-analysis actions (#2674)
* feat(comprehend): add Amazon Comprehend sync text-analysis actions

Implements DetectSentiment, DetectKeyPhrases, DetectDominantLanguage,
DetectPiiEntities, and ContainsPiiEntities as fixed AWS-shaped stub
responses over the real JSON 1.1 wire protocol
(X-Amz-Target: Comprehend_20171127.*). Input validation (Text and
LanguageCode required, LanguageCode checked against Comprehend's
supported set) matches real API behavior and raises
InvalidRequestException/UnsupportedLanguageException per
botocore's declared error shapes.

The async job/model-training surface (DocumentClassifier,
EntityRecognizer, Flywheel, Dataset, Endpoint) and DetectEntities/
DetectSyntax are out of scope for this PR. Real (non-stub) detection
logic is planned as a follow-up once this lands.

Closes #2660

* fix(comprehend): restrict PII detection to en/es language codes

DetectPiiEntities and ContainsPiiEntities were validated against the
full 12-language set shared with DetectSentiment/DetectKeyPhrases, but
AWS's own operation docs for DetectPiiEntitiesRequest.LanguageCode
state PII detection only supports English (en) and Spanish (es).
Split the allowlist so the two PII operations reject other languages
with UnsupportedLanguageException, matching real Comprehend behavior.

Addresses review feedback on #2674.

* fix(comprehend): reject non-string Text/LanguageCode as SerializationException

getStringField() coerced any JSON value via asText() instead of
enforcing the modeled string type, so a numeric or boolean Text/
LanguageCode silently succeeded instead of being rejected. Reuses the
codebase's existing SerializationException convention (see
JsonErrorResponseUtils.createSerializationErrorResponse()) since a
wrong-typed field is a shape/marshalling mismatch caught before
business logic runs, distinct from a missing field (InvalidRequestException,
a modeled business error). Scoped to ComprehendJsonHandler only.

Addresses review feedback on #2674.
2026-08-28 18:47:22 -04:00
Matan Baruch 277809fb41 feat(aps): add Amazon Managed Service for Prometheus workspaces (#2604)
* feat(aps): add Amazon Managed Service for Prometheus workspaces

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

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

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

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

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

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

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

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

Review follow-ups from #2604:

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

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

- Match the aws: prefix case-insensitively as a plain loop, the same idiom
  as FisService and BatchService, instead of a case-sensitive stream chain.
- Derive key() from keyPrefix() so the :: separator lives in one place, and
  hoist the region prefix out of the scan predicate.
- Replace the two near-identical SigV4 Authorization literals in the
  integration test with an auth(region) helper.
2026-08-28 10:05:42 -04:00
Sam Fakhreddine d60bd6ead2 feat(route53resolver): add Route 53 Resolver with DNS Firewall domain lists (#2582)
* feat(route53resolver): AWS-managed DNS Firewall domain lists

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

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

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

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

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

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

* docs(route53resolver): register the generated action table

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

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

* fix(route53resolver): make creates idempotent on CreatorRequestId

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

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

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

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

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

* docs(route53resolver): correct the scoping limitation

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

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

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

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

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

* fix(route53resolver): reject an empty TargetIps list

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sort by a canonical key that ignores member order instead. Both sides are
re-normalised at comparison time rather than trusting the stored order, so
a record written before this fix still compares as equal.
2026-08-27 14:16:38 -04:00
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 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
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
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
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
Matheus Oliveira 700acc65c7 feat(docs): guard the service matrix against undocumented services (#2465)
* docs(services): add SWF, Cloud Control API, and EMR Serverless to the service matrix

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(docs): fail CI when a registered service has no service-matrix row

check_service_matrix.py compares descriptor() registrations in
ResolvedServiceCatalog.java against the matrix, via an alias/deferred
registry in tools/docs/service_matrix.yaml. Deferred entries require a
`by:` expiry date so the exemption can't become permanent (see #2436).

Wired into `make docs-check`.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-23 21:04:30 -04:00
William St John Bacon 87e804492a feat(organizations): add AWS Organizations service (#2489)
* feat(organizations): add AWS Organizations service

Implements the AWS Organizations control plane over JSON 1.1
(AWSOrganizationsV20161128.*): organizations and roots, the OU tree,
member accounts, all policy types, tags, trusted service access,
delegated administrators, the organization resource policy, and the
invitation/handshake flow.

Organizations is global and cross-account, so records are addressed
through the explicit *ForAccount methods on AccountAwareStorageBackend
rather than the request-context-derived get/put: a member account
calling DescribeOrganization has a different request account than the
one owning the data. The caller account is used for authorization
instead — mutations are management-account only, members get read
access to their own organization, and outsiders get
AWSOrganizationsNotInUseException.

Because Floci already resolves a 12-digit access key id to an account,
an account created by CreateAccount is immediately usable as a caller
identity against every other service.

* fix(organizations): emit only AWS's handshake resource types

Review feedback on #2489.

The ORGANIZATION resource on an INVITE handshake was carrying a
MASTER_ACCOUNT_ID child. HandshakeResourceType is a closed enum and that
value is not in it, so the AWS SDK deserializes it as
UNKNOWN_TO_SDK_VERSION rather than failing loudly. AWS's documented
children are MASTER_EMAIL and MASTER_NAME; emit those instead. The
javadoc already described the correct pair, so it was the code that
deviated. Adds an integration test pinning the resource types against
the enum so this cannot regress.

Also from review:

- POLICY_TYPES and EFFECTIVE_POLICY_TYPES are rendered into validation
  messages, but Set.of's iteration order is unspecified and salted per
  JVM run, so the same rejection could read differently between runs.
  Declare them as ordered Lists with companion Sets for O(1) membership.
- listHandshakesForAccount called organizationById — itself a full scan —
  once per handshake. Build the orgId to management-account map once.
2026-08-23 17:18:42 -04:00
Alex Banna 04d120fdd5 feat(fis): add AWS FIS support (#2435)
* feat(fis): add AWS FIS support

* refactor: add typed FIS persistence models

* ci(fis): retrigger timed-out build

* fix(fis): reject trailing JSON request bodies
2026-08-21 00:09:04 -04:00
Matheus Oliveira 3374bfeb04 feat(rds): add option group CRUD (#2352)
Adds CreateOptionGroup, DescribeOptionGroups, ModifyOptionGroup and
DeleteOptionGroup, mirroring the DB parameter group actions. DB instances now
accept OptionGroupName and report OptionGroupMemberships, so a group still
attached to an instance faults on delete.

Fixes #2304

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-18 07:13:20 -04:00
1cc97d57c1 feat(cloudhsmv2): implement CloudHSM v2 service (#1776)
* feat(cloudhsmv2): implement CloudHSM v2 service

* refactor(cloudhsmv2): delete HSM parameters and docs

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

* fix: greptile bot reviews

* refactor(cloudhsmv2): delete HSM parameters and docs

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

* fix: greptile bot reviews

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

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

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

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

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

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

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

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

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

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

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

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

* docs(stepfunctions): document map concurrency

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after OpenTofu registry flake

* test(stepfunctions): pin Map item selection order

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

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

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* ci: retry transient gosu downloads

---------

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

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after autoscaling test flake

---------

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

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

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

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

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

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

Closes #2210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

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

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

* fix(cloudformation): delete resources after stack updates

* test(cloudformation): wire cloudfront fixture dependency

* fix: include Step Functions update date in describe response

* fix: preserve Step Functions describe response shape

* fix: preserve generated Step Functions names

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat(cloudfront): enforce signed private content

* chore: re-run CI

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

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

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

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

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

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

* revert(test): revert CloudFrontClient addition to TestFixtures

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

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

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

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

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

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

* style(cloudhsmv2): remove trailing whitespace in CloudHsmV2Test

---------

Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in>
Co-authored-by: Aniket Shukla <aniketshukla619@gmail.com>
Co-authored-by: Alex Banna <alexanderbanna@gmail.com>
Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
Co-authored-by: TiM <tim@nuimarkets.com>
Co-authored-by: Olamide Kosile <64154023+Mide69@users.noreply.github.com>
Co-authored-by: lex00 <121451605+lex00@users.noreply.github.com>
2026-08-17 00:00:49 -05:00
Andre Kurait ecad6acf58 feat(swf): add Simple Workflow Service emulation (#2257)
* feat(swf): add Simple Workflow Service emulation

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

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

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

State machine:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Addresses three review findings.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Addresses two AWS compatibility gaps from review.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
2026-08-14 11:16:21 -04:00
Priamo Germosen d78520d5cb feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2) (#1914)
* feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2)

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

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

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

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

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

Tests updated accordingly and verified live against the packaged jar.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat(kinesisanalytics): add CreateApplicationPresignedUrl and SnapshotsEnabled

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

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

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

The readiness poller only called putApplication when advanceToRunning reported
RUNNING, not when it merely assigned flinkJobId after submitting the job (which
returns false until the job state catches up). pendingJars — a separate,
in-process-only cache — is already cleared by that point, so an emulator
restart between job submission and reaching RUNNING would leave the
application stuck: no persisted flinkJobId to resume polling, and no cached
JAR left to resubmit.
2026-08-09 15:01:30 -04:00
Priamo Germosen 1795e131a2 feat(applicationautoscaling): add Application Auto Scaling control plane (#2159)
* feat(applicationautoscaling): add Application Auto Scaling control plane

Adds a services/applicationautoscaling package emulating the Application
Auto Scaling API (JSON 1.1, AnyScaleFrontendService. target prefix,
application-autoscaling signing name). This is a distinct service from the
existing EC2 Auto Scaling package, which speaks Query under the
autoscaling signing name.

Implements the nine actions Terraform exercises: RegisterScalableTarget,
DescribeScalableTargets, DeregisterScalableTarget, PutScalingPolicy,
DescribeScalingPolicies, DeleteScalingPolicy, and the ListTagsForResource
/ TagResource / UntagResource trio.

Notable behaviours:

- Identity is the (ServiceNamespace, ResourceId, ScalableDimension)
  triple; RegisterScalableTarget upserts on it and leaves unsupplied
  parameters unchanged, matching AWS.
- ScalableTargetARN uses the application-autoscaling service name while
  PolicyARN uses plain autoscaling and embeds the resource path and policy
  name — the two ARN families genuinely differ.
- Tagging resolves by ScalableTargetARN because the Terraform provider's
  transparent-tagging interceptor calls ListTagsForResource on every read,
  keyed on the ARN it reads from DescribeScalableTargets.
- Target-tracking policies create the real pair of CloudWatch alarms AWS
  creates on the caller's behalf; deregistering a scalable target deletes
  its policies and their alarms.
- Optional configuration fields are only echoed back when supplied, so
  Terraform never sees a value it did not configure.

Scaling policies are stored and described but inert: nothing evaluates
them and no capacity is adjusted, mirroring EC2 Auto Scaling's existing
PutScalingPolicy. This is documented in docs/services/applicationautoscaling.md.

Closes #2157

* refactor(applicationautoscaling): stop exposing the scalable target's tag map

getTags() handed out the live internal map, and the service mutated it in
place at three call sites. listTagsForResource also returned that same
live reference out to the handler layer, so a caller could alter stored
state without going through the service.

getTags() now returns an unmodifiable view, with putTags/removeTags for
the mutations the service actually needs, and a test pins the read-only
contract.

Reported by github-code-quality on #2159.
2026-08-07 17:27:36 -05:00
Jason van Zyl fe2008848f fix(rds): preserve network placement metadata (#1735)
* fix(rds): honor request region for subnet placement

* fix(rds): persist DB instance VPC security groups

* docs: sync service action tables

* fix(rds): tidy region-aware query dispatch
2026-07-10 23:17:28 -05:00
kotov228 97b64a1d3b feat: add AWS Lightsail emulation (#1583)
* feat(lightsail): add AWS Lightsail emulation

* fix(lightsail): align error responses with AWS

* fix(lightsail): address review edge cases

* fix(lightsail): reject attached disk reattach

* fix(lightsail): reject static ip reattach

* fix: register lightsail docs handler
2026-07-10 20:43:42 -05:00
TiM 7d70f64162 feat(docs): generate Supported Actions tables from handler source (#1641)
* feat(docs): generate Supported Actions tables from handler source

The "Supported Actions" tables in docs/services/*.md were hand-maintained and
drifted from the handlers. For example secrets-manager.md omitted RestoreSecret,
which SecretsManagerJsonHandler dispatches, and acm.md listed RenewCertificate,
which is not implemented anywhere in src/.

Derive the action list from handler source so it cannot drift, while keeping the
hand-written Description column:

- tools/docs/regen_action_docs.py extracts actions from `case "X" ->` switch arms
  (including multi-label arms) and JAX-RS REST controllers, and rewrites only the
  rows between the <!-- floci:actions --> markers. Descriptions are preserved by
  action name; new actions get a "-" placeholder. PascalCase-only matching avoids
  picking up SCREAMING_CASE labels from non-action switches.
- tools/docs/services.yaml registers 18 single-table switch services and lists the
  remaining switch handlers under deferred_handlers, so the new-service sentinel
  fires only on a genuinely unregistered handler.
- make docs-sync / docs-check / docs-test, plus a Python-only CI workflow that
  gates on handler, doc, and tooling changes.
- Migrate 18 service docs into marker blocks, reconciling real drift (adds
  RestoreSecret, ImportCertificate, and others; drops the unimplemented
  RenewCertificate).

Revives the parser and CI gate from #738 by @ericbsantana and completes the
description-preservation its spec described. REST-mode, mixed-mode, multi-table,
non-tabular, S3, and ecr docs are deferred and tracked in deferred_handlers.

* docs: drop standalone design spec from action-docs tooling

Remove ideas/auto-generated-action-tables.spec.md and the four references
to it (CONTRIBUTING.md, Makefile, regen_action_docs.py docstring,
services.yaml). It was a planning artifact; the operational docs live in
CONTRIBUTING.md and the tooling is self-documenting. The #738 / @ericbsantana
credit is preserved in the PR description.

* chore: address review on action-docs tooling

- pin actions/checkout to v7.0.0 in docs-actions workflow to match the
  repo-wide bump (#1690), so dependabot does not immediately flag the new file
- document in the generator docstring that a switch case label counts as
  supported purely by existing, so a per-action UnsupportedOperation stub
  would be a false positive (handlers here reject from the default arm)

* docs: regenerate action tables against current handler source

Resync the generated Supported Actions tables to handler source after
rebasing onto the latest main:

- cloudformation: add DescribeStackInstance and DescribeStackSetOperation
  now emitted by the handler, and keep the implemented StackSet descriptions
- cloudtrail: add LookupEvents
- firehose: add UpdateDestination
- step-functions: add PublishStateMachineVersion, ListStateMachineVersions,
  DeleteStateMachineVersion
- register the cloudcontrol handler in deferred_handlers so the strict
  unregistered-handler gate passes (no standalone action table yet)

* fix(docs): prevent action-table generator from silently dropping actions

Address the latest review pass on the action-docs tooling:

- switch extraction now captures case arms whose labels wrap across lines
  (valid Java 14+ syntax). The capture group excludes only `{ } ;` boundaries,
  so it spans newlines between labels but stops at the arm's `->`. A wrapped
  arm was previously missed, and docs-check would stay green because the doc
  and the generated output agreed on the omission, defeating the whole
  drift-prevention guarantee.
- REST extraction skips Javadoc / inline comments between a verb annotation
  and the method signature; such a line otherwise reset the lookahead and
  dropped the action.
- parse_marker_block raises a descriptive error when a marker is not on its
  own line, instead of a bare "substring not found".
- doc, source, and registry reads/writes are pinned to UTF-8 so generation is
  locale-independent (the docs contain non-ASCII text).
- the docs-actions push trigger watches Makefile and the workflow file,
  matching its pull_request trigger.

Adds regression tests for the multi-line arm and comment-skip paths (20 total).
2026-07-06 21:02:04 -05:00