Commit Graph
74 Commits
Author SHA1 Message Date
Mario Toffia f248eb51af fix(cloudformation): send the stack's StackId to custom resources (#4861)
AWS documents StackId in every Create, Update and Delete request as the
ARN of the stack that contains the custom resource, and handlers rely on
it. #4973 now passes the engine's stack id and stashes it for Delete, but
an engine with no stack ARN still leaks a non-ARN: Cloud Control's
standalone engine uses the stack name as its id, so its custom resources
got StackId "cloudcontrol".

A stack id is now minted when there is no stack ARN to send. A resource
created through Cloud Control has its minted id stashed at Create, so its
Delete repeats it. A resource stashed by an earlier release with no
__FlociStackId, or with a non-ARN one, gets a freshly minted ARN on
Delete, because the delete path does not reach the stack.

An integration test drives Create, Update and Delete through a mocked
handler and checks the event's StackId against Ref AWS::StackId and
DescribeStacks, including a nested stack's own id, and the docs say so.
2026-10-08 14:43:01 -04:00
TATSUNO “Taz” Yasuhiro ee2d1a68a6 feat(cloudformation): pass Lambda DurableConfig through (#5218)
* feat(cloudformation): pass Lambda DurableConfig through

AWS::Lambda::Function.DurableConfig reaches CreateFunction and
UpdateFunctionConfiguration. As on AWS, a RetentionPeriodInDays the
template leaves out is 14 on update too, a durable function created
without Timeout gets min(ExecutionTimeout, 900), and adding or removing
DurableConfig replaces the function.

* test(terraform): cover aws_lambda_function durable_config

The provider creates a durable function, reads it back without a diff,
updates execution_timeout in place, and before destroy stops a RUNNING
durable execution through ListDurableExecutionsByFunction,
StopDurableExecution and GetDurableExecution.

* fix(cloudformation): honor AWS::NoValue, cleared keys and large numbers in DurableConfig

A DurableConfig that Fn::If removes with AWS::NoValue leaves the
function plain. A KMSKeyArn the template leaves out or sets to "" clears
the key, as CloudFormation does on AWS, since Lambda keeps a stored key
when the update omits the member. A number beyond an integer reaches
Lambda unchanged, so its range check rejects it.

* fix(cloudformation): reject a DurableConfig that is not an object

Only an intrinsic that resolves to AWS::NoValue removes DurableConfig.
CloudFormation rejects a string, number or list in its schema check
before the function is touched, so an update with one no longer
replaces and deletes a durable function.

* test(cloudformation): cover Lambda DurableConfig with the AWS SDK

The CloudFormation and Lambda SDK clients create a durable function,
update DurableConfig in place, and remove it by replacing the function.

* fix(cloudformation): require ExecutionTimeout and known members in DurableConfig

CloudFormation checks DurableConfig against the schema on update too: an
update without ExecutionTimeout, or with a member the schema does not
list, fails before the function is touched. Floci let such an update
through and kept the old timeout.

* refactor(cloudformation): look up a Lambda function once per deploy

The name choice and the replacement decision now share one lookup and one
durable check, so they cannot disagree.
2026-10-07 12:39:36 -04:00
Mario Toffia 4be8309e8d feat(cloudformation): provision AWS::IoT::Authorizer (#4830)
* test(cloudformation): cover AWS::IoT::Authorizer against AWS

* feat(cloudformation): provision AWS::IoT::Authorizer

CloudFormation stubbed AWS::IoT::Authorizer with a fake ARN and created
nothing. IotAuthorizerCfnProvisioner now creates a real authorizer
through IotAuthorizerService.

Ref is the authorizer name and Fn::GetAtt Arn the ARN. A missing
AuthorizerFunctionArn fails with the registry's model validation error
before any call. Status, EnableCachingForHttp, AuthorizerFunctionArn and
the token settings update in place, sending only the declared
properties, tags are reconciled, and a failed stack update restores
them from a snapshot. Changing AuthorizerName or SigningDisabled
replaces the authorizer and deletes the old one once the update
commits; a replacement that keeps an explicit name is refused. Delete
deactivates the authorizer first and tolerates one already gone.

Closes #4822

* chore(cloudformation): move the IoT authorizer snapshot constant

It sat at the same insertion point as other pull requests' snapshot constants, so they could not be merged together.

* fix(cloudformation): treat only an empty intrinsic result as AWS::NoValue for IoT authorizers

* fix(cloudformation): undo an IoT authorizer update whose tag reconcile fails

* fix(cloudformation): report a SigningDisabled change on an IoT authorizer as a replacement

* fix(cloudformation): create an IoT authorizer over a dispatcher stub and refuse declaring its generated name

* fix(cloudformation): refuse an IoT authorizer boolean that is neither true nor false

* fix(cloudformation): never delete a dispatcher stub's id in replacement cleanup

* fix(cloudformation): tell a stub from a migrated resource and roll back a stub migration that kept its id

* fix(cloudformation): name an unnamed IoT authorizer <LogicalId>_<12 chars> as CloudFormation does
2026-10-05 14:37:54 -04:00
Matheus Oliveira c6304a26c8 feat(cloudformation): provision AWS::Transfer::User (#5076)
* feat(cloudformation): provision AWS::Transfer::User

Adds the user type to TransferCfnProvisioner with in-place update and replacement.

* Fix #4655

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

* docs: count the IAM SSH public key operations in the service matrix

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

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-04 18:19:43 -04:00
Vũ Thế Huy 108f2b54bf feat(eventbridge): add ApiDestination target support (#4702) (#5009)
* feat(eventbridge): add ApiDestination target support (#4702)

- Add ApiDestination, ApiDestinationState, and HttpParameters models

- Implement CRUD operations for API destinations in EventBridgeService

- Add CreateApiDestination, DescribeApiDestination, UpdateApiDestination, DeleteApiDestination, ListApiDestinations actions in EventBridgeHandler

- Support HttpParameters on targets in PutTargets and ListTargetsByRule

- Implement HTTP delivery to API destinations in EventBridgeInvoker with connection auth and SSRF protection

- Add CloudFormation provisioning for AWS::Events::ApiDestination in EventsCfnProvisioner

- Update docs and tests

* fix(eventbridge): harden ApiDestination delivery and CloudFormation lifecycle

- Throw on delivery failure so TargetDispatcher retries 429/5xx and connection
  errors and dead-letters permanent failures
- Enforce InvocationRateLimitPerSecond per destination
- Run the OAuth client-credentials exchange for OAUTH_CLIENT_CREDENTIALS connections
- Reject non-http(s) endpoints and wildcard hosts, encode path parameter values,
  keep the query before any fragment, and stop logging URLs that may carry secrets
- Resolve destination and connection ARNs only when they match the stored ARN
- Validate every UpdateApiDestination field before applying any of them
- Paginate ListApiDestinations with Limit and NextToken
- Keep HttpParameters on AWS::Events::Rule targets and roll back
  AWS::Events::ApiDestination updates from a snapshot

* fix(eventbridge): keep connection credentials authoritative and require a valid endpoint host

- Apply target headers and query parameters before the connection's so a target
  cannot override its credentials, and replace header names that differ only by case
- Reject endpoints without a parsed host (for example https://:8080/path)
- Sweep stale rate-limit windows once the map grows

* fix(eventbridge): make the ApiDestination rate limit check atomic

Count permits inside ConcurrentHashMap.compute on an immutable window so the
stale-window sweep can no longer remove a window another delivery is using,
which let concurrent deliveries exceed InvocationRateLimitPerSecond.

* refactor(eventbridge): drop the in-service InMemoryStorage constructor and tidy tests

- Remove the compatibility constructor that instantiated InMemoryStorage inside
  EventBridgeService; tests pass the ApiDestination store explicitly
- Import classes instead of qualifying them inline in the ApiDestination integration test
- Surface worker failures in the concurrent rate limit test by checking each Future

* docs: correct the EventBridge and IAM operation counts in the service matrix
2026-10-04 18:03:31 -04:00
Mario Toffia 2749cd6fcd feat(cognito): provision user group attachments (#4806)
* feat(cognito): provision user group attachments

Serve AWS::Cognito::UserPoolUserToGroupAttachment through a new per-service
provisioner. Ref is <UserPoolId>|<GroupName>|<Username>, as measured on AWS.
Every property is createOnly, so a change replaces the membership and the old
one is removed in cleanup; delete tolerates a membership that is already gone.

* test(cognito): read stack outputs with XmlPath

* fix(cognito): attach users to groups from their recorded parts, as AWS does

* test(cognito): cover pipe group names and alias updates, delete seeded pools

* fix(cognito): remove an unrecorded attachment named unambiguously by its id

* test(cognito): pin that a failed rollback keeps the replacement's recorded parts

* fix(docker): finish a failed tar copy's writer before retrying

* test(docker): wait for each attempt's tar writer instead of racing it

Restores RetryingTarCopier.copyStreamed to its state on main: joining a failed attempt's writer could block on a writer stalled outside the pipe.

* docs(cloudformation): note the no-op delete of a short membership id

The class Javadoc said an unrecorded id that does not split into exactly three parts is refused. An id of fewer parts names no membership and its delete does nothing; only more parts is refused.

* fix(cloudformation): keep __Floci attributes out of Fn::GetAtt

Provisioners keep private state under __Floci attribute keys. Fn::GetAtt and Fn::Sub resolved them like any attribute, so a template could read, for example, an attachment's recorded pool, group and username, while AWS resolves no such attribute. They now resolve as unresolved, like any attribute a type does not have.

* docs(cloudformation): note that custom resource Data keys under __Floci are reserved
2026-10-04 17:00:35 -04:00
Vũ Thế Huy 99a6b4050c feat(redshift-serverless): add running workgroups and Data API WorkgroupName support (#5012)
* feat(redshift-serverless): add running workgroups and Data API WorkgroupName support

Redshift Serverless workgroups get full CRUD (Create/Get/List/Update/Delete),
tagging by ARN, and the AWS::RedshiftServerless::Namespace and ::Workgroup
CloudFormation types with dotted Fn::GetAtt keys taken from the registry
schema. A namespace has at most one workgroup, and DeleteNamespace is refused
while one is attached.

Each workgroup runs a PostgreSQL container behind an authenticating proxy,
sharing the managers and the proxy port pool with provisioned Redshift. Add
GetCredentials, accept WorkgroupName (name or ARN) in the Redshift Data API,
and push a changed namespace adminUserPassword down to the running backend.
The runtime is re-attached when Floci restarts.

Not covered: snapshots, usage limits, endpoint access, and COPY/UNLOAD/Spectrum
on workgroups.

* fix(redshift-serverless): stop the runtime when workgroup creation fails after it started

If persisting the workgroup record failed after the container and proxy were
already running, the runtime was left behind with no record. createWorkgroup
now stops it (best effort) and releases the endpoint on the failure path.

Fix the CloudFormation error for a NamespaceName change: suggesting a new
WorkgroupName can never succeed because a namespace holds only one workgroup.

* fix(redshift-serverless): reset omitted CloudFormation properties and order startup observers

When UpdateStack drops a property from the template, the provisioner now sends
its default (BaseCapacity, EnhancedVpcRouting, PubliclyAccessible, Port,
TrackName, PricePerformanceTarget) instead of keeping the stored value, which
matches CloudFormation semantics. MaxCapacity has no default and keeps its
stored value.

Give the workgroup StartupEvent observer a @Priority after RedshiftService so
every persisted cluster has reserved its proxy port before workgroups restore
theirs.

Also remove an unused import and move DEFAULT_DATABASE to the top of
RedshiftContainerManager.

* fix(redshift-serverless): address review findings on password rotation and namespace updates

- Roll the backend password back when a rotation cannot be completed or stored, and apply
  it last so validation failures never leave the backend ahead of the stored namespace.
- Keep a workgroup endpoint reserved when its runtime cannot be stopped during clear().
- Reject an in-place DbName change in CloudFormation, since it is fixed at creation.
- Reset an omitted KmsKeyId and DefaultIamRoleArn on CloudFormation updates.

* fix(redshift-serverless): keep rollback failures from masking errors and drop stale GetAtt role

- Do not reset the proxy password when the role restore fails, and attach restore
  failures to the original exception instead of replacing it.
- Remove Namespace.DefaultIamRoleArn from the stack resource when an update no
  longer declares a default role.

* docs: correct the Redshift Serverless operation count in the service matrix

* fix(redshift-serverless): expose Workgroup.ConfigParameters through Fn::GetAtt

* fix(redshift-serverless): parse ConfigParameters resolved from a GetAtt attribute

* docs(redshift-serverless): list every unsupported operation group
2026-10-04 15:34:24 -04:00
Mario Toffia 66f04cde25 feat(eventbridge): provision AWS::Events::Archive (#4818)
* fix(eventbridge): make UpdateArchive a partial update

UpdateArchive reset the event pattern to null and the retention to 0
whenever a request omitted them. On AWS an omitted Description,
EventPattern or RetentionDays keeps the stored value, an empty
Description or EventPattern clears it, and RetentionDays 0 sets 0.

* feat(eventbridge): provision AWS::Events::Archive

CloudFormation stubbed AWS::Events::Archive with a fake ARN and created
nothing. EventsArchiveCfnProvisioner now creates a real archive through
EventBridgeService.

Ref is the archive name and Fn::GetAtt Arn the archive ARN. ArchiveName
is generated when omitted and kept across updates. Description,
EventPattern and RetentionDays update in place, sending only the
properties the template declares, and a failed stack update restores
them from a snapshot. Changing SourceArn or ArchiveName, or dropping an
explicit name, replaces the archive and deletes the displaced one once
the update commits. A replacement that keeps an explicit name is refused
with CloudFormation's custom-named resource error before any change.
KmsKeyIdentifier is ignored.

Closes #4815

* fix(eventbridge): reject an archive source that is not an existing bus of the account and region

CreateArchive now checks EventSourceArn as AWS does, before the archive
name: a bus in another account fails with AccessDeniedException, one in
another region with ValidationException, and a bus that does not exist
with ResourceNotFoundException. The AWS::Events::Archive provisioner goes
through the same service call, so a stack can no longer reach
CREATE_COMPLETE with an archive that could never capture an event.

* test(eventbridge): roll back an in-place archive update when a later resource fails

A stack update changes an archive's description and retention in place,
then fails on a second archive whose source bus does not exist. The stack
ends UPDATE_ROLLBACK_COMPLETE, DescribeArchive shows the original values
and the second archive was never created. The golden case passes on AWS
and is mirrored in the Floci integration test.

* fix(cloudformation): refuse declaring a generated archive name explicitly

Adding ArchiveName with the name CloudFormation generated for an unnamed
archive asks AWS to replace the archive under the same custom name, which
it refuses with the custom-named resource error and rolls the stack back.
Floci took the in-place path and reached UPDATE_COMPLETE; the existing
refusal now also fires when the previous name was generated.

* fix(cloudformation): provision a real archive when updating a stack whose archive was stubbed

A stack created before AWS::Events::Archive had a provisioner holds the dispatcher's stub, whose physical id names no archive. Its next update now creates the archive instead of failing to describe that id, and the stub id is left to the replacement cleanup.

* fix(eventbridge): validate archive description, pattern and retention as CreateArchive and UpdateArchive do

CreateArchive and UpdateArchive now reject a description over 512 characters, an event pattern over 4096 characters and a negative retention with the ValidationException AWS returns, all violations reported together. The check runs before the source, existence and duplicate checks, so it also fails the AWS::Events::Archive resource in a stack.
2026-10-04 13:39:49 -04:00
Aymen JAMAAOUI 2c544fdb9f feat(cloudformation): provision AWS::ApiGatewayV2::VpcLink (#5008)
* feat(apigatewayv2): implement UpdateVpcLink and VPC link tagging

* feat(cloudformation): provision AWS::ApiGatewayV2::VpcLink

* fix(cloudformation): keep VPC link and integration connection state on updates

* fix(cloudformation): restore the integration connection when its own update fails
2026-10-04 09:09:18 -04:00
Mario Toffia ae0a591bb1 feat(cognito): provision user pool users (#4805)
* feat(cognito): provision user pool users

Add a CloudFormation provisioner for AWS::Cognito::UserPoolUser. Ref is the
username Cognito reports (the sub in an email-as-username pool). Every property
is createOnly: a changed custom-named user is refused as on AWS, any other change
replaces the user, and each delete targets the pool the user was created in.

* fix(cognito): refuse a RESEND user pool user that already exists

* fix(cognito): keep the user's pool out of Fn::GetAtt

* fix(cognito): keep only owed users in the pool record
2026-10-03 15:15:50 -05:00
Mario Toffia 9e178d77a0 feat(wafv2): provision web ACL associations (#4804)
* feat(wafv2): provision web ACL associations

WafV2CfnProvisioner now serves AWS::WAFv2::WebACLAssociation with Ref
ResourceArn|WebACLArn, as measured on AWS. Any property change replaces
the pair through ReplacementCleanup. Delete disassociates only while the
resource still uses that ACL, so cleanup of an old pair keeps the new one.
Rollback re-associates the restored pair.

* test(wafv2): cover ResourceArn replacement and read stack outputs with XmlPath
2026-10-03 15:01:18 -05:00
XuJian bcb50b765f feat(cloudformation): provision Transfer Family servers (#4809)
* feat(cloudformation): provision Transfer Family servers

* fix(cloudformation): clear Transfer update snapshot after success

* test(cloudformation): cover Transfer tag rollback

* fix(cloudformation): match Transfer server return values
2026-10-01 22:28:47 -04:00
Mario Toffia a338a430cc feat(cloudformation): provision Cloud Map namespaces and services (#4599)
* feat(cloudformation): provision Cloud Map namespaces and services

AWS::ServiceDiscovery::PrivateDnsNamespace, PublicDnsNamespace,
HttpNamespace and Service were stubbed, so a stack reported them created
while nothing existed in Cloud Map and Fn::GetAtt resolved to literals.

CloudMapCfnProvisioner creates them through CloudMapService. Ref returns
the id; Fn::GetAtt exposes Id and Arn, HostedZoneId on a DNS namespace and
Name on a service. An unnamed service is named <LogicalId>-<12 chars>, as
measured on AWS. Description, DnsConfig, HealthCheckConfig and Tags update
in place; a createOnly change replaces the resource through
ReplacementCleanup, and a rolled-back replacement restores the createOnly
record. A Ref to a Number parameter is coerced back to a JSON number for
DnsRecords TTL and FailureThreshold.

Closes #4596
* fix(cloudformation): roll back in-place Cloud Map updates

An in-place namespace or service update followed by a later resource
failing left the Cloud Map changes live and the stack in
UPDATE_ROLLBACK_FAILED, since rollbackUpdate only undid replacements.
The provisioner now keeps the description, DnsConfig, HealthCheckConfig
and tags an in-place update overwrites and puts them back on rollback;
a committed update drops the snapshot.
* fix(cloudmap): reject DNS record type changes on service update

UpdateService only changes the TTLs of a service's existing DNS records on AWS. An in-place CloudFormation update that changes the record types, or gives a DnsConfig to a service without one, now fails with InvalidInput instead of being applied, so it rolls back like on AWS and a rollback never has to remove a DnsConfig.
* fix(cloudmap): accept only TTL changes in a service DnsConfig update

UpdateService carries only DnsRecords on AWS and CloudFormation does not support a RoutingPolicy update. Comparing the record types as a set let a RoutingPolicy change or an added record of the same type through; the requested and stored DnsConfig now have to match apart from the TTLs.
* fix(cloudmap): ignore DNS record order in a service DnsConfig update

A TTL-only update that listed the same records in another order was rejected. The comparison now uses the sorted record types, so counts, types and RoutingPolicy still have to match.
* test(cloudformation): restore a real HealthCheckConfig in the Cloud Map rollback test

The in-place rollback test went from a null health check config to null, so dropping it from the snapshot would have passed.
2026-09-30 21:45:18 -05:00
Mario Toffia 560de5c13f fix(tagging): find resources by the tags their own service holds (#4563)
* fix(tagging): list resources by the tags their own service holds

GetResources, GetTagKeys and GetTagValues merge the tagging store with every
ResourceProvider, so SQS, Lambda and Logs tags are discoverable. Resource type
filters now parse colon and leading-slash ARNs (function:f, log-group:x, /apikeys/k),
and TagResources/UntagResources write through to the owning TagHandler.

* fix(apigateway): expose tagged resources and API key tags to the tagging API

ApiGatewayService is a ResourceProvider for REST APIs, stages, API keys, usage plans and
domain names, and ApiGatewayTagHandler serves /apikeys/<id> ARNs, so GetResources finds
API Gateway resources by tag and tagging-API writes land on the API key itself.

* fix(cloudformation): forward AWS::Lambda::Function Tags

CreateFunction now receives the template Tags; an in-place UpdateStack untags dropped keys and retags the desired set, mirroring SqsCfnProvisioner.

* fix(tagging): scope global-ARN resources by region and clamp stale page tokens

Provider resources with an empty ARN region use their own region, stale page tokens
past the end return an empty page, and provider tags are copied inside the skip guard.

* test(compat): discover SQS, Lambda, Logs and API Gateway resources by tag

* docs(tagging): describe owning-service discovery

* fix(tagging): forward tags only for resources the owning service lists

* fix(apigateway): report the calling account and tag usage plans

* docs(cloudformation): note Lambda tag reconciliation on update

* fix(tagging): match declared resource types and scope owner writes to the request

API Gateway API key and usage plan ARNs must now name the key or plan at the
start of the resource part, so a nested /apikeys/ segment no longer tags the key.

* fix(tagging): match AWS type filters, regions and failure codes

Compared against a live AWS account: type filters, IAM listing, cross-region
TagResources and FailedResourcesMap entries now answer as AWS does.

* fix(cloudformation): keep Lambda tags added outside the template

* fix(tagging): route TagResources to V1 tag handlers too

* fix(apigateway): reject sub-resource ARNs when tagging a REST API

* fix(tagging): write tagging API tags through to SQS, Lambda and Logs

TagResources and UntagResources now reach the queue, function or log group's own tags through TagHandler beans qualified @TaggingApiOnly, so ListQueueTags, Lambda ListTags and Logs ListTagsForResource show them. The qualifier keeps these handlers off the /tags/{arn} and /v1/tags/{arn} paths, since each service defines tags in its own protocol.

* fix(cloudformation): forward SSM parameter tags

AWS::SSM::Parameter now applies its Tags after the overwriting put. On UpdateStack only the keys the previous template set and the new one drops are removed, tracked in the internal FlociSsmTemplateTagKeys attribute, so tags added outside the template are kept.

* fix(tagging): hide tagging-store copies of global resources

GetResources no longer lists an IAM role or user tagged through TagResources, since AWS never lists global resources.

* fix(tagging): reject every wildcard log group ARN

TagResources and UntagResources now send a log group ARN ending in :* to CloudWatch Logs even when the group does not exist, so it is rejected as in AWS instead of stored.

* fix(tagging): clear store tags on every untag

UntagResources now removes the keys from the tagging store for every ARN, even one the owning service rejects, so a copy stored earlier can always be cleared.

* fix(cloudformation): tag an adopted Lambda function

When CreateFunction conflicts and the provisioner adopts the existing function, the template's tags are now applied to it.

* fix(apigateway): tag only exact domain and stage ARNs

A domain or stage segment nested elsewhere in an API Gateway ARN, such as /restapis/<id>/domainnames/<d>, is now rejected instead of tagging that domain or stage.

* fix(cloudformation): leave an adopted Lambda function's tags alone

Adoption uses the existing function as it is, as before, so a function outside the stack keeps its tags.

* fix(cloudformation): record no template tag keys for an adopted Lambda function

An adopted function keeps its own tags, so a later update adds the template's tags without removing any it never set.

* fix(tagging): never list IAM ARNs from the tagging store

A role tagged through TagResources stays hidden after DeleteRole, as AWS never lists IAM resources.

* fix(tagging): fail a write when an owning service cannot be read

A provider that fails while routing TagResources or UntagResources now returns InternalServiceException instead of writing the tagging store and reporting success.

* fix(tagging): fail only unresolved ARNs when a provider cannot be read

A provider failure no longer fails the whole TagResources or UntagResources call; only ARNs whose owner could not be resolved are reported in FailedResourcesMap.

* fix(tagging): report another account's ARN instead of storing it

TagResources and UntagResources report an ARN from another account in FailedResourcesMap with AccessDeniedException, as AWS reports it per ARN, and never write it to the tagging store.

* fix(tagging): keep stored tags for an ARN an untag could not resolve

UntagResources leaves the tagging store unchanged for an ARN it reports as unresolved or from another account; an ARN its owner rejected is still cleared.

* fix(tagging): fail an unresolved ARN only when its own service cannot be read

A provider failure now only affects unlisted ARNs of the services that provider declares.

* fix(tagging): copy stored tags under the writers' lock

GetResources, GetTagKeys and GetTagValues no longer race a concurrent TagResources on a stored mapping.

* fix(apigateway): reject reserved tags when tagging a usage plan

TagResources on a usage plan now refuses floci:override-id as the other API Gateway tag paths do, instead of dropping it and reporting success.

* fix(apigateway): reject tag ARNs with an account or another region

The /tags path now answers an ARN with an account segment with BadRequestException and one naming another region with NotFoundException, as AWS does, instead of resolving the id in the caller's region.

* fix(ssm,lambda): reject tag keys outside the AWS pattern

AddTagsToResource, PutParameter, TagResource and CreateFunction now reject a tag key outside the AWS pattern or 1 to 128 characters with ValidationException, as AWS does, which also keeps the CloudFormation managed-key attributes lossless.

* fix(ssm,lambda): validate CloudFormation tag keys before changing the resource

* docs(tagging): say every handled ARN ending in :* reaches its service

* fix(tagging): read a negative pagination token as the first page
2026-09-30 06:10:27 -04:00
stodan 60d112542d fix(cloudformation): delete UPDATE_FAILED resources on DeleteStack (#4470)
* fix(cloudformation): delete UPDATE_FAILED resources on DeleteStack

A failed update whose rollback cannot restore a resource leaves it
UPDATE_FAILED with its physical id and the stack in
UPDATE_ROLLBACK_FAILED. DeleteStack only walked CREATE_COMPLETE,
UPDATE_COMPLETE and DELETE_FAILED resources, plus UPDATE_FAILED ones
whose provisioner opted in, so every other failed resource was skipped
without an event and the stack still reached DELETE_COMPLETE, leaving
the role, log group or bucket behind.

Delete every UPDATE_FAILED resource that has a physical id. Delete a
CREATE_FAILED resource only when the provisioner marked its entity as
created by the stack, as the create rollback does, since a failed
create can name an entity that existed before.

Closes #4467

* test(cloudformation): clean up the outside log group when the test fails

* docs(cloudformation): list the resource statuses DeleteStack deletes

* fix(cloudformation): mark a failed nested stack the operation created as stack-owned

A nested stack whose child fails during creation came back CREATE_FAILED
with the child's stack id but no ownership marker, so neither the create
rollback nor DeleteStack deleted the child stack.

* test(cloudformation): clean up the stack, role and log group when the test fails

* docs(cloudformation): update the hasPendingRollbackCleanup javadoc now that DeleteStack no longer calls it
2026-09-26 16:23:44 -05:00
Mario Toffia 4abba5a218 fix(lambda): preserve CloudFormation event source mapping options (#4316)
AWS::Lambda::EventSourceMapping now forwards MaximumBatchingWindowInSeconds,
MaximumRetryAttempts, MaximumRecordAgeInSeconds, BisectBatchOnFunctionError,
FilterCriteria, DestinationConfig and ScalingConfig to LambdaService, so a
stack-created mapping matches an API-created one. On UpdateStack each of
these that the template omits is sent as null, which clears it.

ParallelizationFactor and TumblingWindowInSeconds are not modeled and remain
ignored; the resource-type table notes this.

Fixes #4313
2026-09-24 21:05:00 -04:00
stodan 34f4f72e82 fix(cloudformation): pass Lambda hot-reload code through to the Lambda service (#4093)
* fix(cloudformation): pass Lambda hot-reload code through to the Lambda service

AWS::Lambda::Function code of {S3Bucket: hot-reload, S3Key: /host/path} is
Lambda's bind-mount hot-reload convention: the bucket is a marker and the key
is a directory on the Docker host. The provisioner probed S3 for the pair
before calling CreateFunction, so no such object existed and the stack failed
with a ValidationError (or, with allow-stub-lambda-code on, quietly deployed
the stub handler).

Skip the S3 probe for the hot-reload bucket and hand the Code map to
LambdaService unchanged, which keeps enforcing hot-reload enablement, the
absolute-path rule and the allow-list, and reports its own error as the
resource status reason. Record a hot-reload code identity so a redeploy with
the same path is a no-op, and compare adopted functions by host path since a
hot-reload function carries no S3 bucket or key.

* fix(cloudformation): canonicalise the hot-reload code identity

LambdaService stores a hot-reload host path normalised (#4053), while the
provisioner recorded the raw template key as the code identity and compared
adopted functions against it. A template that spelled the same directory with
a trailing slash or a ".." segment, or a function adopted from a direct
CreateFunction, therefore looked like a code change and triggered an
UpdateFunctionCode that mounted the same directory again.

Build the identity from, and compare against, the normalised path. The raw key
still goes to Lambda so its validation and error messages are unchanged. Also
cover the documented SAM CodeUri form, s3://hot-reload//abs/path, through the
transform.
2026-09-23 18:03:35 -05:00
Allen Sanborn 67f06c3ac9 feat(cloudformation): list a deleted stack and report its DeletionTime (#4246)
* feat(cloudformation): list a deleted stack and report its DeletionTime

A deleted stack is already retained so DescribeStacks and DescribeStackEvents
keep answering for it by stack id after the delete, but the record they answer
with was incomplete in two ways.

It carried no deletion time, so DescribeStacks reported DELETE_COMPLETE with
nothing saying when. Stack now has a deletionTime, set as the stack reaches
DELETE_COMPLETE from the same service clock the retention window uses, and the
query handler emits DeletionTime wherever AWS does.

ListStacks omitted deleted stacks entirely. AWS keeps one there as
DELETE_COMPLETE long after DescribeStacks has stopped answering for it by name,
which is how a client reconciles what it deployed against what is left, and a
StackStatusFilter of DELETE_COMPLETE selects exactly those. Retained stacks are
now merged into the listing, still scoped to the caller's account and region and
still dropped once the window passes. A name reused after a delete lists twice,
once per stack id, as it does on AWS. Resource Explorer reads the live map
directly and is unaffected.

Restores deleted-stack-retention-seconds to application.yml, which #849 dropped
in a merge: the knob kept working on its @WithDefault, but the repository YAML
is the source of truth for what a deployment actually runs. Pinned in the test
YAML too, since the retention tests advance the clock past that exact window.

Nothing here changes how a delete runs, and it does not make a multi-stack cdk
destroy work: that client polls a destroy entirely by stack name, so a record
retained by stack id, these two members included, never enters its path.
DeleteStack does already return before the delete finishes, and the stack does
pass through DELETE_IN_PROGRESS, but the whole delete completes in roughly 15ms,
well inside one poll interval, so a client that starts watching when it issues
the delete finds the stack gone by name on its first poll. Giving a deleting
stack an observable window is separate work.

* fix(cloudformation): set a stack's deletion time before publishing the status

Stack.status is volatile and is documented as the publishing write of a deploy:
a reader that observes a terminal status is guaranteed to observe every write
that preceded it. deletionTime was assigned after it, outside that guarantee, so
a DescribeStacks running concurrently with the last step of a delete could
observe DELETE_COMPLETE while deletionTime was still null and answer with no
DeletionTime element at all.

Assigning it first puts it inside the same happens-before edge as the rest of
the delete. The window is nanoseconds wide and no test can land in it reliably,
so this carries none; the ordering rule is the thing being fixed, and the
comment records it so the next edit here keeps it.

* fix(cloudformation): retain a deleted stack before it leaves the live map

The handover at the end of a delete removed the stack from the live map, wrote
its removal through to storage, and only then retained it as deleted. A
ListStacks landing between the removal and the retention found it in neither
map and dropped it from the listing, though the stack both existed a moment ago
and is retained a moment later.

Retaining before removing closes that window. The stack is then briefly in both
maps, which is harmless: they hold the same Stack, and listStacks now reduces by
stack id, so it is listed exactly once throughout. Nothing else reads both maps,
since resolveStackForDescribe consults the retained one only after the live
lookup has missed.

Greptile reported the listing could also show the stack twice. It could not:
the old order removed before it inserted, so the two maps never overlapped. The
duplicate only becomes possible with this ordering, which is why the reduction
comes with it.

The test drives 60 deletes with four concurrent listings each. It fails on every
run against the old ordering and passes on every run against this one. It pins
the retention window open through a profile: the window is measured on the test
MutableClock, which advances on every read, and the pollers would otherwise
expire the retained record themselves.

* style(cloudformation): order the Stream import with the rest of java.util

java.util.stream.Stream landed between java.util.regex and java.util.concurrent
when it was added. It now follows both, the order AGENTS.md asks for. Only the
line this branch introduced moves; the block's older irregularities are left
where they are.

* fix(cloudformation): read the live stacks before creating the deleted-stack view

Retaining a stack before removing it keeps it in at least one map at every
instant, but listStacks built both of its views up front, the retained one
first and the live one after. A ConcurrentHashMap view reflects the table at
some point at or since its own creation and is not guaranteed to reflect a
modification made after it, so the retained view, created before the retain,
need never show the stack, while the live view, created after the remove, can
already miss it. A listing landing there loses the stack in both, which is the
window the retain-before-remove ordering was meant to close. Traversing the
retained view second does not help: creation bounds the guarantee, not
traversal.

The maps are now read one after the other instead of through a concatenated
pipeline, the live one first and in full, so the retained view is created after
any remove the live pass could have missed, and therefore after the retain that
preceded it. The reduction by stack id stays: the overlap it covers is real.

No test. The fault is the absence of a JDK guarantee rather than a behaviour:
these views do in practice reflect a later put, so the old ordering passes every
time and nothing can force it not to. The existing listing-race test still
covers the retain-before-remove ordering this rests on.

The java.util.stream.Stream import goes with Stream.concat, which the change
removes.

* test(cloudformation): stop the listing-race pollers on every exit path

The pollers were stopped after awaitDeleted returned, so a throw from the delete
or the wait left four non-daemon threads spinning on listStacks for the rest of
the run. That holds the test JVM open and buries the failure that caused it
under a hang, which is a far worse thing to debug than the failure itself.

Shutdown moves into a finally, so a failing delete stops them on its way out.
Each join is bounded and a thread still alive afterwards is interrupted and
recorded, with the poller loop now checking its own interrupt flag so that
interrupt is not merely decorative. The check that they all stopped is asserted
after the try and never inside the finally, where it would replace whatever the
delete threw with its own failure. The threads are daemons as a backstop, so a
future edit that throws somewhere nothing throws today still cannot wedge the
suite.

Also replaces an assertTrue(false, ...) in the wait helper with fail(...), which
says the same thing and reads as what it is. Noted here rather than slipped in.
2026-09-23 18:01:55 -05:00
lex00 28ca34ad6c fix(cloudformation): apply an S3 bucket's declared configuration and its policy (#3950)
S3CfnProvisioner translated CorsConfiguration and VersioningConfiguration
and nothing else, and AWS::S3::BucketPolicy took a physical id and stopped,
so a stack reported CREATE_COMPLETE for a bucket with no lifecycle, no
public-access block, no default encryption, no tags and no policy.

PublicAccessBlockConfiguration, LifecycleConfiguration, BucketEncryption
and Tags are now translated into the XML their S3 API calls take and handed
to the same service methods, so they are validated and stored exactly as a
direct PutBucket* would be. The policy document has its intrinsics resolved
and is put on the bucket.

The policy's physical id is the bucket name, as the registry schema's
primaryIdentifier declares, and deleting the resource removes the policy,
tolerating a bucket the stack already deleted. The class javadoc names the
properties that are covered and those still dropped.

Closes #3947
2026-09-21 22:27:54 -05:00
Priamo Germosen 8af15a71c4 fix(cloudformation): remove the login profile when deleting an IAM user (#3975)
Since login profiles became real state, DeleteUser returns DeleteConflict while one exists, so deleting a stack whose AWS::IAM::User was given a password out of band ended in DELETE_FAILED. The provisioner now deletes the login profile before the user, tolerating a user that has none. The resource-type table notes that the template LoginProfile and PermissionsBoundary properties are ignored.
2026-09-20 09:13:36 -05:00
Chris Jovanovski d9a4db0290 fix(cloudformation): provision Cognito user pool groups (#3695)
* fix(cloudformation): provision Cognito user pool groups

Create and reconcile user pool groups, and namespace custom schema attributes while preserving standard attributes.

* fix(cloudformation): keep a generated Cognito group name across updates

GroupName is optional, and provision generated a fresh stand-in on every call. Because
provision is also the update path, the second UpdateStack derived a different name, took
the create branch and left the group the stack already owned orphaned behind it.

Use ProvisionContext.stablePhysicalName so the prior physical id is reused when the
template does not name the group, and reusesPriorEntity for the create-or-update choice,
which is the pairing that keeps a stable name from turning an update into a duplicate
create.
2026-09-19 20:06:58 -05:00
XuJianandxujiantop-crypto 0142d443ac feat(cloudformation): provision CloudWatch log streams (#3869)
* feat(cloudformation): provision CloudWatch log streams

* fix(cloudformation): preserve conditional log stream name omission

---------

Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com>
2026-09-18 20:45:44 -05:00
Mario Toffia 22b0627245 test(compat): assert recorded metric filter publishing through the SDK modules (#3809)
* feat(logs): add metric filters with per-event metric publication

Implements PutMetricFilter, DescribeMetricFilters, DeleteMetricFilter and
TestMetricFilter on the CloudWatch Logs JSON 1.1 handler, backed by a filter
pattern engine for term, space-delimited and JSON patterns. The grammar is
checked against 148 TestMetricFilter cases recorded from AWS, kept as
fixtures under src/test/resources/cloudwatchlogs and recaptured with the
opt-in script under tools/aws-capture/cloudwatchlogs.

Validation follows the observed AWS wire behavior: the five regex-bearing
filters per log group quota is shared with subscription filters through one
canonical backend monitor, a filter pattern may hold at most two regular
expressions, defaultValue must be a JSON number, DescribeMetricFilters
requires metricName and metricNamespace together in both directions, and
TestMetricFilter reports one-based event numbers with an empty public
extractedValues map for JSON patterns.

Ingested events publish samples into CloudWatch Metrics per event at the
event timestamp: matching events contribute the extracted or literal value,
non-matching events contribute defaultValue, dimensions are all-or-none, and
system dimensions only attach to matching events. Failed publications are
retried from a bounded queue of 10,000 samples with stable publication ids.

Resettable gains beforeReset and afterReset default hooks so the metric
filter publisher can pause and drain before a state reset wipes storage and
resume afterwards. EmulatorInfoController.performReset is serialized and
calls the hooks around the existing container teardown and storage wipe,
running afterReset in a finally block so a failed wipe cannot leave a
publisher paused. The GetMetricStatistics and GetMetricData Query responses
now carry the CloudWatch namespace so both read paths return the same
samples.

* feat(cloudformation): provision AWS::Logs::MetricFilter

Adds LogsMetricFilterCfnProvisioner for creates, in-place updates, name
changes and deletes. Ref and PhysicalResourceId are the filter name alone,
as observed on AWS; the log group is kept as private resource metadata.
A replacement deletes the old filter before creating the new one, matching
the DELETE then CREATE event order AWS emits, and a failed replacement
recreates the previous definition on rollback.

Every mutation records an APPLIED, NOT_APPLIED or UNKNOWN outcome under the
service lock so a failed or ambiguous call can never authorize deleting or
overwriting a filter the stack does not own. Ownership that cannot be proven
is resolved conservatively before the next mutation.

The engine gains three small provisioner hooks that this type needs and
others may reuse:

- ProvisionContext carries a progress consumer so a provisioner can emit
  the intermediate DELETE_IN_PROGRESS and DELETE_COMPLETE events of a
  delete-first replacement while provision is still running.
- rollbackUpdate(resource, progress) lets a provisioner restore its own
  previous state during UPDATE_ROLLBACK and report the steps as events.
- hasPendingRollbackCleanup and retainsFailedUpdateState let a provisioner
  tell the engine that an UPDATE_FAILED resource still holds its own
  rollback snapshot, so the engine neither restores the previous resource
  over it nor refuses a later DeleteStack. Both default to false; only this
  provisioner overrides them.

The type is listed in supported-resource-types.tsv, the generated resource
table and CfnProvisionerFixture, with unit, integration, storage reload and
SDK coverage.

* docs(logs): document metric filters and the AWS verification record

Describes the metric filter operations, publication semantics and
CloudFormation support in docs/services/cloudwatch.md and adds
cloudwatch-metric-filters-verification.md, the record of what was observed
on AWS in eu-west-1, with which tools, and where each recorded fixture came
from. Registers the handler and the verification page with the docs tooling
and teaches the service inventory test to count facet pages.

* feat(logs): publish metric filter samples off the PutLogEvents thread

PutLogEvents evaluated each filter and wrote one CloudWatch Metrics sample
per filter and event on the request thread while holding the filter-store
monitor, up to a million writes for a maximal request, so ingestion latency
depended on the Metrics sink and every PutMetricFilter waited behind the
whole batch.

The request thread now only evaluates the group's filters as they are at
ingestion and hands the resulting immutable samples, with their stable
publication ids, to a bounded queue of 100,000 samples. The existing single
worker drains it and writes one sample per monitor acquisition, so a
PutMetricFilter or a reset waits for at most one write. A batch that does
not fit the queue is written inline on the request thread rather than
dropped. Failed writes still land in the 10,000 sample retry map with the
same ids and cadence as before.

Reset pauses the worker, discards queued and failed samples and bumps a
generation counter so a batch taken before the reset is never written into
the wiped store. Shutdown drains the queue before storage shuts down and
clears the retry map only after the worker has terminated. Samples ingested
while Metrics is disabled are discarded at startup.

Integration and SDK tests poll for the sample, as they would against AWS.

* test(compat): assert recorded metric filter publishing through the SDK modules

Extends the Java compatibility module with the publishing scenarios recorded
from AWS: mixed defaults and quiet traffic, extraction and ordinary dimension
series, system dimensions on matches only, and a Sum alarm driven by quiet
defaults. Each series is read through the SDK's CloudWatch JSON protocol and
again as a signed legacy Query request, so GetMetricStatistics and
GetMetricData agree on every sample, timestamp, unit and dimension set.

Expected values come from module-local copies of the root fixture
metric-filter-publishing-aws.json. MetricFilterFixturePackagingTest checks
the Java copy loads from the classpath and the root
CloudWatchLogsMetricFilterFixturePackagingTest fails when either SDK module
copy drifts from the root file.

The Python module gains tests/metric_filter_replay.py, an opt-in replay of
the same scenarios against a Floci endpoint or, with explicit profile,
region and write acknowledgement, against AWS. Its logic is covered offline
by tests/test_metric_filter_replay.py with the network blocked. Both module
Dockerfiles are unchanged: the Java image already runs the whole suite and
the Python image already copies tests/.

* test(compat): assert every recorded statistic and poll for published samples

The SDK publishing assertions compared only Sum and SampleCount although the
AWS fixture also records Minimum and Maximum for the default-value scenarios.
Both the SDK JSON reads and the signed legacy Query reads now assert every
statistic the fixture carries, on GetMetricStatistics and GetMetricData.

Publication now happens shortly after PutLogEvents returns, so present series
are polled and absent series are asserted only after a later positive control
of the same filter is visible, which the publisher's ordering guarantees. The
read window ends at second 59 so a sample stamped on the following minute is
never in scope.

The live replay's Region check names the commercial partition explicitly.
botocore already defaults get_available_regions to partition_name="aws", so
GovCloud and China Regions were rejected before; the offline test now pins it.

* test(compat): keep the metric filter SDK test on the Java 17 API of the compat image

List.getLast() is Java 21; the sdk-test-java image compiles with Temurin 17.
2026-09-17 13:53:35 -04:00
Matheus André 2ee3aa67c0 feat(apigateway): support Gateway Responses on REST APIs (#3326) (#3585)
Add the PutGatewayResponse / GetGatewayResponse / GetGatewayResponses /
UpdateGatewayResponse / DeleteGatewayResponse family, keyed per REST API by
responseType across the 21 AWS types. Uncustomised types are reported with
defaultResponse=true, their AWS default statusCode and the default
{"message":$context.error.messageString} template; UpdateGatewayResponse
patches /statusCode, /responseParameters/<name> and
/responseTemplates/<content-type>, and DeleteGatewayResponse restores the
default.

ImportRestApi and PutRestApi read the x-amazon-apigateway-gateway-responses
extension, and AWS::ApiGateway::GatewayResponse is provisioned by a new
CloudFormation provisioner whose Ref / Fn::GetAtt Id is
<restApiId>-<responseType>.

On the execute plane every gateway-generated answer (unmatched path or
method, AWS_IAM and Lambda authorizer rejections, missing API key, request
validation, unsupported media type, integration configuration errors and
Lambda proxy failures) resolves the customisation for its type, then
DEFAULT_4XX / DEFAULT_5XX, and applies the configured statusCode, the
gatewayresponse.header.* parameters (static, method.request.*, context.*,
stageVariables.*) and the response templates, with $context.error.* exposed
to VTL. An expired SigV4 signature selects EXPIRED_TOKEN and a malformed or
mismatching one INVALID_SIGNATURE, as AWS keeps those two contracts apart.
This is what puts Access-Control-Allow-Origin on a browser-visible
401/403/400 so the frontend can read the real status instead of a CORS
failure. Without a customisation every answer is unchanged.

Closes #3326
2026-09-15 07:44:45 -04:00
Vũ Thế Huy e5bd8be405 feat(redshift): provision AWS::Redshift::Cluster through CloudFormation (#3427)
* feat(cloudformation): provision AWS::Redshift::Cluster (create path)

* feat(cloudformation): AWS::Redshift::Cluster update and replacement

* feat(cloudformation): force replacement on Redshift cluster createOnly property change

* feat(cloudformation): force replacement on Redshift cluster DBName change

* feat(cloudformation): provision Redshift parameter, subnet and security groups

* chore(cloudformation): register Redshift provisioner in inventory and docs

* test(cloudformation): end-to-end AWS::Redshift::Cluster stack

* docs(redshift): document CloudFormation cluster provisioning

* test(cloudformation): assert ClusterSubnetGroupNotFound error code on subnet group deletion

* fix(cloudformation): correct attribute handling for Redshift security group provisioning

* fix(cloudformation): apply Redshift parameter group Parameters and fix docs

ClusterParameterGroup silently dropped Properties.Parameters on both
create and update instead of calling ModifyClusterParameterGroup, and
did not replace the entity when Description or ParameterGroupFamily
changed, even though AWS marks both as replacement properties.

Also remove the Id GetAtt claim from the Cluster docs: neither the
provisioner nor AWS's own schema expose it for AWS::Redshift::Cluster.
2026-09-13 18:45:40 -05:00
Anders Wasen 55ada9b8a3 feat(cloudformation): provision the AppSync resource types (#3424)
Adds AppSyncCfnProvisioner, serving AWS::AppSync::GraphQLApi, GraphQLSchema, DataSource,
FunctionConfiguration, Resolver and ApiKey. Without it a template's AppSync resources fall
to the dispatcher's stub arm, which reports CREATE_COMPLETE while creating nothing and
resolves Fn::GetAtt to the literal "LogicalId.Attr".

Two things are not simple property mapping. The AppSync control plane is REST-JSON with
camelCase members, so every property is lower-camelised on the way in, with DynamoDBConfig
as the one member that does not follow the rule (it is dynamodbConfig). And schema creation
is asynchronous: while it is PROCESSING every other call for that API is refused with a 409,
so the GraphQLSchema resource waits for a terminal status before completing, as CloudFormation
does.

Also carries the service-layer changes the provisioner needs: a PIPELINE resolver reaches its
data through pipelineConfig and names no data source, which createResolver refused outright;
CreateFunction and UpdateFunction now keep the runtime a JS resolver declares; and
UpdateFunction applies a new name, which a CloudFormation rename goes through.
2026-09-13 18:45:32 -05:00
Anders Wasen 10becc593f feat(cloudformation): provision AWS::Lambda::Url (#3423)
A function URL in a template was falling to the stub arm, so a stack exported the literal
string "LogicalId.FunctionUrl" in place of a URL and nothing was listening on it.

The physical id is the FunctionArn the URL is attached to, the alias ARN when Qualifier names
one, which is the registry schema's primary identifier and enough to address the config again
since a qualified ARN parses back into function and qualifier. TargetFunctionArn and Qualifier
are create-only, so an update that moves the URL creates against the new function and removes
the one it displaced.
2026-09-13 18:45:25 -05:00
Mario Toffia 460aa0718e feat(cloudwatch): provision AWS::CloudWatch::Dashboard (#3231)
* feat(cloudwatch): provision AWS::CloudWatch::Dashboard

The dashboard name is the physical id, generated when the template gives none
and kept across updates. An update with the same name puts the body again and
drives the tags to the template's set, since PutDashboard leaves an existing
dashboard's tags alone. A changed name creates the new dashboard and leaves
the displaced one to the ReplacementCleanup record, which deletes it once the
update commits or restores it on rollback. The body may be written as a JSON
object in the template and is stored as the string the API takes.

The CloudWatch docs now list the dashboard and tag actions the handlers
already serve.

* fix(cloudwatch): roll back in-place dashboard updates and replace a dashboard whose explicit name is dropped

An in-place update keeps the body and tags it replaces on the resource, or
the fact that the dashboard did not exist, and a failed stack update puts
them back in full. The name mode is recorded as the Logs provisioner does, so
a template that drops an explicit DashboardName gets a generated name and a
replacement, as on AWS, while an unnamed dashboard keeps its generated name.
The Tags list is checked against the schema's cap of 50 on every provision,
since the tag operations an update reconciles through do not enforce it. The
integration test reads stack events with XmlParser.

* fix(cloudwatch): keep the dashboard rollback snapshot until the restore succeeds

A restore that throws left no snapshot behind, so the next rollback attempt
reported success without restoring anything. The snapshot is now spent only
after the body and tags are back.

* fix(cloudwatch): unwind a dashboard update that failed after it changed the body

An in-place update puts the body and then reconciles the tags. When the tag
calls failed, the exception left the dashboard carrying the new body while
CloudFormationService put the resource the stack held before the attempt back
in its place. That object never carried the snapshot taken by the attempt, so
the walker marked it restored and skipped rollbackUpdate: the stack reported a
completed rollback over a dashboard that still had the update's body, or a half
reconciled set of tags.

The mutating calls now unwind themselves through rollbackUpdate, the way
IotDomainConfigurationCfnProvisioner unwinds a replacement, and report the
resource restored. An unwind that cannot put the body back keeps the snapshot
and records the failure on the resource, so the stack ends in
UPDATE_ROLLBACK_FAILED rather than claiming the prior dashboard is intact, and
the original failure is still what the stack reports.

Tests: anInPlaceUpdateThatFailedOnItsTagsPutsTheBodyBack,
anUnwoundInPlaceUpdateIsMarkedRestored,
anUnwindThatCannotRestoreIsReportedAsARollbackFailure.

* fix(cloudwatch): record a dashboard unwind failure before joining it to the update failure

The unwind repeats the tag call the update just made, so a service that
keeps failing hands the unwind the very exception that interrupted the
update. Throwable.addSuppressed rejects a throwable suppressed under
itself, and that IllegalArgumentException escaped the unwind before the
rollback failure was recorded: the dispatcher reported "Self-suppression
not permitted" as the resource failure, no failure attribute reached the
stored resource, and the stack ended UPDATE_ROLLBACK_COMPLETE over a
dashboard whose tags were never put back.

The failure attribute is now written first and the two exceptions are
joined only when they differ, as PipesCfnProvisioner does. Two stack-level
tests drive the whole path through CloudFormationService with a spied
CloudWatchDashboardsService, the way CloudFormationPipesCleanupIntegrationTest
does: a one-off tag failure ends in UPDATE_ROLLBACK_COMPLETE with the prior
body and tags live, a persistent one in UPDATE_ROLLBACK_FAILED naming the
dashboard and carrying the unwind's reason.

Tests: anUnwindThatFailsWithTheUpdatesOwnExceptionIsStillRecorded,
anUpdateThatFailedOnItsTagsPutsTheDashboardBackAndTheStackRollsBackCleanly,
aFailedRestoreLeavesTheStackInUpdateRollbackFailedNamingTheDashboard.
2026-09-09 22:37:45 -05:00
Hector Ventura 895adce214 fix(cloudformation): provision CloudFront policies and origin access controls (#3228)
* fix(cloudformation): provision CloudFront policies and origin access controls

AWS::CloudFront::ResponseHeadersPolicy, CachePolicy, OriginRequestPolicy
and OriginAccessControl had no provisioner, so the dispatcher's stub arm
reported CREATE_COMPLETE with a synthetic id and a distribution that
referenced it failed with "The specified response headers policy does not
exist."

A new CloudFrontCfnProvisioner creates each type through CloudFrontService:
the physical id is the service id, Fn::GetAtt exposes Id and LastModifiedTime
(Id only for the origin access control, per the registry schemas), updates go
through the service's etag-guarded update, and deletes tolerate only the
type's own not-found code so an in-use policy fails the stack delete as on
AWS. The response headers configuration is reshaped into the flattened form
the service's codec stores through the new
ResponseHeadersPolicyConfigCodec.fromItemsTree.

Closes #2441

* fix(cloudfront): reject deleting a cache or origin request policy in use

DeleteCachePolicy declares CachePolicyInUse and DeleteOriginRequestPolicy
declares OriginRequestPolicyInUse, both 409 sender faults, and both are
documented as refusing the delete while the policy is attached to a cache
behavior. Floci checked only two of the four policy-shaped types:
deleteResponseHeadersPolicy and deleteOriginAccessControl raised their in-use
errors, while these two deleted unconditionally once the etag matched. A policy
still referenced by a distribution could be removed, leaving that distribution
pointing at something that no longer existed.

Both now raise the modeled error after the etag check, matching the ordering the
other two deletes already use. Cache, origin request and response headers
policies all hang off the same two places, a distribution's default cache
behavior and its ordered ones, so the three near-identical scans collapse into
one helper that differs only in which id it reads. The per-distribution
association count keeps its own entry point, since it asks about one config at a
time and can be handed a distribution with none.

Found while reviewing the CloudFormation provisioner in this PR, which was
already written for this: its delete tolerates only NoSuch<Type>, so it fails
the stack correctly now that the service raises the in-use error. The
CloudFormation integration test covers that end to end: it attaches both
policies to a distribution and still deletes the stack cleanly, because
CloudFormation removes the distribution before the policies it references.

Four tests: a cache policy attached to a default behavior and to an ordered one,
an origin request policy in use, and an unattached policy still deleting.

* test(cloudformation): parse stack outputs with XmlParser

The CloudFront policies integration test pulled Outputs out of the DescribeStacks
response with two regular expressions over <member> and <OutputValue> blocks.
XmlParser.extractPairs already does exactly this, and seventeen sibling
CloudFormation integration tests define the same one-line helper over it, so the
twelve-line version was reinventing a shared utility. It also matches the repo's
rule against parsing XML with regex.

Behaviour is unchanged, including the failure message that names the missing key.

* fix(cloudformation): roll back a recreated CloudFront policy on a failed update

When an update finds the prior policy or origin access control already deleted
out of band, the provisioner recreates it under a new physical id. If a later
resource then failed the stack update, the rollback left that new object behind:
the engine only deletes resources the update ADDED, inside the previous == null
branch of rollbackUpdatedResources, so an existing resource that merely acquired
a new physical id fell through to the "Rollback is not implemented" arm, which
deletes nothing.

ReplacementCleanup already models exactly this, and CognitoCfnProvisioner wires
it for the same situation, so the provisioner records the displaced entity after
each provision and delegates the cleanup hooks and rollbackUpdate to it. A
rollback now names the prior id again with the attributes it carried and deletes
the object the failed update created.

The physical id changes here only when the prior object was already gone, since
prior() returns the entity whenever the service still knows it, so the recorded
displaced entity is always one that no longer exists and its cleanup delete is a
no-op tolerated by the type's not-found code. The hooks are still needed, or a
recorded entity would stay owed a delete forever.

An in-place update keeps its physical id, so nothing is recorded and
rollbackUpdate answers false: putting a committed in-place change back needs a
configuration snapshot this provisioner does not keep, the same limitation
AWS::Cognito::UserPool has. A test pins that so it stays a decision.

Raised by the review on this PR. My first reply argued the finding did not hold,
generalising from the create path; that was wrong for this one, and the
correction is on the thread.
2026-09-09 09:32:52 -04:00
Sam Fakhreddine fd3c4d9ab6 feat(cloudtrail): support AdvancedEventSelectors and CloudFormation Trail provisioning (#2720)
* feat(cloudtrail): support AdvancedEventSelectors in PutEventSelectors and S3 capture

Adds AdvancedEventSelector/AdvancedFieldSelector models, JSON wiring
through PutEventSelectors/GetEventSelectors, mutual-exclusivity
enforcement against basic EventSelectors, and field-selector evaluation
(Equals/NotEquals/StartsWith/NotStartsWith/EndsWith/NotEndsWith) in the
S3 data-event capture path. Lets a trail exclude its own log-delivery
bucket via resources.ARN NotStartsWith, avoiding the CloudTrail
circular-logging cost problem. Basic-selector behavior is unchanged.

* feat(cloudtrail): add CloudFormation provisioner for AWS::CloudTrail::Trail

Handles create/update/delete of AWS::CloudTrail::Trail via
CloudTrailService, applies EventSelectors or AdvancedEventSelectors
(mutually exclusive, same JSON shapes as PutEventSelectors), starts
logging when IsLogging is true, and sets the trail ARN as the
resource's physical id and Arn attribute. Delete is idempotent when
the trail is already gone.

* feat(cloudtrail): implement ListTrails and trail tagging

Adds ListTrails (returns Name/TrailARN/HomeRegion for trails visible
in the region, including multi-region trails), plus AddTags/ListTags
backed by per-trail stored state, keyed by trail name or ARN.

* fix(cloudtrail): emit data events for the trail's own log deliveries

CloudTrailLogWriter.flushTrail() wrote delivered log files via a direct
S3Service.putObject() call, bypassing S3Controller.emitCloudTrailEvent()
- the only place that recorded an S3 data event. A trail whose selector
matched its own destination bucket (the exact circular-logging config
from upstream issue #1192 / PR #1194) never saw its own deliveries,
so the emulator could prove the dangerous config was live but not
reproduce the loop it causes.

flushTrail now calls cloudTrailService.emitS3DataEvent() after each
delivery, so internal writes are evaluated against selectors identically
to API-driven ones. Closes issues/0034.

* docs: mark issue 0034 fixed

* fix(cloudtrail): resources.type reflects actual S3 resource, not hardcoded object

Advanced selector matching hardcoded resources.type to AWS::S3::Object for
every event, so an object-scoped AdvancedEventSelectors exclusion (the
real-world fix for the issue 0034 self-delivery loop) still let bucket-level
calls like ListObjects through against the excluded bucket. Now derived per
event from whether an object key is present.

Live-verified on 1160-ct: loop confirmed unbounded and compounding with
external writes, then confirmed stopped by the real AdvancedEventSelectors
remediation, with this gap found and closed in the same pass. Details in
issues/0034 and issues/0035.

* docs(0034): add raw delivery-size timeline from 1160-ct verification

Per-cycle size data showing the burst-compounding and the fix-stop point
concretely, not just summarized.

* fix(cloudtrail): match delete() to current CfnResourceProvisioner signature

Upstream/main dropped the accountId parameter from
CfnResourceProvisioner.delete() since this branch was originally
authored; the provisioner never used accountId in its body, so the
fix is a straight signature match with no behavior change.

* docs(cloudtrail): regen action table and register CFN Trail resource type

New ListTrails/AddTags/ListTags actions and the CloudFormation
AWS::CloudTrail::Trail resource type need doc entries per the repo's
docs-check gate.

* fix(cloudtrail): enforce AddTags 200-tag list limit

Botocore's AddTagsRequest.TagsList models a 200-item max (service-2.json,
cloudtrail 2013-11-01); the handler accepted an unbounded list. RED test
added first (addTagsRejectsMoreThanTwoHundredTags), confirmed failing
(200 instead of 400), then fixed by rejecting oversized lists with
TagsLimitExceededException, matching AWS's modeled error for AddTags.

* fix(cloudformation): close two audit-control gaps in CloudTrailCfnProvisioner

Local code review flagged two HIGH findings in the new CFN provisioner:

- physicalId was only set after selector validation and startLogging
  succeeded, so a create that failed on the mutually-exclusive
  EventSelectors/AdvancedEventSelectors check left a real trail with no
  recorded physical id for the engine to clean up. Now set immediately
  after createTrail returns.
- update only called startLogging when IsLogging was explicitly true,
  never stopLogging when it was explicitly false, so a template setting
  IsLogging: false on a currently-logging trail silently left logging
  enabled.

RED tests confirmed both failures against the pre-fix code, then GREEN
after the fix (6/6 provisioner tests, 51/51 CloudTrail suite).

* docs(issues): ledger deferred CloudTrail local-review findings

MEDIUM/LOW findings from the local code-review pass, plus a few
inherited-not-ours items on code this branch didn't touch, that are
real but out of scope for the CFN provisioner / advanced-selectors PR.

* style(cloudtrail): brace unbraced conditionals in ListTrails and event-matching traversal

Per AGENTS.md style rule (always use braces in conditionals).

* fix(cloudtrail): avoid NPE on List.of(trailName) when TrailName is missing

PutEventSelectors/GetEventSelectors called List.of(trailName) with a
possibly-null trailName before findTrailOrThrow could validate it,
throwing an NPE (500 InternalFailure) instead of the modeled
TrailNotFoundException. Guard the lookup so the null flows through to
the existing validation.

* fix(cloudtrail): do not re-queue records on self-delivery emission failure

flushTrail wrapped the self-delivery emitS3DataEvent call in the same
try/catch as the S3 write. A failure there re-queued records that were
already durably written, causing the next flush to redeliver the same
batch. Split the write and the emission into separate try blocks so
only a write failure triggers requeue.

* docs(cloudformation): register AWS::CloudTrail::Trail in the resource-type inventory

CfnResourceInventoryTest and the docs-sync resource-type table both
derived from supported-resource-types.tsv, which never picked up
CloudTrailCfnProvisioner's registration.

* docs(issues): drop fork-local ledger files from the PR

Per maintainer review, the issues/ ledger entries are fork-local tracking notes and are kept out of the upstream contribution.

* fix(cloudformation): wire CloudTrailCfnProvisioner into CfnProvisionerFixture

CfnProvisionerFixtureTest.everyProvisionerIsReachableThroughThePublicBuilderOrExplicitlyExempt
failed because CloudTrailCfnProvisioner had no field, setter, or
construction arm in the test fixture, so a test naming CloudTrailService
would silently fall through to the stub arm instead of exercising the
real provisioner.

Add cloudTrailService field, cloudTrail(CloudTrailService) setter, and
the discovered.add(new CloudTrailCfnProvisioner(...)) construction arm,
mirroring the existing Route53Service wiring.

* fix(cloudtrail): drop em-dashes from new test comments per AGENTS.md style check

* fix(cloudtrail): reject mixed basic and advanced selectors with InvalidEventSelectorsException

PutEventSelectors does not model InvalidParameterCombinationException; the
error it declares for an invalid selector combination is
InvalidEventSelectorsException (botocore cloudtrail/2013-11-01). Both the
JSON handler and the AWS::CloudTrail::Trail provisioner now throw that
code, and the integration test pins it. Also braces the remaining
one-line conditionals in matchesAdvancedFieldSelector.
2026-09-08 19:38:13 -05:00
Mario Toffia af42564cb3 feat(lambda): provision AWS::Lambda::EventInvokeConfig (#3230)
* feat(lambda): provision AWS::Lambda::EventInvokeConfig

The physical id is the registry schema's composite FunctionName|Qualifier
identifier. A create puts the configuration, an update with the same identity
applies the template's settings through the merge-style update call, and a
changed function or qualifier is a replacement whose displaced configuration
the ReplacementCleanup record deletes once the update commits or restores on
rollback. The schema's MaximumRetryAttempts and MaximumEventAgeInSeconds
bounds are checked before any call, as CloudFormation validates them before
the handler runs.

The Lambda docs now list the five event invoke config operations, which the
page wrongly called not implemented, and say that asynchronous invocations do
not yet apply the settings.

* fix(lambda): update the event invoke config in place for equivalent names and roll back in-place changes

A short name and the function's ARN address one configuration, so an update
that changes between them updates in place under the prior physical id
instead of recording a replacement whose cleanup would delete that one
configuration. An in-place update keeps the settings it replaces on the
resource, and a failed stack update puts them back in full. DestinationConfig
is resolved before it is looked at, so a conditional that resolves to
AWS::NoValue is omitted rather than sent as an empty destination set. The
integration test reads stack events with XmlParser.

* fix(lambda): keep the event invoke config rollback snapshot until the restore succeeds

A restore that throws left no snapshot behind, so the next rollback attempt
reported success without restoring anything. The snapshot is now spent only
after the settings are back.
2026-09-08 07:34:52 -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
lex00 3a4982c294 feat(cloudformation): provision AWS::ApiGateway::UsagePlan and UsagePlanKey (#3123)
* feat(cloudformation): provision AWS::ApiGateway::UsagePlan and UsagePlanKey

Per-service provisioner over ApiGatewayService. A plan's Ref and Fn::GetAtt
Id are the plan id. Every plan property is mutable, so an update patches name
and description in place and adds or removes API stages as the template moves
them. Tags are driven to the template's desired state through the new
replaceUsagePlanTags.

A key's Ref and Fn::GetAtt Id are <keyId>:<usagePlanId>, as on AWS. All three
of its properties are createOnly, so a change to any of them is refused as a
replacement rather than re-associating a different key under the old id. The
composite id is what lets delete find the association without scanning every
plan.

Stack deletion removes the plan and the association and tolerates either
being gone already.

Ported from lex00/floci#118. Tracked in lex00/floci#192.

* fix(cloudformation): validate usage plan key properties and survive a recreated plan

An association only counts as still there while its plan does. deleteUsagePlan
leaves associations behind, and a plan recreated after an out-of-band delete has
a new id, so the stale association no longer reads the new UsagePlanId as a
rename. KeyType must be API_KEY and both ids must be present, per the registry
schema, and a non-list ApiStages is refused instead of read as empty.
replaceUsagePlanTags strips the reserved id-override tags the way createUsagePlan
does rather than refusing them.

* fix(cloudformation): check a usage plan key's KeyId even while recovering drift

The createOnly checks sat behind the association lookup, so a template that
changed KeyId while its plan was missing created an association for the new key
instead of refusing the change. KeyId is checked against the prior composite id
either way now. UsagePlanId stays conditional, since a plan recreated after an
out-of-band delete legitimately has a new id.
2026-09-06 22:09:54 -05:00
lex00 17af9590c7 feat(cloudformation): provision AWS::AutoScaling::ScalingPolicy (#3124)
* feat(cloudformation): provision AWS::AutoScaling::ScalingPolicy

Per-service provisioner over AutoScalingService. Ref and Fn::GetAtt Arn are
the policy ARN and Fn::GetAtt PolicyName the generated name, since the type
has no PolicyName property. PutScalingPolicy is an upsert keyed by group and
name, so an update reuses the name recorded at create time and rewrites the
policy in place. AutoScalingGroupName is createOnly, so moving the policy to
another group is refused as a replacement rather than left behind on the old
group. Omitted ScalingAdjustment and Cooldown take the Query handler's
defaults.

Ported from lex00/floci#118. Tracked in lex00/floci#192.

* fix(cloudformation): scope the scaling policy lookup to its group

Policy names are unique only within a group. The update path now looks for the
recorded name on the template's group first and treats a same-named policy on
another group as a move only when it is not there, so an unrelated group's
policy cannot block a valid update.

* fix(cloudformation): take a scaling policy's identity from its recorded group

Finding the recorded name on the group the template asks for read the
destination group's own same-named policy as this resource, so a move
overwrote that policy and orphaned the original. The group is recorded on the
resource at create time and compared directly instead, which drops both
DescribePolicies lookups. A resource provisioned before the attribute existed
has no prior group and keeps the previous behaviour.
2026-09-06 15:13:58 -05:00
lex00 cbde58f238 feat(cloudformation): provision AWS::ApiGateway::ApiKey (#3122)
* feat(cloudformation): provision AWS::ApiGateway::ApiKey

Per-service provisioner over ApiGatewayService. Ref and Fn::GetAtt APIKeyId
both yield the key id. Description, Enabled and Tags update in place. Name,
Value and GenerateDistinctId are createOnly, so a change to any of them is
refused as a replacement rather than applied to the existing key. A template
that omits Name keeps its generated name across updates instead of minting a
second key. Stack deletion deletes the key and tolerates one already gone.

ApiGatewayService gains replaceApiKeyTags so an update can drop a tag the
template no longer declares.

Ported from lex00/floci#118. Tracked in lex00/floci#192.

* fix(cloudformation): keep an API key's create-time reserved tags across updates

replaceApiKeyTags checked the whole desired map against the reserved list,
so a key created with a reserved floci tag could never change an ordinary tag
afterwards. Only a reserved tag that is new or changed is an update-time
override attempt and is refused now. Adds a test that dropping Description
from the template clears it on the key.
2026-09-06 15:12:50 -05:00
lex00 ba3dd657b6 feat(cloudformation): provision AWS::SNS::TopicPolicy (#3126)
Adds the type to SnsCfnProvisioner beside Topic and Subscription. A topic
policy is not an entity of its own: it writes the Policy attribute of every
topic the template lists, so re-applying on UpdateStack is what an update
means. The document goes through resolveJsonAttribute like FilterPolicy, so a
Ref to a topic inside Resource resolves to the ARN. The physical id is
synthetic and stays put across updates, as AWS::SQS::QueuePolicy does, and Ref
and Fn::GetAtt Id both return it. An empty Topics list or a missing
PolicyDocument is refused. Delete touches nothing, as with QueuePolicy.

Ported from lex00/floci#118. Tracked in lex00/floci#192.
2026-09-06 15:11:42 -05:00
Franklin G. Mendoza 41022d09fb feat(cloudformation): support service-managed stacksets (#3055)
* feat(cloudformation): support service-managed stacksets

* fix(cloudformation): restrict service-managed account targeting

* docs(cloudformation): sync resource type table

* fix(cloudformation): align service-managed stackset contracts

* test(cloudformation): isolate stackset organization fixture

* fix(cloudformation): preserve stackset update handling after rebase

* fix(cloudformation): preserve stackset OU deletion targets

* fix(cloudformation): preserve overlapping stackset targets

* fix(cloudformation): reconcile stackset deployment targets
2026-09-06 13:59:54 -05:00
Mario Toffia dec348d382 feat(iot): provision AWS::IoT::Thing, Policy and TopicRule (#3014)
* feat(iot): provision AWS::IoT::Thing, Policy and TopicRule

CloudFormation now creates, updates and deletes things, policies and
topic rules through the existing IoT operations. Ref returns the name;
Fn::GetAtt returns the thing ARN and id, the policy ARN and id (the
name, as on AWS) and the rule ARN. Attribute payloads are replaced in
place, a changed policy document becomes a new default version, a rule
is replaced in place, and a rename replaces the entity. The topic rule
payload is handed to the service in the API's own shape. A policy is
detached from its principals before it is deleted.

* test(iot): keep policy variables verbatim in a stack-created policy

* fix(iot): cap a policy at five versions and prune the oldest on a stack update

CreatePolicyVersion refuses a sixth version with VersionsLimitExceededException (HTTP 409), as AWS does, and every policy version write runs under one lock so racing creates cannot slip past the check. A stack update with a changed document now does what the AWS CloudFormation handler does when the service refuses: it deletes the oldest version, after moving the default to the newest when the oldest is the default, and creates the new version again. Before this change the versions of a policy updated by a stack piled up without limit.

* fix(iot): keep pruning when another version fills the slot before the retry

The prune and the retry are separate calls, so another client could create a version between them and the single retry failed the stack update. The provisioner now prunes and tries again, up to as many times as a policy has versions, before it gives up.

* fix(iot): delete the oldest policy version in one step under the version lock

A stack update pruning a full policy selected the oldest version, moved the default and deleted it in separate service calls, so a direct client could delete or promote that version in between and the stale delete failed the update. The selection, the default move and the delete are now one step in IotService under the version lock; the provisioner only asks for it and retries.

* fix(iot): make room for a policy version in one step and lock the policy delete

A policy persisted before the cap can hold more than five versions, and the one-version prune then needed one failed stack update per four surplus versions. The service now deletes the oldest versions until one more fits, in one step under the lock, and the provisioner asks for that. DeletePolicy takes the same lock: a version created in the middle of a delete used to put the policy back after the delete had returned. The limit error now carries the message AWS sends, and the tolerated limit error is logged at debug level.

* docs(cloudformation): regenerate the resource-type table after the rebase onto main
2026-09-06 11:06:47 -04: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
Mario Toffia 3600038a3f fix(ssm): set the Arn attribute on AWS::SSM::Parameter (#3019)
The registry schema lists Arn as the type's only read-only property,
but the provisioner never set it, so Fn::GetAtt [Param, Arn] resolved
to the literal "Param.Arn" and CfnSchemaCoverageTest fails on main
once the schema corpus is present.

The ARN uses AWS's parameter/<name> form: a name without a leading
slash gets one inserted, a name with one is not doubled.
2026-09-04 01:09:19 -05: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 f3c251ef20 feat(cognito): provision AWS::Cognito::UserPoolDomain (#3005)
* feat(cognito): provision AWS::Cognito::UserPoolDomain

The type was a stub: the stack turned green, but Fn::GetAtt
CloudFrontDistribution resolved to the literal
LogicalId.CloudFrontDistribution, so a Route 53 alias record for a
custom domain pointed at that text.

CognitoCfnProvisioner creates the domain through the existing
CreateUserPoolDomain. Ref is the domain name and CloudFrontDistribution
is the CloudFront name DescribeUserPoolDomain reports. A changed Domain
or UserPoolId replaces the domain; any other change is applied in place
through the new UpdateUserPoolDomain operation, so the distribution a
DNS alias points at survives a certificate change, as on AWS. Delete
uses the pool id recorded at create time and tolerates an already
deleted domain.

UpdateUserPoolDomain is also exposed on the Cognito API, with the same
response shape as CreateUserPoolDomain.

* feat(cognito): treat null domain settings as absent and pin the same-name replacement failure

Review follow-ups for AWS::Cognito::UserPoolDomain:

- A JSON null inside CustomDomainConfig was copied as the text "null",
  which would have passed for a certificate ARN. Null values are now
  skipped, so the service rejects the missing ARN as it should.
- ManagedLoginVersion on CreateUserPoolDomain and UpdateUserPoolDomain
  treated an explicit null as 0, overwriting the stored version. Null
  now counts as omitted, and a value of another JSON type is a
  SerializationException, as on AWS.
- Moving an unchanged domain to another pool fails on the create,
  because domain names are unique across pools and the replacement is
  created before the original is deleted, exactly as on AWS. The unit
  test that mocked this path as a success is replaced by one that pins
  the failure and checks the original domain is left in place.

* test(cognito): cover domain replacement, prefix domains and SecurityPolicy updates

The stack test now also renames the domain through UpdateStack, asserting the old domain is gone and the new one has its own distribution, and a second stack proves a prefix domain resolves Fn::GetAtt CloudFrontDistribution to an empty string rather than the literal attribute name. The service test covers a SecurityPolicy change and that an omitted policy is kept. The in-place check reads ctx.reusesPriorEntity(domain), as the sibling provisioners do.

* test(cognito): provision the stack test's certificate through AWS::CertificateManager::Certificate

With the ACM provisioner merged, the stack test now declares the certificate as a resource and references it with Fn::GetAtt, the way CDK does. Rotating to a new certificate resource updates the domain in place and removes the old certificate once nothing references it. A wildcard name keeps a domain rename from replacing the certificate.
2026-09-04 00:55:19 -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
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
Facundo Paredes 5dc0808bda feat(cloudformation): report a stubbed unsupported resource type instead of hiding it (#2971)
An unsupported resource type was stubbed at debug, so the stack reached CREATE_COMPLETE and a green stack did not prove its resources existed.

The stub is now reported at warn, naming the type, and the resource carries a status reason saying nothing was created, which DescribeStackEvents returns. A new floci.services.cloudformation.allow-stub-unsupported-resource-types setting (default true) turns the stub into a stack failure for suites that need a green stack to mean every resource exists. An unexpanded SAM resource type warns on its own, and the delete path names the physical id it does not remove.

Closes #2967
2026-09-02 20:22:49 -05:00
Facundo ParedesandFacundo Paredes 77b4881fe4 fix(cloudformation): merge Fn::Transform AWS::Include before provisioning, and honour GetTemplate TemplateStage (#2886)
* test(cloudformation): pin Fn::Transform AWS::Include merging against the deployed template

The expected values come from a deployed stack's original and processed templates,
read with get-template, and from get-template-summary probes against real AWS.
Every assertion states its expected value as a literal, including the spliced
multi-line Fn::Sub value with its line breaks intact.

* fix(cloudformation): merge Fn::Transform AWS::Include before provisioning

The template engine evaluated ten intrinsics and Fn::Transform was not among them,
so an AWS::Include node was neither expanded nor rejected: it reached provisioning
as an ordinary key. A state machine whose DefinitionSubstitutions came from a
snippet therefore reached CreateStateMachine with a key literally named
Fn::Transform and without any of the snippet's keys, leaving every ${placeholder}
unsubstituted in the stored definition. The stack still reported CREATE_COMPLETE.

Measured against a deployed stack: 41 Fn::Transform nodes in the original template,
all Name AWS::Include, all with the same s3:// Location, all at
Resources.<id>.Properties.DefinitionSubstitutions; 0 in the processed template. At
one of those positions the six sibling keys keep their original order and the five
snippet keys are appended after them, and the spliced multi-line Fn::Sub value keeps
its line breaks: nothing is folded or re-serialized.

Three controlled get-template-summary probes settle the summary contract. A template
with no transform reports DeclaredTransforms null and its ResourceTypes; the same
template with an embedded Fn::Transform, and one with a top-level Transform, both
report DeclaredTransforms AWS::Include. GetTemplate keeps returning the body as
submitted, matching AWS's TemplateStage=Original default, while the change-set
baseline uses the merged body so a byte-identical resubmission reports no change.

* test(cloudformation): pin Fn::Transform AWS::Include rejection when Parameters is absent entirely

* test(cloudformation): pin Fn::Transform AWS::Include rejection when Location is present but blank

* fix(cloudformation): name the Fn::Transform node when AWS::Include Parameters is absent or Location is blank

* test(cfn-transform): pin AWS::Include Location error message for blank and null-Parameters shapes

Renames the existing empty-string test to name the shape it actually feeds,
adds coverage for a whitespace-only Location (which today leaks its raw
value with no quoting) and for an explicit null Parameters (which already
renders the Fn::Transform node, with no test pinning that literal).

* fix(cfn-transform): reject whitespace-only Location and stop leaking non-object Parameters

describeLocation checked isEmpty() where its own javadoc promised blank, so a
whitespace-only Location leaked its raw unquoted value into the rejection
message instead of a quoted string. It also enumerated missing and null as
the only non-mapping Parameters shapes, so a scalar or a list Parameters fell
through to Location's MissingNode and the message rendered Parameters itself
as if it were the rejected Location. Both guards now ask a single question
each: isBlank() for the Location text, and isObject() for the Parameters
shape, dropping the OR out of the second guard.

* test(cfn-transform): pin AWS::Include Location error message for scalar and list Parameters

Closes the coverage gap for defect 2: before the isObject() guard, a scalar
or list Parameters fell through to Location's MissingNode and the rejection
message rendered Parameters itself as if it were the Location, which a
reader could mistake for a valid rejected URI. Both templates go red against
the pre-hunk isMissingNode()||isNull() guard and green against isObject().

* test(cloudformation): pin GetTemplate TemplateStage selecting Processed vs Original

Processed must return the SAM-expanded, AWS::Include-merged body with no
AWS::Serverless::Function or Fn::Transform node left; Original and the
no-stage default must return the caller's raw YAML byte for byte; an
invalid stage must reject with the AWS enum ValidationError; and a plain
stack with no transform must return identical bodies for both stages and
advertise StagesAvailable on every GetTemplate call.

* fix(cloudformation): honor GetTemplate TemplateStage instead of always returning Original

GetTemplate accepted no TemplateStage, so a caller asking for Processed was
silently answered with Original. It now validates the parameter against
AWS's Original/Processed enum, returns stack.templateBody (the SAM- and
AWS::Include-merged body) for Processed and stack.originalTemplateBody
(the caller's raw submission, also the default) otherwise, and reports
StagesAvailable on every response, matching real AWS.

* test(cloudformation): pin GetTemplate TemplateStage validation ordering and empty-string rejection

Pins two AWS-measured behaviors GetTemplate does not have yet: TemplateStage
Bogus is rejected with the enum ValidationError even when the named stack was
never created, proving AWS validates the request shape before the stack
lookup; and TemplateStage="" (present but empty) is rejected the same as any
other value outside the enum, distinct from the omitted case which defaults
to Original.

* fix(cloudformation): validate GetTemplate TemplateStage before the stack lookup and reject an empty value

Two ordering and parsing gaps measured against a real account: an invalid
TemplateStage was rejected with "Stack ... does not exist" instead of the
enum ValidationError when the stack was absent, because the lookup ran
first; and TemplateStage="" (present but empty) was silently accepted as
Original instead of rejected, because isBlank() treated it the same as the
omitted case. Both are hoisted/tightened to match AWS. The two stage names
are also named once as constants instead of retyped across the enum list,
the StagesAvailable list, the stage-selection check and the default, and the
rollback comment and docs are rewritten to describe today's two-stage
behavior instead of the pre-TemplateStage one.

* docs(cloudformation): correct GetTemplate Processed-stage claim, drop a self-evident comment

The GetTemplate doc claimed AWS::LanguageExtensions, a third-party macro, and the
top-level Transform AWS::Include short form always leave Processed unexpanded.
SamTransformProcessor removes the whole Transform section unconditionally when the
template also declares the SAM transform, so any of those three shapes co-declared
with SAM is gone from Processed too; the sentence now states that condition.

Also drops the block comment above STAGE_PROCESSED/STAGE_ORIGINAL: it restated what
the constant names already show.

* docs(cloudformation): drop the CAPABILITY_AUTO_EXPAND deviation, measured as parity

A CreateChangeSet carrying an embedded Fn::Transform/AWS::Include was
accepted against a real account with CAPABILITY_IAM alone, so requiring
no capability for AWS::Include matches AWS rather than deviating from
it. The known-deviation count drops from three to two, and the
unmeasured CreateStack path is named as unmeasured.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-09-01 23:05:26 -05:00
Olamide Kosile 961d82dda9 fix(cloudformation): provision AWS::Scheduler::ScheduleGroup (#2796) 2026-09-01 21:26:02 -05: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
Sam Fakhreddine 8a705d0aae feat(cloudformation): provision WAFv2 web ACLs and AWS Config rules (#2701)
* feat: provision WAFv2 web ACLs

* feat: provision AWS Config rules

* fix: adapt provisioners to current 3-arg CfnResourceProvisioner.delete()

* fix: preserve new-resource tracking when replacement cleanup fails, and stop dropping inline-object InputParameters

Local code review (review-local.ts) flagged two ordering bugs on the replacement
path in both provisioners: the new resource's physicalId/attributes were only
recorded after the old resource's delete call succeeded, so a delete failure
(e.g. WAFAssociatedItemException, or a Config rule still referenced elsewhere)
left the stack tracking the old resource while the newly created one leaked
untracked. Both now record the new resource first and treat old-resource
cleanup failure as non-fatal, matching the existing precedent in
Ec2LaunchTemplateCfnProvisioner.

Also fixed AWS::Config::ConfigRule.InputParameters being silently dropped
when a template supplies it as an inline JSON object (the common case) rather
than a pre-stringified JSON string: JsonNode.asText() returns empty string
for object nodes.

* fix(cloudformation): preserve intrinsic-resolved JSON fields on WAFv2 WebACL, log tolerated replacement-cleanup failures, add GetAtt coverage

raw() in WafV2CfnProvisioner used JsonNode#isEmpty(), which is true for every
scalar node, so any field CloudFormationTemplateEngine#resolveNode collapsed
into a TextNode (e.g. an Fn::Join-built DefaultAction) silently became null
instead of the literal JSON text. Mirror ConfigCfnProvisioner's existing
isTextual()-aware handling.

Also log (previously fully swallowed) exceptions when replacement cleanup of
the superseded WAFv2 WebACL or Config rule fails, so a leaked old resource is
diagnosable, and add an integration test asserting the exact Fn::GetAtt keys
for both provisioners resolve through CloudFormation to the real resource.

Config's PutConfigRule call being unconditional on every provision is correct
AWS upsert semantics ("Adds or updates" per the Config API), not a missing
create/update branch.
2026-08-29 15:28:23 -04:00