Commit Graph
456 Commits
Author SHA1 Message Date
Aniket Shukla c30ca8fb5f fix(cognito): name missing user pools in errors (#2936)
* fix(cognito): name missing user pools in errors

* test(cognito): address missing pool review
2026-09-03 00:12:14 -04:00
Vũ Thế Huy 14ca62d9f7 feat(ecs): honor UpdateService forceNewDeployment and emit EventBridge lifecycle events (#2938)
* feat(ecs): honor UpdateService forceNewDeployment (#2557)

* feat(ecs): add EcsEventPublisher for aws.ecs lifecycle events (#2557)

* feat(ecs): emit ECS Task State Change events on task start/stop (#2557)

* feat(ecs): emit ECS Deployment State Change events (#2557)

* test(ecs): end-to-end ECS EventBridge lifecycle events + docs (#2557)

* fix(ecs): log diagnostic when task ARN region parse fails (#2557)

* fix(ecs): synthesize lifecycle events from a task snapshot, not the shared instance

emitTaskLadder toggled the live task's lastStatus in place to synthesize
each phase, so a concurrent DescribeTasks/ListTasks could observe a
status the task never actually occupied while the four-phase ladder
was in flight. Build the ladder from a shallow copy instead.

Also bump the ARN region-parse fallback log from debug to warn, since
debug is off by default and made the fallback effectively invisible.
2026-09-02 23:09:37 -04:00
Kenshin Okinaka 812911fd03 feat(ses): support tag operations on tenant ARNs (#2832)
* feat(ses): support tag operations on tenant ARNs

* fix(ses): shield the stored tenant record from tag-callback mutation

* test(ses): cover the cross-region guard for tenant TagResource/UntagResource

* docs(ses): drop em dashes from the tenant tag additions
2026-09-02 22:14:39 -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
Scott Steen 44655751c6 feat(bedrock-runtime): implement ConverseStream for stub and proxy backends (#2889)
Both backends now emit the real application/vnd.amazon.eventstream framing
Bedrock SDK clients expect: a messageStart/contentBlockDelta/contentBlockStop/
messageStop/metadata event sequence, framed with the same AwsEventStreamEncoder
helper already used by S3 Select and Kinesis SubscribeToShard.

The proxy backend posts to /chat/completions with stream:true (matching
Converse) and translates the OpenAI SSE response into Bedrock stream events,
including basic tool-call accumulation. A response - streaming or not - that
never produces real completion content surfaces as a ModelErrorException
instead of a fabricated empty success:

- ConverseStream: no usable SSE chunks, chunks that only carry role/usage/
  finish_reason with no text or tool_calls, a stream that ends without a
  finish_reason or "[DONE]" (truncated mid-generation), or a tool_calls
  fragment missing its id/name or with arguments that never form valid JSON.
- Converse: a 2xx response with no choices at all.
2026-09-02 19:55:40 -05:00
Sam Fakhreddine 279f2776b7 docs: fix port ranges, OpenSearch default image and quick-start snippets (#2690)
Corrects the documented port ranges, the OpenSearch default image tag, the quick-start snippets and a duplicate CloudTrail nav entry so the docs match application.yml and EmulatorConfig.
2026-09-02 19:19:38 -05:00
Simone Primarosa 309043baf6 fix(eks): validate IAM authentication tokens (#2912)
Reject forged, expired, and cross-cluster EKS authentication tokens before granting cluster-admin access.
2026-09-02 19:37:26 -04:00
Priamo Germosen 671628b525 feat(cloudtrail): implement AddTags, RemoveTags and ListTags (#2934)
* feat(cloudtrail): implement AddTags, RemoveTags and ListTags

CloudTrailJsonHandler dispatched none of the three tag actions, so any
trail lookup went through the unsupported-action path — including the
Terraform AWS provider's transparent-tagging ListTags call on every read
of aws_cloudtrail, which broke refresh/plan/destroy for any state
containing a trail regardless of whether it was tagged.

Tags are tracked per-trail in CloudTrailEntry (not the wire-serialized
Trail record, which AWS never includes tags on) and are resolved by ARN
only, matching AWS's actual request shape for these three actions. An
ARN that isn't a well-formed CloudTrail trail ARN raises
CloudTrailARNInvalidException; a well-formed ARN with no matching trail
raises ResourceNotFoundException, so a stale Terraform state entry
surfaces as a real error instead of an empty tag list.

Fixes floci-io/floci#2297

* fix(cloudtrail): omit Value from ListTags response for valueless tags

AddTags only requires Key, so a tag can legitimately have no Value.
listTags() was serializing that as an explicit "Value":null, but AWS
omits absent optionals from the response entirely.
2026-09-02 17:29:03 -05:00
Christian Franzen 39b19d1c92 refactor(config): move max-request-size and ecr-base-uri into sub-mappings (#2902)
floci.max-request-size and floci.ecr-base-uri sat at the config root but
belong with related settings. Relocate them:

- max-request-size -> floci.protocols.max-request-size (ProtocolsConfig)
- ecr-base-uri      -> floci.services.lambda.ecr-base-uri (LambdaServiceConfig)

A new FlociConfigRelocationsInterceptor (SmallRye ConfigSourceInterceptor,
registered via META-INF/services) keeps the old flat keys and their
FLOCI_MAX_REQUEST_SIZE / FLOCI_ECR_BASE_URI env vars working: the legacy key
is consulted when the new key is requested, and iterateNames() rewrites it so
config-mapping validation does not flag it as unknown. Future relocations are
one entry in its RELOCATIONS list.

ImageResolver, both application.yml files, the affected tests and the
configuration docs are updated to the new keys.
2026-09-02 18:14:55 -04:00
Brian Taylor 0a3bc030f6 feat(cognito): implement identity provider configuration CRUD (#2858)
* feat(cognito): implement identity provider configuration CRUD

CreateIdentityProvider, DescribeIdentityProvider, ListIdentityProviders,
UpdateIdentityProvider and DeleteIdentityProvider were unsupported, so
infrastructure tooling could not manage a user pool's federated providers.

Stores provider configuration alongside the other user pool sub-resources and
matches the response and update semantics measured against the live API:

- IdpIdentifiers is echoed by create and update only when the request supplied
  the member, whatever the stored value; describe always returns it
- AttributeMapping defaults to username -> sub when the member is absent at
  create, while an explicitly empty map is stored as given
- members a request omits are preserved rather than cleared
- a duplicate provider name raises DuplicateProviderException
- ListIdentityProviders returns name/type/date summaries, never ProviderDetails

Federated sign-in itself is out of scope: Floci has no /oauth2/authorize or
/oauth2/idpresponse endpoint, so providers are stored configuration only.

* test(cognito): match identity provider exceptions on the SDK error name

`rejects.toThrow(/re/)` matches the error message, but the JS SDK maps the wire
`__type` onto `error.name` and puts the AWS text in `message`, so the duplicate
provider assertion never matched. Assert the name, and pin the enum text with
an explicit message matcher.

* fix(cognito): delete a pool's identity providers with the pool, and update a copy

Two review findings, both reproduced first.

DeleteUserPool left provider records behind. A pool recreated on a pinned id
(`floci:override-id`) then inherited the dead pool's providers, ProviderDetails
client_secret included. Pool deletion now removes them the way it already
removes groups.

UpdateIdentityProvider mutated the instance the store handed back, so two
concurrent updates could interleave into a state matching neither request. It
now writes a copy, which makes the losing update simply lose — what AWS does.

* fix(cognito): serialise identity provider mutations

UpdateIdentityProvider is a read-modify-write: it copies the stored provider,
applies only the members the request supplied and writes the whole record back.
Two overlapping updates copied the same base, so the later write restored the
other's omitted members to their stale values and silently dropped an update.

Live Cognito merges omitted members rather than clearing them, and applies that
merge atomically, so both updates survive there. One lock now guards every
mutating path, since create (check-then-put) and delete (check-then-act) carry
the same race, matching the existing identityLinkLock idiom.

The regression test runs two writers touching different optional members across
25 rounds; it fails on the first round with the lock reverted.

* fix(cognito): guard the pool deletion provider cascade with the same lock

DeleteUserPool clears a pool's identity providers outside identityProviderLock,
so a create or update interleaving with the cascade could reinstate a provider
for a pool that is going away. It now takes the same lock as the mutations it
races, closing the last unguarded path in that set.

* fix(cognito): recheck the pool under the lock when creating a provider

CreateIdentityProvider validated the pool before taking identityProviderLock and
never rechecked it, so a DeleteUserPool whose cascade ran in between left the
create writing a provider for a pool that no longer exists. It now reasserts the
pool inside the lock, immediately before the duplicate check and the write.

UpdateIdentityProvider needs no equivalent: the cascade deletes the provider, so
its own lookup throws ResourceNotFoundException. The outer validation stays where
it is to keep error ordering unchanged for ordinary single-request calls.
2026-09-02 12:00:26 -04:00
Brian Taylor 1e4e8b9ee8 feat(cognito): implement managed login branding (#2869)
* feat(cognito): implement managed login branding

CreateManagedLoginBranding, DescribeManagedLoginBranding,
DescribeManagedLoginBrandingByClient, UpdateManagedLoginBranding and
DeleteManagedLoginBranding were unsupported, so a config declaring
`aws_cognito_managed_login_branding` could not be applied against Floci.

A branding belongs to one app client and is stored on it. Behaviour matches what
the live API does:

- a second branding for the same client raises ManagedLoginBrandingExistsException
- ManagedLoginBrandingId must be a version 4 UUID, checked before the lookup
- Settings is omitted from the response when the caller supplied none, while
  Assets is always returned
- members an update omits are left unchanged

Settings is stored opaquely rather than validated against AWS's unpublished
schema, and ReturnMergedResources does not merge Cognito's default corpus.

Closes #2856

* fix(cognito): reject malformed CreateManagedLoginBranding members

Create coerced an absent UseCognitoProvidedValues to false and silently ignored a
wrongly typed Settings or Assets, so a malformed request produced persisted state.

Measured against AWS:

  neither UseCognitoProvidedValues nor Settings -> InvalidParameterException:
      useCognitoProvidedValues or settings should be specified (but not both)
  Assets of the wrong type   -> SerializationException: Unexpected field type
  UseCognitoProvidedValues of the wrong type -> accepted, not rejected

Create now enforces the first rule and type-checks Settings and Assets. A
non-boolean UseCognitoProvidedValues is still accepted, because AWS accepts it.

AWS answers a wrongly typed Settings with a 500 InternalErrorException; Floci
returns the same client error it returns for Assets rather than reproducing that,
and the divergence is documented.

* fix(cognito): check Assets elements before converting them

The Assets reader validated only the outer array, so a scalar element reached
Jackson's convertValue and escaped as a 500 InternalFailure. This is the same
class of bug as the LogConfigurations one, which I fixed in that reader without
applying it here.

AWS separates the two failures, and they differ from the LogConfigurations rules:

  [1, 2] / ["str"] -> SerializationException: Unexpected value type in payload
  [null]           -> InvalidParameterException: 1 validation error detected:
                      Value '[null]' at 'assets' failed to satisfy constraint:
                      Member must satisfy constraint: [Member must not be null]

A null element is rejected here, where LogConfigurations drops it.

* fix(cognito): match AWS branding source validation

A managed login branding request must select exactly one source of branding,
and the same rule governs create and update. Measured against Cognito in
ap-southeast-1:

  useCognitoProvidedValues  settings   result
  absent                    absent     InvalidParameterException
  true                      absent     accepted
  false                     absent     InvalidParameterException
  absent                    present    accepted
  true                      present    InvalidParameterException
  false                     present    accepted

Create rejected only the neither case, update validated nothing at all, so
naming both members and updating with no source both succeeded where the
service rejects them. Presence of the member is not the test: false selects no
source, which is why it needs settings alongside it.

Reading the flag had to move with it. AWS coerces a JSON string rather than
rejecting it, storing true for "true" and for "yes" and false for "false",
while Jackson maps every string except "true" to false. That turned "yes" into
a request selecting no source, so the coercion now follows the service.

* fix(cognito): reject malformed UseCognitoProvidedValues types

Jackson's asBoolean() maps a number, a JSON null, an object and an array all to
false, so a malformed flag alongside valid Settings passed source validation and
persisted as branding state that was never requested.

Measured against Cognito in ap-southeast-1: 1, null, {} and [] are each a
SerializationException, with or without Settings, while omitting the member is
accepted and stores false. Only booleans and strings are read now, strings still
coerced the way the service coerces them, and everything else raises
SerializationException the way SesController already does.

* fix(cognito): bound managed login branding assets at 40

Neither create nor update checked the documented 40-item maximum on Assets, so
an oversized request was accepted and stored where AWS rejects it.

Measured against Cognito in ap-southeast-1:

  create 40 assets            passes the bound, reaches the source rule
  create 41 assets            InvalidParameterException, length constraint
  create 41 + unknown client  the length error, not the missing client
  update 41 + malformed id    2 validation errors, the length one first
  update malformed id alone   1 validation error, before the pool lookup

The asset and branding-id checks now run before anything is looked up and
share one message, matching those last three rows. DescribeManagedLoginBranding
ran its pool lookup ahead of the branding-id check, which the fourth row shows
is the wrong way round, so it moved with them.

The length message embeds the request model's toString. The blob renders as the
decoded buffer, confirmed at three payload sizes; the decoder used here is the
lenient one so that building a rejection cannot itself fail.
2026-09-02 11:50:47 -04:00
Brian Taylor b8f1e22c74 feat(cognito): implement log delivery configuration (#2867)
* feat(cognito): implement log delivery configuration

SetLogDeliveryConfiguration and GetLogDeliveryConfiguration were unsupported, so a
config declaring `aws_cognito_log_delivery_configuration` could not be applied
against Floci.

The configuration is stored on the user pool and validated the way the live API
validates it:

- LogLevel accepts ERROR or INFO, EventSource accepts userNotification or
  userAuthEvents, both reported with AWS's 1-based member path
- every entry must name a CloudWatch, Firehose or S3 destination
- Set replaces the list rather than merging, so an empty list clears it
- Get always returns LogConfigurations, as [] when nothing is configured

Floci stores the configuration and delivers nothing: the destination is neither
written to nor required to exist, and the pricing-tier gate AWS applies to
userAuthEvents is not reproduced.

Closes #2855

* fix(cognito): reject a null LogConfigurations instead of clearing the configuration

SetLogDeliveryConfiguration treated an omitted, null or wrongly typed
LogConfigurations as an empty replacement, so a malformed request returned 200
and erased the pool's stored configuration.

AWS rejects all three. An omitted or null member fails validation, and a value of
the wrong JSON type fails deserialization:

  omitted / null -> InvalidParameterException: 1 validation error detected: Value
                    null at 'logConfigurations' failed to satisfy constraint:
                    Member must not be null
  wrong type     -> SerializationException: Expected list or null

Also drops two em-dashes from the docs, per AGENTS.md.

* fix(cognito): translate malformed LogConfigurations elements the way AWS does

A scalar inside the array reached Jackson's convertValue directly, so an
IllegalArgumentException escaped as a 500 InternalFailure instead of a client
error, and a null element would have failed on the validation loop.

AWS answers both without a 500:

  [1, 2] / ["a string"] -> SerializationException: Expected null
  [null]                -> 200, the null element is dropped

Elements are now checked before conversion: nulls are skipped and non-objects
raise SerializationException.

* fix(cognito): bound LogConfigurations and reject a repeated event source

SetLogDeliveryConfiguration validated each element but never checked the list
itself, so a request with three or more well-formed configurations, or two
naming the same event source, was accepted and stored where AWS rejects it.

Measured against Cognito in ap-southeast-1:

  3 well-formed configs   InvalidParameterException, length constraint on
                          'logConfigurations', max 2
  2 duplicate sources     InvalidParameterException, "appear more then once"
  3 configs, one bad enum 2 validation errors, the length one reported first
  unknown pool, bad enum  the validation error, not ResourceNotFoundException
  0 configs               200 OK

The shape checks now run before the pool lookup, matching that last row, and
collect every violation into one message instead of throwing on the first.
The duplicate and missing-destination complaints share one message with the
missing-destination clause first, and each event source is named once however
many configurations carry it, as measured.

"more then once" is the service's own spelling, kept so the message matches.

The length message embeds the request model's toString, which the emulator now
reproduces for all three destination shapes and for an absent destination.
2026-09-02 11:44:18 -04:00
NAMAN JAIN de6bf8f599 feat(glue): jobs and crawlers (#2591)
* feat(glue): implement CRUD operations for Jobs and Crawlers

* fix(glue): resolve edge cases in jobs, crawlers, and tagging implementation

- Fix DynamoDBTarget ScanAll/ScanRate JsonProperty casing
- Support MaxResults and NextToken pagination in GetJobs and GetCrawlers
- Throw EntityNotFoundException for unknown Job/Crawler deletions
- Retain existing configuration values during Crawler updates
- Use centralized ResourceGroupsTaggingService for non-schema TagResource/UntagResource/GetTags actions

* test(glue): add CRUD, pagination, and tagging tests for Jobs and Crawlers

* fix(glue): validate pagination limits and ARN existence for tagging

* fix(glue): enforce AWS-compliant validation, semantics, and responses

- Add required field validation to Job and Crawler CRUD operations.

- Persist SourceControlDetails and ProfileName across Job updates.

- Set default State (READY) and Version for Crawlers on creation.

- Standardize empty-body responses to bare Response.ok() per AWS specs.

- Add handler-level integration tests for request payload parsing.

- Refactor GlueServiceTest to use valid mock objects and standard imports.

* fix(glue): add missing ARN validation for databases, tables, and UDFs

- Restore EntityNotFoundException when attempting to tag nonexistent Databases, Tables, or UserDefinedFunctions.

- Expand tagging tests to verify behavior for these resources.

* chore(glue): apply AWS defaults for Job creation and remove unused Crawler DTOs

- Apply default GlueVersion (5.1) and Timeout (480/2880 based on version) for newly created Jobs.

- Remove empty Create/Update/DeleteCrawlerResponse models since they are unused.

* fix(glue): throw EntityNotFoundException for unmodeled resource ARNs

- Prevent validateResourceExists from silently passing when an ARN type isn't supported (e.g. connections).

- Any ARN not matching jobs, crawlers, databases, tables, or UDFs now throws.
2026-09-02 11:39:10 -04:00
TATSUNO “Taz” Yasuhiro fad54f3c7a fix(stepfunctions): fail an intrinsic argument that matches nothing (#2872)
* fix(stepfunctions): fail an intrinsic argument that matches nothing

States.Format('{}', $.nope) resolved to null and the state succeeded. Real AWS
fails it with States.Runtime and names the whole expression. An index past the
end of an array is a miss here, where the same path written directly resolves
to null.

Closes #2870

* docs(stepfunctions): drop the States.Format template gap note

The gap is not fixed or caused by this change, so it is tracked on its
own issue instead of riding along in this pull request.

* test(stepfunctions): point the format template gap at issue #2927
2026-09-02 10:31:20 -04: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
Priamo Germosen 3b7ba5c687 feat(batch): add UpdateComputeEnvironment and DeleteComputeEnvironment (#2857)
Mirrors the existing UpdateJobQueue/DeleteJobQueue pair. DeleteComputeEnvironment
requires DISABLED state and rejects deletion while still referenced by a job
queue's computeEnvironmentOrder, matching AWS; updating computeResources is a
partial merge (only the sent fields change), not a full replace. Both
UpdateComputeEnvironment and CreateComputeEnvironment now validate state is
ENABLED or DISABLED, so an invalid value can never be persisted and later
block deletion.

CloudFormation stack-delete wiring for AWS::Batch::ComputeEnvironment/
JobQueue/JobDefinition (currently a silent no-op on stack teardown) is left
for a follow-up that migrates all of Batch's CFN handling into a per-service
provisioner, rather than adding more cases to the legacy switch.

Closes #2293, closes #2803.
2026-09-01 18:06:57 -05:00
Allen Sanborn 906af8c632 feat(ec2): support standalone network interface create/attach/detach (#2843)
* feat(ec2): support standalone network interface create/attach/detach

CreateNetworkInterface returned UnsupportedOperation unconditionally,
blocking every root that attaches a standalone ENI: the attach-eni and
override-default-eni examples in terraform-aws-server, the with-elb
example in terraform-aws-asg, and vpc-blackhole-routes in
terraform-aws-service-catalog (floci-kt9 in the floci-harness compat
survey).

Adds CreateNetworkInterface, DeleteNetworkInterface,
AttachNetworkInterface and DetachNetworkInterface, backed by a new
standalone ENI store separate from the implicit primary interface each
instance already carries. DescribeNetworkInterfaces now merges both
without double-counting. RunInstances also accepts a pre-existing
standalone ENI as an instance's primary interface via
NetworkInterface.1.NetworkInterfaceId, the shape Terraform's
network_interface { network_interface_id = ... } block sends for
override-default-eni.

* fix(ec2): keep a standalone ENI's own record when it is attached

Review found two ways the attachment state ended up recorded on only one side.

AttachNetworkInterface updated the standalone ENI and stopped there, so
DescribeNetworkInterfaces reported an attachment that DescribeInstances denied —
and the device-index conflict check, which reads the instance's own interface
list, could never see anything this operation had attached: two interfaces could
take device index 1 on the same instance. The instance now carries the interface
too, and DetachNetworkInterface removes it again.

RunInstances took the opposite approach and deleted the standalone record,
leaving the interface represented only inside the instance. Terminating that
instance then made a caller-created ENI vanish -- InvalidNetworkInterfaceID.
NotFound rather than returning to "available" -- so it could not be reused. AWS
attaches a pre-existing interface with deleteOnTermination false precisely so it
outlives the instance. The standalone record is now kept and marked attached,
and terminate releases it; describeNetworkInterfaces skips the instance-side
copy of any id the standalone store owns, so it is still reported exactly once,
from the side that knows its real attach time and its deleteOnTermination.

Also braces a single-line conditional, per AGENTS.md.

* fix(ec2): release an ENI whose instance died without TerminateInstances

TerminateInstances is not the only way an instance reaches "terminated": a
container-backed launch that fails or is cancelled ends there asynchronously,
inside Ec2ContainerManager, which has no access to the interface store. An ENI
the launch had already marked in-use therefore stayed pinned to an instance that
no longer runs, and every later attempt to reuse it failed with
InvalidNetworkInterface.InUse.

Rather than chase each terminal transition, the attachment is reconciled when
the interface is next read: an attachment naming an instance that is gone or
terminated is cleared, and the interface reports "available" again. That covers
attach, launch, delete and describe through the one path they share.

* fix(ec2): let a dead instance release its copy of a reclaimed ENI

Releasing the standalone record alone left the terminated instance still
reporting the interface, so once the ENI was reused two instance records claimed
it and nothing in DescribeInstances picks a winner. Reclaiming now clears both
sides, and the unit test asserts the instance no longer lists it.

Also drops the em-dashes from the comments and docs this branch adds, per
AGENTS.md.

* fix(ec2): drop the instance's copy on the TerminateInstances path too

The previous commit fixed only the reclaim-on-read path. TerminateInstances
released the standalone record while leaving the mirrored interface on the
terminated instance, so reusing the ENI still produced two instance records
claiming it. Both paths now clear the instance's copy, and the integration test
asserts DescribeInstances no longer mentions the interface before the same ENI
is handed to a second launch.
2026-09-01 18:21:57 -04:00
Vũ Thế Huy 10192f05d5 feat(translate): add Amazon Translate mock service (#2879)
* feat(translate): add Amazon Translate mock service

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

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

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

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

Replace em-dashes in the Translate doc page and Java comments with colons,
commas, or periods, and the ellipsis in the error-message preview helper
with "...". Addresses the Greptile review note on PR #2879.
2026-09-01 14:47:33 -04:00
Allen Sanborn db182b3048 fix(efs): implement UpdateFileSystemProtection and report protection on describe (#2842)
A file system's replication overwrite protection was missing in two ways that
compound: the operation that sets it did not exist, and the field that reports
it never reached the wire.

UpdateFileSystemProtection had no route, so the terraform AWS provider's PUT to
/2015-02-01/file-systems/{id}/protection fell through to the S3 handler and came
back as an XML error body, which the SDK reported as "deserialization failed,
invalid character '<'". Every consumer of gruntwork's terraform-aws-data-storage
EFS module hits this rather than only those who opt in, because the module emits
the aws_efs_file_system `protection` block unconditionally.

Separately, protection was never reported. createFileSystem left the field null,
and FileSystem's accessor was named getFileSystemProtectionDescription() -- the
*shape* name. Under UpperCamelCaseStrategy the accessor name is the JSON key, so
even a populated field would have gone out as FileSystemProtectionDescription
rather than the member name FileSystemProtection that FileSystemDescription
actually declares.

So:
  - add UpdateFileSystemProtection (PUT .../{FileSystemId}/protection), returning
    FileSystemProtectionDescription, 404 for an unknown file system
  - default new file systems to ENABLED, which is what AWS documents
  - apply that default on read as well, so file systems in a store written before
    protection was modelled describe the same as one created today
  - rename the accessor to getFileSystemProtection()/setFileSystemProtection()

Authority: efs/2015-02-01/service-2.json -- operations.UpdateFileSystemProtection,
shapes.FileSystemDescription.members.FileSystemProtection.

Verified three ways: EfsIntegrationTest 13/13; a real AWS SDK round trip
(create -> describe reports ENABLED -> update DISABLED -> describe reports
DISABLED), which only passes if the wire names match the model; and
terraform-aws-data-storage/examples/efs, previously FLOCI_UNIMPLEMENTED at
apply, now OK through destroy.
2026-09-01 10:00:34 -04:00
BingEdward 7513b2241b docs(cognito): add UpdateResourceServer to the Resource Servers table (#2873)
UpdateResourceServer is dispatched by CognitoJsonHandler and implemented in
CognitoService, but the hand-maintained Resource Servers table in
docs/services/cognito.md did not list it.

Fixes #2854
2026-09-01 09:36:04 -04:00
Allen Sanborn 14f99a5123 feat(ec2): support VPC peering connections (#2654)
* feat(ec2): support VPC peering connections

CreateVpcPeeringConnection was entirely unimplemented, returning
UnsupportedOperation and blocking all three VPC-peering examples in
terraform-aws-vpc (vpc-peering, vpc-peering-cross-accounts,
vpc-peering-external).

Adds CreateVpcPeeringConnection, AcceptVpcPeeringConnection,
DescribeVpcPeeringConnections, ModifyVpcPeeringConnectionOptions and
DeleteVpcPeeringConnection, matching the resources those examples
actually use (aws_vpc_peering_connection,
aws_vpc_peering_connection_accepter, aws_vpc_peering_connection_options).
Connections start pending-acceptance and only move to active via an
explicit accept, same as real AWS; Terraform's auto_accept convenience
is provider-side, not API-side, so no same-account special-casing is
needed here.

CreateRoute now also accepts VpcPeeringConnectionId as a target and
reports it back on DescribeRouteTables - every one of the three
examples routes traffic through the peering connection via aws_route,
and without this the provider would see permanent drift on the route
resource it just created.

* fix(ec2): enforce cross-account peering identity and fix route target bugs

Addresses Greptile's 0/5 review of #2654:

- AcceptVpcPeeringConnection now resolves the connection across every
  account's storage partition (findAnyAccountEntry, same pattern as
  Ec2IpamService's RAM-shared IPAM lookups) and rejects a caller that is
  not the connection's accepter, instead of only ever finding a
  connection the accepting account itself created.
- DescribeVpcPeeringConnections, ModifyVpcPeeringConnectionOptions and
  DeleteVpcPeeringConnection get the same cross-account resolution, and
  Describe now filters to connections visible from the caller's account
  and region instead of leaking every account's connections in every
  region.
- CreateRoute rejects a VpcPeeringConnectionId combined with another
  target, matching the existing EgressOnlyInternetGatewayId check.
- ReplaceRoute accepts VpcPeeringConnectionId as a target, so a peering
  route created by CreateRoute can actually be repointed.

Adds a cross-account integration test covering acceptance identity,
region-scoped visibility, and the two route-target fixes.

* fix(ec2): record the actual caller as peering requester, enforce region on mutations

Two more issues from Greptile's re-review of #2654:

- CreateVpcPeeringConnection recorded requesterVpcInfo.ownerId as the
  emulator's configured default account rather than the account that
  actually made the request. A non-default requester could never
  describe, modify or delete its own connection, while the unrelated
  default account was treated as the requester and granted those
  operations. Same fix applied to the accepter-owner fallback when
  PeerOwnerId is omitted (same-account peering).
- AcceptVpcPeeringConnection, ModifyVpcPeeringConnectionOptions and
  DeleteVpcPeeringConnection now enforce the same regional-visibility
  invariant Describe already did: an endpoint in a region belonging to
  neither side of the connection reports it as absent instead of acting
  on it.

Extends the cross-account integration test to cover both: the actual
requester managing its own connection while the default account cannot,
and mutations issued from an unrelated region being rejected.

* fix(ec2): enforce per-endpoint ownership on ModifyVpcPeeringConnectionOptions

Greptile's third pass on #2654: a participant that is legitimately part of a
connection could still set the *other* side's DNS-resolution option, e.g. the
requester setting AccepterPeeringConnectionOptions. AWS scopes each option
block to that side's own VPC owner, not to participation in the connection
generally.

ModifyVpcPeeringConnectionOptions now checks the caller against the specific
side's owner for whichever option block(s) the request actually sets, and
rejects a cross-endpoint attempt with OperationNotPermitted. Adds a test
covering both directions (requester setting the accepter's option and vice
versa).

* fix(ec2): resolve the peer VPC's real owner instead of trusting PeerOwnerId

Greptile's fourth pass on #2654: CreateVpcPeeringConnection recorded the
requester-supplied PeerOwnerId as the accepter's identity without checking it
against the peer VPC's actual owner. Since AcceptVpcPeeringConnection
authorizes against that recorded value, a requester could name another
account's real VPC while claiming itself (or anyone) as PeerOwnerId and
self-authorize acceptance of a connection it doesn't actually control.

The peer VPC is now resolved across every account's partition, same as a
peering connection's own id lookup. When it's known locally, that storage
partition is authoritative and overrides any conflicting PeerOwnerId; the
claim is trusted only for a genuinely external/cross-account peer this store
never seeded, where there's nothing to validate against.

Adds a test creating the peer VPC under a real "victim" account and
confirming the forging account can't accept the connection while the real
owner can.

* fix(ec2): take the per-connection lock in DeleteVpcPeeringConnection

Greptile's fifth pass on #2654: accept and modify already synchronized on
lockFor(vpcPeeringConnectionId) before loading and saving the connection, but
delete did not take that lock at all. A delete could run between one of those
mutations' load and its unconditional save, and that save would resurrect the
row delete just removed.

Wraps delete's lookup, visibility check, and removal in the same lock.

* fix(ec2): surface peeringOptions in VPC peering connection responses

CreateVpcPeeringConnection, AcceptVpcPeeringConnection, and
DescribeVpcPeeringConnections never echoed the DNS-resolution setting
under requesterVpcInfo/accepterVpcInfo, even though it's a real field
there in AWS's own examples. ModifyVpcPeeringConnectionOptions stored
it correctly, but Terraform's aws_vpc_peering_connection_options
resource reads the value back via Describe on every plan, not by
re-issuing Modify, so a config setting DNS resolution would show
permanent drift. Flagged in review:
https://github.com/floci-io/floci/pull/2654#pullrequestreview-5054115075

* fix(ec2): reject a peer VPC named with the wrong PeerRegion

CreateVpcPeeringConnection resolved the peer VPC only within the region the
requester supplied, and treated a miss as "external peer, trust PeerOwnerId".
That left the ownership forgery closed on the previous commit reachable again:
name another account's real VPC, point PeerRegion at a region that VPC is not
in, and the requester's own claimed PeerOwnerId is recorded unchallenged --
after which AcceptVpcPeeringConnection authorizes the requester against it.

Real AWS resolves the peer VPC globally and answers InvalidVpcID.NotFound when
the named region is not the one it lives in, so a lookup miss now falls back to
trusting PeerOwnerId only when the id is absent from every region. A genuinely
external peer VPC -- one this emulator has never seen -- behaves as before.
2026-09-01 09:32:51 -04:00
Anders Wasen 46283f3209 fix(rds-data): fixing empty array response from statement (#2880) 2026-09-01 08:24:23 -04:00
Hector Ventura ec97063362 docs: use x.y.z in the pinned image example (#2863)
Every emulator README pinned a concrete version in its compose example and
every one had gone stale: 1.5.11 against 1.7.0, 0.5.0 against 0.7.0, 0.9.0
against 0.11.0, 0.1.0 against 0.3.0. The channel table directly above each
example already writes the pinned channel as x.y.z, so the example now agrees
with its own table and cannot drift again.

The line above it, image: floci/floci:latest, stays copy-pasteable and is the
recommended one; the pinned line reads as the pattern.
2026-08-31 22:38:45 -05:00
Brian Taylor ca4c84c9e0 fix(lambda): delete only the named version when DeleteFunction has a Qualifier (#2824)
* fix(lambda): delete only the named version when DeleteFunction has a Qualifier

DeleteFunction accepted a Qualifier and dropped it: the controller never
bound the query parameter, so every call took the unqualified path and
removed the function, $LATEST and every other version. A caller pruning
one old version silently lost the whole function, with a success
response and no warning.

The qualified path now removes that version alone. Error behaviour
follows the live service rather than the reference, which documents none
of it: deleting $LATEST by qualifier and naming an alias are both
InvalidParameterValueException, a version an alias references is a
ResourceConflictException, and a version that does not exist is a silent
success rather than a 404.

Closes #2819

* test(lambda): cover qualified DeleteFunction through the AWS SDK

The integration test drives the endpoint over raw HTTP, so nothing
exercised the qualified delete through a real SDK client. Adds SDK
coverage for the four cases: deleting one version leaves the function
and its other versions, $LATEST cannot be deleted by qualifier, a
version an alias references is refused, and an absent version is a
no-op.

* fix(lambda): pattern-validate the DeleteFunction qualifier

Character.isDigit accepts non-ASCII decimal digits, so a full-width or
Arabic-Indic digit was read as a version number and answered with a
silent 204 instead of being rejected. The live service pattern-validates
the qualifier before anything else and its constraint is ASCII-only;
that check now runs first, and the digit test no longer relies on
Character.isDigit.
2026-08-31 22:01:34 -04:00
Brian Taylor 7473c57720 fix(ses): return DeliveryOptions from v1 DescribeConfigurationSet (#2841)
PutConfigurationSetDeliveryOptions already persisted the TLS policy — v2
GetConfigurationSet returned it correctly — but the v1 projection never
read it back, omitting the DeliveryOptions member even when deliveryOptions
was named in ConfigurationSetAttributeNames.

The Terraform provider reads aws_ses_configuration_set through the v1
DescribeConfigurationSet, so the missing member made every plan re-add a
delivery_options block that apply never converged.

The two APIs spell the enum differently and the write path already
normalises v1 Require/Optional to the stored REQUIRE/OPTIONAL; the read
path converts back, so each API answers in its own casing.
2026-08-31 21:45:09 -04:00
Hector Ventura 10ce6be8cd docs: state the release cadence in CONTRIBUTING and the docs site (#2850)
* docs: state the release cadence in CONTRIBUTING and the docs site

Follow-up to the release-train documentation. CONTRIBUTING described how a
release is cut but never when, and the published contributing page said
nothing about releases at all, so the cadence was only discoverable from the
README.

- CONTRIBUTING: the 1st and 3rd Tuesday train leads the release section, and
  merging to main is stated not to cut a release.
- docs/contributing.md: a Releases section, including why the commit type
  matters, since semantic-release derives the version from it.
- docs/configuration/docker-images.md: the Channel table said release images
  publish "on every release", which explained nothing; it now names the train.

Three corrections in the same table, all pre-existing:

- The nightly row said 22:00 CT. nightly.yml is cron '0 23 * * *' pinned to
  America/Chicago, and observed runs land at 04:0x UTC, so it is 23:00 CT.
- Dated nightly tags were described as fixed and never moving. The workflow
  accepts workflow_dispatch and pushes unconditionally, so a same-day rerun
  republishes that day's tag. Reproducibility is a release-tag property.
- The pinned example was 1.5.11, six minor versions behind.

Em-dashes in the touched files replaced with ordinary punctuation, per the
documentation style rule in AGENTS.md.

* docs: correct three points raised in review

- Nightly availability was overstated. A merge after the nightly workflow
  starts misses that run, so the text no longer promises "that night's"
  image; it says the change reaches nightly on the next nightly build.
- The published contributing page called CHANGELOG.md never hand-edited,
  omitting the changelog-edit label that the root CONTRIBUTING documents as
  the route for a genuine correction.
- docker-images.md recommended 1.7.0 in the channel table while its Quick
  Reference still pinned 1.5.11.

Each was fixed in all four emulators, not only where it was flagged.
2026-08-31 20:14:02 -05:00
Brian Taylor 44629631ca fix(lambda): honour ListLayers and ListLayerVersions query parameters (#2817)
* fix(lambda): honour ListLayers and ListLayerVersions query parameters

CompatibleRuntime, CompatibleArchitecture, MaxItems and Marker were
accepted and ignored, and NextMarker was never emitted, so a client
paginating with MaxItems saw a single page and silently got the whole
list, while a runtime or architecture filter returned layers that do
not match it.

Both actions now filter, paginate and emit NextMarker. Validation
follows the live service rather than the API reference: range and enum
failures accumulate into one ValidationException in a fixed member
order, a non-integer MaxItems is a SerializationException that
short-circuits validation, and a Marker the service did not issue is
InvalidParameterValueException "Invalid pagination key.".

Under a filter, LatestMatchingVersion is the newest version that
matches rather than the newest overall, so ListLayers needs every
version of each layer rather than the latest of each.

Closes #2808

* fix(lambda): sign layer pagination markers

The tag identifying a Marker as Floci's was a fixed string, so a caller
could base64 a cursor of their own with the same prefix and have it
accepted. That cursor was then applied to the page, silently skipping
results or emptying the list where AWS rejects an unissued token.

Markers now carry an HMAC over the cursor, keyed per process, so a
fabricated or edited token fails the check. A marker from an earlier run
is stale for the same reason, which is what AWS does with an expired one.

* test(lambda): cover layer listing parameters through the AWS SDK

AGENTS.md prefers SDK clients over raw HTTP for management-plane
validation. The integration test covers the parameters through the wire
protocol; this adds the same filtering, pagination and enum rejection
through @aws-sdk/client-lambda, so a marshalling regression that only
the SDK would notice does not pass unseen.
2026-08-31 19:38:30 -04:00
Allen Sanborn afe26c6ad1 fix(elb): route Classic (v1) requests to a dedicated handler instead of ELBv2 (#2619)
* feat(elb): implement Classic (v1) Elastic Load Balancing

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

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

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

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

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

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

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

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

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

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

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

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

Also from review: the empty-Listeners ValidationError carried a message copied
from an unrelated subnet/AZ check, and the new cross-reference to the Classic
docs page split elb.md's opening sentence mid-paragraph instead of following it.
2026-08-31 19:05:07 -04:00
Brian Taylor a7b2b79492 fix(lambda): honour Publish on CreateFunction and UpdateFunctionCode (#2825)
The Publish flag was never read on either path, so no version was ever
created unless the caller made a separate PublishVersion call, and both
actions reported Version as $LATEST. Terraform reads Version and
qualified_arn straight from that response, so every aws_lambda_function
with publish = true recorded $LATEST — which Lambda@Edge cannot use.

Both actions now publish and report the new version. The ARN they return
differs, following the live service rather than the reference, which does
not distinguish them: CreateFunction keeps the unqualified FunctionArn
while UpdateFunctionCode returns the qualified one, as PublishVersion
does.

Closes #2820
2026-08-31 14:52:19 -04:00
Brian Taylor 968ff78e25 fix(lambda): make the code-volume populate concurrency configurable (#2830)
Concurrent first-time code-volume populates are capped by a semaphore sized
Math.max(2, availableProcessors() / 2). The JVM honours the container's cgroup
CPU quota, so a CPU-constrained Floci container derives 2 permits and concurrent
cold starts of *distinct* large functions complete in waves of two instead of in
parallel.

Measured on main, six distinct functions with 41MB packages, all cold, fired
concurrently, varying only the quota on Floci's own container:

  unlimited (16 cpu)  ->  8 permits  ->  one wave of 6   ->   8.3s
  --cpus=8            ->  4 permits  ->  waves of 4, 2   ->  13.2s
  --cpus=4            ->  2 permits  ->  waves of 2,2,2  ->  19.2s

The wave sizes track the formula exactly, which rules out generic CPU starvation
- that would slow all six uniformly rather than produce discrete equal-size waves.

The populate is IO-bound (creating a helper container and streaming a tar into
it), so CPU count is a weak proxy for how many the Docker daemon can absorb. The
cap itself is still worth having: the daemon overload it was added to prevent is
real. What was missing is a way to decouple it from the CPU allocation, so this
adds floci.services.lambda.code-volume-populate-concurrency
(FLOCI_SERVICES_LAMBDA_CODE_VOLUME_POPULATE_CONCURRENCY) and leaves the derived
default untouched.

Values below 1 fall back to the derived default with a warning: zero permits
would deadlock every populate, and a negative Semaphore count would make
acquire() block until that many releases arrived.

The semaphore becomes an instance field so the permit count can come from
config. Floci runs a single @ApplicationScoped launcher, so it is still one gate
for the whole emulator.

Refs #2050
2026-08-31 11:14:29 -04:00
TATSUNO “Taz” Yasuhiro 63a2a60a30 fix(stepfunctions): let a mocked response with no attempts start the execution (#2823)
A MockedResponses entry with no attempt keys was rejected at StartExecution, so a
generated mock file failed the whole execution when the collection it was built from
was empty. Step Functions Local starts the execution and fails it with States.Runtime
only when the state that names the entry is entered.

An empty entry is a lookup that finds nothing, not a malformed entry. Floci already
accepts a mock that defines attempt 1 but not attempt 0 and fails the same way at run
time. Every other malformed entry keeps its 400 at StartExecution, which stays stricter
than Step Functions Local.

Verified against amazon/aws-stepfunctions-local:2.0.0.

Refs #2523
2026-08-31 11:09:43 -04:00
Kenshin Okinaka b0fe8311a0 feat(ses): support v2 tenant-scoped sending with association gate (#2815)
* feat(ses): support v2 tenant-scoped sending with association gate

* fix(ses): guard tenantForSending against a null TenantName and pin the raw-test charset

* fix(ses): validate an inline bulk template before the tenant gate
2026-08-31 09:35:40 -04:00
Brian Taylor 5b363ffa2d fix(lambda): implement GetLayerVersionByArn (#2812)
* fix(lambda): implement GetLayerVersionByArn

GET /2018-10-31/layers?find=LayerVersion&Arn={arn} is GetLayerVersionByArn,
but only ListLayers was bound to that path and it ignored both query
parameters. A GetLayerVersionByArn call was therefore answered with a
ListLayers body and HTTP 200: an SDK deserialises that against the
GetLayerVersionByArn output shape, finds none of its members, and hands the
caller an empty result instead of the layer version or a
ResourceNotFoundException.

AWS gives the two actions the same method and path, discriminated only by
`find`, and JAX-RS cannot route on a query parameter, so the branch lives in
the handler.

The semantics below were measured against the live service rather than
inferred from the reference:

  find=LayerVersion&Arn=<present>  200 + LayerVersion object
  find=LayerVersion&Arn=<absent>   404 ResourceNotFoundException
  find=LayerVersion, no Arn        400 ValidationException, must not be null
  find=LayerVersion&Arn=junk       400 ValidationException, pattern in message
  find=Nonsense                    200 + ListLayers body
  find=layerversion                200 + ListLayers body (match is case-sensitive)

The Arn pattern enforced here is the one the live service reports in its own
ValidationException, not the one the API reference publishes: it constrains
the region segment more tightly and additionally accepts the AWS-managed
arn:<partition>:lambda:::awslayer:<name> form, which the reference omits.

The response reuses the builder GetLayerVersion already returns, and resolves
Content.Location against the layer's own region rather than the caller's,
matching the lookup resolveLayerByArn already keys on.

* fix(lambda): scope GetLayerVersionByArn to the caller's account

resolveLayerByArn keys on region, layer name and version. Storage is already
partitioned per account, so that lookup runs inside the caller's own partition
— an ARN naming a different account did not reach that account's layers, but it
did resolve to the caller's own same-named layer and return it.

Measured on main, without this action: account B publishes
arn:...:111111111111:layer:acct-probe:1, then calls CreateFunction with
Layers=[arn:...:000000000000:layer:acct-probe:1]. The call succeeds and the
function records account A's ARN while B's own layer is what resolves. Account
B never sees account A's layer — GetLayerVersion by name and ListLayers both
return nothing for it — so this is a wrong-resource answer, not a cross-account
read.

GetLayerVersionByArn is the one layer action that takes an account explicitly,
so it honours it: an ARN outside the caller's account is a 404, which is what
the caller already gets from GetLayerVersion for a layer it cannot see. No
layer can be shared cross-account here — layer permissions are unimplemented —
so a foreign account is always a miss, and the check is the place sharing would
hook in if that changes.

The same account-blindness reaches CreateFunction and UpdateFunctionConfiguration
through validateLayersResolvable, and the container launcher through the same
resolver. Those are pre-existing on main and change behaviour for existing
actions, so they are left for a separate change rather than folded in here.

* fix(lambda): reject a layer ARN naming another partition

The account guard compared only the account, and resolveLayerByArn drops
the partition as well as the account, so an ARN in another accepted
partition with the same account, region, name and version resolved to
the caller's local layer and was returned under the foreign-partition
ARN. The live service rejects those outright with
InvalidParameterValueException.
2026-08-31 09:10:49 -04:00
Vũ Thế Huy 426fbcb284 feat/redshift auth proxy (#2751)
* feat(redshift): add auth proxy port range and endpoint-host config

* feat(redshift): add containerHost/containerPort/proxyPort to Cluster model

* feat(redshift): add RedshiftAuthProxy reusing the RDS PostgreSQL protocol handler

* feat(redshift): add RedshiftProxyManager registry with shutdown hook

* feat(redshift): front new clusters with an auth proxy and advertise it

* feat(redshift): stop/update proxy on delete/modify, start it on snapshot restore

* feat(redshift): keep proxy port stable across reboot and adopt-on-startup

* test(redshift): integration coverage for JDBC through the auth proxy

* test(redshift): reinstate JDBC connectivity check now that the proxy exists

* docs(redshift): document the cluster auth proxy and its config

* fix(redshift): prevent minor port leak when proxy fails to start

* fix(redshift): rollback container on proxy failure and surface teardown errors

* fix(redshift): stop auth proxy on rollback to prevent listener collisions

* fix(redshift): ensure proxy shutdown failure does not abort container and port cleanup

* fix(redshift): add proper logging for intentionally ignored cleanup exceptions

* fix: Wait for Redshift database readiness before proxying

Previously, RedshiftContainerManager just slept for 3 seconds before marking the container as started. On slower CI environments, the PostgreSQL database might take longer to initialize, resulting in Connection Refused when the RedshiftAuthProxy forwards connections.
Now, RedshiftContainerManager polls the database using psql until it's ready, up to 60 seconds.

* fix(redshift): prevent proxy port reallocation on shutdown failure

Addresses a review comment indicating that if a Redshift auth proxy fails to shut down during rollback or deletion, its port must not be released into the available pool. Reassigning a still-bound port would cause subsequent cluster creations to fail with a BindException.
Instead, we now tolerate proxy shutdown errors but intentionally leak the port allocation to prevent collisions.

* fix(redshift): fix failing tests due to proxy changes

1. RedshiftOperationsTest checked for a hardcoded port 5440, but the RedshiftService now allocates dynamic proxy ports. Removed the exact port assertion.
2. RedshiftContainerManager's psql readiness check was connecting via local Unix socket, which succeeded before PostgreSQL was actually ready to accept remote TCP connections from the proxy. Added '-h 127.0.0.1' to enforce TCP readiness.

* test(redshift): use Awaitility to connect to proxy

Use Awaitility to retry the initial connection in RedshiftProxyIntegrationTest to prevent transient 'Connection attempt failed' errors on slower CI environments.

* chore(redshift): use proper imports instead of fully-qualified class names in tests

* fix(redshift): fix compiler errors introduced during import cleanup

* fix(redshift): resolve proxy lifecycle bugs and CI network issues

- Throw RuntimeException from RedshiftProxyManager.stopProxy if proxy is not found. This allows RedshiftService to catch it and intentionally leak the port, preventing port collisions if a proxy fails before registration.
- Force RedshiftProxyIntegrationTest to connect via 127.0.0.1 instead of the endpoint address, which resolves to host.docker.internal in CI environments and causes UnknownHostException.

* fix(redshift): prevent proxy port exhaustion on startup failures

Instead of blindly assuming missing proxies denote a leaked port, RedshiftProxyManager now tracks proxies that failed their socket cleanup during startup. stopProxy throws an exception only if the socket is known to be leaked. This allows RedshiftService to safely release ports after clean proxy startup failures, addressing Greptile's feedback about port exhaustion.

* fix(redshift): retain proxy reference to allow retry on close failure

As identified by Greptile, stopProxy previously removed the proxy from the registry before calling proxy.stop(). If stop() threw an exception, the proxy reference was lost, preventing any subsequent retry from ever finding it and attempting to close it again. stopProxy now only removes the proxy from the registry after stop() returns successfully. Additionally, failedCleanups is now retained instead of cleared, ensuring retries continue to safely leak the port if cleanup remains impossible.

* fix(redshift): abort cluster deletion if proxy fails to stop

As highlighted by Greptile, previously deleteCluster would swallow proxy shutdown failures and delete the cluster metadata anyway. This eliminated the retry path, stranding the unclosed proxy and its port reservation until the process exited. Now, if stopProxyAndReleasePortSafely fails, deleteCluster throws an exception to preserve the cluster metadata so the deletion can be retried.

* test(redshift): lock in proxy lifecycle failure-recovery behaviors

Bổ sung test cho ba hành vi hardening chưa được cover, để refactor sau
không âm thầm phá vỡ:

- stopProxy giữ lại proxy trong registry khi close() ném, cho phép retry
  gọi lại đúng instance và chỉ deregister sau khi stop sạch
- marker leak khi startup cleanup thất bại được retain qua mọi retry và
  chỉ bị xoá bởi một lần start mới thành công
- deleteCluster abort với InternalFailure, giữ nguyên container + metadata
  khi proxy không stop được; retry sau đó hoàn tất khi proxy stop OK

Đồng thời bỏ "-p 7100-7199:7100-7199" trong compatibility.yml: proxy bind
0.0.0.0 trong container floci và sdk-test-java chạy trên compat-net nên
JDBC đi container-to-container qua alias "floci", không cần publish port
ra host. Giữ lại FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST=floci.

* fix(redshift): keep an unclosable proxy reachable for later retry

Theo phản hồi mới của Greptile: khi start/replace proxy thất bại và
cleanupFailedStart cũng không đóng được listener, code cũ chỉ lưu relayKey
vào một Set rồi vứt object RedshiftAuthProxy. stopProxy sau đó ném vĩnh
viễn mà không còn cách nào chạm tới listener để thử đóng lại, khiến
cluster không xoá được và port bị giữ mãi trong dải hữu hạn.

Thay Set<String> failedCleanups bằng Map<String, RedshiftAuthProxy>
unclosableProxies. cleanupFailedStart giữ lại chính proxy đó; stopProxy và
stopAll thử đóng lại, chỉ gỡ entry khi stop thành công. startProxy không
còn xoá marker khi start mới — chỉ một lần stop thành công mới gỡ, vì
listener cũ có thể vẫn đang bound.

* fix(redshift): retry proxy port bind to absorb reboot rebind race

rebootCluster giữ nguyên proxy port của cluster để endpoint ổn định, nên
listener cũ bị đóng rồi bind lại đúng port đó chỉ vài ms sau. Dưới tải
(CI runner ARM) kernel có thể chưa nhả port và SO_REUSEADDR không giúp
được khi accept loop cũ đang teardown -> BindException -> RebootCluster
trả 500. Đây là nguyên nhân test RedshiftOperationsTest.
testClusterAndSnapshotLifecycle fail chập chờn.

start() giờ retry bind tối đa ~1s, chỉ nuốt BindException; IOException
khác vẫn propagate ngay. Thêm test dựng cảnh port bị chiếm tạm thời rồi
nhả, xác nhận proxy vẫn bind được.

* fix(redshift): tear down proxy and release port when rebootCluster fails

Nếu startProxy/restoreSnapshot ném sau khi proxy đã (re)start trong
rebootCluster, hai nhánh catch chỉ set status "failed" rồi rethrow —
proxy mới vẫn chạy và port vẫn nằm trong usedPorts, không nhánh nào dọn.
Giờ cả hai catch gọi stopProxyAndReleasePortSafely như createCluster và
restoreFromClusterSnapshot đã làm; proxyPort được hoist ra ngoài try với
sentinel -1 để rollback an toàn kể cả khi chưa cấp port.

Thêm test: restoreSnapshot ném -> proxy được stop lại, AwsException nổi lên.

* fix(redshift): serialize createCluster/deleteCluster/restoreFromClusterSnapshot

modifyCluster và rebootCluster đã synchronized nhưng create/delete/restore
thì không, dù cả năm method đều chạy chuỗi container + proxy + port nhiều
bước trên cùng một cluster. deleteCluster(x) chạy song song rebootCluster(x)
có thể để lại metadata mồ côi trỏ tới container/proxy đã dừng. Thêm
synchronized cho ba method còn lại để nhất quán.

* fix(rds,redshift): close backend socket when the auth handshake fails

handleConnection mở kết nối TCP tới container Postgres trước khi gọi
handleAuth. Chỉ nhánh thành công (bridge) và vài nhánh lỗi có kiểm soát
mới đóng backend; nếu handleAuth trả về sớm ở một probe trần (SSLRequest
không kèm startup) hoặc ném IOException (client ngắt giữa handshake), catch
cũ chỉ đóng client -> mỗi health-check TCP làm rò một connection tới
Postgres, ăn dần max_connections.

Chuyển việc đóng socket sang finally, đóng cả client lẫn backend
(idempotent, nhánh thành công đã đóng sẵn). Áp cho cả RdsAuthProxy vì
RedshiftAuthProxy được copy từ đó. Thêm test: client drop giữa handshake
-> backend nhận EOF.

* fix(redshift): stop replacement container and keep dump on failed reboot

Rollback của rebootCluster (b44fd1e3) mới chỉ stop proxy + release port,
để container thay thế chạy tiếp sau một cluster "failed", và finally vẫn
xoá tempDump. Vì container gốc đã stop và không có volume, tempDump là bản
sao duy nhất của data -> mất data không khôi phục được (bug có sẵn, giờ
mới lộ).

rollbackReboot() giờ stop luôn container thay thế (như createCluster/
restoreFromClusterSnapshot). tempDump chỉ bị xoá khi reboot thành công;
khi fail thì giữ lại và log đường dẫn để khôi phục thủ công.

* fix(redshift): make reboot rollback phase-aware to protect the original

Commit trước cho rollbackReboot stop container vô điều kiện. Nếu reboot
fail ngay ở takeSnapshot hoặc stopProxy — lúc container gốc (chứa data,
không volume) VẪN đang chạy — thì rollback lại force-remove chính nó, huỷ
bản sao data hoàn chỉnh duy nhất và chỉ còn dump rỗng/dở.

Thêm hai cờ:
- originalTornDown: đã stop proxy + container gốc -> rollback mới được
  đụng vào proxy/port
- replacementStarted: đã start container thay thế -> rollback mới được
  stop container
Fail trước hai mốc đó: không đụng gì, trạng thái gốc còn nguyên.

Thêm test: takeSnapshot ném -> cm.stop và stopProxy không được gọi.

* fix(redshift): clean an orphan replacement container on failed reboot

containerManager.start có thể tạo container Docker rồi mới ném ở
waitForReady, nên cờ replacementStarted (set sau khi start return) bỏ sót
trường hợp này -> orphan chạy dưới tên cluster.

Bỏ replacementStarted, gate rollback theo mỗi originalTornDown: một khi
proxy + container gốc đã stop thì container gốc chắc chắn biến mất, nên
containerManager.stop (xoá theo tên) chỉ có thể chạm replacement — kể cả
replacement do start() tạo dở rồi ném.

Thêm test: start() ném -> rollback vẫn gọi cm.stop để dọn orphan.

* fix(redshift): remove orphan cluster metadata on failed create/restore

* fix(redshift): keep failed cluster metadata if proxy stop fails

* fix(redshift): fix TooManyActualInvocations in proxy tests

* fix(redshift): clear proxyPort on reboot rollback if port is released

* fix(redshift): retain reserved port on reboot startup failure

* fix(redshift): retain proxy port in reboot rollback and teardown failed startup recovery

* fix(redshift): skip failing cluster and retaining dump if reboot fails before teardown
2026-08-31 09:03:26 -04:00
Facundo ParedesandFacundo Paredes f7f16cd2a3 fix(stepfunctions): bound $range allocation at the AWS memory limit (#2790)
* fix(stepfunctions): open a JSONata query evaluation cause with the AWS sentence

evaluateField now wraps a thrown JSONata failure with "The JSONata expression
'<expr>' specified for the field '<field>' threw an error during evaluation"
before the existing tail, matching real AWS. The separator is ". " when the
tail carries a JSONata error code and ": " when it is a bound message with
none. evaluate() keeps producing the bare tail unchanged for its direct
callers.

evaluate() stays the only place the JSONata engine is called and the only
catch around it: evaluateField calls it and enriches the failure it throws,
rather than reaching the engine itself. QueryEvaluationFailure carries the
separator across that throw, so a catch added to evaluate() later covers both
entry points. All 11 AslExecutor call sites reach the evaluator through
evaluateField or resolveTemplate, so a catch installed anywhere else would be
dead on every real execution path.

* fix(stepfunctions): catch Error from JSONata evaluation as States.QueryEvaluationError

An OutOfMemoryError or StackOverflowError raised while parsing or evaluating a JSONata
expression escaped JsonataEvaluator's catch (Exception) and reached AslExecutor's own
last-resort catch (Error), failing the whole execution as States.Runtime before the
state's own Retry and Catch ever ran. JsonataEvaluator.evaluate now also catches Error at
the same seam and translates it into a FailStateException with States.QueryEvaluationError,
so a Catch on the state (or on States.ALL) can recover, matching real AWS.

Closes #2738

* fix(stepfunctions): match AWS on the JSONata expressions it refuses

Four expression classes where Floci and AWS disagreed on whether the state
fails at all, all measured against us-east-1 with test-state.

The evaluation-depth ceiling drops from 500 to 100, which is AWS's own: five
nesting shapes bisected one n at a time all put its last accepted evaluation at
depth 100 and its first refusal at 101. An addition chain nests one level per
term and AWS accepts 100 terms; parentheses, brackets and the chain operator
nest one level more than their count and AWS accepts 99 of each; a
non-tail-recursive $f(n) nests 3n+5 and AWS accepts n=31, depth 98, refusing
n=32, depth 101.

The memory an expression may hold is now bounded, which it was not: one value an
evaluation step produces may hold 6,990,256 bytes, counting a number as eight
and a character as one. The two shapes AWS was bisected on, [1..873782] and a
string doubled 22 times, bracket a number at between five and nine bytes a
character: with the bound at 873,782 numbers, anything in that range leaves
4,194,304 characters inside it and 8,388,608 outside, and four or ten does not.
Eight is what a double costs, and it is inside the bracket. The check walks the
value and stops at the bound, and a lazy range is counted from its length rather
than materialised.

$eval is unbound, as AWS disables it, so a call to it answers T1006 the way AWS
does and $parse stays the replacement.

A non-finite number the expression itself evaluates to comes back as the string
AWS writes for it, since JSON has no literal for one: 1/0 and 1e308*10 are
"Infinity" and $parseInteger("abc","0") is "NaN", where the first two raised
D1001 and the third returned nothing and failed the field. One the library's
arithmetic buries inside a value, as in [1/0], still fails the state, because
the refusal is the only place the library leaves the value and it has already
unwound what was being built; one a function answers nests like any other value.
$formatNumber checks its picture string against the fourteen rules of XPath F&O
4.7.3 first, so $formatNumber(1, "x") fails with D3086 instead of answering "x1".
Which of the fourteen codes AWS reports is what fixes the order the rules are
read in: a picture with no digit breaks D3085 and D3086 at once and AWS reports
the second, so the last rule broken names the failure rather than the first.

Closes #2737

* fix(stepfunctions): bound $range allocation at the AWS memory limit

AWS accepts $range(1, 360145, 1), all 360,145 elements, and refuses one
element more on its own memory limit. Floci's $range had no such bound:
it built the array in full before the memory check on the value ever ran,
so a call far past AWS's limit spent gigabytes and either exhausted the
heap or hung instead of failing the state cleanly.

range() now refuses a call whose produced element count exceeds the
measured bound before allocating, throwing the same
States.QueryEvaluationError JException the held-memory check raises,
whose message is now a single shared constant. Other built arrays keep
the looser, byte-based bound.

* test(stepfunctions): pin the number model of the execution input

Measured against real AWS (test-state, 2026-08-30): a Pass state with
Output {"v": "{% $states.input.amount %}"} answers {"v": 1} for input
{"amount": 1.0} and {"v": 9.223372036854776E18} for input
{"amount": 9223372036854775808}. That is exactly what routing the
execution input through toJsonataValue/toJsonataNumber already
produces, so these two tests pin it against silent regression.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-31 00:16:52 -04:00
Facundo ParedesandFacundo Paredes ead70eae4d fix(stepfunctions): refuse the definitions AWS refuses, at both validation entry points (#2786)
* fix(stepfunctions): reject definitions with no terminal state, dangling targets or unsupported fields

Enforce the ASL rules AWS applies at both ValidateStateMachineDefinition
and CreateStateMachine: a workflow needs a terminal state
(MISSING_END_STATE, top-level only, suppressing the unreachable-state
reachability check but not a dangling-target check), every reachable
state and every Next/Choices[].Next/Default/Catch[].Next target must
exist (MISSING_TRANSITION_TARGET), recursing into ItemProcessor and
Branches with structured paths, and TimeoutSeconds/Catch/Retry are
refused outside the state types that support them
(SCHEMA_VALIDATION_FAILED, "Field '<name>' is not supported").

CreateStateMachine's wire message always renders " at <location>",
printing the literal "null" when there is none, matching AWS exactly;
ValidateStateMachineDefinition keeps omitting the location field
entirely when null, which is the correct, unchanged behavior for that
API.

Remove the now-dead Parallel TimeoutSeconds handling in AslExecutor:
no definition carrying that field can reach execution anymore.

* fix(stepfunctions): reject JSONata expressions that do not parse at definition time

Report INVALID_JSONATA_EXPRESSION when a JSONata expression fails to parse,
using the parser's own message with its S0xxx code prefix stripped, at the
field's location. Also report UNSUPPORTED_JSONATA_EXPRESSION for '$$' and
for '$states.errorOutput' outside a Catch entry's own Output or Assign.

Previously these were accepted at ValidateStateMachineDefinition and
CreateStateMachine time and only failed later, at execution, with
States.QueryEvaluationError.

Every message asserted was measured against real AWS us-east-1 with
`aws stepfunctions validate-state-machine-definition`, including
`phone %.other` and the empty expression, which AWS also refuses.

The three booleans the definition walk threaded through every recursive
call (insidePayload, isCatchEntry, insideCatchOutputOrAssign) travel as a
single JsonataScope value, which drops collectTopLevelReferences back under
the Sonar S3776 limit.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-31 00:11:55 -04:00
Matheus André 6f123e83b8 feat(batch): add update and delete job queue endpoints with corresponding service logic (#2807) 2026-08-30 23:35:09 -04:00
kotov228andPriamo 8765cde6dd test(terraform): expand Floci IaC compatibility coverage (#1834)
* test(terraform): expand Floci IaC compatibility coverage

* fix(terraform): use current S3 backend path style option

* fix(terraform): route ElastiCache provider calls to Floci

* fix(compat): resolve Firehose name collision, drop resources with live Floci gaps

- aws_kinesis_firehose_delivery_stream.compat collided with main's
  .events stream (both named floci-compat-firehose); renamed to
  floci-compat-firehose-basic.
- Removed aws_codebuild_project, aws_cloudtrail, and aws_opensearch_domain
  from both suites: running the suite end-to-end surfaced real Floci gaps
  behind them (BatchGetProjects ARN lookup, CloudTrail ListTags, OpenSearch
  CognitoOptions nil deref crashing the provider) that only show once
  Terraform gets past apply into the post-create refresh. Tracked as
  #2799, #2800, #2801.
- Updated test counts in README to match (70/44/2,582).

* fix(compat): force_destroy the compat bucket, drop resources with live teardown gaps

- aws_s3_bucket.app now sets force_destroy = true: the CUR report now
  actually emits into this bucket (format=Parquet finally lets the
  report definition get created), so terraform destroy needs to be
  able to clear a non-empty bucket.
- Removed aws_transfer_server: Floci's DeleteServer wrongly requires
  OFFLINE state, which isn't real AWS behavior (confirmed against the
  API reference and terraform-provider-aws's own delete logic, which
  never calls StopServer first). Tracked as #2802.
- Removed aws_batch_compute_environment: UpdateComputeEnvironment
  (called by terraform destroy to disable it first) isn't implemented
  at all, so the request falls through to an HTML error page instead
  of a modeled error. Tracked as #2803.
- Updated test counts in README to match (68/42/2,578).

* fix(compat): drop aws_api_gateway_rest_api pending Floci apiStatus fix

CI (native / compat-terraform) showed terraform apply deterministically
timing out on aws_api_gateway_rest_api: terraform-provider-aws waits for
the REST API's apiStatus field to reach AVAILABLE, and Floci never sets
it (confirmed apiStatus is a real, current field in the apigateway wire
model). Removed from both suites; tracked as #2804.

Updated test counts in README to match (67/41/2,576).

* fix(compat): drop redundant ECS containerInsights setting causing drift

CreateCluster silently drops the settings field on Floci (confirmed:
handleCreateCluster never parses req.path("settings"), unlike the
update handlers), so a subsequent plan always proposes re-adding it -
permanent drift on the suite's "re-planning reports no changes" check.
containerInsights=disabled is AWS's actual default, so the block was
functionally redundant; dropped it rather than block on a Java fix.
Tracked as #2806.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-08-30 22:44:33 -04:00
Facundo ParedesandFacundo Paredes 9288769607 fix(stepfunctions): bound a running execution the four ways AWS does (#2782)
* fix(stepfunctions): enforce both TimeoutSeconds clocks

The state machine's top-level TimeoutSeconds was read back by
DescribeStateMachine and copied into activityScheduledEventDetails but
never used as a deadline, so an execution ran to completion however long
it took. Compute the budget once in doExecute, check it before every
state and inside the Wait sleep, and end the execution TIMED_OUT with
stopDate set, no error, no cause, and one ExecutionTimedOut event
carrying States.Timeout and previousEventId 0.

A Task's two bounds were swapped: HeartbeatSeconds acted as the total
wait and TimeoutSeconds was decorative, so "TimeoutSeconds": 5,
"HeartbeatSeconds": 60 failed at 60 seconds instead of 5. awaitToken now
bounds the whole wait with TimeoutSeconds and the gap between heartbeats
with HeartbeatSeconds. SendTaskHeartbeat only logged, so the gap bound
needed a per-token timestamp: the service now records one when the token
is registered and again on every heartbeat, and forgets it when the
waiting task stops listening.

Either clock ends the state as a TaskTimedOutException, which is what
us-east-1 answers for a heartbeat expiry: an ActivityTimedOut event
carrying error States.Timeout and no cause, then an execution reading
FAILED with error States.Timeout and no cause key, over the six-event
history ExecutionStarted, TaskStateEntered, ActivityScheduled,
ActivityStarted, ActivityTimedOut, ExecutionFailed. A Catch still
matches a heartbeat expiry under States.HeartbeatTimeout, so ErrorEquals
matching now asks the failure which names it answers to rather than
comparing one string.

The Wait sleep stops at the execution deadline instead of sleeping its
full duration first, which would have reported the timeout as many
seconds late as the Wait outlasts the budget and left a WaitStateExited
behind for a state AWS never finished. awaitToken discards its token on
the way out; without that the token would stay pending for the life of
the process and a later SendTaskSuccess would be answered as if someone
were still waiting.

Neither timeout carries a cause, so failExecution now reads a null cause
as the failure having none and leaves the key out of both
DescribeExecution and the ExecutionFailed event. The two other failures
that reach it without a cause -- a Fail state with no Cause, and
SendTaskFailure with no cause -- keep reporting an empty one, since
AWS's shape for those is unmeasured.

Refs #2733

* fix(stepfunctions): bound an execution's history and make StopExecution stop it

AWS puts two bounds on a running execution that floci did not: it ends one that
reaches 25,000 history events with States.Runtime, event 25,000 being the
ExecutionFailed event itself, and StopExecution stops the worker rather than
relabelling an execution that goes on to overwrite the status it wrote.

Counting an event against that limit and numbering it in the published history
are two meanings that one AtomicLong was carrying. They are separated here.
producedEventCount counts every event the execution produces, the top-level
flow's and those of its Parallel branches and inline Map iterations alike, and
is what the limit judges. The published history numbers its own events: an
event's id is its position in the list, which makes the list the only authority
for the next id, where the counter and the seal in StepFunctionsService used to
be a second one that agreed with it only at rest. A branch's events are counted
and never built, so executeBranch no longer assembles HistoryEvent objects with
full input and output JSON into a list it throws away.

A Distributed Map runs each item as a child execution on AWS, and a child
execution has a history of its own, so its items are counted against their own
limit rather than the parent's: a Distributed Map over 13,000 items no longer
fails the parent partway through with States.Runtime.

The count is taken before it is judged. Reading it and then taking it let 40
concurrent inline Map iterations through the same check and spent more events
than the execution had.

StopExecution records its abort against a history that need not be in memory.
Executions are stored and histories are not, so a restart in persistent mode
brings a RUNNING execution back with nothing behind it, and the same window
opens between a reset emptying the cache and emptying the store; the abort was
written to the store and then thrown away as a 500.

* fix(stepfunctions): end an execution that spends its budget waiting

A state machine's TimeoutSeconds budget was read only between states and
around the two pauses a definition asks for, a Wait and a Retry backoff. Every
other way a state blocks outlasted it: a Task waiting for its token, a
states:startExecution.sync or ecs:runTask.sync poll, and a Parallel or Map
waiting for its branches. Those executions ended past their budget, and ended
FAILED or SUCCEEDED rather than TIMED_OUT.

Each of those waits now stops at the budget, and the Task path publishes no
failure event for the state it cuts. Measured against us-east-1: a state
machine with TimeoutSeconds 5 over an activity Task whose own TimeoutSeconds
is 60 stops at exactly 5.000 s with status TIMED_OUT, and its history is
ExecutionStarted, TaskStateEntered, ActivityScheduled, ExecutionTimedOut, with
no ActivityTimedOut and no ExecutionFailed.

---------

Co-authored-by: Facundo Paredes <naranjax@MAC-69786.local>
2026-08-30 18:40:07 -04:00
Brian Taylorandlocal 881695ea3b feat(apigatewayv2): OpenAPI import and Terraform-visible API/stage attributes (#2714)
* feat(apigatewayv2): implement ImportApi and ReimportApi

HTTP APIs had no PUT route on /v2/apis or /v2/apis/{apiId}, so ImportApi and
ReimportApi fell through JAX-RS matching to the S3 path-style handler and came
back as NoSuchBucket. Terraform's aws_apigatewayv2_api calls ReimportApi
whenever `body` is set, so any HTTP API defined by an OpenAPI document failed
to apply.

Add an OpenAPI importer for the v2 object model, reusing the swagger-parser
already used by ImportRestApi/PutRestApi on the v1 side. It materialises
routes, integrations and authorizers from x-amazon-apigateway-integration,
x-amazon-apigateway-authorizer, x-amazon-apigateway-any-method and
x-amazon-apigateway-cors, honouring document- and operation-level security.

ReimportApi replaces routes, integrations and authorizers as AWS does, but
leaves API settings an OpenAPI document cannot express (CORS when the spec
carries no x-amazon-apigateway-cors, tags, disableExecuteApiEndpoint) intact,
so a Terraform resource whose cors_configuration lives outside body does not
flap.

Both actions are wired for the restJson1 and JSON 1.1 protocols.

* fix(apigatewayv2): tag stages, not just APIs

TagResource, UntagResource and GetTags read the API id from the last segment of
the resource ARN, so a stage ARN (/apis/{apiId}/stages/{stageName}) yielded the
stage name as the API id and failed with "Invalid API id specified". Parse the
resource path by segment instead, and route the operation to the stage when the
ARN names one.

Stage had no tags field at all, so tags supplied to CreateStage were dropped and
never returned on read. Add it, populate it on create, and serialise it in both
the restJson1 and JSON 1.1 stage representations.

Terraform's aws_apigatewayv2_stage sets tags on create and then reconciles them,
so both halves were needed for a stage with tags to converge.

* feat(apigatewayv2): stage access logging, throttling and API version

Four attributes were accepted on write but dropped on read, so Terraform
re-proposed them on every plan and an aws_apigatewayv2_api/aws_apigatewayv2_stage
pair never converged:

- Api.version, also carried across from an imported document's info.version, as
  AWS does
- Stage.accessLogSettings (CloudWatch destination and format)
- Stage.defaultRouteSettings and per-route Stage.routeSettings (throttling,
  data trace, detailed metrics, logging level)

Throttling and logging fields are boxed rather than primitive: AWS omits unset
knobs instead of defaulting them, and emitting a zero would leave Terraform
seeing a changed value forever.

Stage also gains description, which CreateStage accepted and discarded.

Serialised for both the restJson1 and JSON 1.1 protocols.

* feat(apigatewayv2): honour basepath and failOnWarnings on OpenAPI import

ImportApi and ReimportApi accepted both documented query parameters and then
discarded them, so basepath=prepend or split produced routes at the wrong paths
with no error, and failOnWarnings never rolled anything back.

- basepath now resolves the base path the OpenAPI 3 way — a "basePath" server
  variable first (the first one, if several are declared), otherwise the path
  carried by server.url — and applies ignore, prepend or split. An unrecognised
  value is a BadRequestException rather than silence.
- failOnWarnings turns swagger-parser messages into a 400. Parsing and
  validation now happen before ReimportApi deletes anything, so a rejected
  reimport leaves the existing routes, integrations and authorizers untouched
  instead of gutting the API it was going to replace.
- The Api resource carries the warnings and importInfo the AWS model defines,
  the latter noting definition properties the import ignored.

* fix(apigatewayv2): validate authorizers before reimport mutates, warn on unenforceable security

Two review findings on the OpenAPI importer:

- Authorizer resolution ran while the spec was being applied, so a definition
  that parsed cleanly but declared an unsupported authorizer type — or a REQUEST
  authorizer with caching and no identitySource — was rejected only after
  ReimportApi had already deleted the previous routes, integrations and
  authorizers. Resolution now happens in the planning phase, side-effect free, so
  the rejection leaves the existing definition untouched. This mirrors
  validateImportedAuthorizers on the v1 side.
- A security requirement naming a scheme with no AWS binding — a plain bearer or
  apiKey scheme, or a misspelling — silently produced authorizationType NONE, so
  a document that declares security could yield a publicly invokable route. That
  now raises a warning naming the route and the schemes, which failOnWarnings
  escalates to a 400.

Also adds the braces AGENTS.md requires to the conditionals introduced by the
earlier commits in this branch.

* fix(apigatewayv2): examine ANY-method routes and compound security on import

Two more review findings, both in the warning collection added by the previous
commit:

- The diagnostic passes walked PathItem.readOperationsMap(), which does not
  include x-amazon-apigateway-any-method. An ANY route whose security named an
  unbindable scheme therefore produced no warning, failOnWarnings could not
  reject it, and it was still imported as NONE — the same silent-public-route
  hole the previous commit closed for ordinary operations, left open for the
  route type that matches every method. Route creation and both collectors now
  share one forEachImportedOperation enumeration so they cannot diverge again.
- Several schemes inside a single SecurityRequirement is OpenAPI's AND. A route
  carries one authorizer, so resolveSecurity enforced the first resolvable
  scheme and dropped the rest silently. That now warns, naming the dropped
  schemes and the one actually enforced.

* fix(apigatewayv2): report that imported AWS_IAM routes are not enforced

A sigv4 security scheme imports to an AWS_IAM route, which is what AWS records,
but HTTP API dispatch enforces only JWT and CUSTOM. A document declaring SigV4
therefore produced a route that looks authenticated and is not.

The route keeps AWS_IAM — downgrading it to NONE would misreport the definition
to anything reading the control plane — and the import now warns that the
emulator records the type without enforcing it. The dispatch gap itself predates
this change: CreateRoute has always accepted AWS_IAM unvalidated, and
ApiGatewayExecuteController already notes that v1 dispatch does not implement
AWS_IAM either.

* fix(apigatewayv2): validate jwtConfiguration shape before reimport mutates

jwtConfiguration was copied out of the authorizer extension unchecked, but
audience reaches the store as a List<String> and is cast as one. A scalar
audience — the form the extension is commonly written with — therefore threw a
ClassCastException inside createAuthorizer, after ReimportApi had already
deleted the previous routes, integrations and authorizers.

Normalise it during planning instead: a scalar audience becomes a single-element
list, a list is copied element-wise, and any other shape (or a non-string issuer)
is a BadRequestException raised before anything is deleted.

This was the last unvalidated field in authorizerSpecs; type, identitySource,
result-TTL caching and jwtConfiguration are now all resolved in the planning
phase, so no authorizer defect can reach the mutating half.

---------

Co-authored-by: local <local@example.com>
2026-08-30 17:16:25 -04:00
Ahmed khaled e2e69f65f5 feat(core): add configurable mock responses for stub AI services (#2765)
* feat(core): add configurable mock responses for stub AI services

Adds AiMockConfigLoader, a shared mock-response config file (path via
AI_MOCK_CONFIG env var or floci.ai-mock-config-file) that lets callers
override Textract/Comprehend/Rekognition's fixed stub responses on a
per-call basis, so application logic that branches on detection
results (e.g. "escalate if sentiment is NEGATIVE") can be exercised
end-to-end against floci. Mirrors Step Functions' SFN_MOCK_CONFIG
mechanism (same mtime-cached reload without restart), but is shared
across three services and never throws: a missing file, unset env
var, or no matching entry all fall back to the existing default stub,
since mocking here is opt-in on top of an always-available default,
not the only way to invoke an action.

Lookup keys: Comprehend keys on the exact Text value; Textract and
Rekognition key on "<Bucket>/<Name>" from S3Object (a Bytes-backed
image/document has no such key, so mocking only applies to
S3Object-based calls). CompareFaces keys off SourceImage only. The
Textract async Start*/Get* job flow does not support mocking.

Closes #2764

* fix(core): catch unchecked exceptions when loading AI mock config

Path.of(path) throws InvalidPathException (unchecked) for a malformed
path string, and filesystem access can raise other unchecked
exceptions IOException alone doesn't cover. load() only caught
IOException, so a bad AI_MOCK_CONFIG value would propagate past the
loader and turn a normal Comprehend/Textract/Rekognition request into
a 500 — the exact opposite of this loader's contract (mocking is
optional; it must never break the default stub). Wrapped the load
logic in an outer catch (RuntimeException) that falls back the same
way the existing IOException cases already do.

Addresses review feedback on #2765.
2026-08-30 14:44:12 -05:00
lex00 0b46d804c0 feat(codegurureviewer): repository association lifecycle with tagging (#2741)
* feat(codegurureviewer): repository association lifecycle with tagging

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

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

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

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

A JAX-RS Integer binding fails during parameter conversion, so
MaxResults=abc surfaced as 404 before the handler ran. The parameter is
now bound as a String and parsed in the controller, routing bad values
through the modeled 400 ValidationException.
2026-08-30 14:44:08 -05:00
Matheus André eaecb36425 fix(eks): implement cluster restoration after restart to maintain state (#2780)
Signed-off-by: Matheus André <matheusandr2@gmail.com>
2026-08-30 14:44:05 -05:00
Matheus Oliveira cfe8566511 fix(cloudwatch): evaluate alarms over CloudWatch's wider evaluation range (#2771)
Querying exactly EvaluationPeriods buckets fell back to TreatMissingData as soon
as one was empty. Real datapoints reaching further back now decide the state
first, and the premature-transition rule is honored.

Fixes #2700

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-30 14:40:40 -05:00
Allen Sanborn 2a014d2add fix(s3): accept the log-delivery-write canned ACL (#2653)
PutBucketAcl/PutObjectAcl rejected x-amz-acl: log-delivery-write with
"Unsupported x-amz-acl value", even though it is a standard AWS canned
ACL (Terraform's aws_s3_bucket_acl / access-logging modules send it to
grant the S3 log-delivery service group permission to write access logs
into a bucket). Of the eight AWS canned ACL values, this was the only
one missing from cannedObjectAclXml's switch - the rest were already
handled.

Add the log-delivery-write case, translating it to WRITE and READ_ACP
grants for the well-known LogDelivery group URI
(http://acs.amazonaws.com/groups/s3/LogDelivery), following the same
groupGrant pattern used for public-read/public-read-write.
2026-08-30 14:40:35 -05:00
lex00 7b6266e902 feat(connect): instance management (CreateInstance family, attributes, storage configs, tags) (#2740)
* feat(connect): instance management (CreateInstance family, attributes, storage configs, tags)

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

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

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

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

* fix(connect): validate boolean instance attribute values

UpdateInstanceAttribute stored any nonblank string while the inbound/outbound
flags coerced it to boolean, so an invalid value read back inconsistently
across DescribeInstanceAttribute and DescribeInstance. Reject anything but
true/false with InvalidParameterException and store the canonical lowercase
form.
2026-08-30 15:15:49 -04:00
Kenshin Okinaka fc3c28323a feat(ses): support v2 tenant suppression attributes and tenant-scoped suppression list (#2743)
* feat(ses): support v2 tenant suppression attributes and tenant-scoped suppression list

* fix(ses): guard runWithTenant against a null TenantName

* fix(ses): collapse an absent TenantName to the service-level message on tenant suppression ops

* fix(ses): collapse an absent TenantName to the service-level message on the remaining tenant ops

* fix(ses): collapse an empty TenantName to the service-level message on GetTenant/DeleteTenant
2026-08-30 14:53:06 -04:00
Hector Ventura b76eadc98e docs(cloudformation): generate the supported resource-type table (#2739)
The "Supported Resource Types" table was hand-maintained, and had drifted:
ten provisioned types were undocumented, including the whole CloudFront
row, Lambda's Permission/MicrovmImage/NetworkConnector, RDS DBProxy and
DBProxyTargetGroup, ECS capacity providers, EC2 VPCEndpoint and
ApiGatewayV2 Authorizer.

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

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

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

Also flags two things cheaply, before anyone waits on a Quarkus boot: a
provisioner missing @ApplicationScoped, and a type claimed by both the
legacy switch and a provisioner.
2026-08-30 13:04:29 -05:00