Commit Graph
213 Commits
Author SHA1 Message Date
Alex BannaandAlexander Banna bc21367cc4 feat(cloudformation): provision AWS::Events::EventBus as a real custom bus (#1807)
* feat(cloudformation): provision EventBridge event buses

* fix(cloudformation): restore main's provisioner changes lost in the EventBus merge

The previous conflict resolution took this branch's whole
CloudFormationResourceProvisioner, which silently reverted five commits main had
landed on that file since the merge base — including the DynamoDB/Lambda delete
idempotency from #1803 and AWS::EC2::LaunchTemplate from #1973.

Re-resolve from main's file and apply only this branch's EventBus additions on
top: the ownership-tracking provisioner, its validation helpers, and the typed
rethrow in deleteEventBridgeRuleSafe. main's provisionEventBusPolicy and inline
Policy support are kept, with Policy added to EVENT_BUS_SUPPORTED_PROPERTIES so
the inline form is no longer rejected.

* fix(cloudformation): delete EventBus resources created before ownership tracking

deleteEventBusSafe(StackResource) refused to delete whenever the
FlociEventBusCreatedTime attribute was absent, treating "ownership not tracked"
the same as "ownership changed". Stacks provisioned by an earlier Floci build are
restored from cloudformation-stacks.json without that attribute, so the first
DeleteStack after upgrading left them permanently in DELETE_FAILED.

Only refuse when a recorded created-time actually disagrees with the live bus.
A missing attribute falls back to the pre-tracking behaviour of deleting what the
stack recorded it created.

* fix(cloudformation): adopt untracked EventBus on update and record identity before the policy call

Two provision-side defects, both surfaced in review:

UpdateStack broke for stacks provisioned before FlociEventBusCreatedTime existed.
Those resources are restored without the attribute, so the adoption guard's
'existingCreatedTime == null' arm re-threw ResourceAlreadyExists on every update,
including no-ops. Same inverted guard the delete path already uses: only a recorded
time that actually disagrees means the bus was recreated out of band.

The bus also leaked when Policy application failed. r.setPhysicalId ran after
putPermission, and rollbackCreatedResources skips resources whose physicalId is
null, so a malformed policy left a live bus rollback could not find. Identity and
ROLLBACK_OWNED_ATTR are now recorded before the policy call, matching how
provisionIamRole marks a freshly created role. The attribute is cleared on the
adoption path so rollback never deletes a bus this stack did not create.

* chore: re-run CI

Build and Test failed on RuntimeApiServerTest's extension/stop race, a pre-existing
flake unrelated to this change (no CloudFormation test failed). Root-caused separately:
test-timing half in #2141, server-side shutdown-ordering half filed as an issue.

* fix(cloudformation): adopt tagged pre-tracking event buses

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): reject unsafe EventBus policy updates

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:38:17 -04:00
Alex BannaandAlexander Banna 33ba5ac59c feat(apigateway): route execute-api hostnames for HTTP APIs (#2054)
* feat(apigateway): route execute-api hostnames for HTTP APIs

* fix(apigateway): disambiguate execute-api routing

* fix(apigateway): make the execute-api host filter idempotent

Host matching alone cannot tell whether a request has already been rewritten,
because the Host header still names the execute-api subdomain afterwards. If any
other filter rewrites first, this one rewrites again and produces
/execute-api/{apiId}/execute-api/{apiId}/... which routes to nothing.

Bail out when the path is already under /execute-api/. This keeps the filter
correct regardless of where it sits in the provider chain.

* fix(apigateway): enforce disableExecuteApiEndpoint on the direct execute-api path

The setting was only checked in ApiGatewayExecuteApiHostFilter, which sees the
host-based route (*.execute-api.localhost.*). A request to the direct
/execute-api/{apiId}/{stageName}/... form reaches dispatchV2 without passing the
filter, so the same disabled HTTP API answered 403 by host and 200 by path.

Move the check into dispatchV2, the single choke point both entry points funnel
through, so they cannot disagree. A missing API is left to findMatchingRoute's 404
rather than reported from here.

* test(dynamodb): retain Quarkus port for cleanup

* fix(apigateway): match disabled HTTP API response

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:26:24 -04:00
Alex BannaandAlexander Banna e1f389f61b feat(lambda): support EFS file system configs (#2053)
* feat(lambda): support EFS file system configs

* fix(lambda): prevent stale and shared EFS mounts

* fix(lambda): isolate warm pools by version

* test(dynamodb): retain Quarkus port for cleanup

* fix(lambda): scope warm pool invalidation by environment

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:12:39 -04:00
soreavis f1c81977ec fix(cloudwatch): warn on unsupported Logs Insights filter operators (#2170)
parseFilter scans for the leftmost '!=', '==' or '=' outside a quoted
value, so the '=' inside '>=', '<=' and '=~' won. For '>=' and '<=' the
comparison character was absorbed into the field name ("@message >"),
which resolves to null for every row, and passesFilters treats null as
non-matching; for '=~' the value became the literal "~ /ERROR/". Either
way the query came back with no rows and no warning, because as far as
parseFilter was concerned it had found a valid operator.

Stop the scan when a position starts one of those three operators, so
control reaches the "Ignoring unsupported Logs Insights filter" warning
that '<', '>', 'like', 'not like' and 'in' already hit, and the stage is
dropped instead. Quote tracking is untouched, so a '>=' inside a quoted
value is still just part of the value.

The docs table describing how unsupported syntax degrades had the same
two cases inverted: '=~' listed as warn-and-drop when it mis-parsed, and
bare '<' / '>' as silent-zero-rows when they already warned. Folded into
the one row that now matches the code, and the compound and/or mis-parse
this change does not fix got its own row instead of staying implied.

Refs #2042
2026-08-12 10:52:24 -04:00
AgustinBertagna 819bfedc6c feat(appsync): Phase 6 — Query Execution + HTTP Endpoint (#1884)
* feat(appsync): Phase 6 GraphQL HTTP execute endpoint

Expose POST /v1/apis/{apiId}/graphql with AppSync-compatible error
mapping, dual Content-Type, schema rehydrate on boot, and smoke
execution without Phase 8 DataFetchers.

* fix(appsync): initialize graphql IdGenerator at native runtime

Query execution pulls graphql.util.IdGenerator into the native image
reachability graph; its static Random must not be frozen in the heap.

* fix(appsync): cache GraphQL engines and always set x-amzn-errortype

Cache graphql-java GraphQL wrappers per apiId in SchemaRegistry (invalidate
on register/remove/rehydrate), and emit x-amzn-errortype on all data-plane
non-2xx responses for AWS parity with AppSync transport errors.

* fix(appsync): hide unexpected exception details on GraphQL 500

AppSync returns a fixed InternalFailure message for unexpected
errors; keep the real cause in server logs only.

* chore(appsync): drop redundant native-init comment

* fix(appsync): rehydrate schemas across all accounts on boot

Startup has no request context, so keys()/get() only saw the default
account. Mirror recoverOrphans with scanAllAccountsAsMap, persist SDL via
putForAccount in the worker, and drop the shared .atl/ gitignore entry.

* fix(appsync): keep non-404 AwsException on data-plane envelope

Avoid rethrowing AwsException from the GraphQL execute endpoint into
AwsExceptionMapper (__type). Map unexpected lookup failures to
InternalFailure with the AppSync errors[] shape instead.

* docs(appsync): point error formatter @see at $util.error docs

security-authz.html covers authorization types, not errorType/errorInfo.
Cite built-in-util-js.html where $util.error documents those fields.

* refactor(storage): type StorageFactory.create as AccountAwareStorageBackend

The factory always wraps every mode in AccountAwareStorageBackend; declaring
that return type removes unsafe casts at AppSync/CodePipeline/CloudFormation
call sites and updates test overrides/mocks to match production.

* fix(test): stub StorageFactory.create with AccountAware backends

thenAnswer stubs that returned bare InMemoryStorage ClassCast after
create() was typed as AccountAwareStorageBackend; align the remaining
service unit tests with the production return type.
2026-08-12 09:32:03 -04:00
Anders Wasen 19a32ab51d feat(rds-data): adding data-api preparedstatement() support (#1887)
* feat(rds-data): adding data-api preparedstatement() support

* feat(rds-data): addressing greptile comments

* feat(rds-data): addressing PR review comments, fixing timestamp
2026-08-12 07:03:06 -04:00
Olamide Kosile c21337c3b1 feat(iam): add GetAccountSummary support (#1986)
Adds all 34 documented SummaryMap fields: live entity counts (Users,
Groups, Roles, customer-managed Policies, InstanceProfiles,
PolicyVersionsInUse) plus IAM quota values, cross-checked against
AWS's published service quotas and independently verified against
moto's AccountSummary implementation. Resources Floci does not track
(MFA devices, SAML/OIDC providers, server certificates, account
password) report 0 rather than being omitted, so callers indexing
into the full AWS field set don't hit a missing-key error.

Part of #1938.
2026-08-12 00:23:51 -04:00
Dennis O'Connor b6765b3056 feat(apigateway): API key management — UpdateApiKey, DeleteApiKey, UsagePlan custom-id, generateDistinctId (#1883)
* feat(apigateway): implement UpdateApiKey and DeleteApiKey

Adds the two missing API key lifecycle operations for API Gateway v1:

- UpdateApiKey (PATCH /apikeys/{apiKeyId}): applies replace patch
  operations for /name, /description and /enabled, 404 when absent
- DeleteApiKey (DELETE /apikeys/{apiKeyId}): 202 on success, 404 when
  absent

Also adds a description field to the ApiKey model so it can be set on
create, returned in responses and patched via UpdateApiKey.

Integration tests cover each patch path, the 404 cases and a repeated
delete. Service docs updated to move both operations out of the Not
Implemented list.

* feat(apigateway): persist and return UsagePlan tags

CreateUsagePlan accepted a tags map but discarded it, so tags never
appeared in CreateUsagePlan, GetUsagePlan or GetUsagePlans responses.
Tags are now stored on the UsagePlan model and emitted by the
controller.

A _custom_id_ tag sets a deterministic plan ID, mirroring the existing
createRestApi behaviour. Tag values are coerced through String.valueOf
rather than an unchecked cast so a non-string value in the request body
cannot produce a ClassCastException on later reads.

The tags field defaults to an empty map, so usage plans already
persisted without it deserialize unchanged.

* fix(apigateway): treat an absent generateDistinctId as id == value

CreateApiKey generated a distinct short-token id whenever
generateDistinctId was absent, so the emulator's default disagreed with
AWS. Only an explicit generateDistinctId: true produces an id that
differs from the key value; absent and false both yield id == value.

A blank supplied value now falls back to a generated UUID on the
distinct-id path too, matching the guard the shared-value path already
had.

Integration tests cover all three states — absent, explicit false and
explicit true — and the service docs gain a table for the behaviour.

* refactor(apigateway): route UsagePlan custom IDs through ReservedTags

The usage plan override read the raw _custom_id_ key directly, which
diverged from createRestApi after #2045 made floci:override-id the
reserved key. It now calls ReservedTags.extractOverrideApiId, so the
plan gets the same validation (non-blank, no whitespace, no control
characters, no /?#) and the same precedence when both keys are present.

Persisted tags go through stripApiGatewayReservedTags, so neither
override key survives into CreateUsagePlan, GetUsagePlan or
GetUsagePlans responses.

Tests assert the reserved keys are absent from the returned tags and
cover the deprecated key, the precedence rule and both rejection paths.

* fix(apigateway): stop deleted and disabled API keys authenticating

A UsagePlanKey stores its own copy of the API key value, and the data
plane resolves requestContext.identity.apiKey by matching the x-api-key
header against those copies. Neither revocation path reached them:

- DeleteApiKey removed the key from apiKeyStore but left every usage
  plan association behind, so a deleted key stayed listed by
  GetUsagePlanKeys and kept being recognised on the data plane. It now
  detaches the key from every plan in the region first, matching AWS.
- resolveApiKeyForRequest never read enabled, despite its javadoc
  saying it matched enabled keys, so patching /enabled to false changed
  nothing about request handling. It now requires the key to still exist
  and be enabled, via a new non-throwing findApiKey lookup.

Floci has no apiKeyRequired gate, so a revoked key yields a null
identity.apiKey rather than a 403; the docs now say so explicitly. The
new integration test pins both paths and fails on all three assertions
without these changes.
2026-08-12 00:02:32 -04:00
f17dd1ed81 feat(iam): support OIDC identity providers (#2106)
* feat(iam): support OIDC identity providers

Implement CreateOpenIDConnectProvider, GetOpenIDConnectProvider,
DeleteOpenIDConnectProvider, AddClientIDToOpenIDConnectProvider,
RemoveClientIDFromOpenIDConnectProvider, UpdateOpenIDConnectProviderThumbprint
and the provider tag actions, and back ListOpenIDConnectProviders with real
data instead of a fixed empty list.

A provider is identified by its URL, so the ARN is derived from it and the
scheme is stripped: GetOpenIDConnectProvider reports the URL without https://,
matching AWS. Creating the same URL twice returns EntityAlreadyExists.

Thumbprints are stored and echoed back but never validated against the remote
endpoint, since nothing here performs the TLS handshake they describe.

Closes #2102

* test(iam): cover OIDC provider persistence and cap the provider URL

Add IamServicePersistenceTest: IAM state is persisted through StorageFactory,
so a restart must preserve providers along with their client IDs, thumbprints,
tags and creation time. The model carries an Instant and two lists, so a broken
serialization round trip would surface here first.

Also enforce the documented 255-character limit on the provider URL, which was
otherwise unchecked and would have produced an oversized ARN.

* fix(iam): match verified AWS behaviour for OIDC providers

Checked the emulated surface against a live AWS account and corrected where it
diverged:

AddClientIDToOpenIDConnectProvider and RemoveClientIDFromOpenIDConnectProvider
are idempotent on AWS. Adding a client ID that is already present, and removing
one that was never added, both succeed and change nothing; they previously
raised EntityAlreadyExists and NoSuchEntity.

Exceeding the thumbprint limit reports InvalidInput, not LimitExceeded. The
client ID quota and duplicate-provider messages now use the AWS wording, and
DeleteOpenIDConnectProvider reports its own not-found phrasing.

Confirmed unchanged: the ARN is derived from the scheme-less URL, Get echoes the
URL without its scheme, the URL is capped at 255 characters, the client ID quota
is 100 with LimitExceeded, and URLs are not normalized, so a trailing slash or a
case difference yields a separate provider.

* fix(iam): reject missing required parameters on OIDC mutators

A null ClientID read as "not in the client ID list", so
RemoveClientIDFromOpenIDConnectProvider reported a no-op success for a request
that never named one. DeleteOpenIDConnectProvider had lost its ARN check when
it stopped routing through getOpenIDConnectProvider to report the not-found
wording AWS uses for that action, so a request with no ARN came back as
NoSuchEntity rather than a required-parameter error.

Route every OIDC mutator through shared ARN and client ID checks so a malformed
request fails as ValidationError before any lookup.

* fix(iam): unbreak the reflective test fixture for the new constructor arity

IamServiceTestHelper resolves the package-private IamService constructor
reflectively against a hardcoded parameter list, so the extra storage backend
broke it at run time with nothing failing at compile time. Every test using the
fixture errored, and one of them blocks on a socket read rather than failing,
which exhausted the CI job before it could report. Extend both lookups and both
newInstance calls to the new arity.

* fix(iam): reject empty tag collections on OIDC providers

TagOpenIDConnectProvider with no Tags and UntagOpenIDConnectProvider with no
TagKeys performed a no-op mutation and returned 200. AWS rejects both, as
InvalidInput rather than ValidationError, with distinct messages for the map and
the key list; checked against a live account. Validate the ARN on the tag path
too, so a missing one fails before the lookup like the other mutators.

---------

Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com>
Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
2026-08-11 23:07:37 -04:00
Mihai BlidaruandMihai Blidaru a79e04e4ec fix(firehose): build S3 object keys with AWS prefix expressions and name suffix (#1858)
* fix(firehose): build S3 object keys with AWS prefix expressions and name suffix

Delivered objects now follow the AWS key format
<evaluated prefix><stream>-<version>-<yyyy-MM-dd-HH-mm-ss>-<uuid> observed on
real AWS: default prefix yyyy/MM/dd/HH/ when no Prefix is set, literal
concatenation of the time prefix for expression-free prefixes,
!{timestamp:<pattern>} and !{firehose:random-string} evaluation, no .json
extension, and CustomTimeZone support. The non-AWS {year}/{month}/{day}/{hour}
placeholders are gone.

See floci-io/floci#1857 for the behavior captured against a real AWS account.

* refactor(firehose): cache the default time-prefix DateTimeFormatter

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-08-11 21:40:24 -04:00
lex00 40e8aad55a feat(lambdamicrovms): AWS Lambda MicroVMs service module and its CloudFormation types (#2079)
* feat(lambdamicrovms): AWS Lambda MicroVMs service module

Adds the Lambda MicroVMs control plane, a service AWS took GA on 2026-06-22:
MicroVM images with a version and build lifecycle, the managed base-image
catalog, MicroVM CRUD, and VPC egress network connectors.

Two service models rather than one. Lambda Microvms (apiVersion 2025-09-09)
carries images and MicroVMs under /2025-09-09; Lambda Core (2026-04-30)
carries network connectors under /2026-04-04. Both sign as lambda, so their
requests arrive under the existing lambda claim in ResolvedServiceCatalog and
route by path. Neither prefix collides with anything LambdaController serves,
and both are enabled by the lambda service rather than adding a toggle.
Tagging rides the classic /2017-03-31/tags/ routes, so LambdaTagController
learns the MicroVM ARN forms.

Resources are stored per account and region. Floci resolves a per-request
account in AccountContextFilter and these ARNs carry it, so region-only
storage would let two accounts sharing a region read and mutate each other's
images, MicroVMs and connectors.

Wire shapes come from the vendored service models and, where the models are
silent or disagree with the service, from responses recorded against live
AWS. Several members the models mark optional are enforced in practice — a
connector needs ClientToken, OperatorRole, NetworkProtocol and
AssociatedComputeResourceTypes despite all four being optional in Smithy — and
several resources are returned in a different projection per operation: an
image in four shapes, a connector in four, with only the list summaries
carrying Type.

Builds converge instantly rather than on a timer, the usual emulator trade.
Where that would otherwise produce an inconsistent body it is handled
explicitly: a create or update reports the transitional state and does not
name the version it is minting as active, because a client reading otherwise
would launch a MicroVM off a version that does not exist yet.

Auth tokens, the per-VM endpoint, and the idle and suspend timers are
deliberately out of scope here; they belong to a full-fidelity MicroVMs
emulator rather than to CloudFormation provisioning.

Verified against a suite of responses recorded from live AWS
(https://github.com/INTENTIUS/m80): 26 checks over the image, MicroVM and
connector lifecycles, 0 failures.

* feat(cloudformation): provision AWS::Lambda::MicrovmImage and AWS::Lambda::NetworkConnector

Registers a CfnResourceProvisioner for the two MicroVM CloudFormation types
against the LambdaMicrovmsService added alongside, so a template declaring
either provisions and deletes rather than being skipped.

Uses the CloudFormationResourceRegistry interface rather than the switch in
CloudFormationResourceProvisioner, following SqsCfnProvisioner.

* test(lambdamicrovms): AWS CLI compatibility coverage for images, MicroVMs and connectors

* fix(lambdamicrovms): wire service state through StorageFactory

Images, MicroVMs and connectors were held in plain in-memory maps, so in
persistent mode a restarted Floci lost them while the CloudFormation stacks that
created them survived. Those stacks then referenced resources that no longer
existed and DeleteStack failed on the 404.

The three stores are now StorageBackedMap over StorageFactory backends, keyed
region/id. MicroVMs are delivered as part of the lambda service, so they share
its storage key and therefore its configured mode and flush interval rather than
declaring their own. The account half of the key is dropped from the service and
left to the backend, which prefixes and strips the same account the
RegionResolver returns, so region and account isolation are unchanged.

StorageBackedMap only marks the backend dirty on put and remove, so every path
that mutated a stored object in place now writes it back: image update, version
status, version delete, rebuild, MicroVM settle and terminate, connector settle
and update, and both tag paths.

* style(core): import the lambda microvms controllers in the service catalog

* fix(lambdamicrovms): register the persisted types for reflection

Moving images, microvms and connectors into StorageBackedMap made their model
classes persisted types, and PersistedModelReflectionTest fails on any that lack
@RegisterForReflection because native-image persistence cannot rebuild them on
restart.
2026-08-10 23:10:48 -05:00
Jan Waś f417164d42 fix(rds): advertise reachable endpoints (#2074)
RDS endpoints currently expose the proxy's container port even when
Docker publishes it on a random host port. That works when the host can
route to the container network, but fails with VM-backed Docker
runtimes.

Resolve the current container's published port when an external
endpoint host is configured while preserving the internal proxy port
used by the listener.
2026-08-10 22:03:52 -04:00
Kenshin Okinaka bd01c1a70b feat(ses): implement SendCustomVerificationEmail for v1 and v2 (#2191)
* feat(ses): implement SendCustomVerificationEmail for v1 and v2

Add the SendCustomVerificationEmail action on both the v1 Query API and the v2 REST
JSON API (POST /v2/email/outbound-custom-verification-emails). The service renders the
stored custom-verification-email template into the inspection mailbox and the SMTP
relay, returns a MessageId, and registers the recipient as a pending-verification
identity, matching AWS. A missing template is the v1-native
CustomVerificationEmailTemplateDoesNotExist (remapped to NotFoundException on v2), with
the v1 send message ("Template <name> does not exist") verified against AWS.

* test(ses): log custom-verification compat cleanup failures instead of swallowing them

The @AfterAll cleanup deleted templates and identities in best-effort try/catch
blocks that swallowed every exception, so a real deletion failure would leave
state behind with no diagnostic. Log the affected template/identity and the
exception message, per AGENTS.md's rule against silently discarding exceptions.
2026-08-10 20:34:09 -04:00
Michal SchreiberandMichal Schreiber ac4b865a34 feat(ec2): support managed prefix lists (#2105)
* feat(ec2): support managed prefix lists

Implement CreateManagedPrefixList, DescribeManagedPrefixLists,
GetManagedPrefixListEntries, ModifyManagedPrefixList and
DeleteManagedPrefixList.

Entries are versioned: a list starts at version 1 and every modification that
changes entries stores a new version, so GetManagedPrefixListEntries can serve
an earlier TargetVersion. Renaming or raising MaxEntries does not create a
version, CurrentVersion makes a modification conditional, and removals apply
before additions so one call can replace an entry's description.

The AWS-managed gateway-endpoint lists are now built once and served by both
DescribeManagedPrefixLists and the existing DescribePrefixLists, so the two
surfaces cannot report different CIDRs for the same list. They are read-only.

Closes #2100

* fix(ec2): validate prefix list input and keep tag copies in sync

Three defects in the managed prefix list surface:

ModifyManagedPrefixList only checked the resulting entry count against
MaxEntries, so a zero or negative MaxEntries on an empty list passed the check
and persisted an impossible capacity.

CreateTags and DeleteTags update the generic tag store and then mirror the
result onto the resource, but updateResourceTags had no arm for prefix lists,
leaving the copy on the model stale for describe responses and tag filters.

MaxEntries and TargetVersion were converted with Integer/Long.valueOf, so
malformed input escaped as an unchecked NumberFormatException and became a 500
rather than a structured EC2 client error.

* fix(ec2): reject a missing PrefixListId and infer the prefix-list tag type

A null PrefixListId reached List.of() inside describeManagedPrefixLists and
threw NullPointerException, so DeleteManagedPrefixList,
GetManagedPrefixListEntries and ModifyManagedPrefixList answered a request that
never named a list with a 500 rather than a client error. Guard the lookup and
raise MissingParameter.

inferResourceType had no pl- arm, so tags on a prefix list were stored but
reported as resourceType "unknown" and were invisible to a DescribeTags filter
on resource-type. The existing test only covered describe and tag: filters,
which is why this went unnoticed.

Also cover the accepting branch of the address-family check, which until now was
only reached by the rejecting case.

* fix(ec2): treat a blank numeric parameter as malformed rather than absent

intOrNull and longOrNull returned null for a present but blank value, which the
callers read as "parameter not supplied". For CurrentVersion that silently
downgraded a conditional ModifyManagedPrefixList to an unconditional one, so a
request that asked to be gated on a version was applied anyway. Only an absent
parameter is null now; a blank one reaches the parse and surfaces as
InvalidParameterValue.

* fix(ec2): report PrefixListVersionMismatch for a stale CurrentVersion

A conditional ModifyManagedPrefixList that loses the version check returns
PrefixListVersionMismatch on AWS, not IncorrectState; verified against a live
account, which also supplies the message. The Terraform provider keys its retry
handling on that code, so the previous one would have left a caller unable to
recognise a losing conditional update.

---------

Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com>
2026-08-10 19:03:26 -05:00
Tim Gibson 50fe67dde6 feat(eventbridge): deliver events to event-bus targets (#1814)
* feat(eventbridge): deliver events to event-bus targets

* fix(eventbridge): skip null resources when republishing to event-bus targets

* fix(eventbridge): validate Detail and resolve account for bus targets

readTree accepts any well-formed JSON value, so an input override producing
"hello" or [1,2] passed the guard and reached the target bus as a scalar
detail, with putEvents reporting success — a silent malformation rather than
the intended warn-and-drop. The pass-through arm had the same hole. Both arms
now share one isObject() check.

Bus targets also went through the two-arg putEvents overload, which passes a
null accountId, so a cross-account bus ARN resolved in the caller's account and
surfaced only as a warning. Thread the ARN's account through, as SQS targets
already do via the queue URL. Same-account and account-less ARNs still forward
null: only that path carries the legacy-key fallback in
AccountAwareStorageBackend.get().

* docs(eventbridge): document event-bus target behavior and limits

* fix(eventbridge): cap bus-to-bus forwarding at one hop, matching AWS
2026-08-10 17:46:13 -04:00
Miguel Carvalho 7e5afae61b feat(eks): support IRSA with a real OIDC issuer and JWT validation (#2108)
* feat(eks): support IRSA with a real OIDC issuer and JWT validation

Every EKS cluster now gets an OIDC identity provider, so the full IRSA flow
works end to end without mocked or hardcoded tokens.

CreateCluster generates an RSA-2048 keypair and an AWS-shaped issuer URL,
returned by DescribeCluster as identity.oidc.issuer. The issuer is a faithful
string for building trust policies but is never dereferenced: STS resolves the
signing key in-process via a new OidcIssuerKeyLookup port, declared in
core.common so services.iam does not depend on services.eks.

Key material lives in storage separate from the Cluster model. Cluster is
serialized straight onto the DescribeCluster wire response, so a private key
carried there would leak; @JsonIgnore would instead lose it across restarts and
break tokens minted earlier.

sts:AssumeRoleWithWebIdentity previously accepted any non-blank token and
returned a hardcoded subject. It now verifies, but only for issuers Floci hosts:

- RS256 signature against the cluster's public key
- iss matches the issuer exactly
- aud contains sts.amazonaws.com
- exp / nbf, with 60s of clock-skew tolerance
- the role's trust policy, via a new WebIdentityTrustPolicyEvaluator matching
  Principal.Federated and the Condition block

The response now carries the token's real claims in
SubjectFromWebIdentityToken, Provider, and Audience. Bad tokens return
InvalidIdentityToken (400); a trust policy that does not permit the subject
returns AccessDenied (403) — a check the web-identity path was missing entirely.

Tokens from an issuer Floci does not host stay permissive, since Floci cannot
verify a third-party signature. Existing behaviour is therefore unchanged and no
configuration flag is required.

WebIdentityTrustPolicyEvaluator is a sibling of AssumeRolePolicyEvaluator rather
than an extension of it: that evaluator serves sts:AssumeRole, hardcodes that
action, reads only Principal.AWS, and ignores conditions. Condition values are
compared with exact, case-sensitive equality instead of the existing
globMatches, which lowercases both operands — case-folding an OIDC subject would
silently admit a different service account.

Because Floci has no kubelet to project a token into a pod, a local-dev harness
can mint one via POST _floci/eks/clusters/{name}/oidc-token and write it to the
file named by AWS_WEB_IDENTITY_TOKEN_FILE. Signing stays server-side so the
private key never leaves Floci. OIDC discovery and JWKS routes are served under
the same _floci namespace, for fidelity rather than because anything fetches
them; the AWS-shaped issuer path is not resolvable by Floci's embedded DNS and
would collide with S3's path-style catch-all.

Adds 51 tests: unit coverage for the verifier, the trust-policy evaluator, and
the OIDC service, plus an end-to-end integration test covering the mint ->
assume -> credentials path and its negative cases (wrong service account,
tampered signature, wrong audience, expired, alg:none).

* fix(iam): close two web-identity validation gaps and backfill cluster OIDC state

Three defects found in review of the IRSA change.

An unsigned "header.payload." token bypassed validation entirely. verify()
split with a -1 limit so a trailing empty segment was preserved, but
parseClaims() — which backs peekIssuer() — did not. Java drops trailing empty
strings by default, so such a token split into two parts, its issuer went unseen,
and STS classified it as an opaque third-party token: signature, claim, and
trust-policy checks were all skipped and credentials were issued for a JWT that
was never signed. Both split sites now pass -1.

StringLike and StringNotLike on an OIDC condition key folded case. They
delegated to IamPolicyEvaluator.globMatches, which lowercases both operands, so
a trust policy scoped to one service account or namespace would admit another
differing only in case — the exact hazard the StringEquals branch was written to
avoid. Adds a case-sensitive glob and uses it for both operators. Action matching
still uses globMatches, which is correctly case-insensitive.

Clusters persisted before this feature never gained an issuer or key, so after an
upgrade DescribeCluster reported no identity.oidc.issuer, minting returned 400,
and the JWKS routes 404'd until the cluster was recreated. EksService now
backfills on startup, and re-runs ensureKey for clusters that already have an
issuer so a restart cannot leave a known issuer without its signing key.

Each fix has a regression test confirmed to fail without it.

* fix(eks): keep IRSA OIDC state scoped to the cluster's owning account

The startup backfill read clusters across every account via scanAllAccounts() but
wrote them back with the request-scoped put(), which resolves to the default
account outside a request context. A cluster owned by any other account kept its
issuer-less record while a duplicate appeared under the default account, leaving
DescribeCluster and the IRSA endpoints broken for the owner. The backfill now
takes the account from the cluster record and writes with putForAccount, per the
pattern StorageFactory documents for work running outside a request.

The same root cause affected key lookup more seriously. findVerificationKey used
the account-scoped scan(), so an issuer owned by a non-default account went
unresolved — and an unresolved issuer is treated as a third-party provider, so
STS accepted the token with no signature, claim, or trust-policy check at all.
It now scans every account, which is correct regardless: an issuer URL is
globally unique, and the account calling AssumeRoleWithWebIdentity need not be
the one that owns the cluster.

deleteKey and findKeyByCluster stay account-scoped; both are only reached from
request-scoped paths (DeleteCluster and the JWKS route), where the caller's
account is the right scope.

Both fixes have a regression test confirmed to fail without them.
2026-08-10 09:04:40 -04:00
Jérémie van der Sande 2594705f9c feat(elbv2): honor preserve_host_header parameter (#2109) 2026-08-09 15:34:30 -04:00
soreavis c8403ac6fc feat(iam): add service-linked role create, delete and deletion status (#2179)
* feat(iam): add service-linked role create, delete and deletion status

aws_iam_service_linked_role calls CreateServiceLinkedRole directly, and one
unsupported operation fails a whole account-bootstrap module. Delete and
GetServiceLinkedRoleDeletionStatus come with it, because create alone leaves
terraform destroy broken.

The role lands under /aws-service-role/<principal>/ with a trust policy for
that principal, and is readable by GetRole afterwards, which is what the
issue asks for.

The role NAME is a deterministic stand-in, not AWS's. The prefix is chosen
by the linked service and is not computable from the principal — AWS turns
lex.amazonaws.com into AWSServiceRoleForLexBots — so this derives a name
from the principal's labels instead: es.amazonaws.com becomes
AWSServiceRoleForEs.
Every label contributes, because rds.amazonaws.com and
rds.application-autoscaling.amazonaws.com are separate roles on AWS and a
config declaring both must not collide on one name.

A CustomSuffix is joined with an underscore, which is the separator callers
parse back out; Terraform recovers custom_suffix by splitting the role name
on it, and that attribute forces replacement, so any other join never
converges.

Deletion is synchronous, so the returned task id is already complete and its
status is SUCCEEDED. Task ids use the documented
task/aws-service-role/<principal>/<role>/<uuid> shape and are held in a
StorageFactory-backed store, so they are account-scoped and survive a
restart like every other IAM record.

Closes #2122

* fix(iam): classify service-linked roles by origin, not by path

CreateRole accepts the /aws-service-role/ prefix, so a role sitting at a
well-formed service-linked path is not necessarily one. Path-based
classification let DeleteServiceLinkedRole delete an ordinary role that
merely lived there.

Roles minted by CreateServiceLinkedRole now carry a marker, and the delete
path keys on that instead. The field is additive, so a role persisted
before this change reads as not service-linked, which is correct.

* fix(iam): protect service-linked roles from ordinary role mutations

DeleteServiceLinkedRole could answer 409 DeleteConflict, a code absent from
that action's published error list (LimitExceeded, NoSuchEntity,
ServiceFailure). It got there by routing through deleteRole, which refuses a
role that still has policies attached — and nothing stopped a caller from
attaching one to a service-linked role first.

AWS never reaches that state. It publishes UnmodifiableEntity (400) on twelve
role actions, and the message names the linked service to go through instead.
So refuse the mutation rather than handle the conflict it would otherwise
cause. This guards the eleven the emulator implements — AttachRolePolicy,
DetachRolePolicy, PutRolePolicy, DeleteRolePolicy,
Put/DeleteRolePermissionsBoundary, UpdateRole, UpdateAssumeRolePolicy,
Add/RemoveRoleFromInstanceProfile and DeleteRole; UpdateRoleDescription is the
twelfth and has no handler here. Several were silent: DeleteRole removed a
service-linked role at 200, UpdateAssumeRolePolicy rewrote its trust policy,
and AddRoleToInstanceProfile attached it to an instance profile. TagRole and
UntagRole stay open, matching AWS. DeleteServiceLinkedRole now removes the
role directly, since deleteRole refuses it.

Also validate CreateServiceLinkedRole's own inputs. CustomSuffix must match
[\w+=,.@-]{1,64}, as AWS constrains it — a suffix containing '/' previously
produced a role name outside RoleName's own pattern, leaving an ARN whose name
segment cannot be recovered. And a derived name over 64 characters is
rejected, because AWS caps RoleName at 64 on every action that takes one and
on the Role this action returns.

Document the three deviations that remain: the role name is derived locally
and will not match AWS for most services, deletion is synchronous so the
deletion status is always SUCCEEDED, and CreateRole accepts the
/aws-service-role/ path that AWS reserves.
2026-08-09 15:11:51 -04:00
Priamo Germosen d78520d5cb feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2) (#1914)
* feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2)

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

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

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

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

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

Tests updated accordingly and verified live against the packaged jar.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat(kinesisanalytics): add CreateApplicationPresignedUrl and SnapshotsEnabled

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

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

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

The readiness poller only called putApplication when advanceToRunning reported
RUNNING, not when it merely assigned flinkJobId after submitting the job (which
returns false until the job state catches up). pendingJars — a separate,
in-process-only cache — is already cleared by that point, so an emulator
restart between job submission and reaching RUNNING would leave the
application stuck: no persisted flinkJobId to resume polling, and no cached
JAR left to resubmit.
2026-08-09 15:01:30 -04:00
Feyikemi Ogunsanya 3b760bd8e5 fix(kinesis): resolve LATEST shard iterator position at GetShardIterator time (#1901)
* fix(kinesis): resolve LATEST shard iterator position at GetShardIterator time

A LATEST iterator recomputed its start position as the shard tip on
every GetRecords call, so records written between obtaining the iterator
and the first poll were skipped forever. Snapshot the tip once when the
iterator is created (matching DynamoDbStreamService) and encode it in
the iterator's index slot. GetShardIterator now also fails fast with
ResourceNotFoundException for an unknown shard, as on AWS.

Fixes #1900

* test(kinesis): add regression tests for tailing with a LATEST iterator

Reproduce issue #1900: a record written after the iterator is obtained
must be returned, both on the first GetRecords call and when polling
via NextShardIterator.

* test(kinesis): cover unknown shard validation for LATEST iterators

GetShardIterator must return ResourceNotFoundException when the shard
does not exist instead of deferring the failure to GetRecords.

* docs(kinesis): document shard iterator semantics

Describe the supported iterator types and the LATEST tip-snapshot
behavior; remove a stray empty Examples heading.

* fix(kinesis): validate shard existence for all iterator types in GetShardIterator

AWS rejects an unknown shard at GetShardIterator time for every
iterator type, not just LATEST. Apply the shard lookup unconditionally
instead of deferring the failure to GetRecords.

Addresses review feedback on #1901.

* test(kinesis): cover unknown shard validation across all iterator types
2026-08-09 00:10:16 -05:00
Alex Banna 6d829ff7a4 feat(s3): resolve index documents for static-website directory requests (#1815)
* feat(s3): resolve static website index documents

* fix(s3): drop the query string from the website folder redirect

Verified against a live S3 website endpoint in us-east-1 rather than inferred: a
bucket with photos/index.html answers

  GET /photos?code=abc&state=xyz  ->  302, Location: /photos/

with a bare Location. Same for HEAD and for nested prefixes (/a/b?x=1 -> /a/b/).

An earlier commit added query-string preservation on the strength of a review
comment asserting AWS behaved that way; the probe shows it does not, and LocalStack's
website_hosting.py agrees with the probe. An SPA whose OAuth callback lands on a
slash-less folder loses its parameters on real AWS too, so the emulator matches
rather than improving on it.
2026-08-08 22:42:26 -05:00
soreavis d943e09a73 feat(ec2): add ReplaceRoute (#2178)
Terraform calls ReplaceRoute whenever an existing route changes target, so
route tables could be created but never updated; the only workaround was
to destroy and recreate the table.

The action replaces the target of the route matching DestinationCidrBlock.
AWS takes exactly one target per call, so the target a request does not name
is cleared rather than carried over; a merge would leave a route holding two
targets at once, which AWS cannot produce.

Only GatewayId and NatGatewayId are modelled by Route, plus LocalTarget,
which needs no new field because `local` is the gateway id a route table's
built-in route already carries. The other ten AWS targets keep the
UnsupportedOperation they returned before this action existed rather than
being accepted and silently clearing the route they were meant to repoint.

Errors follow the EC2 reference: InvalidRoute.NotFound when no route matches
the destination, MissingParameter when DestinationCidrBlock is absent (an
IPv6 or prefix-list request), and InvalidParameterCombination for two
targets or none.

Closes #2087
2026-08-08 22:47:28 -04:00
Hector Ventura 8b8f837728 fix(ecs): report service deployments and MISSING failures on DescribeServices (#2176)
* fix(ecs): report service deployments and MISSING failures on DescribeServices

DescribeServices omitted services[].deployments entirely and always returned an
empty failures list. Both are read by AWS's own ServicesStable waiter, which
accepts on

  length(services[?!(length(deployments) == `1` && runningCount == desiredCount)]) == `0`

and fails fast on failures[].reason == "MISSING" (botocore
ecs/2014-11-13/waiters-2.json). Because that file is codegen'd into every SDK,
`aws ecs wait services-stable` and every SDK waiter polled for the full
40 x 15s before giving up, and Terraform's aws_ecs_service never converged
(terraform-provider-aws internal/service/ecs/service.go:2206 applies the same
len(Deployments) == 1 test). Evaluating the acceptor against the old payload
raises JMESPathTypeError, so it could not even be evaluated.

An ACTIVE service now reports exactly one PRIMARY deployment derived from its
current state, with rolloutState COMPLETED once runningCount reaches
desiredCount. The deployment id is derived from the service ARN and task
definition rather than generated per request, so it is stable across calls and
restarts and rolls over when the task definition changes. An unresolvable
service reference is returned as a MISSING failure carrying the ARN it would
have had, instead of being dropped.

Known deviations are documented in docs/services/ecs.md: a single deployment
with no draining ACTIVE alongside it, no deploymentController gating, and
pendingCount always 0.

Closes #2174

* fix(ecs): stamp a deployment with its own start time, not the service's

A task-definition change mints a new deployment id, but both deployment
timestamps were still taken from the service's creation time, so the payload
contradicted itself: a new deployment claiming to have been created when the
service was. botocore documents Deployment.createdAt as "the time when the
service deployment was created", and moto stamps it at deployment construction
(moto/ecs/models.py:540) rather than reusing the service's.

Track when the current deployment began on the service model, set at creation
and on every task-definition change, and report that. Services persisted before
this field existed fall back to the service creation time.

Raised in review on #2176.
2026-08-08 21:37:59 -05:00
Kenshin Okinaka aed50cc2b2 feat(ses): implement custom verification email templates for v1 and v2 (#1840)
* feat(ses): implement custom verification email templates for v1 and v2

Add the SES custom-verification-email-template CRUD APIs across both protocols,
backed by one shared StorageFactory store (key cvet::<region>::<name>):

- v1 Query: Create/Get/List/Update/DeleteCustomVerificationEmailTemplate.
- v2 REST JSON: the same five operations under
  /v2/email/custom-verification-email-templates.

Behaviour and error shapes were verified against real AWS: duplicate create is
AlreadyExistsException, missing is NotFoundException, the FromEmailAddress must
be a verified identity (NotFoundException otherwise), an invalid redirection URL
is BadRequestException, the template body is not content-validated, List omits
TemplateContent, and the store is shared between v1 and v2. SendCustomVerification-
Email is left as a follow-up.

* fix(ses): serialize custom-verification-template mutations under one lock

Guard the check-then-write of updateCustomVerificationEmailTemplate and
deleteCustomVerificationEmailTemplate on the same lock as create (renamed
cvetCreateLock -> cvetMutationLock) so a concurrent delete can't slip between
an update's existence check and its put and resurrect the just-deleted
template. Also clean up the shared template left by the v1 integration test.

* fix(ses): validate custom-verification-template fields before the existence check on update

UpdateCustomVerificationEmailTemplate ran the existence check before validating
required fields, so omitting TemplateName (possible on the v1 Query API) returned
NotFoundException instead of the required-field InvalidParameterValue (v2
BadRequestException). Validate first, matching CreateCustomVerificationEmailTemplate.
Also drop an unused Hamcrest import in the v2 integration test.

* test(ses): give the custom-verification-template cleanup a unique last order

update_missingTemplateName and cleanup_deleteSharedTemplate both used @Order(8);
with OrderAnnotation equal values have no guaranteed order and the suite is stateful.
Move the cleanup to @Order(9) so it runs last deterministically.

* fix(ses): throw v1 error codes for custom-verification-template not-found/duplicate

The CVET service methods threw the v2 codes (NotFoundException/404, AlreadyExistsException/400)
directly, so remapV1Exception was a no-op and the v1 Query path returned the wrong codes: the
v1 SDK's typed CustomVerificationEmailTemplate* exceptions never fired, and not-found used 404
instead of AWS's 400. Throw the v1-native codes (CustomVerificationEmailTemplateDoesNotExist /
CustomVerificationEmailTemplateAlreadyExists, both 400, verified against AWS) and map them in
remapV1Exception, so v1 is correct while v2 still returns NotFoundException/404 and
AlreadyExistsException/400. Also wrap the get/delete CVET endpoints in remapV1Exception (the
only two that lacked it) and pin the v1 codes with integration assertions.

* fix(ses): throw the v1 code for an unverified custom-verification-template sender

An unverified FromEmailAddress threw NotFoundException/404 from the shared CVET validator, so
the v1 Query wire carried a v2 code. AWS classic SES returns FromEmailAddressNotVerified/400
(verified); throw that v1-native code and map it in remapV1Exception, so v1 is correct while
v2 still returns NotFoundException/404. Pin the v1 code with an integration assertion.
2026-08-08 21:36:21 -05:00
Kenshin Okinaka fa9ed9100e feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2) (#1875)
* feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2)

SendEmail now honors ListManagementOptions (ContactListName / TopicName):

Opt-out suppression — recipients opted out of the named contact list are
suppressed as a Bounce, reusing the existing relay-exclusion and Bounce-event
path. A contact is opted out when UnsubscribeAll is set; with a TopicName, an
explicit OPT_OUT preference (or the topic's OPT_OUT DefaultSubscriptionStatus
when no explicit preference) suppresses; without a TopicName, only
UnsubscribeAll contacts are suppressed. A recipient that is not yet a contact
is created on the list automatically; an unknown contact list fails the send.

Unsubscribe handling — a single-recipient list-managed send gets a functional
unsubscribe link: the {{amazonSESUnsubscribeUrl}} body placeholder is replaced
and List-Unsubscribe / List-Unsubscribe-Post headers are added. The link points
at Floci's own /_aws/ses/unsubscribe endpoint (GET/POST), which applies the
opt-out (topic -> OPT_OUT, no topic -> UnsubscribeAll), auto-creating the
contact if needed. The link uses readable query parameters rather than AWS's
opaque token, and its scheme follows Floci's base URL. Raw sends do not get
link injection yet.

* fix(ses): apply list-management unsubscribe headers to relay + inspection, override duplicates, preserve placeholder in templates

Addresses three review findings on the unsubscribe handling:

- The List-Unsubscribe / List-Unsubscribe-Post headers now reach the SMTP relay
  message (relay() takes the additional headers and applies them) and are stored
  on SentEmail so GET /_aws/ses surfaces them under Headers — previously they
  only appeared in published events.
- withUnsubscribeHeaders now overrides a caller-supplied List-Unsubscribe /
  List-Unsubscribe-Post rather than appending a duplicate, matching AWS.
- applyTemplateData leaves the reserved {{amazonSESUnsubscribeUrl}} placeholder
  intact instead of failing with MissingRenderingAttribute, so a templated body
  can carry it (replacement still happens post-render in the send path).

* fix(ses): sanitize relayed headers against SMTP injection and avoid double-slash unsubscribe URLs

User-supplied SendEmail Headers reach the SMTP relay, where a name or value containing
CR/LF could inject extra headers (e.g. Bcc) into the delivered message. Skip any header
with a blank name or CR/LF in its name/value before adding it to the relay message, and
log the drop. Also trim a trailing slash from the configured base URL when building the
List-Unsubscribe URL so a base-url ending in "/" no longer yields "//_aws/...".

* fix(ses): make the unsubscribe GET a no-mutation confirmation page

The unsubscribe endpoint applied the opt-out on both GET and POST. A GET is a browser
click that AWS answers with a landing page, and treating it as a mutation is the RFC 8058
prefetch hazard: mail clients, scanners and link-preview bots that fetch the URL would
silently unsubscribe the contact. GET now renders a confirmation form that POSTs back;
only the POST (the RFC 8058 one-click request) applies the opt-out. Adds GET test
coverage and updates the docs.

* test(ses): add an SDK compat test for SendEmail with ListManagementOptions

Send with ListManagementOptions through the SES v2 SDK client to prove the nested structure
(ContactListName + optional TopicName) marshals as a real client sends it, and that Floci
actually applies it — an absent recipient is auto-created as a contact on the list. Also note
in the docs that {{amazonSESUnsubscribeUrl}} is left verbatim on a send without
ListManagementOptions (Floci behavior, not verified against real SES).

* fix(ses): harden the unsubscribe confirmation page and document its trust model

Escape '&' as '&amp;' in the confirmation form's action attribute (valid HTML), and add the
RFC 8058 one-click hidden field so the form's POST body matches the advertised
List-Unsubscribe-Post header. Also document — in the controller Javadoc and the SES docs — that
the endpoint carries the target in readable query parameters and, like the rest of Floci, is
unauthenticated, so it is only safe on a trusted dev/test network.

* fix(ses): filter unsafe headers once so all send surfaces stay consistent

The SMTP relay dropped user-supplied headers with a blank name or CR/LF, but the stored
SentEmail (GET /_aws/ses) and published events kept the raw list — so inspection and events
could show headers the relay dropped and retain CR/LF injection payloads. Move the safety
check to MessageHeader.isSafe(), filter the headers once in the send path, and use that
sanitized list for storage, relay, and event publishing alike.

* fix(ses): reject SES v2 message headers that omit a required Name or Value

Content.Simple.Headers / Content.Template.Headers entries declare Name and
Value as required members. A header object missing either member was parsed
leniently and later silently dropped, which is surprising when the request is
otherwise accepted. Reject it at parse time the way AWS does — BadRequestException
with the Smithy "Member must not be null" constraint message anchored at the
offending header path and 1-based index.
2026-08-08 21:33:35 -05:00
Kenshin Okinaka ff8d6efdf3 feat(ses): implement v1 receipt rule set actions (stored-but-inert) (#2128)
* feat(ses): implement v1 receipt rule set actions (stored-but-inert)

Add the SES v1 receipt-rule-set management actions: CreateReceiptRuleSet,
DescribeReceiptRuleSet, ListReceiptRuleSets, DeleteReceiptRuleSet,
SetActiveReceiptRuleSet, and DescribeActiveReceiptRuleSet. Floci has no inbound-mail
endpoint, so rule sets are stored inertly — a set never holds any receipt rules and
routes no mail — but the management API round-trips so tools like Terraform can declare
a rule set during bootstrap without hitting UnsupportedOperation.

Behavior matches AWS (verified): RuleSetDoesNotExist for a missing set, AlreadyExists
for a duplicate name, idempotent DeleteReceiptRuleSet, and an empty
DescribeActiveReceiptRuleSet when no rule set is active. Individual receipt rules and
receipt filters are out of scope.

* fix(ses): reject deleting the active receipt rule set and read active state under lock

DeleteReceiptRuleSet removed the active rule set unconditionally; AWS rejects it with
CannotDelete/400 (verified), so reject it and preserve the set. DescribeActiveReceiptRuleSet
read without the lock, so a concurrent set-active replacement (clear-then-set) could expose
its intermediate no-active state; read under receiptRuleSetLock so the reader sees the old or
new active set, never the gap.

* fix(ses): validate the receipt rule set name against AWS's constraints

RuleSetName was only checked for non-blank, so Floci accepted names AWS rejects. Validate
it as AWS does (verified): a character outside ^[a-zA-Z0-9_.-]+$ is a ValidationError, and a
name over 64 characters or that does not start and end with an alphanumeric is an
InvalidParameterValue ("Not a valid ruleSetName"). Applied on create/describe/delete and on
set-active when a name is given.

* chore(ses): tidy receipt rule set import order and record the RuleSetName probe provenance

Address review nits: move the ReceiptRuleSet import into alphabetical position in
SesQueryHandler, and expand the RuleSetName validation comment to record that the
constraints come from probing live SES (the botocore model has no pattern), so the
next reader can re-verify rather than treat them as settled.
2026-08-07 23:23:01 -04:00
Hector Ventura ee15447ba4 docs(cloudformation): document the per-service provisioner path for new resource types (#2153)
New CloudFormation types belong in services/cloudformation/provisioners/, not in the
CloudFormationResourceProvisioner monolith, but nothing outside a gitignored design
doc said so: CONTRIBUTING.md, AGENTS.md, docs/ and the PR template were all silent,
so contributors read the monolith and copied a case.

Adds a step-by-step section to CONTRIBUTING.md and AGENTS.md covering the three
traps behind the recurring review findings: Ref and Fn::GetAtt are separate
mechanisms and a missed attribute resolves to the literal LogicalId.Attr; provision
is also the update path, so creating unconditionally throws AlreadyExists or orphans
the old resource; and an unmapped type is stubbed as CREATE_COMPLETE, so status-only
assertions cannot detect a type that was never wired.

Also refreshes the resource-type table, which had drifted: EC2 gains LaunchTemplate
and VPCGatewayAttachment, EventBridge gains EventBus and EventBusPolicy and its
Events::Rule naming is normalized.
2026-08-07 17:37:36 -05:00
soreavis 9b451ccc82 fix(iot): match topic rules outside the default region (#2169)
* fix(iot): match topic rules outside the default region

Topic rules are stored per region — topicRuleKey(region, ruleName) — but
handlePublish looked them up with a hardcoded config.defaultRegion(). A
rule created in any other region was stored, gettable and listable yet
never evaluated: republish/SQS/SNS/Kinesis/DynamoDB/Lambda actions were
silently dropped while Publish still returned 200.

IotDataController.publish now resolves the region from the request's
SigV4 credential, as the shadow endpoints in that controller already do,
and threads it through IotService.publish into handlePublish. A publish
that carries no region — MQTT, or an unsigned data-plane request —
evaluates every region's rules, mirroring the fallback
ApiGatewayService.resolveRestApiRegion applies to unsigned REST API
invocations.

executeTopicRule derives the rule's own region from its ARN and targets
the action sinks with it instead of the default region, so a rule created
in eu-west-1 delivers to eu-west-1 resources.

Closes #2065

* fix(iot): treat a non-SigV4 publish header as an unresolved region

IotDataController.publish skipped region resolution only for a missing
or blank Authorization header. Any other non-SigV4 value — a bearer JWT,
say — fell through to resolveRegionFromAuth, whose miss path returns the
configured default region. So a publish carrying such a header evaluated
only the default region's rules, while one carrying no header at all
evaluated every region's: the same absence of region information, two
different outcomes.

RegionResolver.resolveRegionFromAuthOrNull returns the credential's
region, or null when there is nothing to parse, and publish threads
that through — so every publish that names no region is treated the
same way.
2026-08-07 17:33:01 -05:00
soreavis 0203bc7f7e feat(cognito): add AdminLinkProviderForUser (#2166)
* feat(cognito): add AdminLinkProviderForUser

Linking a federated identity to an existing user pool user returned
400 UnsupportedOperation, because the action had no arm in the
CognitoJsonHandler switch and fell through to the default case.

Add the action to the handler and service. The link is recorded as an
entry in the destination user's `identities` attribute, matching the
JSON array AWS documents: userId, providerName, providerType, issuer,
primary and dateCreated. CognitoUser.attributes is already a free-form
map and AdminGetUser emits every attribute as a UserAttribute, so the
linked identity surfaces without a model change.

dateCreated is stored in epoch milliseconds. That differs from the
seconds this service uses for its own user timestamps, but it is what
AWS emits in the identities attribute and the ID token claim.

providerType is only set when the source provider name is one of the
provider types AWS also uses as a name (Facebook, Google,
LoginWithAmazon, SignInWithApple). SAML and OIDC types, and issuer, are
properties of a registered IdP, which the emulator does not model, so
they stay null rather than being guessed.

A source identity may be linked to at most one user per pool; a
conflicting link throws AliasExistsException, a documented error of
this operation.

Source provider names are not validated against a configured IdP, and
the five-identity cap is not enforced. Both are noted as deliberate
divergences in the pull request.

Closes #1563

* fix(cognito): validate link fields and serialize the uniqueness check

AdminLinkProviderForUser accepted requests with a missing SourceUser
ProviderName or ProviderAttributeValue: path().asText() turns absent
fields into empty strings, so a bad request returned 200 and persisted
an identity with an empty providerName or userId. Require the three
fields up front and answer InvalidParameterException, matching how
this service already reports missing required input.

The uniqueness check and the write could also interleave: two
concurrent links of the same source identity to different users could
both pass the scan before either wrote. Wrap the check and the write
in synchronized (pool), the pattern the tag operations already use.

* fix(cognito): serialize identity links on a stable monitor

The uniqueness check locked the UserPool object, but updateUserPool
replaces the stored instance (convertValue copy + poolStore.put), so
two links racing an update could hold different monitors and both pass
the scan. Serialize on a dedicated lock instead, declared beside the
one method it guards.

Dropping the describeUserPool lookup also changes the unknown-pool
error source: adminGetUser reports it as ResourceNotFoundException 400,
which is how every sibling admin user mutator already reports it.

Verified with an 8-thread probe linking the same source identity to
eight users: one winner and seven AliasExistsException with the lock,
eight winners without it.
2026-08-07 17:30:11 -05:00
soreavis 7d9b9aedd2 feat(cloudformation): honor resource-level DeletionPolicy (#2167)
A resource's DeletionPolicy attribute was never read off the template,
so every managed resource was deleted regardless of what it declared:
deleteStackResources and rollbackCreatedResources both called
provisioner.delete unconditionally.

Read DeletionPolicy alongside Type in executeTemplate and apply it at
both delete sites. Retain keeps the resource on every stack operation.
RetainExceptOnCreate keeps it too, except when the create that made it
is rolled back — deleting it there is the entire meaning of that value,
and rollbackCreatedResources runs only for a failed create.

A retained resource is reported as DELETE_SKIPPED, on the resource and
as a stack event, and is not counted as a failed delete, so the stack
still reaches DELETE_COMPLETE. That also lets a stack owning a
non-empty S3 bucket be deleted, which otherwise fails on the objects.

Any other value falls through to the existing delete. That includes
Snapshot: floci cannot take the snapshots AWS supports for those types,
and AWS does delete the resource under Snapshot, so Delete is the
faithful half. The docs record that and the other divergences.

The policy is set on the resource after the provisioner returns,
because provision() and executeNestedStack() both return a fresh
StackResource that replaces the map entry.

Closes #1555
2026-08-07 17:29:48 -05:00
Priamo Germosen 1795e131a2 feat(applicationautoscaling): add Application Auto Scaling control plane (#2159)
* feat(applicationautoscaling): add Application Auto Scaling control plane

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

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

Notable behaviours:

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

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

Closes #2157

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

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

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

Reported by github-code-quality on #2159.
2026-08-07 17:27:36 -05:00
Hector VenturaandMarcel Herhold 760115db14 feat(kms): implement ListKeyPolicies (#2046)
* feat(kms): implement ListKeyPolicies

ListKeyPolicies failed with UnsupportedOperation, so clients enumerating
policy names before a GetKeyPolicy call could not proceed. GetKeyPolicy
and PutKeyPolicy were already supported, so this was a hole in an
otherwise complete area.

Returns the single `default` policy name, which is what the model
prescribes ("The only valid value is default"), with Truncated false and
NextMarker omitted rather than serialized as null, since AWS only emits
NextMarker when Truncated is true.

Limit and Marker are accepted and ignored. One policy name cannot be
paginated, and ListKeyPolicies is the one KMS list operation that does
not declare InvalidMarkerException, unlike ListKeys, ListAliases,
ListGrants, ListKeyRotations, ListResourceTags, ListRetirableGrants and
DescribeCustomKeyStores. There is therefore no marker it could
legitimately reject, and no undeclared error code is invented for one.

Closes #1528

Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>

* chore: drop hand-written ListKeyPolicies changelog entry (semantic-release owns CHANGELOG.md)

* fix(kms): drop unused ListKeyPolicies pagination params and fix test claims

Review follow-up, validated against the local AWS references: Limit/Marker are
accepted at the wire by never being read (matching moto's list_key_policies), so
the service signature drops the dead parameters and the structurally vacuous
paging unit test goes with them; the integration test remains the real coverage.
The javadoc justification now states the leniency honestly: SDKs do not fully
enforce LimitType [1..1000] client-side (botocore validates only the minimum),
so out-of-range values can arrive and are deliberately tolerated. The ARN
resolution test no longer claims alias coverage the operation does not have.

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
2026-08-05 23:36:07 -05:00
Oleh Melnyk 875e0f2d3b feat(bedrock): add proxy backend for real LLM responses via OpenAI-compatible API (#1789)
* feat(bedrock): add proxy backend for real LLM responses via OpenAI-compatible API

* fix(bedrock): preserve leading text when a tool call response also has content

OpenAI-compatible backends can return assistant text alongside tool_calls in
the same response (e.g. a preamble before invoking a tool). The Converse
translation only emitted the toolUse block in that case, silently dropping
the text.

* fix(bedrock): use InternalServerException for proxy serialization failures

InternalFailure isn't a bedrock-runtime error shape in botocore/the Java
SDK, so clients couldn't map it; InternalServerException is the declared
500 for this API.

* fix(bedrock): map proxy backend timeouts to ModelTimeoutException (408)

HttpTimeoutException (connect or request timeout) was falling into the
generic catch and surfacing as ModelErrorException/424, which the AWS
SDKs treat as terminal. Bedrock's dedicated 408 shape is retryable under
the default SDK retry strategy, so this distinction is load-bearing, not
cosmetic.

Also makes the request timeout configurable
(proxy.request-timeout-seconds, default 60s) since larger models on
CPU-backed backends may need more headroom than the default.

* fix(bedrock): fail fast on InvokeModel under the proxy backend

Falling back to StubBackend's canned response meant a caller who
configured a real proxy backend and called InvokeModel got a
plausible-looking, entirely fabricated completion with no signal beyond
a server-side log line. That's inconsistent with Converse, which already
fails loudly on misconfiguration, and worse: InvokeModel is still the
default entry point for many SDK wrappers, so this could silently mask
a broken integration.

Also fixes the streaming-endpoint error messages, which blamed "the
Floci stub" for a limitation that's actually unconditional (streaming
isn't implemented for any backend).
2026-08-05 17:17:02 -05:00
Alex Bannaandabanna 62a576c8d4 feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment (#1804)
* feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment

AWS::SecretsManager::SecretTargetAttachment previously fell through the
default branch, so its Ref yielded a generated placeholder rather than the
secret ARN. Per the CloudFormation resource reference, this resource's Ref
returns the ARN of the secret named in SecretId, and consumers such as
Secret.fromSecretCompleteArn(...) require the complete ARN (with the
trailing -6char suffix).

Resolve SecretId (a Ref to the Secret, a friendly name, or a raw ARN) to
the canonical complete ARN via describeSecret and expose it as the
resource's physical id / Arn attribute, falling back to SecretId as-given
if the lookup fails. Deleting the attachment is a detach no-op — it must
not delete the underlying secret.

* fix(cloudformation): require SecretId on SecretTargetAttachment

SecretId is a required property of AWS::SecretsManager::SecretTargetAttachment.
Resolving it as optional let a template omit it and still create (falling back to
the logical id); reject a missing SecretId instead. Adds a regression test.

* fix(cloudformation): complete secret target attachment lifecycle

* fix(cloudformation): require attachment metadata on delete

* fix(cloudformation): tolerate detached secret overwrites

* fix(cloudformation): align secret target attachment behavior

* docs(cloudformation): document secret target attachments

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>
2026-08-05 17:11:25 -05:00
Priamo Germosen 7e4e3e8c50 feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor) (#2086)
* feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor)

Adds a new services/mwaa package following the EKS lifecycle pattern
(Controller/Service/EnvironmentManager, one Docker container-set per
resource, readiness polling) and the Neptune/ElastiCache proxy pattern
(MwaaWebProxy/MwaaProxyManager: Floci owns the host-facing port, the
backing container stays internal-only).

Each environment is backed by two real containers — postgres:16-alpine
for the metadata DB and apache/airflow:<version>-python3.12 running
LocalExecutor — with AirflowVersion genuinely selecting the image tag
(validated against a configured allow-list), unlike EKS's cosmetic-only
version field. MwaaWebProxy fronts the real Airflow webserver and
intercepts POST /aws_mwaa/cli, bridging it to a docker-exec'd `airflow`
CLI call and returning the documented {stdout, stderr} shape.

DAGs and requirements.txt sync from S3 on a poller, reusing the existing
S3Service in-process rather than a new AWS-facing surface. The Airflow
container is pointed back at Floci via LaunchedContainerAwsEnv (the same
mechanism Lambda/ECS containers already use), so a DAG's own boto3 calls
resolve against Floci instead of real AWS.

StartupScriptS3Path is supported end-to-end: fetched from S3 at create
time, injected before the container starts (create -> inject -> start,
mirroring EksClusterManager's config-injection sequencing), sourced
before migrate/scheduler/webserver so exported vars propagate. The
airflow user gets a passwordless sudo grant (verified against the real
image — sudo ships but isn't passwordless by default, and AWS's own
startup-script examples assume sudo just works), and a fixed set of
Floci-critical env vars (Fernet key, DB DSN, executor, AWS-SDK-redirection
vars) are snapshotted before and restored after the script runs, mirroring
real MWAA's reserved-environment-variable protection.

Verified end-to-end against real Docker (not just the mock=true unit
suite): environment reaches AVAILABLE, proxy pass-through and the CLI
bridge both work with real output, a DAG uploaded to S3 syncs and parses,
a second environment on a different AirflowVersion pulls a genuinely
distinct image, and delete tears down both containers/volumes and the
proxy cleanly.

45 new tests (unit + RestAssured integration, all against mock=true in
the default suite so Docker is never required for `mvnw test`); full
suite otherwise unchanged.

* fix(mwaa): hard-fail startup-script injection failures, release proxy ports on delete

Two issues from review:

copyFileIntoContainer swallowed every failure identically, including the
one case where that's wrong: a configured StartupScriptS3Path that fails
to copy into the container. The entrypoint's "if [ -f /startup.sh ]"
guard would silently skip it and the environment would reach AVAILABLE
having never applied the requested setup, contradicting the documented
intent of gating environment creation on startup-script failure (matching
real MWAA). copyFileIntoContainer now reports success/failure; the
startup-script call site checks it and throws, while DAG sync and the
best-effort sudoers grant keep their existing soft-fail behavior.

deleteEnvironment allocated a proxy port via PortAllocator on create but
never released it on delete, unlike every other service that uses
PortAllocator (Lambda, MSK, EC2, ECR) — repeated create/delete cycles
would eventually exhaust the configured proxy port range even with zero
MWAA proxies actually running.

* fix(mwaa): roll back allocated proxy port and containers on create failure

If startEnvironment() succeeded (containers running) but PortAllocator.allocate
or MwaaProxyManager.startProxy failed afterward, createEnvironment's catch
block set CREATE_FAILED without releasing the reserved port or stopping the
containers that had already started — leaking both on every such failure.

Mirrors NeptuneService.createDbCluster/rollbackDbCluster's already-proven
shape for this exact class of problem (container + proxy + port, partial
failure must roll back everything): a provisioned flag set only after every
step succeeds, and a try/finally that runs rollbackFailedCreate whenever it
doesn't — stopping the proxy (a no-op if it never started), stopping any
containers that did start (MwaaEnvironmentManager.stopEnvironment already
null-checks each container id, so it's safe for partial startup too), and
always releasing the port.

* fix(mwaa): correct CreateEnvironment error shape, namespace container names, add docs

Two items from maintainer review:

- Duplicate CreateEnvironment threw ResourceAlreadyExistsException, a shape the
  operation doesn't declare (verified against the real botocore mwaa/2020-07-01
  model: CreateEnvironment's only errors are ServiceUnavailableException,
  ValidationException, InternalServerException) — SDK clients couldn't map it.
  Now throws ValidationException.

- dbContainerName/airflowContainerName built names via raw string concatenation
  instead of routing through ContainerStorageHelper.dockerName like every other
  Docker-backed service (EKS, RDS, ...), so MWAA alone didn't participate in the
  FLOCI_DOCKER_RESOURCE_NAMESPACE convention that keeps multiple Floci instances
  sharing one Docker daemon from colliding. Both static methods now take the
  EmulatorConfig and route through the shared helper; volume names inherit the
  fix automatically since they're built by extending the container name.

Also adds docs/services/mwaa.md (mkdocs nav updated) following eks.md's
structure — operations table, mock/real mode, the web/CLI proxy, startup-script
behavior (sudo grant, reserved-variable protection), config reference, ARN
format, CLI/SDK examples, and an honest "Not Implemented" section covering the
known gaps already discussed on the PR (PluginsS3Path, cross-account container
naming, restart restoration).
2026-08-04 22:16:14 -05:00
floverfeltandFlorian Overfelt b543aa4baa feat(lambda): support extra /etc/hosts entries on Lambda launch (#2073)
* feat(lambda): support extra /etc/hosts entries via FLOCI_SERVICES_LAMBDA_EXTRA_HOSTS

* feat(lambda): support ipv6 addresses.

---------

Co-authored-by: Florian Overfelt <joverfelt@meso-scale.com>
2026-08-04 21:50:25 -05:00
Alex Banna 78ba5b3457 feat(iam): list entities attached to managed policies (#1808) 2026-08-01 16:36:11 -05:00
Alex Bannaandabanna aadc93e306 feat(rum): add CloudWatch RUM app-monitor service (#1797)
* feat(rum): add CloudWatch RUM app-monitor service

Adds a minimal CloudWatch RUM service (restJson1) covering the app-monitor
lifecycle — CreateAppMonitor, GetAppMonitor, UpdateAppMonitor, DeleteAppMonitor,
ListAppMonitors — backed by an in-memory store.

Previously restJson1 RUM requests (e.g. POST /appmonitor) fell through to the S3
path-style catch-all (@Path("/{bucket}")) and returned an XML error that
restJson1 SDKs (and the CDK AwsCustomResource used for RUM AppMonitor custom
resources) cannot parse. Literal /appmonitor and /appmonitors paths take JAX-RS
precedence over S3's /{bucket} template (the same mechanism eks/mq use), so the
routes win with no extra routing wiring.

Verified with aws-cli 2.33.18 against a dev-mode emulator: CreateAppMonitor
returns an Id, GetAppMonitor/ListAppMonitors round-trip, DeleteAppMonitor then
GetAppMonitor returns ResourceNotFoundException.

* fix(rum): make monitor updates atomic

* fix(rum): align app monitor lifecycle with AWS

* chore: retry flaky Node compatibility check

* fix(rum): address app-monitor review feedback

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>
2026-08-01 15:28:54 -05:00
Hector VenturaandMarcel Herhold 02385da37b feat(apigateway): support floci:override-id for v1 and v2 (#2045)
* feat(apigateway): support floci:override-id for v1 and v2

API IDs were generated randomly, so endpoint URLs changed on every
recreate. v1 accepted an undocumented `_custom_id_` tag and echoed it
back as a normal tag; v2 had no override at all. Other services already
pin IDs through the reserved `floci:override-id` tag.

Both CreateRestApi and CreateApi now accept `floci:override-id`, routed
through ReservedTags.getOverride so the value is validated rather than
used verbatim: non-blank, no whitespace or control characters, and no
`/`, `?`, `#`, since those break the endpoint URL. Override keys are
consumed rather than stored, so they no longer appear in the returned
tags, and supplying either key to TagResource is rejected because an ID
cannot change after creation.

`_custom_id_` keeps working as a deprecated fallback and is now stripped
the same way; `floci:override-id` wins when both are present so callers
can set both during a migration. The key stays API Gateway specific: the
shared strip and reject helpers are untouched, so KMS and Cognito still
treat `_custom_id_` as an ordinary tag.

Error code is BadRequestException, declared by CreateRestApi, CreateApi
and TagResource on both services. The shared reject helper's
ValidationException is declared by neither, which is why API Gateway gets
its own guard rather than reusing it.

Closes #1593

Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>

* fix(apigateway): reject duplicate override ids with ConflictException

CreateRestApi (v1) and CreateApi (v2) now return 409 ConflictException
when the resolved API id already exists in the region, instead of
silently overwriting the existing API, matching how KMS and Cognito
treat duplicate override ids.

---------

Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
2026-07-29 23:40:27 -05:00
武田隆志 86134e8c7f docs(cloudwatch): document Logs Insights subset and missing Logs actions (#2044)
docs/services/cloudwatch.md listed 14 of the 24 actions that
CloudWatchLogsHandler dispatches. The handler is on the deferred_handlers
allowlist in tools/docs/services.yaml, so the table is maintained by hand and
had drifted as actions were added.

Most notably Logs Insights (StartQuery / GetQueryResults / StopQuery, added in
1.5.31) was undocumented, leaving no way to discover which parts of the query
language are implemented.

Add the 10 missing actions and a Logs Insights section covering the supported
commands, the field syntax, and how each kind of unsupported input degrades:
a dropped filter stage returns every row, a >= or <= comparison is mis-parsed
into a field name and returns none, a missing projected field becomes an empty
string, and an unrecognised sort direction falls back to ascending.

Also note the PutSubscriptionFilter and GetDataProtectionPolicy
simplifications, document
FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS in both the service
page and the central environment-variable list, correct the
MAX_EVENTS_PER_QUERY description, and add a start-query example.
2026-07-29 23:38:24 -05:00
Kenshin Okinaka 881c45b393 feat(ses): implement identity (sending authorization) policies for v1 and v2 (#1750)
* feat(ses): implement identity (sending authorization) policies for v1 and v2

Add the SES identity-policy APIs across both protocols, backed by one shared
StorageFactory store (key policy::<region>::<identity>::<policyName>):

- v1 Query: PutIdentityPolicy (upsert), GetIdentityPolicies, ListIdentityPolicies,
  DeleteIdentityPolicy (idempotent).
- v2 REST JSON: CreateEmailIdentityPolicy (fails on duplicate),
  GetEmailIdentityPolicies, UpdateEmailIdentityPolicy (fails when missing),
  DeleteEmailIdentityPolicy.

Behaviour and error shapes were verified against real AWS: the per-identity
limit of 20, the v1/v2 create/update/delete strictness asymmetry, PolicyName
constraints, and the shared v1<->v2 store. Floci stores and returns policies but
does not enforce the authorization (Principal-account existence, Resource-ARN
match) or gate sending on them.

* test(ses): inject policyStore into the test SesService constructor

Thread the identity-policy store through the package-private constructors as a
parameter instead of hardcoding a new InMemoryStorage, matching every other
store and keeping the test constructor aligned with the production wiring.
2026-07-27 22:36:47 -05:00
Guilherme Lima 024d74e5c4 feat(cloudtrail): in-process CloudTrail with S3 data event emission (#1460)
* feat(cloudtrail): in-process CloudTrail with S3 data event emission

New service supporting CreateTrail / DescribeTrails / DeleteTrail /
UpdateTrail / PutEventSelectors / GetEventSelectors / StartLogging /
StopLogging / GetTrailStatus.

S3 ops (PutObject / GetObject / HeadObject / DeleteObject / ListObjects
/ GetObjectAcl) emit CloudTrail data events through a per-trail buffer.
The CloudTrailLogWriter scheduler flushes pending records as gzipped
JSON envelopes into the destination bucket at AWS-shaped key paths
(AWSLogs/<account>/CloudTrail/<region>/yyyy/MM/dd/<file>.json.gz) on
a configurable cadence (default 60s).

IAM-enforcement denials emit matching AccessDenied records by hooking
IamEnforcementFilter. IamActionRegistry now distinguishes
s3:GetObjectAcl / PutObjectAcl / {Get|Put|Delete}ObjectTagging from
their base ops via ?acl / ?tagging query parameters so the right
event names land in the trail.

Seeded AWSCloudTrail_FullAccess / _ReadOnlyAccess managed policies.

* fix(cloudtrail): return LatestDeliveryTime in GetTrailStatus after StartLogging

The sdk-test-java compatibility test asserts latestDeliveryTime() is
non-null immediately after startLogging. Seed it with the startLoggingTime
so the field is always present once logging has been started.

* fix(cloudtrail): emit SnsTopicARN alongside SnsTopicName in CreateTrail/UpdateTrail responses

Accept both SnsTopicARN and SnsTopicName on input (SnsTopicARN takes
precedence). Emit both fields on output so clients reading the current
field name (SnsTopicARN) get a non-null value.

* fix(cloudtrail): wildcard S3 ARN matching, trail name validation, LookupEvents

- matchesS3DataResourceArn: handle bare "arn:aws:s3", "arn:aws:s3:::*", and
  "arn:aws:s3:::*/*" wildcard forms so trails configured via the AWS Console
  "capture everything" selector actually record events (previously fell through
  silently). Unit tests added to CloudTrailSelectorMatchingTest.

- createTrail: enforce AWS trail name rules (3–128 chars, start/end with letter
  or digit, only letters/numbers/./_/-). Integration tests in new
  CloudTrailNameValidationTest.

- CloudTrailJsonHandler: add LookupEvents stub returning an empty Events array,
  matching upstream's addition in #1603.

* fix(cloudtrail): log empty catches, key selectors/logging by trail home region

- CloudTrailLogWriter.stop(): log at WARN instead of silently swallowing the
  final-flush exception (AGENTS.md: never leave a catch block empty).

- CloudTrailService.putEventSelectors / getEventSelectors / startLogging /
  stopLogging / getTrailStatus: use trail.homeRegion() as the storage key
  instead of the request region. Previously a cross-region call (e.g. accessing
  a trail by ARN from a different-region endpoint) stored selectors and logging
  state in the wrong region's map, so trailsMatching() found an empty selector
  list and logging never fired.

- S3Controller.emitCloudTrailEvent / IamEnforcementFilter.emitS3DenialIfApplicable:
  replace empty inner catch blocks with LOG.tracev() so unexpected failures
  during request-context extraction surface at trace level.

* fix(iam): distinguish bucket-level vs object-level ?acl / ?tagging IAM actions

resolveS3SubResourceAction was always mapping ?acl and ?tagging to object-level
actions (s3:PutObjectAcl, s3:GetObjectAcl, etc.) regardless of path depth.
A PUT /{bucket}?acl request requires s3:PutBucketAcl, not s3:PutObjectAcl —
callers with the correct bucket-level permission were incorrectly denied.

Fix: inspect the URL path after stripping the leading slash. When there is no
slash (or the path ends with one), the target is a bucket; otherwise it is an
object. Applies to all six variants: GetBucketAcl, PutBucketAcl,
GetBucketTagging, PutBucketTagging, DeleteBucketTagging (and their object
counterparts).

* fix(cloudtrail): re-queue records on flush failure instead of dropping them

drainPendingRecords atomically dequeues all records before the S3 write.
If serializeAndGzip or s3Service.putObject threw, those records were gone —
permanently lost before the re-throw reached flushAll.

Fix: wrap the serialize+write block in a try-catch that calls requeueRecords
before rethrowing. Records are added back to the tail of the queue and will be
retried on the next flush cycle. The new CloudTrailService.requeueRecords helper
also makes the re-queue path unit-testable independently of flushTrail.

* fix(s3): emit GetObjectAcl error record under correct event name

getObjectAcl was called inside the outer GET-object try block. On any
AwsException (NoSuchKey, AccessDenied, etc.) the catch at the bottom fired
and emitted a GetObject error record. CloudTrail consumers auditing ACL
errors would see the wrong event name.

Wrap the acl branch in its own try-catch that emits GetObjectAcl on both
success and failure paths, mirroring the pattern used by the other hooked ops.

* ci: retrigger

* fix(test): pass CloudTrailService and CurrentVertxRequest to IamEnforcementFilter constructor

* fix(cloudtrail): persist trail state via StorageFactory instead of volatile in-memory maps

* fix(cloudtrail): address review feedback on region, name lookup, and ACL detection

- S3Controller: use request region (from credential scope) instead of
  getDefaultRegion() for CloudTrail event emission, matching the IAM
  denial hook behaviour so allowed and denied calls land in the same trail.

- CloudTrailService.findTrail: name lookup now uses regionKey(region, name)
  directly; ARNs still do a cross-region scan. Prevents two same-name
  single-region trails from resolving ambiguously by map iteration order.

- TrailKey: add eventRegion field so multi-region trail events are written
  to the correct S3 delivery path (CloudTrail/<eventRegion>/) rather than
  always the trail home region. drainPendingRecords/requeueRecords now take
  a TrailKey to carry all three dimensions.

- IamActionRegistry: fix isBucketLevel — trailing slash is a valid S3 key
  character, so /bucket/folder/?acl is an object ACL request. Replaced the
  endsWith("/") check with an index-based test. Add IamActionRegistryTest
  cases for the folder/ regression.

* docs(cloudtrail): sync action table order with make docs-sync
2026-07-21 12:10:19 -04:00
Ioannis Lafiotis 095e167bae Nodegroups eks fargate eks (#1523)
* feat(eks): add nodegroups and fargate profiles

* docs: sync generated action tables
2026-07-15 01:03:24 -04:00
Kenshin Okinaka 10f799a2b7 feat(ses): implement Contact CRUD for SES v2 (#1723)
* feat(ses): implement Contact CRUD for SES v2

Add the SES v2 Contact APIs under /v2/email/contact-lists/{name}/contacts:
CreateContact, GetContact, ListContacts (POST .../contacts/list),
UpdateContact, DeleteContact. Contacts carry per-topic subscription
preferences, an unsubscribe-all flag, and free-form attributes;
TopicDefaultPreferences is derived at read time from the list's topics.

Behaviour is verified against real AWS: validation order (Smithy enum ->
EmailAddress format -> list existence -> topic existence), AlreadyExists /
NotFound / invalid-topic / invalid-email error shapes, and the UpdateContact
semantics (TopicPreferences merge by topic name; AttributesData and
UnsubscribeAll replaced). Covered by a RestAssured integration test and an
AWS Java SDK v2 compatibility test.

* refactor(ses): resolve contact list once for reads and delete under lock

Address review consistency findings on the Contact CRUD read/delete paths:

- getContact/listContacts returned only the contact(s), so the controller
  fetched the ContactList a second time to render TopicDefaultPreferences.
  Between the two calls a concurrent delete could turn a successful read into a
  misleading "List not found". The service now returns the resolved list
  alongside the contact(s) (ContactWithList / ContactsWithList), so the read is
  a single, consistent lookup.
- deleteContact re-checked list existence before acquiring contactMutationLock,
  unlike createContact/updateContact which re-check inside it. Move the
  getContactList check inside the lock so a concurrent deleteContactList
  surfaces "list not found" rather than "contact not found".
2026-07-10 23:15:59 -05:00
kotov228 97b64a1d3b feat: add AWS Lightsail emulation (#1583)
* feat(lightsail): add AWS Lightsail emulation

* fix(lightsail): align error responses with AWS

* fix(lightsail): address review edge cases

* fix(lightsail): reject attached disk reattach

* fix(lightsail): reject static ip reattach

* fix: register lightsail docs handler
2026-07-10 20:43:42 -05:00
TiM 321394fea0 docs: fill supported action descriptions (#1819)
* docs: fill supported action descriptions

* docs(elb): describe listener default rule as non-deletable, not immutable

The CreateListener row called the default rule "immutable", which contradicts
the ModifyListener row (updates default actions) and the file's own note that
the rule can be changed via ModifyListener. The rule cannot be deleted or
reprioritized, but its action is mutable, so "non-deletable" is accurate.
2026-07-10 17:45:51 -05:00
Alex Banna 4a16266f48 feat(cloudformation): support UpdateTerminationProtection (#1692)
* feat(cloudformation): support UpdateTerminationProtection

CDK bootstrap calls UpdateTerminationProtection on the CDKToolkit stack; Floci returned
UnknownAction. Add it: a boolean enableTerminationProtection on Stack, a
CloudFormationService.updateTerminationProtection(stackName, enabled, region) that sets and
persists it, a handler returning the UpdateTerminationProtectionResult/StackId envelope, and
the flag echoed as <EnableTerminationProtection> in DescribeStacks. Register the action in
AwsQueryController's CloudFormation action set so the Query-protocol POST routes to
CloudFormation instead of falling through. Adds an integration test toggling the flag and
asserting it round-trips through DescribeStacks.

* docs: regenerate action tables
2026-07-09 00:16:38 -05:00
Alex Banna 0e85ac92c7 feat(pipes): apply EventBridge Pipe enrichment before target delivery (#1658)
* feat(pipes): apply EventBridge Pipe enrichment before target delivery

PipesPoller delivered the raw source record straight to the target; pipe.getEnrichment() was
stored but never invoked. Implement the AWS Pipes source->filter->ENRICHMENT->target flow: when an
enrichment Lambda is configured, invoke it once with the filtered events (bare JSON array) and
forward its response to the target (null/empty response skips the target, per AWS). Also resolve
qualified Lambda ARNs (:$LATEST) in PipesTargetInvoker. Covered by PipesTargetInvokerTest.

* fix(pipes): deliver enrichment result to the target as an event array

EventBridge Pipes delivers events to a target as a batch (JSON array). The
enrichment path forwarded a single-object enrichment response verbatim, so a
target expecting an array (e.g. a Step Functions state machine with
InputPath "$.[0]") received an object and resolved null. Wrap a non-array
enrichment response in a one-element array before target delivery. Covered by
PipesPollerTest.asEventArray*.

(cherry picked from commit f160f66857c2362e3f1bad3bbfdb025396b281a0)

* fix(pipes): treat a target/enrichment Lambda FunctionError as failed delivery

invokeLambda (the Lambda target path) discarded the InvokeResult, so a target
Lambda that returned a FunctionError (unhandled exception, throttle) was treated
as a successful delivery and the source record was consumed. Surface it (throw)
so the caller routes the record to the DLQ. Also switch applyEnrichment's
FunctionError failure from a bare RuntimeException to AwsException, per the
service-layer convention. Covered by PipesTargetInvokerTest.invoke_lambdaTargetFunctionErrorThrows.

* fix(pipes): only array-wrap the enrichment response for Lambda targets

deliverEnrichedBatch wrapped the enrichment response in a JSON batch array before invoking
the target unconditionally. That is correct for a Lambda target (which expects an
SQSRecord[]-style batch) but corrupts every other target — a Step Functions execution, SQS
message, SNS publish or EventBridge event must receive the raw enrichment response. Gate the
wrapping on isLambdaTarget, matching the non-enrichment delivery path. Adds pollSqs tests for
both a non-Lambda (raw) and a Lambda (wrapped) target.

* fix(pipes): align enrichment empty/unsupported handling with AWS + document SQS-only wiring

Review feedback:
- applyEnrichment now also skips the target when the Lambda enrichment returns an
  empty object {} or empty array [] (whitespace variants included), matching AWS;
  a non-empty array such as [{}] still invokes the target.
- A non-Lambda enrichment type (API destination, API Gateway, SFN Express) now
  fails the batch to the DLQ instead of silently delivering the unenriched payload.
- Documented that enrichment is currently applied only on the SQS source path
  (Kinesis/DynamoDB Streams/Kafka bypass it) in code and docs/services/pipes.md.
- Generalized a comment that named a specific downstream consumer.
- Tests: empty {}/[] skip, [{}] invokes, unsupported type throws.

* docs: regenerate action tables
2026-07-09 00:14:53 -05:00
Alex Banna 45ed00ebc7 feat(ecs): apply EFS access point POSIX ownership to shared local volumes (#1686)
* feat(ecs): apply EFS access point POSIX ownership to shared local volumes

#1569 materialises an ECS task's efsVolumeConfiguration volume as a shared
local Docker named volume (floci-efs-<fileSystemId>). Docker creates a named
volume root:root 0755, so a task whose image runs as a non-root USER — as
containers mounting an EFS access point typically do — cannot create files on
it and fails with EACCES.

Real EFS initialises an access point's root directory per
RootDirectory.CreationInfo {OwnerUid, OwnerGid, Permissions} and applies the
access point's PosixUser to all I/O regardless of the process uid. This change
emulates that mechanism for the shared local volume, driven by generic config:

- New floci.storage.efs.* block (owner-uid, owner-gid, root-permissions,
  setgid, init-image, mount-user, mount-group-add). Every value is empty/false
  by default, so a shared volume behaves exactly as before (a plain named
  volume, no ownership change) unless explicitly configured.
- ContainerLifecycleManager.ensureSharedVolume(...) ensures the volume then, if
  ownership is configured, chowns/chmods the mount root once (run-once guard;
  optional setgid so subdirectories inherit the owner gid) inside a short-lived
  helper container.
- ContainerSpec/ContainerBuilder gain withUser/withGroupAdd; wired into
  createContainerCmd.withUser and HostConfig.withGroupAdd.
- EcsContainerManager initialises the EFS volume root via ensureSharedVolume
  before mounting it.

Unit tests cover the no-op default (no helper container, no image pull), the
one-off chown/chmod/setgid helper with the run-once guard, the builder
round-trip, and the EcsContainerManager wiring.

* fix(ecs): apply configured EFS PosixUser to containers mounting a shared volume

Wire the previously-inert floci.storage.efs.mount-user / mount-group-add config into the
ECS container spec: a container mounting an EFS-backed shared volume now runs under the
configured uid[:gid] and adds the supplementary group, emulating the access point's
PosixUser squashing. Without this a non-root image USER could not write a volume owned by
owner-uid/owner-gid. Also add the floci.storage.efs.* section to application.yml (the
source of truth for effective defaults) and correct the root-permissions Javadoc, which
implied leaving it empty always skips volume init even when owner/setgid are set.

* docs: regenerate action tables
2026-07-08 23:24:48 -05:00
Kenshin Okinaka 312fe377fc feat(ses): implement PutEmailIdentityConfigurationSetAttributes for SES v2 (#1698)
* feat(ses): implement PutEmailIdentityConfigurationSetAttributes for SES v2

Add the v2 PutEmailIdentityConfigurationSetAttributes API and wire an email
identity's default configuration set into the send path so its event
destinations fire. This includes Raw sends with no explicit FromEmailAddress:
the configuration set is re-resolved from the MIME "From" header once parsed,
so an omitted-sender Raw send still routes through the identity default.
Unknown identities surface the AWS-matched error message.

* test(ses): log instead of swallowing cleanup failures in the identity config-set compat test

* docs(ses): clarify default config-set precedence and clear-on-null semantics

* fix(ses): fail send when an identity's default configuration set was deleted

Per the SES Developer Guide, sending through an identity whose default
configuration set has been deleted fails with a bad-request error. The default
resolution was silently dropping the stale association; make it throw
BadRequestException ("Configuration set <name> does not exist.") to match AWS.
2026-07-08 23:23:28 -05:00