Commit Graph
3688 Commits
Author SHA1 Message Date
Mario Toffia f413a667d0 feat(iot): indexing configuration (#4896)
AWS IoT fleet indexing had no routes in Floci, so a stack or script
calling UpdateIndexingConfiguration or GetIndexingConfiguration failed
with "Unknown operation: POST /indexing/config", and there was no
stored configuration for a later SearchIndex to consult.

A new IotFleetIndexingService and IotFleetIndexingController, wired
into the iot descriptor beside the domain configuration controller,
serve UpdateIndexingConfiguration and GetIndexingConfiguration on
/indexing/config and DescribeIndex on /indices/{indexName}. There is
one configuration per account and region, kept through StorageFactory;
a region never updated reports the OFF shape AWS returns.

The behaviour follows what real AWS returned when measured: an update
that carries only one of the thing and thing group configurations
keeps the other, turning thing indexing OFF clears the whole thing
configuration, and managedFields are derived from the modes rather
than stored. Client sent managedFields are only checked against the
fields AWS manages and their types. Validation uses AWS's messages for
a missing configuration, null and out of set enum values (the modes,
field types, filter socket information and geolocation order),
secondary modes without thing indexing, named shadow indexing without
shadow names, unknown managed fields, and a thing custom field named
after a managed field. A geolocation sent without an order is stored
with LatLon, the default AWS returns. DescribeIndex returns the
schema the modes select and is ACTIVE at once, a disabled index is
ResourceNotFoundException and an unknown name InvalidRequestException.

Thing group managedFields are checked the same way, also while group
indexing is OFF, and neither group managedFields nor customFields are
stored. A member of the wrong JSON type is a SerializationException,
as on AWS. The fleet indexing, domain configuration and authorizer
controllers now share one strict body reader, so a malformed body or
content after it is a SerializationException on all three, which is
what AWS returns there.

ListIndices, SearchIndex and the statistics APIs are not modeled.
2026-10-09 16:52:30 -04:00
David 9f224d9de6 fix(core): verify SigV4 header signatures for every service under validate-signatures (#5268)
* fix(core): verify SigV4 header signatures for every service under validate-signatures

FLOCI_AUTH_VALIDATE_SIGNATURES verified signatures for S3 only, so SQS,
KMS, IAM, Scheduler and every other service accepted a request signed
with the wrong secret. SigV4HeaderSignatureFilter verifies the
Authorization header of every request outside S3 and execute-api when
the flag is on, rebuilding the canonical request from the request as it
arrived and answering in the protocol the request used. Unsigned
requests are left alone, and the default configuration is unchanged.

The filter runs after matching so it can hash the body. The SQS
queue-URL router now records the bytes it appends to a Query body, and
the CBOR content type is read from the header that preserves it, so
neither rewrite breaks a valid signature.

With the flag on, an unknown or synthetic access key is now refused by
every service, as S3 already refused it.

Closes #5195

* fix(core): skip signature checks by matched resource, strip the spoofable content-type header

The filter skipped any request whose credential scope named s3 or
execute-api, so a caller could sign an SQS or KMS call under either and
pass with the wrong secret, and S3 Control was never checked. It now
steps aside only for the resources another verifier owns: S3Controller
and the API Gateway execute controllers.

AwsCborContentTypeFilter removes any client-sent
X-Floci-Original-Content-Type, so a signed Content-Type cannot be
swapped behind a forged copy. REST-XML services (Route 53, CloudFront,
S3 Control) get XML errors. Header and scope parsing reuse
SigV4AuthorizationHeader and CredentialScope, and the canonical request
moves into SigV4Canonicalization, shared with ExecuteApiSigV4Authorizer.

* fix(core): leave AppSync GraphQL signatures to AppSync's own check

AppSync's GraphQL endpoint verifies IAM signatures itself and answers a
failure with the UnauthorizedException envelope AppSync clients parse.
With validate-signatures on, the header filter reached it first and
answered with a JSON InvalidSignatureException. AppSyncExecutionController
joins the resources the filter steps aside for.
2026-10-09 16:31:22 -04:00
David Wooldridge 91c15be74a fix(rds): apply PostgreSQL startup parameters to IAM sessions as the token's role (#5304)
* fix(rds): apply PostgreSQL startup parameters to IAM sessions as the token's role

* fix(rds): refuse a session_authorization change and match PostgreSQL's parsing for IAM startup parameters

* test(rds): share the IAM integration tests' setup and document RESET for IAM startup parameters
2026-10-09 16:22:21 -04:00
Salil Chincholikar 84dbed14af fix(ec2): resolve interface endpoint fallback address collisions (#5347)
* fix(ec2): resolve interface endpoint fallback address collisions

Different subnet IDs can have the same modulo-256 hash, giving an interface
endpoint duplicate fallback IPv4 addresses. Reserve configured and
IPv4-derived addresses first, then resolve fallback collisions in stable
subnet order.

Cover colliding subnet hashes, missing IPv4 CIDRs, address reservations,
and stable addresses across repeated reads and subnet reordering.

Closes #5345

* fix(ec2): reserve endpoint IPv4 addresses by numeric value
2026-10-09 16:15:02 -04:00
Vũ Thế Huy 5d5e39a15e fix(sqs): reject batch requests with more than 10 entries (#5331)
* fix(sqs): reject batch requests with more than 10 entries

SendMessageBatch, DeleteMessageBatch and ChangeMessageVisibilityBatch now
fail with TooManyEntriesInBatchRequest before processing any entry, on
both the Query and JSON protocols. The JSON type mapping is keyed on the
prefixed Query code so the JSON error type matches what botocore expects.

Fixes #5319

* fix(sqs): address review findings for batch entry limit validation

- Count distinct batch entry indices in Query handler across numbering gaps and missing IDs
- Reject missing or non-array Entries in JSON batch handlers with 400
- Seed messages and verify receipt handles in integration tests to detect partial mutations

* fix(sqs): reject empty batch requests and tidy batch limit tests

Return EmptyBatchRequest for a batch with no entries on all three batch
actions, and share the queue-count and receipt-handle entry helpers in the
JSON protocol test.

* fix(sqs): match AWS EmptyBatchRequest message per action and tidy query tests
2026-10-09 16:06:35 -04:00
Vũ Thế Huy 1a6f336e9f feat(redshift): run Data API statements from Step Functions and Scheduler (#5312)
* feat(redshift): run Data API statements from Step Functions and Scheduler

Step Functions: add the arn:aws:states:::aws-sdk:redshiftdata:<action> Task
integration. It reuses RedshiftDataJsonHandler, so every Data API action
Floci implements works for provisioned clusters (ClusterIdentifier) and
Serverless workgroups (WorkgroupName). Arguments and results keep the wire
PascalCase names, CreatedAt and UpdatedAt are ISO-8601 at any depth, errors
surface as RedshiftData.<Code>Exception, and the task fails when redshift
or redshift-data is disabled. .sync resources are rejected, as AWS has no
such variant.

Scheduler: add the redshiftdata:executeStatement and
redshiftdata:batchExecuteStatement universal targets. The call runs as the
schedule's account and region, because the dispatcher thread carries no
request account and cluster and statement storage is account-aware. A SQL
error stays on the statement; a request the Data API rejects propagates so
the existing retry and dead-letter handling applies.

* fix(redshift-data): validate task input and isolate statement storage by account

* fix(redshift): run scheduled Data API statements off the dispatcher thread

Keep the request check on the dispatcher so a rejected request still
retries, and run the SQL on its own thread under the schedule's account.
Ask ServiceRegistry whether redshift-data is enabled instead of repeating
the rule, keep the resolver and connection factory package-private, and
cover the provisioned-cluster account in the resolver test.

* fix(scheduler): await scheduled Redshift Data statement in docker test
2026-10-09 15:51:11 -04:00
XuJian 07b529e150 feat(cloudformation): add optional-value and delete cleanup hooks (#5067) 2026-10-09 15:04:03 -04:00
Ovidiu (Ovi) 4f34a903fc feat(ssm): support UnlabelParameterVersion (#5339)
* feat(ssm): support UnlabelParameterVersion

Remove one or more labels from a parameter version. Labels attached to
the version are returned in RemovedLabels; labels that are not on that
version, including ones attached to a different version, are returned in
InvalidLabels and left in place. A missing parameter is ParameterNotFound,
a missing version ParameterVersionNotFound, and an omitted ParameterVersion
or an empty or oversized label list a ValidationException.

* fix(ssm): match AWS errors and ordering in UnlabelParameterVersion

Verified against real AWS (us-east-1):

- Report every missing or invalid member in one ValidationException, in
  the order name, parameterVersion, labels, and render the label list
  the way AWS does ('[prod, ]').
- Reject a string or boolean ParameterVersion and a non-string Name or
  label with SerializationException; truncate a fractional version and
  clamp one outside the range of a long, as AWS does.
- Reject an ARN, a malformed or ssm-prefixed name, and deny an
  aws-prefixed one before the lookup; ignore surrounding whitespace in
  the lookup but echo the name as sent in error messages.
- Word ParameterVersionNotFound as AWS does.
- Return RemovedLabels in the order the labels are stored on the
  version, and InvalidLabels in request order.

LabelParameterVersion shares the label-list parsing, so its label
validation messages and non-string labels now match AWS too.

* fix(ssm): take the service monitor when deleting parameters

PutParameter, LabelParameterVersion and UnlabelParameterVersion already
run under the SsmService monitor, but DeleteParameter and
DeleteParameters did not. A delete landing between a label or unlabel
call's lookup and its history write left orphaned history that a later
PutParameter of the same name appended to.

Also pin LabelParameterVersion's AWS-verified label validation messages
and its SerializationException for a non-string label in its own
integration test, and share the parameter-name format rule between the
two reserved-name messages.
2026-10-09 13:11:29 -04:00
Salil Chincholikar 07ebc33d28 feat(scheduler): substitute schedule context attributes in target Input (#5194)
* feat(scheduler): substitute schedule context attributes in target Input

Replace <aws.scheduler.schedule-arn>, <aws.scheduler.scheduled-time>,
<aws.scheduler.execution-id> and <aws.scheduler.attempt-number> in the
target Input for templated and universal targets, using the occurrence's
scheduled time and the retry attempt the dispatcher tracks.

* test(scheduler): share one harness between the scheduler integration tests

SchedulerContextAttributesIntegrationTest copied its schedule creation,
scoped dispatcher, unique names and cleanup from
SchedulerStepFunctionsIntegrationTest. Both now use SchedulerTestHarness,
which also builds the at() expression they each formatted by hand.

* fix(scheduler): keep dead-letter context aligned with the last attempt

Materialize the target request before every invocation so an exhausted
occurrence's dead-letter body carries the same execution id and attempt
number as its last attempted delivery. Preserve that request when the
occurrence expires before another retry.

Share scheduled-time formatting across context attributes, default events
and dead-letter attributes. Cover retry-count and event-age exhaustion
and remove the documented first-attempt body limitation.

* style(scheduler): fix shared harness static import order

Place ROLE_ARN before atExpression to satisfy the ImportOrder rule used
by the PR's merged Checkstyle configuration.
2026-10-09 12:08:34 -04:00
Aniket Shukla 5dfb45d71f fix(cognito): run missing post-confirmation triggers (#5207)
* fix(cognito): run missing post-confirmation triggers

* fix(cognito): forward confirmation client metadata
2026-10-09 10:23:06 -04:00
Mario Toffia 0ec64add2d fix(cloudformation): wait for a stable ECS service (#4880)
AWS CloudFormation reports an AWS::ECS::Service CREATE_COMPLETE or
UPDATE_COMPLETE only once the service is stable: it polls
DescribeServices until the desired number of tasks of the current
task definition are running. Floci reported the resource complete as
soon as CreateService or UpdateService returned. The tasks were
started later by the ECS reconciler, every five seconds, and the
service's runningCount only caught up a tick after that, so a client
reading the service right after the stack operation saw runningCount
0.

EcsService.awaitServiceStable now waits, like
Ec2Service.awaitContainerLaunch, for runningCount to equal
desiredCount, for the current deployment to run that many tasks, and
for no task of an earlier deployment to be running. Instead of idling
until the next tick it submits up to three reconcile passes to the
single reconciler thread, so they never overlap a scheduled tick.
After five minutes it fails with "Service <arn> did not stabilize.".

The wait ends at once when the service's tasks cannot start. The
reconciler now keeps, in memory, why its last attempt to launch a
task for a service failed, for example an unknown subnet, and the
deployment it was launching for. Only a failure of the deployment
being awaited ends the wait, so a pass that began before an update
cannot fail the update. The record is cleared on a successful launch,
on DeleteService and on a state reset. A task that stops with
TaskFailedToStart during the wait ends it too. A task the reconciler
launches is stamped with the deployment read before its task
definition, not after the launch, so a launch that an update overtakes
counts as the earlier deployment's and is replaced.

The ECS provisioner calls the wait after an in-place update and after
a create. A created service stays marked as owned by the stack while
it waits, so the create rollback deletes it. A replacement created by
a stack update is deleted when it does not stabilize. A service
updated in place that does not stabilize is put back on the task
definition, desired count and network configuration it had, and the
provisioner waits for that to stabilize too, as CloudFormation's
rollback does. A restore that fails or does not stabilize is reported
as a rollback failure, so a rolled-back stack does not claim the prior
configuration is running when it is not.

The ECS service test in CloudFormationIntegrationTest used subnets
and a security group that do not exist, so its tasks could never
start. It now uses the default VPC's.
2026-10-09 10:05:39 -04:00
Hector Ventura 3b36a4d0d8 fix(core): reuse pooled Docker connections and validate them after a second idle (#5333)
Every control-plane Docker call carried Connection: close, so that pool
never reused a connection: each call opened a new socket. The header was
there because docker-java disables httpclient5's stale-connection check,
so a socket the daemon or Podman had closed could be leased again and fail
on its next write.

With the Unix socket honouring read timeouts since #5294, that check works.
Both pools now validate a connection idle for more than a second before
reusing it, replacing it if the daemon closed it, and close idle
connections after 30 seconds. The retry wrapper passes requests through
unchanged.
2026-10-09 07:03:53 -04:00
David Phillips b28eac9142 fix(rds): reject malformed instance boolean flags (#5332)
* fix(rds): reject malformed instance boolean flags

* fix(rds): reject malformed modify placement and password flags
2026-10-08 22:40:48 -05:00
David Phillips c70e1b05ee fix(rds): delete managed instance secrets (#5330)
* fix(rds): delete managed instance secrets

Remove the managed master-password secret when its standalone database
instance is deleted, so obsolete credentials do not remain afterward.

* fix(rds): retain instances when secret cleanup fails

* fix(rds): reject blocked secret cleanup before database teardown

* fix(rds): complete deletion when managed secret cleanup fails
2026-10-08 23:37:45 -04:00
Matheus Oliveira 93cc2ff957 fix(rds-data): reject result rows larger than 64 KB (#5290)
Return UnsupportedResultException 'Packet for query is too large'.

* Fix #5113

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-08 22:26:59 -05:00
Alessandro Lattao 3041d6bd90 fix(rds,elasticache): decode IAM auth token parameters once (#5039)
* fix(rds,elasticache): decode IAM auth token parameters once

SigV4RequestValidator, which verifies the IAM auth tokens the RDS, Redshift,
ElastiCache and MemoryDB proxies receive, URL-decoded every query parameter
as it looked it up, then decoded X-Amz-Credential and X-Amz-Security-Token a
second time. Session tokens are drawn from an alphabet that includes '+',
'/' and '='. A presigner writes '+' as %2B; the first decode restored it and
the second turned it into a space, so the session no longer matched and the
token was refused with "password authentication failed". Every token signed
with a Lambda function's execution-role credentials failed this way, from
the AWS CLI, botocore and the Go SDK's feature/rds/auth alike, while
AssumeRole credentials passed only because their tokens are alphanumeric.
The second decode also let a token carrying %252B stand in for a session
whose token holds a literal '+'.

SigV4 defines the canonical query string as each parameter name and value
URI-encoded (only A-Z a-z 0-9 - . _ ~ left as they are, uppercase hex, a
space as %20, '/' encoded), sorted by encoded name and then by value. The
validator now decodes each parameter exactly once, keeping a literal '+' as
a plus as the API Gateway and EKS verifiers already do, looks the session
up with that value, and rebuilds the canonical query string from the
decoded parameters rather than hashing the bytes on the wire, so the token
is checked against the string its signer hashed whichever valid
percent-encoding it travelled in. Using the raw pairs as before would have
fixed the session lookup alone, but would still reject a token whose
credential travels with literal slashes or lowercase hex.

The test token helper encoded values with URLEncoder, whose form encoding
writes a space as '+' and leaves '*' unescaped, which no SDK presigner does;
it now applies SigV4's UriEncode. S3 presigned URLs do not go through this
validator and read X-Amz-Security-Token once already: a URL presigned with
a Lambda session's credentials is served, and one whose token reads a space
for the '+' is refused.

* fix(rds): authorize the key the token's signature was verified with

The signature check reads a token's parameters with their names
percent-decoded, and takes the first X-Amz-Credential it finds. The
rds-db:connect check read the credential again from the raw query, matching
the name byte for byte. A token that spelled its signer's credential as
X-Amz%2DCredential and added a plain X-Amz-Credential of a key IAM does not
know was verified with the signer's key and authorized on the unknown one,
which IAM enforcement waves through: the connection was allowed whatever
the signer's policy said.

SigV4RequestValidator.queryParameter reads a parameter exactly as the
signature check does, and RdsSigV4Validator takes the credential scope from
there, so the key authorized is the key that signed.
validateAuthorizesTheKeyTheSignatureWasVerifiedWith signs such a token as
SigV4 signs a query and expects it refused; it was accepted before.

RdsIamAuthLambdaSessionIntegrationTest now creates its database inside the
try whose finally deletes it, so a create that fails an assertion leaves no
container behind.
2026-10-08 22:23:11 -05:00
Vũ Thế Huy 38ce99ba54 feat(redshift): support more COPY and UNLOAD options (#5204)
* feat(redshift): support more COPY and UNLOAD options

COPY now accepts REGION, CREDENTIALS, key-based credentials, EMPTYASNULL,
BLANKSASNULL, REMOVEQUOTES, ACCEPTINVCHARS and TRUNCATECOLUMNS. UNLOAD now
accepts REGION, CREDENTIALS, key-based credentials and EXTENSION. Field
content options run in a new CopyRecordTransformer; TRUNCATECOLUMNS reads
column lengths from the catalog and so needs the Simple Query protocol.
Clauses that cannot be honoured still fail open to PostgreSQL.

* feat(redshift): support UNLOAD ESCAPE, CLEANPATH and server-side encryption options

UNLOAD now accepts ESCAPE (text framing only), CLEANPATH, ENCRYPTED AUTO and
ENCRYPTED with KMS_KEY_ID, which is stored as aws:kms server-side encryption
on the data and manifest objects. CLEANPATH lists and authorizes every delete
up front but removes the objects only when the first output arrives, so a
query that PostgreSQL rejects keeps the previous export. An empty prefix,
ALLOWOVERWRITE and client-side encryption still fail open to PostgreSQL.

* fix(redshift): address review findings on COPY and UNLOAD options

- Reject blank access key, secret, session token and IAM role so an empty
  pair cannot enable unsigned S3 access.
- CLEANPATH lists and authorizes the prefix again when the first output
  arrives, so an object uploaded since preparation does not survive.
- REMOVEQUOTES no longer closes a text-mode field on an escaped quote.
- TRUNCATECOLUMNS counts characters, as PostgreSQL does for varchar(n),
  and cuts decoded text so escape sequences are never split.
- Bound the heap used by field-level COPY options with a per-object size
  limit and a budget shared across connections.

* fix(redshift): delete the CLEANPATH prefix under one bucket lock

S3Service.deleteObjectsWithPrefix lists the prefix, authorizes every key
and deletes them while holding the bucket monitor that PutObject and
DeleteObject already use, so an upload cannot land between the listing
and the deletes and survive next to the new export.

* fix(redshift): measure TRUNCATECOLUMNS in bytes and tighten review follow-ups

Redshift counts CHAR(n) and VARCHAR(n) in bytes, so TRUNCATECOLUMNS now
measures decoded bytes and cuts on a character boundary instead of
counting characters. The UNLOAD docs described bare ENCRYPTED as
client-side; client-side is the MASTER_SYMMETRIC_KEY form. The
concurrent-put lock test now waits for the put thread to be BLOCKED
instead of a fixed 300 ms timeout.

* style(redshift): fix import order in S3CopySimulatorTest
2026-10-08 23:19:40 -04:00
Priamo Germosen 88d429a968 fix(iam): open every ValidationError with the count AWS puts on it (#5280)
hectorvent asked on #5240 whether the account-property constraint messages should
carry the "1 validation error detected: " prefix that #5239's two recorded
messages have, noting there is no recording for PutAccountProperties itself.

There is evidence, just not on that operation. Across the AWS-validated snapshots
for IAM, CloudWatch and SNS, every recorded constraint message opens with the
count: six of six. The prefix is the envelope the front end puts on a validation
report, not a property of the member being validated, and SNS settles the part
the question turned on, because two of its recordings are map members and both
carry it:

    1 validation error detected: Value null at 'attributes' failed to satisfy
        constraint: Member must not be null
    1 validation error detected: Value null at
        'messageAttributes.attr1.member.dataType' failed to satisfy constraint:
        Member must not be null

The first of those is this change's absent-map case almost verbatim, down to
"Value null at '<map>'".

Looking for that turned up something wider than the question. IamQueryHandler's
requireParam, which every required member in the service is read through, emitted
its message without the prefix, while StsQueryHandler's validateRequired in the
same package and TagDispatcher in core.common both already carry it on the
identical sentence. IAM was the outlier, so one line fixes all 28 call sites.

The five messages here are the four on the account-properties path and that one.
Each was probed by reverting it on its own, and each fails only the tests that
cover it.

Three more constraint reports were still opening without the count, so the title
did not hold when it was written: the ListPolicies scope enum, the
GenerateServiceLastAccessedDetails granularity enum, and optionalInt. No test
pinned any of their text, which is how they survived a change that touched every
other one.

A fourth, the CredentialAgeDays range check, survived a sweep for that phrase
because its message builds "failed to " and "satisfy constraint" as separate
literals, so the phrase never appears contiguously in the source. The sweep now
joins adjacent literals before matching, which finds that one and no others.

optionalInt is reachable only through CredentialAgeDays on
CreateServiceSpecificCredential, so its case sits beside the test that already
exercises that path and asserted only the error code.

Two things deliberately left as they are. No snapshot in any service records a
map *key* constraint, so the "Map keys must satisfy constraint: [...]" tail is a
reasonable shape rather than an attested one, and the same goes for how a
string-valued map spells its value path. The prefix is the attested part and the
only part this changes.

Not touched either: CloudWatch's recorded enum message names both the offending
value and the permitted set, where IAM's omits both. That they differ is the
point, and it is why #5239 changed only IAM's rendering.

Refs #5240
2026-10-08 22:15:12 -05:00
TATSUNO “Taz” Yasuhiro 9c2db353f1 fix(lambda): list changed durable operations in creation order (#5328)
AWS lists the operations in a checkpoint answer, and the ids in
UpdatedOperationIds, in the order they were created. Floci listed them
in the order they changed, so a step finished after a newer one started,
a wait that fell due, or a chained invoke that failed at once came out
of place.
2026-10-08 22:31:42 -04:00
David Phillips c8f16d2484 fix(rds): reject malformed upgrade flags (#5329)
Reject malformed AutoMinorVersionUpgrade values before creating or
modifying an instance, so invalid input cannot silently change its
upgrade policy.
2026-10-08 22:24:42 -04:00
Sam Fakhreddine b6eeae92e1 fix(dns): validate forwarded DNS responses against the query and its target (#4671)
* fix(dns): accept forwarded DNS responses only from the target that was queried

Fixes #4670

- M1 PASS: RED run: org.opentest4j.AssertionFailedError: array contents differ at index [0], expected: <1> but was: <9>
- M2 PASS: gates green, last summary: [INFO] Tests run: 183, Failures: 0, Errors: 0, Skipped: 1
- M3 PASS: 2 file(s), all in scope
- M4 PASS: no new public members in main code
- M5 PASS: main diff 1 changed lines, limit 10
- M6 PASS: no em-dash in added lines
- A1 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:608` `fwd.connect(addr, target.port());`
- A2 PASS: `src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java:676` `assertArrayEquals(new byte[] {1, 2, 3}, response);`
- A3 PASS: Test results: `[INFO] Tests run: 183, Failures: 0, Errors: 0, Skipped: 1`
- A4 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:607-615` (diff shows exactly one line added `+ fwd.connect(addr, target.port());` and zero changes to method signature, loop structure, timeout, fallback logic, or exception handling)
- G1 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:608` `fwd.connect(addr, target.port());`
- G2 PASS: `src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java:676` `assertArrayEquals(new byte[] {1, 2, 3}, response);`
- G3 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:604-620` (diff modifies only line 608; `handleQuery`, `matchesSuffix`, `resolveARecord`, `planQuery`, `buildEmptyResponse`, `buildServerFailureResponse`, `resolveEc2PrivateDnsName`, `readName`, `buildAResponse`, `forwar
- G4 PASS: `src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java:608` `fwd.connect(addr, target.port());` (enforces source IP/port validation at OS level, matching AWS DNS resolver behavior)

* test(dns): give forwarding test replies valid DNS headers

The forwarding tests replied with filler bytes that are not a DNS response to the query. Build each reply from the query (same txId and question, QR bit set) so the tests keep passing once forwardToTargets validates responses. The large-response test keeps its 1500-byte size.

* fix(dns): discard forwarded DNS responses whose txId, QR bit or question don't match the query

Fixes #4670

- M1 PASS: RED run: org.opentest4j.AssertionFailedError: array contents differ at index [1], expected: <7> but was: <6>
- M2 PASS: gates green, last summary: [INFO] Tests run: 185, Failures: 0, Errors: 0, Skipped: 1
- M3 PASS: 2 file(s), all in scope
- M4 PASS: no new public members in main code
- M5 PASS: main diff 30 changed lines, limit 35
- M6 PASS: no em-dash in added lines
- A1 PASS: `"if (length < 12)"`, `"if (response[0] != query[0] || response[1] != query[1])"`, `"if ((response[2] & 0x80) == 0)"`, `"Arrays.equals(query, 12, query.length, response, 12, query.length)"`; `"while (true)"` loop with `"resp.setLength(buf.length)"` and `"fwd.receive(resp)"` before next deadline chec
- A2 PASS: `"long deadline = System.nanoTime() + FORWARD_TIMEOUT_MS * 1_000_000L;"` before loop; `"long remainingNs = deadline - System.nanoTime();"` and `"fwd.setSoTimeout((int) (remainingNs / 1_000_000L));"` inside loop
- A3 PASS: `forwardToTargets_discardsWrongTxIdDatagramBeforeRealAnswer`: `"badReply[1] ^= 0x01;"` sent first, then `"realReply"`, `"assertArrayEquals(realReply, response);"`
- A4 PASS: `forwardToTargets_discardsWrongQuestionDatagramBeforeRealAnswer`: `"byte[] wrongQuery = buildQuery("other.corp.internal", (short) 7);"`, `"byte[] badReply = replyTo(wrongQuery, wrongQuery.length);"` sent first, then `"realReply"`, `"assertArrayEquals(realReply, response);"`
- A5 PASS: Only `isValidResponse` (private static) added and `forwardToTargets` modified; `"fwd.connect(addr, target.port())"` stays; `Tests run: 185, Failures: 0, Errors: 0, Skipped: 1`
- G1 PASS: Replaces blind `"fwd.receive(resp); return ..."` with explicit DNS header/question validation loop matching diagnosis exactly
- G2 PASS: `"assertArrayEquals(realReply, response);"` asserts exact literal byte-for-byte match against setup fixture
- G3 PASS: Outer target iteration, `"last = e"` accumulation, and fallback paths untouched; validation loop is strictly contained within the per-target `try` block and does not mutate external state
- G4 PASS: Discards non-responses/mismatches, bounds wait to `FORWARD_TIMEOUT_MS`, throws `SocketTimeoutException` on expiry to trigger next target or fail, matching DNS resolver semantics and AWS upstream behavior

* fix(dns): match forwarded answers on question count and name ignoring case
2026-10-08 22:08:18 -04:00
David PhillipsandJason van Zyl d22b4f107c fix(iam): enforce inline role policy quota (#5327)
* fix(iam): enforce inline role policy quota

Reject role policy updates that exceed the aggregate non-whitespace
quota without changing previously accepted policies, including concurrent
writes and policies restored after a restart.

* fix(cloudformation): rename role policies within quota

* test(iam): share inline policy fixtures

---------

Co-authored-by: Jason van Zyl <jason@vanzyl.ca>
2026-10-08 21:52:36 -04:00
David Phillips da6a7dd085 build: enforce Java import order with Checkstyle (#5326)
* style: align Java imports with project guidelines

* build: enforce consistent Java import order

* style: follow IntelliJ import order
2026-10-08 20:50:53 -04:00
Allen Sanborn 80f25417b3 fix(ssm): return KeyId, AllowedPattern, Tier and Policies from DescribeParameters (#5263)
* fix(ssm): return KeyId, AllowedPattern, Tier and Policies from DescribeParameters

PutParameter accepted KeyId, AllowedPattern, Tier and Policies and dropped
them, so DescribeParameters never returned them and the Tier and KeyId
filters matched hardcoded defaults. Tools that read these attributes back,
such as Terraform's aws_ssm_parameter, saw a permanent diff.

PutParameter now stores the four attributes and DescribeParameters returns
them: KeyId for a SecureString (alias/aws/ssm when none was given), Tier
always, AllowedPattern and Policies when set. Intelligent-Tiering resolves
to Advanced when policies are present or the value exceeds 4 KB, an
overwrite that omits Tier keeps the existing tier, and a value that does
not match AllowedPattern is rejected with ParameterPatternMismatchException.

* fix(ssm): keep policies across overwrites and reject malformed patterns

An overwrite that omitted Policies cleared them; AWS keeps existing
policies until new policies or an empty list are sent. A malformed
AllowedPattern escaped as a 500 instead of InvalidAllowedPatternException,
and a Policies string that parsed to something other than a JSON array was
accepted as an empty list instead of rejected.

* fix(ssm): treat an empty AllowedPattern as no pattern

The Terraform AWS provider sends AllowedPattern="" on every PutParameter
when allowed_pattern is unset. An empty regex matches only the empty
string, so every aws_ssm_parameter apply failed with
ParameterPatternMismatchException (compat-terraform / compat-opentofu).

* fix(ssm): treat empty optional PutParameter fields as absent

The Terraform AWS provider sends every optional PutParameter field and
leaves unset ones as an empty string, which AWS reads as absent. Read
KeyId, AllowedPattern, Tier and Policies through one helper so a blank
value falls back to the default instead of being stored or validated.

* fix(ssm): bound AllowedPattern matching and cap its length

PutParameter matches a caller-supplied AllowedPattern against a
caller-supplied Value, so a pattern that backtracks catastrophically
could hold a request thread. Reject patterns over the 1024 characters
the SSM model allows, and match through a deadline-bounded subject that
aborts after one second with InvalidAllowedPatternException.

The deadline subject already lived inside CodePipelineService for
VariableCheck MATCHES; it moves to core.common so both use one copy.

Also cover the Intelligent-Tiering 4096-byte cutoff with ASCII and
multibyte values, and replace inline fully qualified test names with
imports.

* fix(ssm): keep Advanced on Intelligent-Tiering overwrite, validate Tier, serialize PutParameter

An Intelligent-Tiering overwrite with a small value no longer downgrades an
existing Advanced parameter to Standard. Tier outside Standard, Advanced and
Intelligent-Tiering is a ValidationException. putParameter is synchronized like
labelParameterVersion so concurrent overwrites cannot share a version.

* fix(ssm): validate PutParameter before taking the write lock

The tier, tag, name and AllowedPattern checks read only the request, so
they now run before the lock; only the stored-version read and the write
are synchronized. A pattern match running to its one-second deadline no
longer stalls other SSM writers.

The concurrency test now waits for the second overwrite's thread to reach
BLOCKED instead of waiting a fixed 300 ms for a timeout.
2026-10-08 20:18:29 -04:00
David Phillips 3171b8a745 fix(rds): bind IAM tokens to the published port (#5305)
* fix(rds): Bind IAM tokens to the published port

Docker clients sign tokens for the advertised database endpoint.
Checking the internal proxy port rejects those valid logins after
port mapping. Use the published endpoint port for the same binding.

* fix(rds): keep IAM binding aligned with advertised endpoints

* fix(rds): bind proxy tokens to each listener port
2026-10-08 20:14:57 -04:00
Mario Toffia c1cd5af2bd fix(ecr): advertise the registry at the published address (#4863)
ECR built repositoryUri, the GetAuthorizationToken proxyEndpoint and
the Lambda and ECS image rewrites from floci.port, the port Floci
listens on inside its own container. The Docker daemon performs login,
push and pull, and reaches Floci through the host port that container
publishes. When Floci ran as docker run -p 54321:4566, every advertised
address named port 4566 on the host, where nothing answers, so docker
login, CDK container asset publishing and ECS or Lambda image pulls
failed.

EcrRegistryManager now has advertisedPort(): the host port Floci's
container publishes for floci.port, read through the existing
CurrentContainerNetworkResolver.resolvePublishedPort as RDS does for
its proxy endpoint, or floci.port when Floci is not in a container or
the port is not published. repositoryUri (hostname and path style,
plain and TLS URI mode), proxyEndpoint and rewriteImageUri all use it.

The EKS registry mirror keys must match the URIs pods name, so they
use the same advertised port. The mirror endpoint stays Floci's
in-network address on floci.port.

The resolver now caches every published-port answer, "not published"
and a failed inspect included, as it already caches the network: a
running container's port bindings cannot change, and an inspect that
fails fails the same way next time. ECR requests therefore do not
inspect the container each time.
2026-10-08 20:11:30 -04:00
Allen Sanborn e22bd2c59a feat(ec2): support transit gateway peering attachments (#5122)
* feat(ec2): support transit gateway peering attachments

Add CreateTransitGatewayPeeringAttachment, DescribeTransitGatewayPeeringAttachments,
AcceptTransitGatewayPeeringAttachment and DeleteTransitGatewayPeeringAttachment, the
calls the Terraform provider's aws_ec2_transit_gateway_peering_attachment and
_accepter resources make. Previously each answered UnsupportedOperation.

An attachment is created in pendingAcceptance and moves to available when accepted
from the accepter's region. One attachment id serves both sides, so a cross-region
peering is visible from either region and the transit-gateway-id filter matches either
side's gateway, which is how the accepter finds it. Tags come from the shared tag
store, so CreateTags on the accepter side round-trips through describe.

* style(ec2): order the TransitGatewayPeeringAttachment import

* fix(ec2): hold peered transit gateways and accept peerings only as the peer

DeleteTransitGateway now refuses with IncorrectState while a non-deleted
peering attachment names the gateway at either end, as it already does for
VPC attachments; creation takes the same topology lock so neither lands in
between.

A peering is stored under the requester's account, so lookups search every
account's partition and admit only the two parties, as VPC peering does.
Accept requires the caller to be the accepter's account in the accepter's
region, so a requester can no longer accept its own cross-account request,
and the peer account can now see and accept it. The local-owner-id and
remote-owner-id filters are relative to the viewer's side.

* test(ec2): cover transit gateway peering attachments in the AWS CLI compatibility suite

* style(ec2): drop em dashes from the peering attachment comments

* refactor(ec2): make the peering attachment store final and pass it through the constructor

The StorageFactory constructor now hands the factory-backed store to the
terminal constructor, and the hermetic overload passes an InMemoryStorage,
the same way the other EC2 stores are wired.

* fix(ec2): clear both sides' tags when a cross-account peering attachment is deleted

Tags are per account: each party to a peering sees the tags its own account
set. Deleting the attachment cleared only the caller's, so the other
party's tags outlived it.

* fix(ec2): let a pending peering's accepter delete its transit gateway

Anyone can name any gateway as their peer, so a peering that has not been
accepted no longer holds the accepter's gateway. Deleting that gateway
declines the peering, leaving it rejected. Accepted peerings still hold
both ends, and a pending one still holds its requester's.

* fix(ec2): accept a transit gateway peering only for a gateway the accepter owns

The peer gateway is recorded unresolved at create, so an account could name
another account's gateway as the peer with its own account as PeerAccountId,
accept it, and pin that gateway against its real owner's DeleteTransitGateway.
Accepting now requires the peer gateway to exist in the caller's account and
region, the same lookup create makes for the requester's gateway.

* fix(ec2): route transit gateway peering actions to ec2 without a credential scope
2026-10-08 19:59:39 -04:00
Vũ Thế Huy dc41417e79 fix(ec2): avoid Docker waits on the first CreateVpc (#5179)
* fix: avoid Docker waits on first EC2 CreateVpc

* fix(ec2): reseed default VPC resources after a state reset

Ec2Service now implements Resettable: clear() forgets the seeded account
scopes and seeds the default region again, so a reset followed by
DescribeVpcs still returns the default VPC and subnets.

Also run Ec2CreateVpcLatencyTest in the non-mock EC2 compatibility job,
where VPC planning is active and a regression of the first-call Docker
wait would be caught.

* refactor(ec2): share one default-region seeding method between startup and reset

Ec2Startup and Ec2Service.clear() repeated the same enabled check and seed call. Both now go through Ec2Service.seedDefaultRegionIfEnabled() so they cannot drift apart. Also reorder the Resettable import.
2026-10-08 19:25:31 -04:00
Matt Van HornandMatt Van Horn 37e66ee371 fix(s3): reject aws-chunked S3 uploads whose trailing checksum mismatches (#5176)
* fix(s3): reject aws-chunked S3 uploads whose trailing checksum mismatches

The decoder now keeps each trailer line, keyed by lower-case header
name, and exposes that map once the body has been read. After PutObject,
UploadPart, and the in-memory body read hash the decoded payload, the
checksum named by x-amz-trailer is compared with the computed digest; a
mismatch, a missing trailer line, or a line for a different algorithm
raises 400 BadDigest and the object or part is not published. An
aws-chunked body is hashed with every checksum algorithm so the trailer
can be checked even when it is not the algorithm stored on the object.
Header mismatches use the same text, "The CRC32 you specified did not
match the calculated checksum.", and x-amz-trailer-signature is not
treated as a checksum.

Fixes #5136

* fix(s3): hash only the declared trailer checksum and frame trailer bodies

An aws-chunked body is no longer hashed with every checksum algorithm.
Only the algorithm named up front in x-amz-trailer is added to the
digest set, so a chunked upload with no trailer does no extra hashing.

The decoder keeps just the declared x-amz-checksum-* trailer line and
discards other trailer lines, so trailer storage is bounded. Any other
x-amz-checksum-* line, including one sent with no x-amz-trailer at all,
fails the request with 400 BadDigest.

A body with Content-Encoding: aws-chunked and an x-amz-trailer header
but no streaming x-amz-content-sha256 is now decoded through
AwsChunkedInputStream, so its trailer is verified like a streaming
upload. Without x-amz-trailer the lenient decode is unchanged.

* refactor(s3): resolve x-amz-checksum-* names in one ChecksumAlgorithm helper

Add ChecksumAlgorithm.fromChecksumHeader, which maps an x-amz-checksum-*
header name to its algorithm and returns null for a name it does not
know. S3Controller.trailerChecksumAlgorithm and AwsChunkedInputStream
now both use it, and the stream's private knownChecksum lookup is gone.
fromWireValue shares the same lookup and still throws for unsupported
or unknown algorithm values.

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-10-08 19:18:14 -04:00
MIdhun 63ef2d3a2d fix(kms): return an empty body for operations without output (#5318)
EnableKey, DisableKey, key rotation toggles, aliases, tags, key policy,
description and grant revocation have no output shape. AWS answers them
with HTTP 200 and an empty body; Floci sent {}, which strict clients that
deserialize the output as a unit type reject.
2026-10-08 19:00:18 -04:00
Sam Fakhreddine 89f59dea62 fix(dns): forward queries without per-context ordering (#4643)
Forwards ran through the one-argument executeBlocking, which is ordered per
Vert.x context. Every forward is submitted from the DNS socket's event-loop
context, so one unresponsive upstream or rule target held up forwarding for
every other query until it timed out. Both forwarding paths now go through
submitForward, which passes ordered=false, the same as planQuery already does.

Unordered forwards could otherwise take every thread of the shared worker pool
during a burst of queries to a dead resolver, starving planQuery and the rest
of the emulator, so they run on a dedicated shared executor capped at 8 threads.

Fixes #4606
2026-10-08 18:31:24 -04:00
David PhillipsandJason van Zyl aa94969704 fix(ec2): validate subnet tags before creation (#5306)
* fix(ec2): validate subnet tags before creation

Reject invalid subnet tag specifications before creating a subnet, so
failed requests do not leave resources behind. Include the enclosing
specification in nested tag errors.

* fix(ec2): preserve subnet tag parsing and clean up failures

---------

Co-authored-by: Jason van Zyl <jason@vanzyl.ca>
2026-10-08 15:39:31 -04:00
Mario Toffia 8b1ece9c24 fix(ecr): retry occupied registry ports (#4857)
* fix(ecr): retry occupied registry ports

The backing registry reserved one port from the configured range and gave
up when Docker refused to publish it, although the next port was free. The
allocator's probe races `docker run`, and from inside a container it cannot
see a host process holding the port, so a refusal is expected and not fatal.

A start Docker refuses as a host-port collision now moves on to the next
port in the range; any other failure still fails at once. Refused ports stay
reserved until the start finishes so each is tried once, then are released.
When the range runs out the error names the refused ports. EC2's collision
check moves to PortAllocator so both callers share it.

Closes floci-io/floci#4856

* chore(ecr): keep the port retry tests independent of host ports

The unit tests now use an allocator that skips the host probe, so a busy
6100 or 6101 on the machine cannot change their outcome. The integration
test picks its port pair with the Docker-aware allocator, so a container
already publishing a port is skipped as well, and drops its logger.

* docs(ecr): say other registry start errors still fail at once

The paragraph said startup fails only when the range is full, but a daemon
or image failure still fails without trying another port. The exhaustion
tests now also allocate the last refused port, so releasing only some of
them fails.

* refactor(ec2,ecr): share the port retry loop in PortAllocator

Review asked for the allocate, start and retry loop itself to live in one
place, not just the collision check. PortAllocator.allocateAndStart takes
the start as a callback, moves past ports Docker refuses as in use, and
releases the refused ports when it returns. ECR and EC2 both call it.

EC2 used to mark a refused SSH port reserved for the life of the process.
It now releases it after the launch, as ECR does, so a port whose holder
goes away is usable again.

With the loop moved, a launch cancelled between attempts can now reach
the worker's failure path. When Docker is also gone that path marked the
instance running without a container, so it now goes through markRunning
and leaves a cancelled instance terminated.

* test: share one host-blind PortAllocator across the port tests

PortAllocatorTest, EcrRegistryManagerTest and the ECR port-conflict
integration test each built their own allocator that skips the host
probe. HostBlindPortAllocator replaces the three copies.
2026-10-08 15:31:03 -04:00
Mario Toffia f248eb51af fix(cloudformation): send the stack's StackId to custom resources (#4861)
AWS documents StackId in every Create, Update and Delete request as the
ARN of the stack that contains the custom resource, and handlers rely on
it. #4973 now passes the engine's stack id and stashes it for Delete, but
an engine with no stack ARN still leaks a non-ARN: Cloud Control's
standalone engine uses the stack name as its id, so its custom resources
got StackId "cloudcontrol".

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

An integration test drives Create, Update and Delete through a mocked
handler and checks the event's StackId against Ref AWS::StackId and
DescribeStacks, including a nested stack's own id, and the docs say so.
2026-10-08 14:43:01 -04:00
TATSUNO “Taz” Yasuhiro ebd364e23e fix(lambda): end the invocation when a checkpoint closes a durable execution (#5299)
* fix(lambda): end the invocation at the checkpoint that closes a durable execution

On AWS a checkpoint that closes the execution also ends the invocation.
The history shows InvocationCompleted before ExecutionSucceeded or
ExecutionFailed. A chained invoke started in that batch comes between
them. What the handler returns after that checkpoint is ignored.

The invocation now runs under a request id that Floci picks, so
InvocationCompleted names the same request the function saw.

* fix(lambda): answer a closing durable checkpoint with no operations

AWS answers the checkpoint that closes the execution with an empty
Operations list and no token, even when the batch changed other
operations.

* fix(lambda): fail an unreachable chained invoke before the invocation ends

When a chained invoke target cannot be invoked, AWS logs
ChainedInvokeStarted at its place in the batch and ChainedInvokeFailed
after the batch, before InvocationCompleted. This also holds in a batch
that closes the execution, where Floci logged no ChainedInvokeFailed.
A target that can be invoked still starts after the batch, and after
InvocationCompleted when the batch closes the execution.
2026-10-08 14:34:34 -04:00
Simone Primarosa 6fc957a3b4 feat(eks): join EC2 instances to a cluster as nodes (#5091)
Support joining real EC2 instances to an EKS cluster as Kubernetes nodes.
Inspect instance user data during RunInstances for bootstrap scripts or
nodeadm YAML targeting an EKS cluster, recording pending joins and
reconciling node registration asynchronously via the readiness poller.

Ensure RunInstances returns without blocking on kubectl or shared locks,
and guard storage mutations under the deletion lock so deleted clusters
cannot be resurrected. Scope restoration tracking per account.
Support AL2023 MIME multipart nodeadm configurations, and share the
in-use IP check and cursor loop between subnet and subnetless launches.

Update node metadata derivation to match AWS conventions, using instance
private DNS names for node names and aws:///<az>/<instance-id> for
provider IDs, with topology and instance-type labels.
2026-10-08 11:56:43 -04:00
Hector Ventura 0d4b8cda74 fix(route53): return the health check on a CreateHealthCheck retry (#5298)
* fix(route53): return the health check on a CreateHealthCheck retry

CreateHealthCheck refused any CallerReference already in use with
HealthCheckAlreadyExists. AWS treats the same reference with the same
settings as a retry and returns the health check it already created;
only different settings are refused. The Go SDK resends the same input
after a transient failure, so a Terraform or OpenTofu apply failed on
Floci where it succeeds on AWS. A matching retry now returns the
existing health check, and the docs note that a deleted health check's
reference is reusable at once here, while AWS keeps refusing it.

* fix(route53): compare a CreateHealthCheck retry on every setting it sends

The retry check compared only the seven HealthCheckConfig fields Floci
models, so two requests that differed in an unmodelled setting such as
EnableSNI passed as a retry, and a retry stating RequestInterval or
FailureThreshold at its default was refused as different from one that
omitted it. The controller now records the request's settings in a
canonical form, every value under HealthCheckConfig sorted (Regions and
ChildHealthChecks are sets), with an omitted RequestInterval or
FailureThreshold counted as AWS's default of 30 or 3 except for
RECOVERY_CONTROL, and a retry must match it. A non-numeric Port,
RequestInterval or FailureThreshold is now InvalidInput instead of being
dropped.

* refactor(route53): read the health check settings with XmlParser.extractElementTree
2026-10-08 11:39:52 -04:00
Hector Ventura 4927f71ce1 fix(ecs): look up a task definition without failing on a stored record with no ARN (#5296)
* fix(ecs): look up a task definition without failing on a stored record with no ARN

resolveTaskDefinitionOrThrow compared each stored definition's ARN with
d.getTaskDefinitionArn().equals(ref), so a family or family:revision lookup
threw a NullPointerException when the region held a definition with no ARN.
The comparison is now null-safe, and EcsTaskDefinitionLegacyKeyTest covers a
family lookup next to such a record.

* fix(ecs): answer a missing task definition reference with ClientException

A null or blank reference reached the lookup's comparisons and threw a
NullPointerException, a 500, once the region held any task definition:
the family fallback's family.equals(...) failed even before the
null-safe ARN comparison. It is now refused up front with the same
ClientException an unknown reference gets.

* test(ecs): cover the family lookup in the existing no-ARN test
2026-10-08 11:15:40 -04:00
Vũ Thế Huy d39c7e1381 fix(s3): reject unverified credentials and malformed auth in account routing (#4825) (#5059)
* fix(s3): enforce SigV4/SigV4A algorithm prefix in AccountResolver

* fix(s3): require X-Amz-Algorithm in AccountContextFilter presigned query resolution

* fix(s3): reject malformed Authorization header in S3HeaderSignatureFilter

* fix(s3): reject query presigned requests missing X-Amz-Algorithm in PreSignedUrlFilter

* test(s3): add reproduction tests for unverified credential account routing (#4825)

* fix(s3): isolate presigned query auth and permit SigV4A headers (#4825)

* fix(s3): gate signature checks on validation setting and restore unsigned presigned steering (#4825)

* fix(s3): stop unverified credentials from selecting an account (#4825)

Account selection now requires a SigV4/SigV4A Authorization scheme or a
query string carrying X-Amz-Algorithm. A bare "Credential=" header or an
X-Amz-Credential without X-Amz-Algorithm keeps feeding region resolution
only, so it can no longer steer a request into another account.

Credentials rebuilt outside the header (IAM presigned query, presigned
POST form) now carry the AWS4-HMAC-SHA256 scheme so IAM enforcement still
recognises them. With signature validation on, a query holding only
X-Amz-Signature is rejected with AuthorizationQueryParametersError.

* fix(s3): ignore unsupported Authorization headers for region and keep credential-only download URLs working (#4825)

A header without a SigV4/SigV4A scheme now selects neither account nor
region, so it cannot misattribute S3 data events to another region.

Floci's own download URLs (Lambda layers, Kubernetes init containers)
carry only X-Amz-Credential, so that parameter steers the account and
region again without X-Amz-Algorithm.

* fix(s3): let a present Authorization header win over X-Amz-Credential in account routing (#4825)

IamEnforcementFilter reads the query credential only when no Authorization
header exists. AccountContextFilter fell back to the query whenever the
header was unrecognised, so a malformed header plus X-Amz-Credential picked
an account that IAM then skipped. Both filters now use the same precedence.

* fix(s3): treat a whitespace-only Authorization header as absent in account routing (#4825)

S3's authorization parser ignores a blank header and uses the presigned
query credential, so AccountContextFilter must do the same instead of
falling back to the default account.

* fix(iam): treat a whitespace-only Authorization header as absent in IAM enforcement (#4825)

AccountContextFilter and S3 already ignore a blank header and use the
presigned query credential. IamEnforcementFilter only checked for null, so
a blank header made it find no access key and skip authorization for the
account the query credential had selected. All three now agree.

* fix(s3): presign internal lambda download URLs

* test(macie2): include SigV4 algorithm in account routing check

* docs(s3): list the SigV4A and incomplete presigned URL 400s under signature verification (#4825)

* docs(s3): say Floci does not verify SigV4A signatures yet instead of cannot
2026-10-08 10:58:38 -04:00
Priamo Germosen df4fa58ea1 fix(iam): take service-linked role names and suffix support from AWS evidence (#5293)
CreateServiceLinkedRole guessed both things it cannot derive. The role name came
from capitalising the principal, which is wrong for 141 of the 162 services the
table covers: acm.amazonaws.com is AWSServiceRoleForCertificateManager on AWS and
was AWSServiceRoleForAcm here. And a CustomSuffix was accepted for every service,
where AWS refuses one for 68 of the 71 it has been recorded against, so the
emulator minted roles AWS would have rejected outright.

Both now come from iam/service-linked-roles.tsv, generated by
tools/slr/service_linked_roles.py and gated by make slr-check. One table, because
both facts come out of one pass over the same AWS-validated snapshot: the name
from a recorded create response, the suffix verdict from the test's own
parameterisation. Writing either by hand only captures what someone noticed, and
every finding behind this change came from grepping.

Sources, each row recording its own: recording, actual create responses and the only
source that can establish suffix support; policy-documents, role ARNs in the vendored
AWS managed policies, names only; and docs, from AWS's own service-linked role
pages, quoted and linked in the generator. Counts live in the table's header, where
this script keeps them right.

Two shapes in the policy documents have to be refused rather than read, and both
were being read. A name followed by `*` is a prefix pattern: the policy writes
AWSServiceRoleForAmazonCognitoIdpEmail* where the recorded create returns
AWSServiceRoleForAmazonCognitoIdpEmailService, so reading the prefix invents a role
AWS never mints. Twenty-one principals rested on nothing but such a prefix. And a
role name is unique per account, which these documents ignore: they point
maintenance.elasticbeanstalk at the parent's AWSServiceRoleForElasticBeanstalk, so
taking that at face value made the sibling's create fail as a duplicate of a role
it does not own. A collision guard drops the weaker row back to the derived
fallback and says so; an unresolvable collision is an error for a human.

KNOWN_SOURCE_CONFLICTS is empty as a result. Its one entry was never a
disagreement between sources, only that truncated prefix read as a name. The
mechanism stays for a real one.

make slr-check runs offline: policy-documents rows must still match the vendored
JSON, every vendored service must be in the table, it must be sorted, and a suffix
verdict on a non-recording row is an error because nothing but a recording can
establish one. Three extraction traps have a test each, all three being ones the
real data walked into: an underscore can be part of a name, so splitting on the
CustomSuffix separator truncates ApplicationAutoScaling_CassandraTable; a policy
matching suffixed roles writes the prefix with a trailing separator; and a
wildcard ARN names a role without saying which principal mints it, which is how an
earlier pass handed plain GuardDuty the MalwareProtection role's name.

The name was not only wrong against AWS, it was inconsistent within the tree.
ConnectService built an ARN for AWSServiceRoleForAmazonConnect while
CreateServiceLinkedRole minted AWSServiceRoleForConnect for the same principal:
two roles for one purpose. GuardDutyService, MacieController and RamController
each hard-coded their own name too, and all four were right where IamService was
wrong. They read the table now, and a test fails if a principal any of them builds
an ARN for loses its row, since the fallback would quietly derive a name again.

ApplicationAutoScalingService was wrong a different way. It maps a namespace to a
dimension itself, and had no arm for appstream, cassandra, ec2 or sagemaker, so
all four fell to CustomResource where AWS names them AppStreamFleet,
CassandraTable, EC2SpotFleetRequest and SageMakerEndpoint. It prefers the table
now and keeps its switch for the namespaces nothing records, where the shape is
right even when the dimension is a guess. Its dynamodb arm is gone with the rest:
the table covers that namespace, so the arm was unreachable and a second copy of a
fact the table owns, free to disagree with it while never running. A test pins
dynamodb resolving through the table, since removing the arm is what left nothing
else covering it.

Two behaviour changes worth calling out. rds.amazonaws.com is AWSServiceRoleForRDS
rather than the derived Rds, which flipped one existing expectation. And two table
names are long enough that a suffix alone breaches the 64-character RoleName
limit, ApplicationDiscoveryService's ContinuousExport role leaving three
characters and SageMakerEndpoint six, so that check now reports "The role name"
rather than "The derived role name", which stopped being true.

cloud9 is in the table because deleting IamService's three-entry override map
dropped it: autoscaling and ram were covered, cloud9 was not, and it regressed to
the derived AWSServiceRoleForCloud9. Two tests caught it. Rather than restore the
literal, which is the circular sourcing this work exists to remove, its User Guide
settles it and the row carries that citation.

The table is registered in quarkus.native.resources.includes rather than exempted
from it. AwsManagedPolicies is exempt because parsing its 3.5 MB at image build time
and keeping the result in the heap beats shipping the source twice; at 13 KB that
saving is not worth depending on the static initialiser running at build time, and
NativeImageResourceIncludesTest is the thing that says so.

The header records the sha256 of the snapshot the recording rows came from, because
that half cannot be rechecked offline and --check can only say so rather than fix
it. A digest makes the next --refresh a diff against a known source: an unchanged
digest means any difference in the table came from the vendored policy documents,
and a changed one says the recordings moved with it. --check cannot verify the
digest without the snapshot, but it does reject a table that has quietly lost the
line, or one claiming no snapshot while carrying recording rows.

Refs #5084
2026-10-08 07:49:50 -05:00
Priamo Germosen e452ce8671 feat(codeartifact): add DescribePackage for all package formats (#5308)
DescribePackage returns a package's format, namespace, name, and origin
controls, and answers ResourceNotFoundException for a package that does not
exist. Existence is checked where the package actually lives: stored
generic-format package versions for generic, and each format's sidecar for
maven, npm, and pypi. A package whose name merely starts with another's name
does not match it.

Origin controls are reported as publish ALLOW and upstream BLOCK, the default
CodeArtifact assigns to a package whose first version was published directly.
Floci never ingests packages from upstream and does not store origin controls,
so these values are fixed.

For maven, npm, and pypi the existence check starts that repository's sidecar
if it is not already running, the same side effect the asset bridge has.
RepositorySidecarManager gains packageExists, implemented by each sidecar client.
2026-10-08 07:49:38 -05:00
Mario Toffia 5a8694e97a fix(ecs): accept a service ARN in ListTasks (#4859)
ListTasks looked the serviceName filter up by the string it was given,
so only a bare service name matched. A service ARN, which is what CDK
passes, found no service, and the call returned an empty taskArns list
even while the service had running tasks.

The filter now goes through extractServiceName, the helper UpdateService
and DeleteService already use, which keeps the last path segment. A
name, a full service/<cluster>/<name> ARN, the older service/<name> ARN
and <cluster>/<name> all resolve to the service in the request's
cluster. AWS accepts each of these forms. An unknown service still
lists nothing, which is unchanged.
2026-10-08 07:41:20 -04:00
Hector Ventura ddc47a465d fix(core): make Docker read timeouts real on a Unix-socket host, except for long-lived streams (#5294)
* fix(core): make Docker read timeouts real on a Unix-socket host, except for long-lived streams

docker-java's UnixSocket reads through a blocking channel stream that
ignores SO_TIMEOUT, so on the default unix:// Docker host no call ever
timed out: a 2-second response timeout let a container wait run 153
seconds, and a hung daemon blocked its caller forever. It is also why
httpclient5's stale-connection check, a read with a 1 ms timeout, cannot be
enabled there.

FlociDockerHttpClient now connects to a unix:// host through
UnixDomainSocket, which keeps the channel non-blocking and waits on a
selector, so a read with a timeout fails with SocketTimeoutException. Making
the timeout real would cut off streams that are silent while healthy, so
requests that hold a stream open (container wait, exec and attach output,
followed logs, streamed stats, events, image pulls and builds) get no
response timeout on any host, which also keeps a TCP host's container wait
from dying at five minutes. Every other call keeps the 5-minute timeout.

* fix(core): keep the Unix socket's failures IOExceptions on close and interrupt

Closing the socket while another thread waited in a read or write could
end that wait with the selector's unchecked ClosedSelectorException,
since close() may shut the selector between select() and
selectedKeys(); callers expecting an IOException did not handle it. It
is now a SocketException. A thread reading a silent stream with no
timeout spun once interrupted, because select() returns at once while
the interrupt flag is set; it now closes the socket and throws
ClosedByInterruptException, as the blocking channel it replaced did.

The tests wait with a timed get that expects a TimeoutException rather
than a fixed sleep, so an early return fails at once, and cover a close
during a blocked read and an interrupted read.
2026-10-08 07:27:04 -04:00
Hector Ventura c09c7ae62b chore(elasticache): put restoreCacheCluster's Javadoc back on its method (#5297)
The regionOf helper was inserted between restoreCacheCluster's Javadoc
and the method, so the block describing how a cache cluster is restored
documented regionOf instead, and restoreCacheCluster had none. The
helper now sits above that Javadoc. No behaviour changes.
2026-10-08 07:21:48 -04:00
Priamo Germosen ea77da8a2a refactor(codeartifact): split the pypiserver sidecar into a manager and a client (#5281)
PypiserverSidecarManager now owns only the container lifecycle: starting,
readiness, release, and teardown. The HTTP protocol and PEP 427/440 filename
matching move to PypiserverSidecarClient, which implements
RepositorySidecarManager and is what the registry and CodeArtifactPypiController
use, matching the Verdaccio and Reposilite pairs.

Wire-contract tests move to PypiserverSidecarClientTest against a JDK
HttpServer fake. No behavior changes.
2026-10-07 23:32:27 -05:00
Clement 0848fa6a48 feat(elasticache): add user groups and associate them with replication groups (#4435)
CreateUserGroup, DescribeUserGroups, ModifyUserGroup and DeleteUserGroup
returned UnsupportedOperation, and ModifyReplicationGroup read
UserGroupIdsToAdd as user ids, so RBAC could not be set up the way AWS
and Terraform (aws_elasticache_user_group, user_group_ids) do it.

User groups are now stored resources. CreateReplicationGroup takes
UserGroupIds and ModifyReplicationGroup adds and removes user groups; the
proxy authenticates the members of a replication group's user groups, read
at AUTH time so a ModifyUserGroup applies at once, each by its own
authentication mode. A replication group with a user group associated
admits only its members, even while the group is empty. An id in
UserGroupIdsToAdd that names no user group but names a user still
associates that user directly, so existing setups keep working.

A cache uses either its AUTH token or user groups, as on AWS: while a user
group is attached the token is not accepted and AuthTokenEnabled reads
false. ModifyReplicationGroup takes AuthTokenUpdateStrategy DELETE, which
removes the token and is only allowed together with a user group, and
RemoveUserGroups. Removing the last user group leaves the cache without
access control, still encrypted in transit; a token that was never deleted
applies again. The proxy reads the cache's auth mode per connection, so
these changes take effect without a restart.

Validation follows the RBAC rules: a redis user group needs a user named
default (DefaultUserRequired), members cannot share a user name
(DuplicateUserName), valkey users only join valkey groups, a valkey group
cannot hold a no-password user or serve a redis cache, association needs
in-transit encryption, and a user group in use cannot be deleted
(InvalidUserGroupState). ModifyUser refuses an engine or authentication
change that a user group holding the user would reject. Deleting a user
removes it from its user groups.
2026-10-08 00:24:28 -04:00
Matheus Oliveira f6e76bbe30 fix(cloudformation): default CreateChangeSet type to UPDATE (#5287)
Follow-up to #5015.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-07 22:36:43 -04:00
Matheus Oliveira 673c809eff fix(lambda): add cookies array to function URL events (#5288)
* Fix #5255

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-07 22:35:51 -04:00
Hector Ventura 985921c3db fix(core): fail a Docker call after 30 seconds when its connection pool is full (#5285)
* fix(core): fail a Docker call after 30 seconds when its connection pool is full

With no connection-request timeout set, a call that could not lease a
pooled connection waited httpclient5's default three minutes before failing.
A full pool means the emulator is saturated, so the wait is now configurable
through floci.docker.connection-request-timeout-seconds (default 30), applied
to both pools. The transport retry already treats a lease timeout as pool
exhaustion and never replays it, so the call fails once, after the timeout.

* fix(core): reject a Docker lease timeout below one second

httpclient5 reads a zero connection-request timeout as no timeout, so
floci.docker.connection-request-timeout-seconds=0 let a call on a full
pool wait forever, and a negative value reached the client unchecked.
It now has to be at least 1, checked the way the two pool sizes are,
through one helper that names the setting and its environment variable.

The two producer tests that build the beans from a mocked config now
stub the timeout; they ran with zero before. The lease test's socket
list is shared with the acceptor thread, so it is a concurrent list.
2026-10-07 20:59:11 -04:00
Hector Ventura a3027c07cf fix(lambda): keep watching for a runtime exit after the wait stream fails (#5284)
* fix(lambda): keep watching for a runtime exit after the wait stream fails

The exit watcher streams Docker's wait-for-exit and was never re-armed once
that stream ended with an error. On a tcp:// Docker host the control-plane
client's five-minute response timeout becomes the socket read timeout, and
the stream sends nothing until the container exits, so any container alive
past five minutes lost its watcher: a runtime that crashed after that was
reported as Function.TimedOut instead of Runtime.ExitError, the case #3314
fixed. Any other stream failure (a dropped connection, a daemon restart) had
the same effect on every host.

The watcher moves to LambdaExitWatcher. When the stream ends with an error it
inspects the container: still running re-arms the watch, already exited
reports the inspected exit code, and gone reports nothing. Repeated immediate
failures stop the re-arming, so a daemon that cannot hold the stream does not
spin it.

* fix(lambda): retry the exit watch after a delay, and through a failed inspect

A dropped connection or a daemon restart usually fails the inspect that
follows the stream error too, and that path ended the watch for good;
the quick re-arms also ran back to back, spending the whole budget
within milliseconds of the daemon going away. A failed inspect now
counts as a quick failure, and each quick failure re-arms after a delay
that starts at one second and doubles, up to five in a row (31 seconds
in all). A stream that lived past five seconds still re-arms at once
and resets the count.

The clock and the scheduler are injected, so the tests drive the
backoff, the reset after a long-lived stream, and a failed inspect
followed by the exit it then reports.
2026-10-07 20:46:28 -04:00