Commit Graph
205 Commits
Author SHA1 Message Date
Alex BannaandAlexander Banna d9e4447aeb feat(cloudformation): resolve dynamic references in RDS credentials (#1809)
* feat(cloudformation): resolve dynamic references in RDS credentials

* test(cloudformation): pin secret resolution failures

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 19:38:51 -04:00
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 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
Aniket Shukla 2f5bc39680 fix(s3vectors): return cosine distance from queries (#2175)
* fix(s3vectors): return cosine distance from queries

Convert cosine similarity to the AWS-compatible distance value and sort query results nearest-first.

* fix(s3vectors): honor query distance response flag

* test(s3vectors): request query distances explicitly
2026-08-12 13:51:45 -04:00
Kenshin Okinaka cd3588b517 feat(ses): honor ConfigurationSetName on CreateEmailIdentity (v2) (#1812)
* feat(ses): honor ConfigurationSetName on CreateEmailIdentity (v2)

CreateEmailIdentity now reads the optional ConfigurationSetName and sets it as
the identity's default configuration set, surfaced by GetEmailIdentity. Verified
against AWS: a non-existent configuration set fails with NotFoundException before
the identity is created (atomic), matching the deleted-default send behavior.

* fix(ses): treat only an empty ConfigurationSetName as absent on CreateEmailIdentity

A whitespace-only ConfigurationSetName was silently ignored (isBlank),
diverging from the PutEmailIdentityConfigurationSetAttributes path, which
routes such a name through name validation. Switch to isEmpty so both paths
reject a whitespace-only name as invalid input (400), and add coverage for
the empty (no default) and whitespace (400) cases.

* test(ses): clarify that empty-string ConfigurationSetName handling deviates from AWS

The comment on the empty-string CreateEmailIdentity test mentioned that AWS stores ""
verbatim without stating that Floci deliberately diverges (treating "" as "no default"),
which could read as if the assertion matched AWS. Reword to make the deviation and its
rationale explicit.

* docs(ses): correct the non-string ConfigurationSetName comment to match the actual response

The comment claimed AWS returns a 400 with an empty body, but the code throws a
SerializationException that AwsExceptionMapper renders as a JSON error body. Reword the
comment to describe the actual response shape.

* fix(ses): reject a non-string EmailIdentity on CreateEmailIdentity

CreateEmailIdentity read EmailIdentity via asText, which coerces a non-string JSON value
(e.g. 123 -> "123") and would silently create an identity named "123". Reject a non-string
EmailIdentity with a 400 SerializationException, matching the ConfigurationSetName handling
in the same method.

* fix(ses): validate Tags before creating the identity on CreateEmailIdentity

parseTagsArray ran after verifyEmailIdentity/verifyDomainIdentity, so a non-array Tags
value (e.g. "Tags":"oops") returned 400 but left the identity created — a half-created
state. parseTagsArray is pure, so hoist it above the create; the identity is now
persisted only after both the ConfigurationSetName and the Tags shape have been
validated, matching AWS.
2026-08-12 00:12:16 -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
Maciej 0cfffbea00 fix(kms): reject mismatched keys in decryption requests (#1893)
* fix(kms): reject mismatched keys in decryption requests

* fix(kms): reject mismatched keys in reencryption requests

* fix(kms): verify if key is usable for cryptographic operations
2026-08-10 23:49:31 -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
Dmitriy Polomoshnov a2b20cc085 fix(dynamodb): compare Value when legacy Expected supplies Exists (#2125)
* fix(dynamodb): compare Value when legacy Expected supplies Exists

A legacy Expected entry that supplies both Exists:true and a Value was
evaluated as an existence check only — the supplied Value was silently
discarded, so any stale value passed the condition.

This is the wire form emitted by version-guarded writes, where the caller
pairs Exists:true with the version it last read:

    "Expected": {"version": {"Exists": true, "Value": {"N": "5"}}}

Because the guard was present on every request and ignored on every
request, conflicting writes were accepted with no visible symptom.

Per the documented ExpectedAttributeValue semantics, Exists:true always
carries a Value and means the attribute must exist AND equal it, which is
the same check as a bare Value. Only Exists:false is a pure absence check.
The three combinations DynamoDB documents as invalid now raise
ValidationException instead of being silently accepted:

  - Exists:true with no Value
  - Exists:false alongside a Value
  - Exists combined with ComparisonOperator / AttributeValueList

Validation runs over the whole Expected map before any condition is
evaluated. PutItem, DeleteItem and UpdateItem all route through
evaluateLegacyExpected, so the change applies to all three.

* fix(dynamodb): compare collection values in legacy EQ conditions

The EQ comparison used by legacy Expected, QueryFilter and ScanFilter
reduced a non-scalar attribute value to an empty string, so any two
values of the same collection type compared as equal. A stale
expectation on an SS, NS, BS, L or M value was therefore always
satisfied and the guarded write was applied.

EQ now delegates to the existing attributeValuesEqual helper — the same
one the ConditionExpression path uses. It is type-strict, compares
numbers via BigDecimal, recurses into M and L, and treats set types as
unordered.

* fix(dynamodb): compare number set members numerically in equality

Number set equality put the members in a HashSet<BigDecimal>, so
membership went through BigDecimal.equals, which is scale-sensitive: 1
and 1.0 were treated as different members. Because NS elements are
normalized on write while a supplied condition value is not, an
otherwise valid condition on a numerically equivalent set was rejected
and the guarded write blocked.

Membership now goes through a TreeSet, whose contains uses compareTo, so
members compare numerically. Applies to both the legacy Expected /
QueryFilter / ScanFilter EQ path and ConditionExpression, which share
this helper.

* fix(dynamodb): compare collection values in legacy NE conditions

NE had the inverse of the collapse the previous commit fixed for EQ: it
compared the scalar projections of both values, which are empty strings
for non-scalar types, so any two collections of the same type looked
equal and NE was always false. A condition asserting an attribute
differs from a set it genuinely differs from blocked the write.

NE now negates attributeValuesEqual, mirroring EQ. Null handling is
unchanged: a missing attribute or a missing comparison value still
satisfies NE.

* test(dynamodb): pin type-strict equality in legacy conditions

EQ and NE compare attribute types as well as values, so a string "5"
does not match a stored number 5. Nothing pinned that, which left room
for a refactor to reintroduce equality via scalar string projections
without any test failing.

* fix(dynamodb): match DynamoDB validation for legacy Expected entries

Verified the legacy Expected rules against DynamoDB itself and aligned
the validation with what the service actually returns.

Error messages now carry the "1 validation error detected: " prefix and
the exact wording, including "Exists and ComparisonOperator cannot be
used together", which differed from the message used before.

Two rules were missing:

  - AttributeValueList without a ComparisonOperator is rejected, and
    that check takes precedence over the Exists rules. It applies
    whether or not Exists is present.
  - An entry with neither Exists nor Value is rejected as well,
    reported as "Value must be provided when Exists is null".

DynamoDB reports only the first offending entry even when several are
invalid, so validation still stops at the first error.
2026-08-09 19:03:42 -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
Oliver Andrews 02288abc11 fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe* (#1740)
* fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe*

DescribeDBInstances/DescribeDBClusters returned an empty 200 when the
identifier parameter matched nothing; real AWS faults for the parameter
form and returns an empty list only for the Filters form. Track whether
the identifier came from the parameter and fault when it matched nothing,
with error codes, messages, and 404 status matching live AWS.

* fix(rds,docdb,neptune): ARN identifiers and Filters-form parity for Describe*

Review follow-ups:

- RDS, DocDB, and Neptune list methods accept an ARN (the identifier
  parameter and the db-instance-id/db-cluster-id filters both allow ARNs
  per the AWS model). The ARN is matched against each resource's stored
  ARN, so a cross-account or cross-region ARN does not resolve a
  same-named local resource.
- DocDbQueryHandler and NeptuneQueryHandler fault only for the identifier
  parameter, not the Filters form, which returns an empty list (mirror of
  the RDS fix).

* test(rds): expect NotFound faults after delete in SDK compat tests

The Go and Java compat suites asserted the old emulator behavior — an
empty 200 when describing a deleted instance/cluster by identifier. Real
AWS faults DBInstanceNotFound/DBClusterNotFoundFault there, which is what
the deletion waiters key on, and the emulator now does the same.
2026-08-08 21:48:17 -05: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
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
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
Alex Banna b245632a2e feat(stepfunctions): implement States.JsonMerge intrinsic (#1662)
* feat(stepfunctions): implement States.JsonMerge intrinsic

The DPS provisioning state machine uses States.JsonMerge, which AslExecutor rejected with "Unsupported intrinsic function: States.JsonMerge". Implement the shallow merge (second object's top-level fields win on conflict); reject the deep-merge form (third argument true) and non-object arguments, as AWS does. Also resolve boolean/null literal intrinsic arguments so the third argument evaluates correctly. Covered by AslExecutorJsonMergeTest.

* fix(stepfunctions): reject a non-boolean States.JsonMerge third argument

The third (deep) argument was read with JsonNode.asBoolean(), which silently
coerces null/number/string/object nodes to false, so States.JsonMerge($.a,$.b,$.x)
with a non-boolean $.x quietly performed a shallow merge instead of failing.
Validate that the resolved third argument is a boolean and raise States.Runtime
otherwise. Covered by AslExecutorJsonMergeTest.nonBooleanThirdArgumentRejected.

* fix(stepfunctions): validate JsonMerge argument types before the deep-merge flag

AWS validates the argument types of States.JsonMerge before evaluating the deep-merge
flag, so two non-objects passed with true should report "requires two JSON objects"
rather than "shallow merge only". Reorder the object-type check ahead of the deep-flag
rejection and add a precedence test.

* test(stepfunctions): adapt JsonMerge test to main's AslExecutor constructor

main's AslExecutor constructor now takes EcsService and EcsJsonHandler; pass the
two new mocks. Also generalize a comment that named a specific downstream system.

* docs: regenerate action tables

* fix(stepfunctions): thread context into States.JsonMerge intrinsic args

The intrinsic pipeline gained a context argument on main (resolveIntrinsicArg /
evaluateIntrinsic now take three parameters). Thread the surrounding case's
root/context through the three States.JsonMerge argument resolutions so the branch
compiles against current main.

* fix: align JsonMerge intrinsic failures

* fix(athena): harden compatibility query polling
2026-07-21 12:14:35 -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
Jason van Zyl aa77d4ce46 fix(elbv2): expose target health reason parity (#1743) 2026-07-14 22:57:45 -04:00
Robert Stupp 05302bc63b fix(iam): pass S3 list condition context to IAM enforcement (#1748)
IAM policy evaluation already supported condition keys, but request-time enforcement did not provide S3 list request parameters to the evaluator. As a result, assumed-role session policies that allowed s3:ListBucket only for a matching s3:prefix were denied because the condition context was empty.

Add an application-scoped IamConditionContextResolver and have IamEnforcementFilter pass resolved condition context into IamPolicyEvaluator. The resolver currently maps S3 ListBucket query parameters to s3:prefix, s3:delimiter, and s3:max-keys, keeping action-specific condition extraction out of the filter.

Add regression coverage for prefix-restricted STS session policies through direct integration tests and the Java SDK compatibility suite. The SDK test also uses a trust policy matching the root/test principal that performs AssumeRole when IAM enforcement is enabled.

Tests:

- ./mvnw test -Dtest=IamConditionContextResolverTest,IamEnforcementFilterTest,IamEnforcementIntegrationTest,StsSessionPolicyS3EnforcementIntegrationTest

- compatibility-tests/sdk-test-java: mvn -q -DskipTests test-compile
2026-07-14 22:38:05 -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
David Phillips a3e8bf5a8b fix: Support S3 auth enforcement (#1689) 2026-07-10 22:41:03 -05:00
AgustinBertagna f915622e36 feat(appsync): Phase 5 — Management API Coverage + AWS Behavior Alignment + Async Schema Creation (#1590)
* test(appsync): strengthen existing integration error tests with __type and message assertions

All 30 existing error assertions (400/404) previously checked only the HTTP
status code. Each now also verifies the AWS error body shape:
  {"__type":"<ExceptionClass>","message":"<...>"}

This locks in the __type field that the AWS SDK v2 uses to instantiate the
typed exception (NotFoundException, BadRequestException, etc.) and guards
against accidental changes to error codes and messages.

* test(appsync): add 409 conflict and 429 limit tests

Add 7 new integration tests covering previously untested error paths:

ConflictException (409):
- createDataSourceDuplicateReturns409
- createResolverDuplicateReturns409
- createTypeDuplicateReturns409
- createDomainNameDuplicateReturns409
- createChannelNamespaceDuplicateReturns409
- associateApiDuplicateReturns409 (domain already associated)

LimitExceededException (429):
- createApiKeyExceedsLimitReturns429 (3rd key exceeds max 2 per API)

All tests are self-contained: create resources, assert the error, then
clean up. Each asserts statusCode + __type + message substring.

* test(appsync): add 404 tests for update/delete and cross-resource create

Add 11 new integration tests covering previously untested 404 paths:

Update/delete of non-existent resources (8):
- updateResolverNonExistentReturns404
- deleteResolverNonExistentReturns404
- updateFunctionNonExistentReturns404
- deleteFunctionNonExistentReturns404
- updateApiKeyNonExistentReturns404
- deleteApiKeyNonExistentReturns404
- updateDomainNameNonExistentReturns404
- updateChannelNamespaceNonExistentReturns404

Cross-resource 404 on create (3) — missing referenced resource:
- createResolverMissingDataSourceReturns404
- createFunctionMissingDataSourceReturns404
- associateApiMissingDomainReturns404

Each asserts statusCode + __type=NotFoundException + message substring.

* test(appsync): add pagination, edge case, and updateChannelNamespace tests

Add 7 new integration tests:

Pagination for previously untested list operations (3):
- listDomainNamesWithMaxResults
- listChannelNamespacesWithMaxResults
- listSourceApiAssociationsWithMaxResults
Each creates >=2 items, verifies page size + nextToken, follows token,
and cleans up.

Pagination edge cases (3):
- listWithMaxResultsZero (empty page + nextToken present)
- listWithNegativeMaxResultsReturns400
- listWithInvalidNextTokenNonApiReturns400 (data sources path)

Update channel namespace (1):
- updateChannelNamespace (verify description field change)

* test(appsync): upgrade SDK error tests to typed exceptions

Upgrade 4 existing SDK error tests from the generic AppSyncException to
the typed exception classes that the AWS SDK v2 maps from the __type
response field:

- getNonExistentApiThrowsException -> NotFoundException
- getNonExistentDataSourceThrowsException -> NotFoundException
- getNonExistentTypeThrowsException -> NotFoundException
- startSchemaCreation_invalidSchema -> BadRequestException

Each now also asserts hasMessageContaining with the expected message
substring. This aligns AppSyncTest with the repo convention used by
ApiGatewayV2ManagementTest, SchedulerTest, and ElbV2Test.

Also strengthen two existing update tests with field assertions:
- updateChannelNamespace: now sets codeHandlers and verifies the response
- updateDomainName: now asserts description field equals updated value

* fix: correct environment variables API path case for SDK compatibility

The AppSync controller used lowercase /v1/apis/{apiId}/environmentvariables
but the AWS SDK v2 sends to /v1/apis/{apiId}/environmentVariables (capital V).
This broke both getGraphqlApiEnvironmentVariables and
putGraphqlApiEnvironmentVariables for all SDK clients.

Fix the @Path annotations in the controller and update integration test
paths to match the SDK-expected casing.

* fix(appsync): align error codes and messages with AWS AppSync behavior

- DataSource duplicate: ConflictException 409 → BadRequestException 400
- Resolver duplicate: ConflictException 409 → BadRequestException 400
- Type duplicate: ConflictException 409 → BadRequestException 400
- DomainName duplicate: ConflictException 409 → BadRequestException 400
- Domain association duplicate: ConflictException 409 → BadRequestException 400
- API key limit: LimitExceededException 429 → ApiKeyLimitExceededException 400
- Add duplicate validation for Source API associations
- Add checkDuplicateSourceApiAssociation helper method
- Update all integration and SDK test assertions to match AWS exact messages

* feat(core): add extended data support to AwsException for AWS error parity

Add optional extended data to AwsException so the exception mapper can
emit structured error payloads matching the AWS error contract (e.g.
AppSync BadRequestException with reason=CODE_ERROR and detail.codeErrors).

The mapper auto-detects extended data and serializes it as additional
JSON fields alongside __type and message. When extended data is null
the previous simple AwsErrorResponse is returned, preserving behavior
for every existing error site.

* fix(appsync): return ConcurrentModificationException for duplicate source API association

AWS AppSync's AssociateSourceGraphqlApi returns ConcurrentModificationException
(HTTP 409) when an association already exists for the same source and merged
API pair. Floci was returning BadRequestException (400) with an association
ID in the message that did not match AWS.

Also filter out associations in DELETION_SCHEDULED status so a new
association can be created after the previous one has been removed, matching
AWS behavior where the previous association is no longer 'live'.

Message format now mirrors AWS: 'Source API association already exists
for Source API ID: <id> and Merged API ID: <id>.'

* refactor(appsync): remove non-AWS endpoints getApiKey and listAllResolvers

AWS AppSync does not expose:
- GetApiKey: there is no GetApiKey operation in the AppSync API
  Reference. API keys can be listed, created, updated, and deleted
  but not retrieved by id.
- ListAllResolvers: ListResolvers requires typeName. There is no
  endpoint that lists resolvers across all types for an API.

Both endpoints were Floci-only and violated the 'no custom endpoint
shapes' rule. The associated service method (listResolvers) is also
removed. The corresponding integration tests are dropped in a
follow-up commit.

The getApiKey service helper stays because it is still used
internally by updateApiKey and deleteApiKey flows.

* feat(appsync): emit AWS-compatible BadRequestException extended format for SDL errors

AWS AppSync's StartSchemaCreation returns 400 BadRequestException with a
reason=CODE_ERROR field and a detail.codeErrors array. Each code error
carries errorType, value, and location{line, column, span}.

This commit:
- Catches SchemaProblem and InvalidSyntaxException from the parser and
  throws BadRequestException with extended data built from
  graphql-java's GraphQLError locations.
- Catches SchemaProblem from makeExecutableSchema for validation errors
  (unknown types, missing fields) with errorType=VALIDATION_ERROR.
- Catches generic RuntimeException without extended data so flow
  exceptions (NPE, OOM) do not produce a misleading codeErrors array.
- Validates unknown AppSync directives with errorType=VALIDATION_ERROR
  and line/column/span from the SDL.

The errorType values follow the AWS Javadoc (PARSER_ERROR, VALIDATION_ERROR)
and span defaults to -1 when unknown, matching CodeErrorLocation.span()
in the AWS SDK.

* test(appsync): cover AWS-aligned error format, dead-code cleanup

- Add Order 157: createSourceApiAssociationDuplicateReturns409 asserts
  ConcurrentModificationException 409 with the AWS message format.
- Add Order 158: createSourceApiAssociationReplacesDeletionScheduled
  covers the new DELETION_SCHEDULED filter (a new association can
  replace a previously deleted one).
- Add Orders 700, 701, 702: extended BadRequestException format for
  PARSER_ERROR (syntax), VALIDATION_ERROR (semantic), and unknown
  directive cases. Each asserts reason=CODE_ERROR, detail.codeErrors,
  and the location{line, column, span=-1} shape.
- Update Order 124 (deleteApiKeyStandalone): the verification step
  used the removed getApiKey endpoint, replace it with listApiKeys
  asserting the deleted key is no longer present.
- Update Orders 600 and 607 to assert the new extended format for
  generic SDL validation and unknown directive cases.
- Drop Order 32 (getApiKey) and Order 62 (listAllResolvers): the
  underlying endpoints no longer exist.
- Drop encodeArn helper and the URLEncoder / StandardCharsets
  imports that were no longer used by any test.

* test(sdk-java): cover AssociateSourceGraphqlApi 409 and extended schema error body

- Add Order 137 (createSourceApiAssociationDuplicateThrowsConcurrentModificationException):
  use the typed AWS SDK exception ConcurrentModificationException instead
  of the generic AppSyncException, validating the message format that
  AWS returns.
- Add Order 200 (startSchemaCreation_syntaxError_throwsBadRequestWithExtendedBody):
  send a raw HTTP POST with an invalid schema, then inspect the JSON body
  to assert the AWS-compatible shape (__type, reason, detail.codeErrors[],
  errorType=PARSER_ERROR, location{line, column, span=-1}). Uses a
  jackson mapper rather than the SDK to read the response body directly.
- Import java.util.List to support the new deserialization in Order 200.

* feat(appsync): async schema creation with 409 in-progress gates

StartSchemaCreation is asynchronous in AWS: the request returns 200 +
PROCESSING, and the schema compiles in a background thread, transitioning
to ACTIVE (success) or FAILED (error) with the extended error format in
the polled GetSchemaCreationStatus response.

This commit:

- Adds SchemaCreationWorker, a singleton executor with configurable
  thread count and graceful shutdown, that transitions the schema
  status asynchronously and serializes the AwsException extended data
  into the FAILED details string.
- Adds SchemaStatusStoreProducer so AppSyncService and the worker see
  the same in-memory state for the schema status store (otherwise
  two StorageFactory.create() calls would create independent maps).
- Refactors startSchemaCreation to set PROCESSING synchronously and
  hand off compilation to the worker.
- Removes the synchronous ACTIVE override from the controller.
- Gates 27 per-API mutations and 2 account-wide operations
  (CreateGraphqlApi, CreateApi) plus self-blocking on second
  StartSchemaCreation with ConcurrentModificationException 409,
  matching the AWS behavior documented in the AppSync API Reference
  and service-2.json.
- Adds recoverOrphans() to EmulatorLifecycle.onStart so schemas left
  in PROCESSING by a previous emulator run are marked FAILED instead
  of permanently blocking the API.
- Adds schemaWorkerThreads and schemaWorkerShutdownTimeoutSeconds
  to EmulatorConfig (FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_THREADS,
  FLOCI_SERVICES_APPSYNC_SCHEMA_WORKER_SHUTDOWN_TIMEOUT_SECONDS).

* test(appsync): cover async schema polling, FAILED state, and 409 gates

- Adapts the 7 existing schema creation tests to the async pattern:
  the post returns PROCESSING, tests poll for the terminal status with
  Awaitility, and the extended format body is now read from the
  polled FAILED details.
- Adds 9 new tests (Orders 703-711) covering the 409 in-progress gates
  for createDataSource, createResolver, createFunction, createType,
  putEnvironmentVariables, startSchemaCreation, createGraphqlApi,
  updateGraphqlApi, and deleteGraphqlApi. The gates are exercised by
  setting the status to PROCESSING directly via the shared store
  backend, which is deterministic and avoids the race window of
  waiting for the worker.
- Updates the EmulatorLifecycleTest constructor for the new
  SchemaCreationWorker dependency.

* test(sdk-java): cover async schema with typed SDK polling

- Adds awaitility 4.2.2 to pom.xml (test scope) so the SDK test for
  the polled status can use the same Awaitility DSL the integration
  tests use.
- Updates the existing getSchemaCreationStatus test (Order 11) to
  poll via the typed SDK call until the terminal status is reached
  (ACTIVE in this case) instead of a single request. Without this,
  the gate added in the previous commit would 409 every subsequent
  SDK test that runs while the schema is still PROCESSING.

* fix(build): remove duplicate awaitility declaration in pom.xml

The pre-existing version-less awaitility declaration (BOM-managed by
Quarkus) was shadowed by the pinned 4.2.2 declaration added in this PR.
Maven resolves the first declaration it encounters, silently ignoring
the BOM version. Removed the version-less dup so the pinned 4.2.2
takes effect.

Addresses P1 from Greptile review.

* fix(appsync): add missing 409 gates and synchronize startSchemaCreation

Validating all 43 ConcurrentModificationException operations from
service-2.json against the code surfaced 5 operations missing the
PROCESSING gate (Greptile caught 1, 4 more were found during review):

- getChannelNamespace: added assertSchemaNotBusy (protects both get
  and deleteChannelNamespace, matching getResolver/getFunction/getType)
- deleteDomainName: resolves the associated apiId from the domain
  association store and gates on it (no-op if no association exists)
- disassociateApi: same pattern as deleteDomainName
- deleteMergedApiAssociation: gate on sourceApiIdentifier
- updateDomainName: resolves the associated apiId and gates on it

Also wraps the startSchemaCreation check-and-set in synchronized(this)
to close the TOCTOU race window between assertSchemaNotBusy and the
PROCESSING put. The async submitSchemaCreation call stays outside the
lock to avoid blocking the worker thread.

Addresses P1 and P2 from Greptile review.

* chore(appsync): document schema worker config in application.yml

Adds the appsync section under storage.services in both main and test
application.yml, documenting the three AppSyncStorageConfig keys:

- flush-interval-ms (5000 main / 60000 test, matching other services)
- schema-worker-threads (4)
- schema-worker-shutdown-timeout-seconds (30)

These already had @WithDefault fallbacks so the code worked without
the YAML entries, but the repository convention (AGENTS.md) requires
storage config to be documented in application.yml as the source of
truth for operators.

Addresses P2 from Greptile review.

* test(appsync): cover additional 409 gates for domain and merged operations

Adds 5 new integration tests (Orders 712-716) covering the PROCESSING
409 gates added in the previous commit:

- 712: deleteChannelNamespace_busy_returns409
- 713: deleteDomainName_busy_returns409
- 714: disassociateApi_busy_returns409
- 715: disassociateMergedGraphqlApi_busy_returns409
- 716: updateDomainName_busy_returns409

Each test creates the necessary resources (temp API, channel namespace,
domain name + association, or merged API association) before setting
the schema status to PROCESSING directly via the shared store, then
asserts the gated operation returns 409 ConcurrentModificationException
with the AWS-style message.

Integration test count: 154 -> 159.

* fix(appsync): remove incorrect CME gate from getChannelNamespace, add to deleteChannelNamespace

GetChannelNamespace does not declare ConcurrentModificationException in
service-2.json or the AWS Java SDK v2. Only BadRequestException,
NotFoundException, UnauthorizedException, InternalFailureException, and
AccessDeniedException are declared. The gate was incorrectly returning
409 during PROCESSING for an undeclared error code.

DeleteChannelNamespace does declare CME, so the gate is now applied
directly in deleteChannelNamespace instead of being inherited from
getChannelNamespace.

* fix(appsync): account-aware schema creation and worker store isolation

Scope schema creation status to the requesting account so concurrent
accounts cannot interfere with each other's in-flight schema operations.

- Add accountId field to SchemaCreationStatus
- Worker uses AccountAwareStorageBackend (putForAccount/getForAccount)
- SchemaStatusStoreProducer now produces AccountAwareStorageBackend
- SchemaStoreProducer CDI bean shares schemaStore between service and worker
- schemaStore.put moved to worker success path only
- assertSchemaNotBusy scoped to current account via getForAccount
- assertNoSchemaBusyAnywhere scoped to keysForAccount
- currentAccountId() helper reads RequestContext
- Worker config moved from AppSyncStorageConfig to AppSyncServiceConfig

* fix(appsync): ACTIVE→SUCCESS terminal schema status

Match AWS behavior: a successfully compiled schema is SUCCESS, not
ACTIVE. ACTIVE is not a valid terminal status in real AppSync.

- Worker marks SUCCESS on successful compilation
- Integration tests assert SUCCESS
- SDK compatibility test asserts SUCCESS

* refactor(appsync): remove circular dependency between SchemaRegistry and SchemaCreationWorker

SchemaRegistry depended on SchemaCreationWorker solely to delegate
submitSchemaCreation calls, creating a circular dependency. AppSyncService
now calls the worker directly, making the delegation unnecessary.

- Remove SchemaCreationWorker dependency from SchemaRegistry
- Remove submitSchemaCreation method

* fix(appsync): add assertSchemaNotBusy to deleteResolver, deleteFunction, deleteType

These three delete operations mutate the schema and should be blocked
while a schema creation is in PROCESSING state, matching the 409 gates
on the other schema-mutating operations.

* fix(appsync): return PROCESSING status synchronously from StartSchemaCreation

The controller was re-reading the status from the store after submitting
to the worker pool. In fast environments the worker could complete
(fail) before the read, causing the POST response to return FAILED
instead of PROCESSING — breaking the SDK compatibility test.

startSchemaCreation now returns the PROCESSING status it just set, and
the controller uses it directly instead of re-reading.
2026-07-10 20:50:14 -05:00
Maciej bf53ff71d8 fix(secrets-manager): return partial result for missing secrets in batch (#1591)
* fix(secrets-manager): return partial result for missing secrets in batch

* fix(secrets-manager): remove hardcoded errorCode mapping

* fix(secrets-manager): report deleted and missing current version secrets in BatchGetSecretValue errors
2026-07-10 20:44:37 -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 13772fb5f8 feat(ecs): resolve containerDefinitions[].secrets at task launch (#1687)
RegisterTaskDefinition now parses and stores containerDefinitions[].secrets
(name + valueFrom) and round-trips them on register/describe as references,
matching AWS (the resolved values are never returned).

At RunTask launch, EcsContainerManager resolves each secret to an environment
variable through the in-process SsmService / SecretsManagerService (the same
local resolution CodeBuildRunner already uses, no extra HTTP hops):

- SSM parameter by name or full ARN -> Parameter.value
- Secrets Manager full ARN -> SecretString
- a full ARN's own region is used, so cross-region references resolve correctly
- env precedence: task-def environment < resolved secrets < RunTask container
  override environment (override still wins on a name collision)

When a referenced secret/parameter cannot be resolved the launch fails the way
AWS does: no container is started and the task goes STOPPED with a
ResourceInitializationError stoppedReason, rather than silently starting the
container without the variable.

Deferred (noted in floci-io/floci#1624): the Secrets Manager valueFrom selector
suffix (:json-key:version-stage:version-id) is not yet parsed; such a valueFrom
is resolved as the plain secret.

Adds handler round-trip tests, container-manager resolution / override /
cross-region unit tests, a stopped-task failure test, and Java SDK
compatibility coverage.
2026-07-10 20:41:43 -05:00
Kenshin Okinaka efc9453fd7 fix(ses): populate VerificationStatus in v2 ListEmailIdentities (#1722)
* fix(ses): populate VerificationStatus in v2 ListEmailIdentities

ListEmailIdentities built each item with only IdentityType / IdentityName /
SendingEnabled, so VerificationStatus always serialized as null and clients had
to call GetEmailIdentity per identity. Populate it from the identity's stored
status (mapped to the v2 enum via toV2Status), and refresh each identity's
state the same way GetEmailIdentity does so the list stays consistent (e.g. a
domain that transitioned to SUCCESS via its DKIM records).

* fix(ses): derive SendingEnabled from verification status in v2 ListEmailIdentities

SendingEnabled was hard-coded to true, so a not-yet-verified identity was
reported as sendable, which is inconsistent now that VerificationStatus is
populated. AWS returns SendingEnabled=true only when the identity is verified
(VerificationStatus SUCCESS) and false otherwise (PENDING/FAILED), matching the
VerifiedForSendingStatus logic already used by GetEmailIdentity. Derive it the
same way here.
2026-07-09 23:54:43 -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
Jason van Zyl c3980ebab0 feat(scheduler): dispatch ECS targets to RunTask (#1733)
* feat(scheduler): dispatch ECS targets to RunTask

* fix(scheduler): preserve ECS target parameters
2026-07-06 21:40:24 -05:00
Jason van Zyl 3a31439a84 fix(ec2): honor launch template default version updates (#1704) 2026-07-06 21:39:37 -05:00
Jason van Zyl ab32758cfe fix(autoscaling): align active instance refresh behavior (#1598)
* fix(autoscaling): reject active refresh config updates

* fix(autoscaling): align active refresh SDK error shape

* fix(autoscaling): reject version-only launch template updates

* fix(autoscaling): match refresh config validation message
2026-07-06 21:00:50 -05:00
Jason van Zyl c233eb4891 feat(ec2): add instance metadata catalog and architecture parity (#1596)
* fix(ec2): expose instance processor architectures

* feat(ec2): add instance type metadata catalog

* fix(ec2): enforce instance architecture parity

* fix(ec2): tighten instance metadata parity
2026-07-05 09:26:38 -05:00
Beytullah GunduzandBeytullah Gunduz 89fadbad81 feat(cloudwatch): add Logs Insights query support (#1448)
* feat(cloudwatch): add Logs Insights query support

Implement StartQuery/GetQueryResults/StopQuery for CloudWatch Logs so
clients using Logs Insights (e.g. boto3 start_query + get_query_results)
work against Floci instead of receiving UnsupportedOperation.

LogsInsightsQuery is a minimal engine covering the common subset: fields,
filter (= / !=), sort, dedup, limit; it resolves @timestamp/@message and
dotted JSON paths (e.g. params.job_id, level). StartQuery times are epoch
seconds while event timestamps are millis, scaled accordingly.

Queries follow a time-driven lifecycle: results are computed eagerly, but
a query reports Running until a configurable completion delay elapses
(FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS, default 0 =
instant for local dev), then Complete; StopQuery cancels a running query
and otherwise returns AWS-faithful errors (InvalidParameterException when
already ended, ResourceNotFoundException for an unknown id). Status is
computed on read from an injectable clock, with no background threads.
GetQueryResults returns ResourceNotFoundException for unknown ids,
reports recordsMatched independent of the Running/Cancelled row masking,
hands out a defensive copy of result rows, and drops rows once cancelled.
Results are cached by queryId with LRU eviction.

Covered by unit tests and an AWS SDK v2 compatibility test exercising the
full StartQuery/GetQueryResults/StopQuery lifecycle (stable against both
instant and delayed completion).

* test(cloudwatch): cover Logs Insights search across multiple log groups

Verify a single StartQuery spanning several log groups finds the same
params.id wherever it was logged (results merged and globally sorted by
@timestamp), and that a matching event in an un-queried group is excluded.

* test(cloudwatch): cover Logs Insights query-language edge cases

Add unit tests for limit (applied after sort), ascending sort on a nested
JSON field, the default @timestamp/@message projection, missing-field
handling (empty projection plus null-safe inequality filtering), graceful
ignoring of unsupported commands (parse/stats), and the recordsScanned vs
recordsMatched statistics.

* fix(cloudwatch): deterministic Logs Insights ordering for same-ms events and dedup

Tie-break the @timestamp/@ingestionTime sort comparators by ingestion sequence
then eventId (matching the event store's EVENT_ORDER), and apply the AWS-documented
default @timestamp desc sort when a dedup stage has no preceding sort — so the
surviving duplicate is the newest, deterministically, rather than depending on
storage-scan order.

* fix(cloudwatch): validate log groups and harden Logs Insights query parsing

StartQuery now de-duplicates the requested log groups (the same group can
arrive via multiple selectors) so it is scanned and counted once, and it
returns ResourceNotFoundException for a log group that does not exist
instead of a successful empty query — matching real AWS. The stage parser
splits on pipes only outside quotes, so a filter value containing '|'
(e.g. filter x = 'a|b') is no longer broken into fragments.

StartQuery still accepts multiple selectors and de-duplicates group names
service-side; strict AWS mutual-exclusivity rejection (InvalidParameterException
for more than one of logGroupName/logGroupNames/logGroupIdentifiers) is deferred
to a handler-side follow-up, since the handler collapses all three selectors
into one service argument.

* fix(cloudwatch): reject empty StartQuery selectors and parse quoted filter operators

StartQuery now rejects a request with no usable log-group selector
(InvalidParameterException) instead of returning a successful empty query.
parseFilter finds the equality/inequality operator outside quoted values,
so a value that itself contains '=' / '==' / '!=' (e.g. filter x = 'a==b')
is no longer misparsed.

* fix(cloudwatch): reject StartQuery requests with more than one log-group selector

AWS requires exactly one of logGroupName, logGroupNames, or logGroupIdentifiers.
The handler now rejects a request that provides more than one selector type with
InvalidParameterException, instead of silently querying the union. The
zero-selector case is already rejected by the service.

* fix(cloudwatch): count serialized StartQuery selector fields, not just non-empty ones

The mutual-exclusivity guard counted a selector only when its value was non-blank,
but the merge path added any present field — so a blank logGroupName alongside a
real logGroupNames slipped past the guard. Count serialized fields uniformly (has),
so a blank or empty selector field can't bypass the check; a lone empty selector
still yields no groups and is rejected by the service.

---------

Co-authored-by: Beytullah Gunduz <beytullah-gunduz@users.noreply.github.com>
2026-07-05 08:48:43 -05:00
Ahmed khaled 188854f2df feat(amazonmq): add Amazon MQ broker control plane backed by RabbitMQ (#1642)
* feat(amazonmq): add Amazon MQ broker control plane for RabbitMQ

* feat(amazonmq): provision RabbitMQ container with rollback

Back a broker with a real rabbitmq:3-management container, following the
MSK/ElastiCache container-manager pattern.

- RabbitMqManager starts the container, publishes AMQP (5672) and
  management (15672) ports, and resolves the broker endpoints
- Service branches on the mock flag; real brokers stay
  CREATION_IN_PROGRESS until a readiness poller observes the management
  API answering, then flip to RUNNING
- Rollback on failed provisioning: the manager removes the half-built
  container and the broker is persisted as CREATION_FAILED
- @PreDestroy stops containers on shutdown; DeleteBroker stops and
  removes the container and its storage

Readiness probes the management UI root (no auth) to avoid RabbitMQ's
loopback-only guest user over Docker port mapping.

* feat(amazonmq): seed broker admin user and reject ActiveMQ-only User API

Amazon MQ's standalone User API (CreateUser/DescribeUser/ListUsers/
DeleteUser) applies only to ActiveMQ brokers; AWS rejects it for RabbitMQ
and directs callers to the RabbitMQ web console. CreateBroker now requires
exactly one broker user (validated against AWS password rules) which is
seeded into the container via RABBITMQ_DEFAULT_USER/PASS, sidestepping
RabbitMQ's loopback-only guest restriction.

* test(amazonmq): SDK compatibility test against live RabbitMQ broker

Adds AmazonMqTest exercising the real container path via the AWS SDK MqClient:
CreateBroker provisions a rabbitmq:3-management container, the broker
transitions to RUNNING once its management API answers, endpoints are
published, the ActiveMQ-only User API is rejected, and DeleteBroker tears the
container down. Uses JUnit Assumptions to skip cleanly when Docker is absent.

* fix(amazonmq): harden error handling, persistence, and shutdown teardown

- Redact the provisioning failure 500: log the cause, return a generic AWS
  error envelope instead of leaking e.getMessage() (which can be null).
- Add @JsonIgnoreProperties(ignoreUnknown = true) to Broker, MqUser, and
  BrokerInstance so old persisted snapshots survive field changes.
- Wire RabbitMQ container teardown into EmulatorLifecycle.onStop() via
  RabbitMqManager.stopAll(), alongside the other container managers; the
  service @PreDestroy now only stops the readiness poller.

* docs(amazonmq): add Amazon MQ service page and bump service count to 66

Adds docs/services/amazonmq.md, lists Amazon MQ in the services overview and
README service tables, and updates the "65 -> 66 AWS services" count across
docs/index.md, docs/services/index.md, and README.md.

* fix(amazonmq): reject RebootBroker unless the broker is RUNNING

RebootBroker unconditionally set the broker to RUNNING, so a non-RUNNING
broker (e.g. CREATION_FAILED, which has no backing container) was silently
promoted to RUNNING and never reconciled by the readiness poller. AWS allows
RebootBroker only on a broker in the RUNNING state; guard it and return a 400
otherwise, matching the Amazon MQ API ("You can reboot only a broker with the
RUNNING status").

* fix(amazonmq): close readiness-probe connection and log tolerated failures

isReady() opened an HttpURLConnection but never disconnected it; since the
probe runs every 2s per pending broker this leaked sockets. Disconnect in a
finally block, and log the tolerated failure at debug with broker/URL context
(AGENTS.md: no empty catch; avoid noise in hot paths) instead of swallowing it.

* fix(amazonmq): tear down broker container by deterministic name after restart

containerId is in-memory bookkeeping (intentionally not persisted, since the
Broker model is serialized straight to DescribeBroker and must not leak it).
After an emulator restart it is null, so stopContainer() previously returned
early and left the container running. It now falls back to the deterministic
container name (floci-amazonmq-{brokerId}) so an explicit DeleteBroker still
removes a container left over from a previous run. Documented the field and
added RabbitMqManagerTest covering both the id and name-fallback paths.

* fix(amazonmq): keep admin password in-memory only and fail loudly if absent

The admin password is a secret used solely to seed the RabbitMQ container at
create time. Persisting it (to make it survive a restart) would write the
credential in cleartext to amazonmq-brokers.json, which the project's security
rule prohibits. It stays in-memory only via @JsonIgnore; startContainer (the
only consumer, called from CreateBroker) now throws if the password is absent
rather than seeding a null credential. Added MqUserTest asserting the password
is never serialized and round-trips to null.

* fix(amazonmq): persist broker volumeId/accountId/containerId without leaking them

These internal fields were @JsonIgnore'd, so they were absent from
amazonmq-brokers.json. After a restart in persistent mode volumeId was null
(removeBrokerStorage could not locate the named volume, leaking it) and
accountId was null (the readiness poller wrote brokers via the non-account-aware
path). Unlike the admin password, these are not secrets, so they should persist.

Remove @JsonIgnore so they round-trip through storage, and build the
DescribeBroker response explicitly in the controller so they are still never
exposed to clients (matches MskCluster, which persists volumeId/containerId).
Adds BrokerTest (round-trip) and asserts the describe response omits them.
2026-07-03 00:01:54 -05:00
Hector Ventura b3c54c1854 feat(firehose): return ExtendedS3DestinationDescription and support UpdateDestination (#1710)
* feat(firehose): return ExtendedS3DestinationDescription and support UpdateDestination

The Terraform/Pulumi provider creates delivery streams with
ExtendedS3DestinationConfiguration and reads ExtendedS3DestinationDescription
back after create; Floci parsed the config lossily and only ever emitted
S3DestinationDescription, breaking the provider read. Store the full config
(RoleARN, ErrorOutputPrefix, CompressionFormat, EncryptionConfiguration),
emit it under both wire keys like real AWS, add the required output members
(VersionId, DeliveryStreamType, HasMoreDestinations, DestinationId), and
implement UpdateDestination with version checking.

Refs #1043

* fix(firehose): reject empty destination updates and guard version parse

* fix(firehose): reject partial BufferingHints instead of absorbing defaults

AWS requires SizeInMBs and IntervalInSeconds to be specified together
(firehose service-2.json: "if you specify a value for it, you must also
specify a value for IntervalInSeconds, and vice versa"). The primitive
fields with initializers made a partial payload indistinguishable from a
full one, silently persisting a default over an existing value. Members
are now null-honest boxed Integers, create and update reject one-sided
hints with the declared InvalidArgumentException before any mutation,
and defaults apply only when the whole object is absent.
2026-07-02 23:59:11 -05:00
Robert Stupp 4f4e7be90e fix(iam): enforce STS session policies (#1636)
* test(iam): expose STS session policy S3 deny gap

* fix(iam): enforce STS session policies

## Summary

STS session policies were recorded on temporary credentials but IAM enforcement evaluated only the caller's identity policies. As a result, an assumed role with broad role permissions could still perform an action even when the inline `AssumeRole` session policy should have denied or narrowed it.

This changes enforcement to evaluate the full caller context, including identity policies, session policies, and permission boundaries. It also keeps temporary-credential lookup account-independent so assumed-role sessions can be resolved after account routing moves the request into the role account, and it uses the resolved request account when building resource ARNs for policy evaluation.

## Type of change

- [x] Bug fix (`fix:`)

## AWS Compatibility

Incorrect behavior: STS `AssumeRole` accepted the standard inline `Policy` parameter, but later requests signed with those temporary credentials did not have that session policy applied by IAM enforcement.

The fix matches AWS policy evaluation semantics: explicit denies in session policies participate in the deny pass, and a present session policy must also explicitly allow the request for the role's permissions to be effective. This preserves the existing Floci bypass behavior for unknown local credentials and the `test` root credential.

## What changed

- `IamEnforcementFilter` resolves a `CallerContext` and evaluates the complete IAM context instead of identity-policy documents only.
- `IamService` resolves STS sessions across account namespaces for caller context, caller ARN, account routing, and temporary secret lookup.
- Enforcement resource ARN construction uses the request account already resolved by `AccountContextFilter`, so assumed-role credentials evaluate account-scoped resources against the role account.
- IAM and multi-account docs now describe session-policy intersection and temporary-credential resolution accurately.
- Java SDK compatibility coverage now checks that an assumed-role session policy deny overrides a role allow.

## Checklist

- [x] `./mvnw test` passes locally - attempted; only failures were unrelated LambdaReactiveSyncIntegrationTest container startup Broken pipe errors
- [x] Selected Java SDK compatibility tests pass locally - in `compatibility-tests/sdk-test-java`: `mvn -q -Dtest=IamEnforcementTest,IamTest,StsTest,S3Test test`
- [x] New or updated integration test added
- [x] Commit messages follow Conventional Commits

* fix(iam): tighten cross-account session lookup
2026-07-02 23:29:23 -05:00
Kenshin Okinaka 3304184bd3 feat(ses): implement ContactList CRUD for SES v2 (#1638)
Add the SES v2 contact list management APIs (CreateContactList, GetContactList,
ListContactLists, UpdateContactList, DeleteContactList) under
/v2/email/contact-lists. A contact list holds subscription topics with
OPT_IN/OPT_OUT defaults. Matching real AWS, an account may hold at most one
contact list per region; a second create is rejected with BadRequestException
("A maximum of 1 Lists allowed per account."), a duplicate name with
AlreadyExistsException, and unknown lists with NotFoundException.

Covered by a RestAssured integration test and an AWS Java SDK v2 compatibility
test.
2026-07-02 23:23:38 -05:00
Hector Ventura 8b39ead1a4 fix(ec2): return groupSet from DescribeInstanceAttribute (#1709)
* fix(ec2): return groupSet from DescribeInstanceAttribute

Ansible's amazon.aws ec2_instance module reads value['Groups'] from
DescribeInstanceAttribute(Attribute=groupSet) in diff_instance_and_params;
Floci returned only instanceId for that attribute, producing the reported
KeyError. DescribeInstances group shapes were already correct.

Refs #1644

* test(ec2): give describeInstanceAttributeGroupSet a unique order slot
2026-07-02 19:13:20 -05:00
Maciej 6dfdd892aa fix(dynamodb): return a null Message for non-failed item cancellation reason (#1623)
* fix(dynamodb): return a null Message for non-failed item cancellation reason

* fix(ec2): fix flaky launchInstanceUserDataStreamToCloudWatch test

* fix: address PR review feedback for TransactWriteItems and revert unrelated imports
2026-07-02 18:23:02 -05:00
shrimptails-f 0ac1a01884 fix(ses): align CreateEmailIdentity DKIM behavior with AWS (#1620)
* fix(ses): align CreateEmailIdentity DKIM behavior with AWS

* test(ses): verify tracking domains via route53 in sdk compatibility tests

* fix(ses): cache pending DKIM Route53 lookups

* test(ses): log cleanup failures in tracking options test
2026-07-02 18:09:36 -05:00
Maciej 6c5f533f34 fix(cognito): do not return optional blocks in CreateUserPoolClient when they are not set (#1615)
* fix(cognito): do not return optional blocks in CreateUserPoolClient when they are not set

* fix(cognito): fix test order in file

* fix(cognito): improve bats assertions
2026-07-02 00:11:41 -05:00
Hector Ventura b87955b630 chore(deps): update maven dependencies and github actions (#1690)
Combines the open dependabot updates with the vulnerable-dependency pins:

- quarkus platform 3.36.0 -> 3.36.3, apicurio 2.6.9.Final -> 2.6.13.Final
- graphql-java 22.0 -> 26.0, neo4j-java-driver 5.28.5 -> 6.1.0 (test)
- import jackson-bom 2.21.4 and pin wire-runtime 6.3.0
- compat tests: aws sdk 2.44.14, netty-bom 4.1.135.Final, postgresql 42.7.11,
  jackson-bom 2.18.8, kafka-clients 3.9.2, commons-lang3 3.18.0
- actions/checkout v7.0.0, configure-aws-credentials v6.2.0, setup-graalvm pin
2026-07-01 23:27:56 -05:00
Alex Banna 058e02630a feat(cloudformation): add StackSets with account-aware provisioning (#1551)
* feat(cloudformation): add StackSets with account-aware provisioning

Implement CloudFormation StackSets so a template can be deployed across
target accounts and regions, and make CloudFormation provisioning land
resources in the correct account.

Provisioning previously ran on a background executor thread with no request
scope, so the downstream service calls fell back to the default account — a
stack created by account B materialised its resources under 000000000000.
executeChangeSet/deleteStack now run the provisioning under a synthetic
request scope bound to the deploying account (the caller's account for a
single stack, the target account for a StackSet instance), mirroring the
pattern other background workers already use. Single-stack resources now
land in the caller's account.

StackSet actions are wired through CloudFormationQueryHandler and
AwsQueryController: CreateStackSet, DescribeStackSet, ListStackSets,
UpdateStackSet, DeleteStackSet, CreateStackInstances, ListStackInstances,
DeleteStackInstances, ListStackSetOperations. CreateStackInstances drives
the existing single-stack engine once per target (account, region),
provisioning each instance into that account's namespace; the stack set,
its instances and its operation history live in the administration account.

Tests: an integration test deploying a StackSet from an admin account into
accounts B and C asserts the resources materialise in B and C and are
invisible to the admin/default account, exercises describe/list/operations
and instance deletion, and covers the not-found / already-exists /
not-empty error paths. A single-stack test asserts resources now land in
the caller's account.

Design aligned with maintainers in floci-io/floci#1550.

* fix(cloudformation): await StackSet instance deletion; test UpdateStackSet

Make the account-scoped deleteStack overload return its Future so
DeleteStackInstances completes synchronously before the operation returns,
rather than racing the async resource removal. Add integration coverage for
UpdateStackSet re-applying the template to existing instances.

* test(cloudformation): add SDK compatibility test for StackSets

Adds an sdk-test-java compatibility test exercising StackSets through the real
AWS SDK CloudFormationClient (CreateStackSet, CreateStackInstances,
DescribeStackSet, ListStackInstances, ListStackSetOperations,
DeleteStackInstances, DeleteStackSet). It asserts the management responses
unmarshal cleanly and that instances provision into each target account's
namespace (verified via per-account SQS clients), per the project's policy of
validating management APIs with AWS SDK clients. Runs in the compatibility CI
on pull requests.

* feat(cloudformation): add DescribeStackInstance and DescribeStackSetOperation

Complete the StackSets API surface with the singular describe operations:
DescribeStackInstance (used by orchestration that polls a single instance's
status) and DescribeStackSetOperation (companion to ListStackSetOperations).
Covered by the integration test and the SDK compatibility test, which confirm
the StackInstance / StackSetOperation response shapes unmarshal through the
real AWS SDK.

* feat(cloudformation): resolve TemplateURL and report StackInstanceStatus.DetailedStatus for StackSets

StackSet create/update now resolve a TemplateURL (fetched from S3) in addition
to an inline TemplateBody, matching how orchestration tools reference templates
staged in S3. DescribeStackInstance and ListStackInstances now also report the
nested StackInstanceStatus.DetailedStatus that AWS returns and that pollers read
to determine when an instance operation has completed.

* feat(cloudformation): derive StackSet operation status and honor RetainStacks

Address review feedback on #1551:

- Operation status is now derived from instance outcomes: CreateStackInstances
  and UpdateStackSet report FAILED if any instance fails to deploy, instead of
  always SUCCEEDED. deployInstance also recognizes a rolled-back create
  (ROLLBACK_COMPLETE, not *_FAILED) as a failed/INOPERABLE instance, which was
  previously mis-reported as SUCCEEDED.
- DeleteStackInstances honors RetainStacks: when true, the instance is detached
  from the stack set but its underlying stack and resources are left in place.
- UpdateStackSet now persists the refreshed instance records.

Tests: RetainStacks retention and the FAILED-operation path; docs updated.

* fix(cloudformation): restore account on active scope; log StackSets test teardown

Greptile review on #1551:
- runUnderAccount now saves and restores the previous account ID when it runs
  inside an already-active request scope, so it can't leave the overridden
  account behind on a reused thread. (Background workers normally have no active
  scope, so this only hardens the synchronous-caller path.)
- CloudFormationStackSetsTest teardown no longer swallows exceptions silently;
  it logs them, per the AGENTS.md no-empty-catch rule.

* fix(cloudformation): report a failed StackSet instance delete as FAILED

deleteStackInstances awaited the underlying deleteStack via a helper that
swallows the failure, then removed the instance record unconditionally and
hardcoded the operation status to SUCCEEDED. A failed non-retained delete was
therefore reported as a success with the instance silently dropped.

await() now returns whether the future completed cleanly. On a non-retained
delete failure the instance record is retained (marked INOPERABLE/FAILED) and
the operation status is derived via deriveOperationStatus, so it reports FAILED
— matching AWS, which does not detach an instance whose stack delete failed.

Adds StackSetServiceDeleteFailureTest covering the failure, success, and
RetainStacks paths.

* fix(cloudformation): reject templateless CreateStackSet and restore interrupt in await

CreateStackSet now rejects a request with neither TemplateBody nor TemplateURL (ValidationError,
matching AWS) instead of storing a null template — which would otherwise make a later
CreateStackInstances deploy empty stacks into every target account. Also handle
InterruptedException separately in await(Future) and restore the thread's interrupt flag, so a
shutdown signal to the backing ExecutorService propagates instead of being swallowed. Adds a
CreateStackSet-without-template integration test.
2026-07-01 23:11:16 -05:00
Jason van Zyl 94468ba56f fix(elbv2): publish resolvable local ALB DNS names (#1492) 2026-06-28 21:02:44 -05:00
nblomquistandnathan 326b495496 feat(iot) Feature/issue 1038 iot core (#1359)
* feat: add IoT endpoint and thing registry

* feat: add IoT thing tagging

* feat: add IoT certificates and shadows

* feat: add IoT MQTT broker

* feat: upgrade IoT MQTT broker to Moquette 0.18

* feat: restore IoT reserved MQTT topics

* feat: add IoT topic rules engine

* feat: improve IoT thing registry compatibility

* feat: complete IoT MVP 1 compatibility

* feat: complete IoT MVP 2 compatibility

* feat: finish IoT MVP 2 coverage

* fix: disable IoT MQTT broker persistence

* fix(docker): include vendored Maven artifacts in source builds

* fix(iot): stabilize MQTT integration test sockets

* fix(iot): verify MQTT test connections

* fix(iot): use Paho for MQTT integration tests

* fix(iot): use Vert.x MQTT broker

---------

Co-authored-by: nathan <nathan@debian-dev-small.localdomain>
2026-06-25 22:58:44 -05:00
Kenshin Okinaka 54ba15c218 feat(ses): implement PutConfigurationSetDeliveryOptions for SES v1 (#1553)
* feat(ses): implement PutConfigurationSetDeliveryOptions for SES v1

The classic SES Query API action was unhandled — only the v2 REST path
reached the existing setConfigurationSetDeliveryOptions service logic.
Route the v1 action through SesQueryHandler and register it in the
AwsQueryController SES action set.

The v1 DeliveryOptions structure carries only TlsPolicy (Require/Optional);
Floci stores the v2 canonical REQUIRE/OPTIONAL, so the handler normalizes
the value before delegating to the shared, already-validated service. An
all-null payload passes null to clear the block, mirroring the v2 path
rather than persisting an empty object.

Tests: v1 Query integration coverage (success, unknown set, invalid TLS
policy) and an AWS Java SDK v1 compatibility test that writes Require via
the v1 SesClient and reads it back as the canonical REQUIRE through v2
GetConfigurationSet, asserts an empty put clears the block, and asserts
the modeled ConfigurationSetDoesNotExistException for an unknown set.

* fix(ses): return v1 ValidationError for an invalid delivery-options TlsPolicy

The v1 PutConfigurationSetDeliveryOptions surfaced the shared service's
v2-style BadRequestException for an invalid TlsPolicy, so a v1 SDK could only
map it to a generic exception. Validate Require/Optional (case-sensitive) in
the v1 handler and throw the Smithy enum ValidationError AWS actually returns.

Verified against real AWS: an invalid or wrong-case TlsPolicy returns
ValidationError "1 validation error detected: Value at
'deliveryOptions.tlsPolicy' failed to satisfy constraint: Member must satisfy
enum value set: [Optional, Require]". The v1 integration test now asserts that
shape; valid Require/Optional still normalize to the canonical value for the
shared service.
2026-06-25 22:49:14 -05:00
AgustinBertagna e20f7d83d2 feat(appsync): Phase 3 — $util runtime library for VTL resolvers (#1223)
* test(appsync): add remaining SDK tests and fix listDomainNames field name

- Add 4 SDK tests: getIntrospectionSchema, listDomainNames, getFunction, listResolversByFunction
- Fix listDomainNames response field from 'domainNames' to 'domainNameConfigs' (AWS SDK v2 expects domainNameConfigs)
- Update integration test assertion to match corrected field name

* feat(appsync): add $util runtime library for VTL resolvers

Standalone utility library matching AWS AppSync $util namespace.
Validated against official AWS AppSync documentation.

Classes:
- VtlErrorSignal: exception for $util.error() and $util.unauthorized()
- AppSyncUtil: top-level $util with error/validate/type-check methods
- StrUtil: $util.str (toUpper, toLower, toReplace, normalize)
- TimeUtil: $util.time (12 methods, epochMilliSeconds-based per AWS)
- MathUtil: $util.math (roundNum, minVal, maxVal, randomDouble, randomWithinRange)
- DynamoDbUtil: $util.dynamodb (24 methods: value + JSON variants)
- TransformUtil: $util.transform (DynamoDB filter, Elasticsearch DSL, subscription filter)
- ListUtil: $util.list (copyAndRetainAll, copyAndRemoveAll, sortList)
- MapUtil: $util.map (copyAndRetainAllKeys, copyAndRemoveAllKeys)

* test(appsync): add unit tests for $util runtime library

234 test cases covering all $util methods with edge cases:
- AppSyncUtilTest: root methods, error, validate, type checks (85 tests)
- DynamoDbUtilTest: DynamoDB attribute value conversion (47 tests)
- StrUtilTest: string operations (21 tests)
- TimeUtilTest: time operations (21 tests)
- MathUtilTest: math operations (19 tests)
- ListUtilTest: list operations (17 tests)
- TransformUtilTest: filter/DSL conversion (12 tests)
- MapUtilTest: map operations (12 tests)

* fix(appsync): fix DynamoDbUtil *Json methods and refactor utils

- Fix 10 *Json methods to return JSON String instead of Map
- Add private helpers: toJson(Map), base64Encode(String) to DynamoDbUtil
- Extract parseInput(Object) helper in TransformUtil to remove duplication
- Chain qr() to quiet() in AppSyncUtil
- Chain validate() overloads in AppSyncUtil
- Update tests to verify *Json methods return correct JSON strings

* fix(appsync): address review feedback on $util methods

- toMapValues: return inner map without M wrapper (matches AWS: toMapValues = toMap.get("M"))
- toBinary/toBinarySet: wrap input as-is, don't re-encode base64
- str.normalize: use Unicode normalization (NFC/NFD/NFKC/NFKD) instead of whitespace collapse
- typeOf: return exact AWS values (Null/Number/String/Map/List/Boolean/Object)
- unauthorized: errorType 'Unauthorized' not 'UnauthorizedException'
- nowISO8601: always include 3 fractional digits per AWS format
- Mark transform.* methods as not-yet-implemented (complex expression building)
- Update all affected tests

* fix(appsync): change default errorType from UnknownError to Unknown

Research confirms AWS AppSync uses 'Unknown' as default errorType when
$util.error(message) is called without errorType argument.

* chore(appsync): remove dead base64Encode helper from DynamoDbUtil
2026-06-25 20:38:58 -05:00
kotov228 efacb37130 feat: Adds initial Elastic Beanstalk Query API support to Floci. (#1362)
* feat: add Elastic Beanstalk query API support

feat: add Elastic Beanstalk query API support

* fix(elasticbeanstalk): configure native-image runtime initialization

* fix(elasticbeanstalk): align missing parameter errors and add application ARN

* test(elasticbeanstalk): add Java SDK compatibility coverage
2026-06-25 19:16:51 -05:00