* feat(secretsmanager): add the five missing actions and correct response fidelity
Secrets Manager implemented 18 of the 23 actions in the API reference. This
adds the remaining five and corrects a number of response and validation
divergences found by working through each operation's reference page.
New actions:
- CancelRotateSecret turns rotation off and reports the half-built AWSPENDING
version an interrupted rotation left behind. The staging labels are left
alone, as AWS leaves them, because that version id is the only handle on a
stale AWSPENDING - and a stale AWSPENDING that is not also AWSCURRENT makes
every later RotateSecret fail with "a previous rotation isn't complete".
- ValidateResourcePolicy reports wildcard principals under the same
REFLEXIVE_PRINCIPAL_CHECK name AWS uses. BlockPublicPolicy on
PutResourcePolicy now enforces the same check.
- ReplicateSecretToRegions, RemoveRegionsFromReplication and
StopReplicationToReplica, backed by a replication model on Secret. Replicas
carry the primary's ARN with the Region swapped, track later writes to the
primary, and are read-only; a primary that still has replicas cannot be
deleted.
Scheduled rotation now fires. RotationRules were stored and echoed back but
never acted on, so AutomaticallyAfterDays and ScheduleExpression described a
schedule that could not happen. A background sweep rotates secrets whose
NextRotationDate has passed, reusing the EventBridge Scheduler expression
parser for rate() and cron(). The schedule advances when a rotation is
dispatched rather than when it succeeds, so a failing rotation cannot pin the
sweep on one secret forever.
Response fidelity:
- ListSecrets honours SortBy, SortOrder and IncludePlannedDeletion, and its
entries carry SecretVersionsToStages, the rotation fields, DeletedDate and
PrimaryRegion.
- PrimaryRegion and ReplicationStatus appear only on multi-Region secrets,
matching AWS's "only returns fields that have a value" rule.
- Versions with no staging labels are deprecated: DescribeSecret and
ListSecretVersionIds omit them unless IncludeDeprecated is set, and an empty
VersionStages array is omitted rather than sent.
- ListSecretVersionIds gained IncludeDeprecated, LastAccessedDate and paging.
Validation, all previously accepted silently:
- DeleteSecret rejects a recovery window outside 7-30 and the
ForceDeleteWithoutRecovery/RecoveryWindowInDays combination. A window of 0
used to fall through to force-delete, turning a request for no recovery
window into an unrecoverable delete.
- CreateSecret uses ClientRequestToken as the version id and is idempotent on
retry; UpdateSecret, which AWS documents as not idempotent, rejects a token
that already names a version.
- RotationRules bounds, secret name charset, SecretString/SecretBinary
exclusivity, KMS key existence and state, and the documented caps on
BatchGetSecretValue, Filters, ExcludeCharacters and ResourcePolicy.
Secret values remain stored in the clear; encrypting them with the emulator's
own KMS would protect nothing while making the store unreadable. KmsKeyId is
validated instead, which is the part a caller can observe.
Two deviations are deliberate and recorded in docs/services/secrets-manager.md:
LastRotatedDate is retained after CancelRotateSecret, and RotateSecret with
RotateImmediately=false does not create the throwaway AWSPENDING version.
* test(secretsmanager): create a real KMS key in the sdk-test-java compat test
kmsKeyIdPreservation asserted that floci round-trips whatever KmsKeyId it is
handed, using an ARN that was never created. That passed only because floci
did not check the key; real AWS rejects a key it cannot access, and so does
the new validation.
The test now creates a key through the emulated KMS and round-trips that ARN,
so it still covers KmsKeyId preservation without depending on the missing
check. A second case pins the rejection itself.
* refactor(secretsmanager): import types instead of qualifying them inline
AGENTS.md asks for imports unless a name collision forces qualification.
AwsException and UUID had neither.
* fix(secretsmanager): hold the rotation lock while promoting a replica
StopReplicationToReplica wrote the promoted replica outside the per-secret
lock every other mutation in this file takes. The promotion races the
primary's replica sync, and losing that race writes the replica back over the
copy the call just promoted.
Also imports KmsKey, ConcurrentHashMap and HashMap rather than qualifying
them inline, per the same AGENTS.md rule.
* test(secretsmanager): assert the KMS rejection by exception type, not message text
createSecretWithAnUnknownKmsKeyIsRejected matched "InvalidParameterException"
against the message, but that is the exception type; the message itself reads
"You can't access the KMS key ... in this Region". The assertion now checks
the typed InvalidParameterException and the text it actually carries.
* test(secretsmanager): give the new KMS compat test its own order
createSecretWithAnUnknownKmsKeyIsRejected inherited @Order(13) from the test
it was added next to, so two cases shared a position. JUnit breaks the tie
deterministically, but the duplicate made the sequence misleading; the tail is
renumbered so each case keeps a distinct order.
Also sorts the new KMS imports, which landed between the lambda ones.
* fix(secretsmanager): guard every write to a secret with its owning monitor
UpdateSecret read, mutated and persisted without taking the secret's lock,
unlike every other mutator in the class, so two concurrent calls could drop
one another's field.
StopReplicationToReplica locked the replica's own ARN, but persist() writes a
primary's replica slots while holding only the primary's lock: two monitors
guarding one store slot, so a sync landing after the promotion could overwrite
the promoted copy. The promotion now runs under the primary's monitor, and its
two halves run in one critical section so nothing lands between them.
SecretsManagerWriteLockTest parks a write mid-flight and asserts the second
caller waits; both cases fail without the fixes.
* fix: enforce safe default network binding
* fix(config): keep signed test authority stable
Pin the integration-test listener to the existing all-interface test bind and
opt into that bind only in the test profile. This preserves localhost-based
SigV4 fixtures while production keeps the loopback default.
* fix(config): keep compat image backward compatible
* chore: retrigger CI
* fix(config): mirror JVM image network binding
The five /v2/email/custom-verification-email-templates endpoints and
their two helpers move out of SesController into SesCvetController. Get,
list and delete call SesCvetService directly, and SesQueryHandler's v1
actions do the same; create and update stay on the SesService facade
because their validation checks the From address against the identity
domain. SesService drops the three pure delegations, and sending a
custom verification email stays with the send endpoints. The new class
is registered on the SES descriptor. No wire behavior changes.
* chore(cloudformation): sweep the dead code out of the legacy resource provisioner
Eleven batches have moved types out of CloudFormationResourceProvisioner and each
left something behind: a constructor parameter that is injected but never assigned,
a helper whose last caller moved, an import for a model type nothing here touches, a
section header with no code under it. None of it is reachable, so none of it needs a
test to remove.
Gone: eight constructor parameters (22 to 14, every remaining one is assigned and
used), eleven private methods with no caller but their own declaration (the nine
JSON put and parse helpers plus resolveOptionalWithoutDynamicReferences and
parseCfnTags, whose last callers left with RDS and DynamoDB), twenty-six imports
with no remaining use, and seven empty section headers. The test fixture drops the
same eight positional arguments; its builder keeps the fields because the inferred
provisioners still take those services. 3,638 lines to 3,430, no behaviour change.
* chore(cloudformation): drop the orphaned CORS Javadoc and reattach the legacy-set Javadoc
Two comment-only leftovers of earlier batches, both found while checking a review
comment on the sweep. The Javadoc for the S3 CorsConfiguration method stayed behind
when #2754 moved the method to S3CfnProvisioner; it goes. The Javadoc describing
LEGACY_SWITCH_TYPES was stacked directly above the DELETE_NEEDS_STACK_RESOURCE one,
so the compiler attached it to nothing and the set it describes had no doc; it now
sits above its own declaration, text unchanged.
* feat(eks): expose IMDS on 169.254.169.254 inside cluster containers
When applications or agents run on Kubernetes nodes or use hostNetwork: true, they expect the AWS Instance Metadata Service (IMDS) at the standard link-local address 169.254.169.254:80. In Floci, EKS k3s cluster containers lacked access to IMDS at this link-local address, preventing workloads from discovering instance identities, node IAM roles, or dynamic cluster credentials without custom endpoint overrides.
This change exposes IMDS on 169.254.169.254:80 inside EKS cluster containers when floci.services.eks.imds is enabled. It configures a background TCP relay via socat pointing to the host's EC2 metadata port, registers a synthesized EC2 node instance with the cluster's IAM role and container IP in Ec2MetadataServer, extracts reusable metadata proxy logic into Ec2MetadataProxy, and documents node network namespace reachability and hop limit handling.
* fix(eks): address review feedback on lifecycle check, default flag, and instance seed
* fix(eks): synthesize distinct node instance profile and import CompletableFuture
* test(eks): enable IMDS profile and provide curl in docker test fixture
The 16 character cap was applied to every engine, but RDS accepts 63 on
PostgreSQL and 32 on MySQL, so an instance whose master username is longer
could not be created at all. The bound now comes from DatabaseEngine, using
the engine createDbInstance already resolves; the character rule and the
error message are unchanged.
Closes#3729
* feat(apigateway): implement GetUsage
GetUsage had no implementation, so a caller asking a usage plan what it
had consumed hit an unsupported action.
This returns the real envelope with zeroed numbers rather than metering
anything. Shape captured from real API Gateway: an items map of API key id
to one pair per day of the inclusive range, alongside usagePlanId,
startDate and endDate, and no position element when there is no further
page.
The pair is [used, remaining], not [used, quota]. Measured on a live usage
plan, the second element is the quota limit minus cumulative use in the
period: a plan with a 1,000,000 limit reported 999863 after 137 calls, then
999740 after 123 more. Anything reading that element as a quota is reading
it wrong.
Both elements are zero here, deliberately. Nothing counts requests per API
key, and a usage plan carries no quota to subtract from, so there is no
limit to report against. Throttle settings are already accepted and stored
without being enforced, so this is consistent with how the service treats
the rest of that surface. Storing a quota on the usage plan and counting on
the execute path are the two pieces still missing, and both the javadoc and
the service docs say so.
A caller that sums the used counts therefore gets zero, which is what it
already got when the action did not exist, without having to special-case a
missing endpoint.
Validation follows the captured errors: an unknown plan is NotFoundException
and an end date before the start date is BadRequestException, "Usage end
date must be after start date".
* fix(apigateway): paginate GetUsage
GetUsage takes limit and position, which this did not accept at all: every
attached key came back in one response, so the implementation only matched
the single-page case the original capture happened to exercise.
Pagination now runs over the API key entries, defaulting to 25 a page. The
token is the last key id already returned rather than a positional offset,
so a page resumes after a known key and a concurrent key attachment cannot
shift it. No position is emitted on the terminal page, matching the shape
captured from real AWS.
Two edges deliberately differ from real API Gateway, because it is not a
good guide there. It answers limit=0 with an InternalFailure, which is a
fault rather than a contract, so a page size below one is a
BadRequestException here. It also accepts a limit past the documented
maximum of 500, so anything larger is clamped rather than refused. Both
choices are written down in the service docs.
An unrecognised position is a BadRequestException, "Invalid position
parameter", which is the message real API Gateway returns.
The existing tests looked keys up with a dotted GPath. API key ids are
random and can begin with a digit, which Groovy then parses as a number, so
every lookup into items now uses bracket notation. That was luck rather
than correctness before.
* fix(apigateway): stop inventing a GetUsage limit ceiling
The previous head clamped any limit above 500 to 500, extrapolated from a
single observation that 501 was accepted. One accepted value does not
establish a rule.
Probed properly against real API Gateway: 500, 501, 1000, 5000, 100000 and
2147483647 are all accepted without error. The documented maximum is not a
rejection boundary, so no ceiling is imposed here either and the regression
asserts the observed rule across that ladder rather than an emulator
specific clamp.
Whether the service caps the page it actually returns above 500 is not
observable without a usage plan holding more than 500 keys, so nothing is
assumed about it and the docs say as much.
The lower bound stays a deliberate divergence, now with both values
measured: limit=0 and limit=-1 both answer InternalFailure on real API
Gateway. That is a fault rather than a contract, so a page size below one
is a bad request here instead of a reproduced 500.
* fix(apigateway): cap the GetUsage page at 500 while still accepting more
Removing the ceiling entirely went too far the other way. The probe shows
real API Gateway accepts a limit above 500, so rejecting one would be
wrong, but it never showed the service returning more than 500 entries in a
single page, and the documented contract caps a page at 500. Returning more
than 500 was therefore as unevidenced as rejecting the request.
Request acceptance and response page size are now separate: a larger limit
is honoured as a request, and the page stays capped at 500 until a real
result with more than 500 keys shows otherwise.
resolveUsageLimit becomes package-private so the distinction can be
asserted directly rather than needing a usage plan with 500 keys behind it.
* fix(apigateway): return GetUsage key usage under the values wire key
The response serialised the per-key usage map as "items", which is the
SDK-side member name, not the wire key. The Usage shape models that
member with locationName "values", so a real client parsing a body keyed
"items" finds the field absent and reads no usage at all.
Verified with botocore's own rest-json parser against the apigateway
service model: a body keyed "values" populates the member, a body keyed
"items" leaves it None.
Assertions and the service docs move with it. Only GetUsage is affected;
the sibling list actions are a different shape and are untouched.
A Distributed Map could only read a JSON dataset: every other InputType failed
the state with "not yet implemented". JSONL now reads one item per line,
skipping blank lines, so a trailing newline is not an item.
ReaderConfig.ItemsPointer stays JSON only, as on AWS, and MaxItems truncates a
JSONL dataset the same way it truncates a JSON one.
A table without an explicit TableName got a fresh generated name on every
UpdateStack, which created a second table and re-pointed Ref at it. TableName is
create-only, so the provisioner now resolves the name through
ProvisionContext.stablePhysicalName: the template's name, else the name the
resource already has, and only failing both a generated one. This is the same fix
earlier batches applied to other types, split out of #3699 at the reviewers'
request so that refactor stayed behaviour-preserving.
CloudFrontServingController (via CloudFrontOriginHttpClient) and
VerifiedPermissionsOidcSignatureVerifier each independently
implemented the same SSRF-protection check rejecting private/
link-local/reserved IPv4 and IPv6 ranges before a server-side fetch,
found via CPD as an 18-line block (#3715). The two files actually
duplicated three methods end to end, differently named
(isBlockedOriginAddress/isBlockedPublicAddress,
isIpv4MappedAddress/ipv4Mapped, isBlockedIpv4Address/blockedIpv4), not
just the one CPD's threshold happened to flag.
Extracted the full check into SsrfProtection.isBlockedAddress in
core.common, and pointed both call sites (plus their tests) at it,
removing all three duplicated methods from both files rather than
leaving a thin wrapper behind.
No behavior change: the blocked ranges and precedence are identical
to both copies before this, only their location changed.
ExecuteApiSigV4Authorizer (API Gateway) and IamAuthValidator (AppSync)
each carried an identical 15-line block splitting Credential=/
SignedHeaders=/Signature= out of a raw AWS4-HMAC-SHA256 Authorization
header value, found via CPD (#3714). Neither #3657 (closing #3650) nor
#3706 (closing #3700), which already deduplicated related SigV4 logic
between these same two files, touched this specific block.
Extracted it into SigV4AuthorizationHeader in core.common.auth,
alongside CredentialScope and SigV4RequestValidator from #3657, and
pointed both call sites at it.
No behavior change: the parsing is identical, only its location
changed. Both files' existing test suites pass unchanged.
* refactor(cloudformation): move the DynamoDB types into DynamoDbCfnProvisioner
AWS::DynamoDB::Table, AWS::DynamoDB::GlobalTable and Custom::DynamoDBReplica leave
CloudFormationResourceProvisioner for a per-service provisioner that owns create,
update and delete for all three. The monolith drops 246 lines, its last DynamoDB
reference and the injected DynamoDbService (24 to 23 constructor parameters), and
its legacy switch goes from 27 to 24 types.
Two behaviour changes ride along, both covered by the new tests. A GlobalTable is
now deleted on stack delete: it had no delete arm and the table leaked.
Fn::GetAtt TableId resolves for both table types, from the same value
DescribeTable reports, which closes the registry schema's read-only attribute the
old arm never set. Replicas on a GlobalTable stays ignored as before.
parseCfnTags is copied rather than moved because the monolith's unused
putTagsObject still references it.
* refactor(cloudformation): publish TableId only for global tables and let a failed replica delete surface
The registry schema declares TableId read-only on AWS::DynamoDB::GlobalTable only; a
plain AWS::DynamoDB::Table exposes Arn and StreamArn, so publishing TableId there
accepted a Fn::GetAtt that CloudFormation rejects. The replica delete tolerated every
exception, which reported a clean delete over a real failure; it now goes through
CfnDeletes.safeDelete and treats only a missing table as already gone, since the
service already ignores removing an absent replica. The unused snsService constructor
parameter on the line this change touches is dropped as well.
Implement the SageMaker control plane over the AWS JSON 1.1 protocol
(X-Amz-Target: SageMaker.*) plus the runtime invocation path:
- Models, endpoint configs, endpoints, training jobs, and tags with
AWS-shaped validation errors (ValidationException / ResourceInUse)
- CreateTrainingJob runs the training image as a real Docker container
using the /opt/ml contract: hyperparameters, resourceconfig and
inputdataconfig under /opt/ml/input/config, S3 channel data under
/opt/ml/input/data/<channel>, and /opt/ml/model uploaded back to S3
as model.tar.gz under the configured S3OutputPath
- CreateEndpoint hosts the model image as a long-lived container with
the serve command, /ping health checks, and ModelDataUrl artifacts
extracted into /opt/ml/model
- POST /endpoints/{name}/invocations proxies to the container and maps
model 5xx responses to ModelError (HTTP 424) like SageMaker Runtime
- Training container logs stream to CloudWatch Logs under
/aws/sagemaker/TrainingJobs
- Storage wired through StorageFactory with memory/persistent modes,
config in EmulatorConfig and both application.yml files
- Unit, integration, and Docker-gated integration tests plus a boto3
compatibility test; service and docs registered in the catalog
BedrockAgentCoreCredentialProviderService and BedrockAgentCoreToolsService
each carried an identical 22-line validateTags method (AgentCore's tag
key/value character-set and length constraints), found via CPD (#3704).
This is distinct from the controller-layer duplication already fixed
in #3592/#3637 (BedrockAgentCoreControllerSupport); this one was at
the service layer.
Extracted it into BedrockAgentCoreTagValidation, package-private in
bedrockagentcorecontrol, following the same convention as
BedrockAgentCoreControllerSupport, and pointed both services at it.
No behavior change: the validation rules and error messages are
identical, only their location changed. BedrockAgentCoreToolsIntegrationTest
already asserts on the exact shared error messages
("tag value does not satisfy AgentCore constraints"), so that path is
directly covered. BedrockAgentCoreCredentialProviderService has no
dedicated test in src/test today (a pre-existing gap, not introduced
here); only compatibility-tests/sdk-test-java exercises it.
handleTerminateInstances, handleStartInstances, and handleStopInstances
in Ec2QueryHandler each hand-wrote the same instancesSet/item/
currentState/previousState response shape, a 17-line block repeated
three times, found via CPD (#3703). Extracted it into
buildInstanceStateChangeXml(responseElementName, changes), used by
all three handlers.
No behavior change: the XML shape is identical, only its construction
is now shared. All three response shapes already have direct
RestAssured coverage in Ec2IntegrationTest.
ElastiCacheContainerManager and MemoryDbContainerManager each carried
an identical 21-line readAsciiLineCrLf helper used while probing a
backend container for readiness, found via CPD (#3702). Extracted it
into RespLineReader in elasticache.container, and pointed
MemoryDbContainerManager at it, the same "MemoryDB depends on
ElastiCache's shared Redis-wire-protocol logic" shape
AbstractRedisAuthProxy already follows for the auth-proxy path (#3568).
No behavior change: the logic is identical, only its location
changed. Both container managers already have tests exercising the
PING/PONG readiness probe against a fake socket server.
ScheduleExpressionParser (EventBridge) and SchedulerExpressionParser
(Scheduler) each independently built an identical cron-utils
CronDefinition, a 20-line block duplicated verbatim, found via CPD
(#3701). This included a non-obvious AWS-specific correction (AWS
numbers day-of-week 1-7 as SUN-SAT, not the Unix 0-6 that cron-utils
defaults to, so Monday is 2) that was only explained in one of the
two copies.
Extracted the construction into AwsCronDefinitions.newParser() in
core.common, and pointed both parsers at it. No behavior change: the
definition is identical, only its location changed. Both parsers
already have direct test coverage of the day-of-week quirk
(dayOfWeekOneIsSunday, dayOfWeekTwoIsMonday,
dayOfWeekSevenIsSaturdayAndIsAccepted), so no new tests were needed.
ExecuteApiSigV4Authorizer (API Gateway) and S3HeaderSignatureFilter
(S3) each carried their own copy of containsHeader/isSha256Hex, a
20-line block found duplicated verbatim via CPD (#3700). Moved both
into SigV4RequestValidator in core.common.auth, alongside the other
shared SigV4 primitives (sha256Hex, hmacSha256, deriveSigningKey)
that both callers already use from there, and pointed both call sites
at the shared version. Added direct unit coverage for the two moved
methods, matching this class's existing pattern of pinning shared
primitives independently of any one caller's request flow.
No behavior change: the moved logic is identical, only its location
and visibility changed.
DefaultCacheBehavior and CacheBehavior each had their own ~250-line
hand-written XML-parsing state machine for the same element shape,
found via a CPD pass (#3652). Extracted the shared logic into one
parseCacheBehaviorScope helper, used by both parsing call sites, with
a small CacheBehaviorSettings interface so the helper can populate
either model type.
The duplication had already caused the exact bug it risked: the
CacheBehavior copy never parsed RealtimeLogConfigArn, even though the
field exists on both types in AWS's real CloudFront wire model and on
the CacheBehavior model class itself. The response XML builders for
both types also never emitted it. Fixed both and added a regression
test.
* feat(sfn): support the s3:listObjectsV2 Distributed Map ItemReader
The Map state listed the resource as accepted at CreateStateMachine
but failed every execution with States.ItemReaderFailed. It now calls
the S3 service in process, reads every page under Prefix, and gives
each child the AWS item shape: Etag, Key, LastModified, Size and
StorageClass. Bucket and Prefix come from Parameters or JSONata
Arguments. An empty prefix succeeds with zero iterations and
ReaderConfig.MaxItems trims the list.
LastModified is epoch seconds. Real AWS renders it as a double in
JSONPath state machines and as an integer in JSONata ones, and the
emulator does the same.
Fixes#3409
* fix(sfn): evaluate ItemSelector in JSONata Map states
A JSONata Map state passed ItemSelector through the JSONPath resolver,
so every {% %} expression reached the child as a literal string. The
Map state now resolves ItemSelector as a JSONata template with
$states.input bound to the Map input and $states.context.Map.Item
carrying Value and Index, as on AWS.
Real AWS evaluates ItemSelector before it records MapIterationStarted.
A failing expression therefore fails the Map state without any event
for that iteration, in both query languages. The evaluation moved
ahead of the iteration event to match.
Verified against real Step Functions in us-east-1 on 2026-09-12.
* chore(sfn): simplify the listObjectsV2 reader and the ItemSelector failure path
The reader listed the bucket page by page although the S3 service
returns the whole sorted listing in one call. The Map state kept two
copies of the iteration failure handling. The tests reuse the shared
mapper and one JSONata Map definition.
* perf(sfn): cap the listObjectsV2 listing at MaxItems
ReaderConfig.MaxItems keeps the first keys in key order on AWS, which
is what the S3 service returns for maxKeys. The reader now passes
MaxItems to the listing instead of building every item and trimming
afterwards.
* chore(sfn): declare local types in the listObjectsV2 reader
Replace var with explicit types in the production code this branch added.
* chore(sfn): declare local types in the listObjectsV2 reader tests
Replace var with explicit types in the test code this branch added.
* fix(sfn): list every object when MaxItems is absent
S3Service now treats max keys 0 as a request for an empty page, as AWS
does for max-keys=0. The listObjectsV2 reader passed 0 when
ReaderConfig.MaxItems was not set, so the Map got no items. It now asks
for Integer.MAX_VALUE in that case, like the DynamoDB import path.
* fix(lambda): back off DynamoDB Streams ESM retries and enforce MaximumRecordAgeInSeconds
* fix(lambda): treat unset MaximumRecordAgeInSeconds as no age cutoff
Keep expired records retrying when no finite Lambda age limit is configured.
The nine /v2/email/dedicated-ip-pools and /v2/email/dedicated-ips
endpoints and their WarmupPercentage helper move out of SesController
into SesDedicatedIpController, which injects SesDedicatedIpService only.
SesService drops its eight dedicated-IP delegations and the unused
dedicatedIpPoolExists wrapper; the delivery-options pool probe now binds
the domain service directly, and the ARN tag dispatch stays. The
account-level auto-warmup setting remains under /account. The new class
is registered on the SES descriptor. No wire behavior changes.
* fix(dynamodb): cancel TransactWriteItems on a key that does not match the schema
AWS checks every member's key against the table schema before it looks for
duplicate items or evaluates a condition. A wrong type, a non-scalar value or a
missing key attribute cancels the transaction. The first such member gets a
ValidationError reason and every other member gets None. An empty key value
still fails the whole request. Floci returned a top-level ValidationException.
An Update that sets an index key to the wrong type now cancels as well, in both
TransactWriteItems and ExecuteTransaction.
Checked against DynamoDB in eu-west-2.
* fix(dynamodb): look up an active table in the transaction key check
The key check read the table through describeTable. That call counts every
item in the table on each member, and it accepts a table that is still
CREATING. DynamoDB answers ResourceNotFoundException "Requested resource not
found" for a CREATING table even when a member key is wrong. Use the same
active table lookup as the other transaction steps.
Checked against DynamoDB in eu-west-2.
* fix(cloudformation): claim change set atomically before execution
ExecuteChangeSet checked that a change set was AVAILABLE and executed
it as two separate steps, with no lock held in between. Two concurrent
ExecuteChangeSet requests for the same change set could both pass the
AVAILABLE check before either flipped the status, so both would submit
the template for provisioning and create every resource in the stack
twice. The internal 4-arg executeChangeSet that CreateStack/UpdateStack
call directly had the same race against an external ExecuteChangeSet
call for the same change set, for example "initial-create" right after
CreateStack creates it.
Unify both entry points behind one atomic claim, claimAndSubmitExecution,
using the same ConcurrentHashMap#compute() idiom createChangeSet already
uses for its own check-then-insert race. The request path requires
ExecutionStatus AVAILABLE, matching AWS; the internal path only refuses
a change set whose execution has already started or finished, so a
failed SAM transform can still reach CREATE_FAILED. Inside the same
claim, every other change set on the stack is deleted, matching AWS's
documented ExecuteChangeSet behavior that executing a change set
deletes every other change set on that stack. After the background
execution finishes, the claimed change set's ExecutionStatus is set to
a terminal EXECUTE_COMPLETE or EXECUTE_FAILED so DescribeChangeSet
stops reporting EXECUTE_IN_PROGRESS forever. The rejection message now
reports the execution status that actually caused the rejection
instead of the change set's unrelated Status field.
* fix(cloudformation): mark pending change sets obsolete on direct stack updates
executeNestedStack detected a failed child only by checking for the
literal statuses CREATE_FAILED/UPDATE_FAILED. rollbackFailedExecution
always overwrites those into a ROLLBACK_* status before returning, so
the check could never match on a create: a nested stack whose own
resource loop failed and rolled back was reported to the parent as
CREATE_COMPLETE regardless, with its Outputs never computed. Every
later Fn::GetAtt on that child's Outputs then fell back to a garbage
literal string, and the parent kept going instead of rolling back.
Replace the failure-string check with a closed allow-list of the
terminal statuses under which executeTemplate actually finished and
computed Outputs. An allow-list rather than a deny-list deliberately:
an unrecognized future status now defaults to failure instead of
silently defaulting to success.
* feat(sfn): apply ItemBatcher to distributed Map children
ItemBatcher was parsed and then ignored: every child execution received one
item regardless of MaxItemsPerBatch, so a state machine that batches ran with a
different payload shape locally than on AWS, silently.
Items are now grouped into batches and each child execution receives
{"BatchInput": ..., "Items": [...]}. A batch closes on MaxItemsPerBatch or
MaxInputBytesPerBatch, in their literal, Path and JSONata expression forms, and
with neither set every item lands in one batch. ItemSelector still runs per item
before grouping, so the transform sees $$.Map.Item as it did before.
MaxConcurrency now bounds concurrent batches, and DescribeMapRun separates the
two counters it used to share: itemCounts counts items, executionCounts counts
child executions.
* fix(sfn): cap a batch at the 256 KiB child-input ceiling
MaxInputBytesPerBatch being optional let MaxItemsPerBatch alone build a child
input larger than Step Functions would ever start, and the byte count measured
the items alone, so a declared cap could still be exceeded by the envelope,
BatchInput and separators.
Batching now measures the serialized child payload and closes a batch at the
declared limit or at 256 KiB, whichever is smaller.
* fix(sfn): fail an item too large to start a child execution
An item whose serialized batch input already exceeded 256 KiB was added anyway,
because the split branch is skipped while the batch is empty, producing a child
input AWS would refuse to start.
Such an item now fails the state with States.DataLimitExceeded, naming its size
and pointing at ItemSelector as the way to reduce it.
* feat(sfn): honour ToleratedFailureCount and ToleratedFailurePercentage
Both fields were accepted and ignored: any failed item failed the Map run, and
DescribeMapRun reported a hardcoded zero for each, so a state machine that
relies on a failure budget behaved differently here than on AWS.
A declared tolerance now absorbs failed items while the run stays within it. An
absorbed failure contributes no result, so the Map output and any ResultWriter
export cover the successful children only. Exceeding the budget fails the state
with States.ExceedToleratedFailureThreshold. Both fields accept their literal,
Path and JSONata expression forms, the percentage is taken over the item count,
and declaring both applies the stricter of the two.
DescribeMapRun now reports the declared values. A Map that declares neither is
unchanged: the first failed item still fails the state with its own error.
* fix(sfn): export tolerated failures to FAILED_0.json
Filtering the ResultWriter input down to the successful children dropped every
absorbed failure from the export, which is exactly what the tolerance is meant
to keep observable.
Failed children now keep their input, timings and error, and are written to
FAILED_0.json with Status FAILED and the child's Error and Cause, listed under
ResultFiles.FAILED in the manifest.
* refactor(sfn): resolve every integer Map field through one helper
MaxConcurrency and the ItemBatcher limits read the same three forms, literal,
Path and JSONata expression, through two near-identical methods. The batcher one
already parameterized the field name, so the pair collapses into a single
resolver with a minimum: 0 for MaxConcurrency, where it means the service
ceiling, and 1 for a batch limit, where it is meaningless.
The shared resolver also clamps an oversized value to Integer.MAX_VALUE, which
only the MaxConcurrency copy did before.
* feat(config): add aggregation authorization CRUD
PutAggregationAuthorization, DescribeAggregationAuthorizations and
DeleteAggregationAuthorization were unrouted, so the JSON handler answered
InvalidAction and aws_config_aggregate_authorization could not be created.
Authorizations are keyed by (AuthorizedAccountId, AuthorizedAwsRegion) within
the request region, persisted through StorageFactory like the other durable
Config resources. Put is an upsert that preserves the ARN and creation time of
an existing authorization, and accepts Tags, which land in the same tag store
that ListTagsForResource reads. Delete of an absent authorization succeeds: the
Config model declares no not-found error for that operation.
* fix(config): remove aggregation-authorization tags on every delete attempt
Tag cleanup ran only when the delete found an entry to remove. A delete that
removed the authorization but did not reach the tags left them behind, and the
retry that should have cleaned them up skipped the cleanup because the entry
was already gone. Put reuses a deterministic ARN, so those tags reappeared on
the next authorization for the same account and region.
The ARN is now derived from the key instead of read off the removed entry, and
its tags are dropped on every attempt. The authorization map is still persisted
only when an entry was actually removed.
* fix(config): apply PutAggregationAuthorization tags at creation only
PutAggregationAuthorization is idempotent, and AWS applies request tags at
creation only: a later Put that finds the authorization already there ignores
its Tags and leaves the existing ones alone. Tagging the existing ARN on every
Put let a local test retag by re-putting, which production would silently
refuse.
Return the existing authorization untouched and tag only the one just created.
Tags still change through TagResource/UntagResource, which is the only way AWS
offers.
* fix(config): make aggregation authorization put/delete atomic
putAggregationAuthorization did a get-then-put on the region map with nothing
holding the two together, and deleteAggregationAuthorization removed-then-
persisted the same way. Two concurrent Puts for one (AuthorizedAccountId,
AuthorizedAwsRegion) could both find nothing and both create: the second
overwrote the first's CreationTime and re-applied creation tags over a set
TagResource may already have changed, so the documented idempotency held only
probabilistically.
Both now take the same per-key lock putConfigRule/deleteConfigRule already use
for rules. The lock keys are namespaced apart from the rule keys in the shared
map rather than relying on rule names never containing '|'.
The regression runs many short rounds rather than one wide one, because the
unlocked window is a few instructions: repeated fresh starts land the race,
more threads on one start do not. It asserts reference identity, which is what
distinguishes the two cases -- the store is keyed on the pair so its size is 1
either way, the ARN is derived from the key so it is equal either way, and
CreationTime is epoch seconds so a racing pair created inside one second is
indistinguishable by timestamp. Verified to fail with the lock removed
(17 mismatches) and pass with it, five runs.
* fix(elbv2): round-trip the authenticate-oidc and authenticate-cognito configs
Action carried no fields for either authentication action, so CreateListener,
CreateRule, ModifyListener and ModifyRule accepted an AuthenticateOidcConfig
or an AuthenticateCognitoConfig and kept only Type and Order. DescribeListeners
and DescribeRules then echoed an action with no Issuer, no UserPoolArn and no
other sub-field, and a client that read its own configuration back saw the
listener as changed on every read.
Both configs are now parsed on all four write operations, stored on the action
and written into the Describe response. SessionCookieName, Scope and
SessionTimeout take the defaults their shapes document, since AWS reports the
resolved value rather than the caller's gap, and the members each shape marks
required are rejected with ValidationError when absent.
ClientSecret is stored but never reported. Real AWS omits it from every
Describe call, which is why Terraform's provider carries it forward from local
state instead of reading it back.
* fix(elbv2): require the OIDC client secret on create and keep it on modify
Review feedback on #3664. parseAuthenticateOidc accepted a missing ClientSecret
on every write and never read UseExistingClientSecret. AuthenticateOidcActionConfig
requires the secret when creating and lets a modify omit it only when
UseExistingClientSecret is true, so a create without one was accepted where AWS
refuses it.
The sharper half is the modify path pgermosen described. Both modify operations
replace the action list wholesale through this same parser, so the documented way
to keep a secret, sending UseExistingClientSecret with no ClientSecret, blanked
the secret instead of preserving it.
parseActions now knows create from modify. A create without the secret is
rejected. A modify may drop it only by asking for the stored one, and
applyExistingClientSecrets puts that secret back before the action list replaces
the old one. A modify that drops the secret without the flag is rejected.
Three tests cover create-without-secret rejection, the modify that preserves and
can then preserve again, and the modify that drops it with no flag. Also imports
RequestSpecification rather than spelling it inline, per the review nit.
* fix(ecs): report serviceConnectConfiguration on the service's deployment
CreateService and UpdateService accepted a serviceConnectConfiguration and
dropped it. DescribeServices then reported nothing, so a client that sets one
saw it missing on every read.
AWS's Service shape declares no serviceConnectConfiguration member. The field
lives on Deployment, which is where a generated client reads it and where
Terraform's aws_ecs_service reads it. Storing it on the service and reporting
it on each deployments[] entry matches the model, and a client that reads it
back no longer sees a pending change on every plan.
The widest createService and updateService overloads take the configuration;
the previous signatures delegate to them, so existing callers are unchanged.
* fix(ecs): roll the deployment when serviceConnectConfiguration changes
Review feedback on #3662. UpdateServiceRequest.serviceConnectConfiguration is
documented as "This parameter triggers a new service deployment", and the
rollover below only fired on a task-definition change or forceNewDeployment. A
Service-Connect-only change therefore reported the new configuration under the
old deployment id and skipped SERVICE_DEPLOYMENT_STARTED.
updateService now treats a changed configuration as deployment-triggering state,
alongside the two conditions already there. An omitted parameter stays a no-op,
and resending an identical configuration is not a change.
Three tests cover it. A changed configuration rolls the deployment id, an
identical one does not, and an update that omits the parameter does not. None of
the original four asserted on deploymentId, which is why they passed.
* feat(network): add opt-in security group enforcement
* fix(ec2): make security group tests order independent
* fix(network): emit valid ICMP nft rules and restart protected instances
Three review findings on the opt-in security-group enforcement foundation:
- SecurityGroupNftCompiler built "icmp type 8 code 0 accept" for an AWS
ICMP rule carrying both FromPort (type) and ToPort (code). nftables
header fields are separate expressions, so nft rejected the whole
compiled policy and the manager then quarantined every endpoint. Each
field now repeats the protocol keyword, and a protocol rule with no
type or code becomes "meta l4proto icmp accept", which was equally
invalid as a bare "icmp accept".
- StartInstances followed the legacy restart path for a protected
workload and waited for a Docker bridge IP on a container that shares
the helper's network namespace and so has no attachment of its own.
The helper survives the workload's stop, so start now reuses its
transport address exactly as launch does, and skips the reachable
private address rewrite the same way.
- Replaced the newly introduced var declarations with explicit types and
imported the inline java.util/model FQCNs, per AGENTS.md.
* fix(network): scope the firewall helper to CAP_NET_ADMIN
The helper only has to program nftables inside the namespace Docker already
gave it, so full --privileged granted far more than the feature needs.
ContainerLifecycleManager now adds CAP_NET_ADMIN for the container carrying
the floci.security-group-helper label, mirroring the capability drop already
applied to protected workloads at the same choke point, and the helper spec
no longer asks for privileged mode.
Also replaces the inline java.util FQCNs the previous commit missed in
Ec2Service with imports, per AGENTS.md.
---------
Co-authored-by: Alexy Grabov <Alexy.Grabov@cyberark.com>
* fix(cloudwatch): return DatapointsToAlarm from the JSON DescribeAlarms response
The Query/XML handler has always written DatapointsToAlarm, TreatMissingData
and Unit into its alarm element. The JSON/CBOR builder in
CloudWatchMetricsJsonHandler.handleDescribeAlarms never emitted any of the
three, so a client speaking smithy-rpc-v2-cbor or application/x-amz-json-1.0
to CloudWatch saw them missing from every DescribeAlarms response. Recent
botocore and AWS CLI versions default to CBOR for this service, so that is the
common path.
PutMetricAlarm already parsed and stored all three on both protocols, so only
the response builder needed the fields.
* fix(cloudwatch): report DatapointsToAlarm only when the caller set one
Review feedback on #3660. Emitting the field unconditionally broke Terraform
idempotency, and native arm64 / compat-terraform caught it. PutMetricAlarm
defaulted DatapointsToAlarm to EvaluationPeriods at storage time for the
evaluator's M-out-of-N maths, and the primitive int on MetricAlarm left nothing
to distinguish a caller's value from that default. Every alarm then reported a
number nobody asked for, and compat-terraform's alarm, which sets no
datapoints_to_alarm, drifted on every re-plan.
MetricAlarm now holds a nullable Integer carrying only what the caller sent.
AlarmEvaluator supplies EvaluationPeriods for the maths instead, so evaluation
is unchanged. Both response builders emit the member only when it is set, which
closes the same latent gap on the Query path.
CloudWatchCfnProvisioner also minted a value from EvaluationPeriods, so a
template that names no M now leaves the alarm without one. Its two tests move
with it, and a third covers a template that does name one.
The class is shared by LaunchedContainerAwsEnv, EC2 and CloudFormation, not
only Lambda. Follow-up to the #3579 review.
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* feat(redshift): implement zero-ETL integrations
DescribeIntegrations had no implementation, so an application that
discovers its zero-ETL integration at runtime could not run against the
emulator.
Implementing that action alone would have been worse than leaving it out.
A caller matches its integration by SourceArn and treats "no match" as a
hard error, so an action that always answered with an empty list would turn
a clean "unsupported" into a confusing "no integration whose source is the
X table". CreateIntegration and DeleteIntegration come with it, so an
integration can exist and the empty list means what it says.
Shape captured from a live integration in us-west-2:
- Status is lower case ("active"), not ACTIVE
- Errors is present but empty on a healthy integration
- the record carries IntegrationArn, IntegrationName, SourceArn,
TargetArn, Status, CreateTime, KMSKeyId, Tags and
AdditionalEncryptionContext
- describing with an unknown IntegrationArn is IntegrationNotFoundFault,
"The requested integration doesn't exist."
- an account with no integrations answers with an empty list, not an
error
- no Marker element is emitted when there is no further page, which is
what stops a caller's pagination loop
This is metadata only: nothing replicates from the source, and the
integration settles as active immediately rather than passing through
creating, because there is no work for it to do.
* fix(redshift): correct the integration Query contract
Three gaps against the modelled Query API, each confirmed in the bundled
botocore service model rather than taken on trust.
Tags arrive under TagList, not Tags. The shape is a list whose member
carries locationName Tag, so a real client sends TagList.Tag.N.Key and
.Value. Reading Tags.Tag.N meant every tag an SDK sent was silently
dropped, which a hand written form-encoded test did not catch because it
used the wrong name too.
DescribeIntegrations is paginated and filterable. MaxRecords, Marker and
Filters.DescribeIntegrationsFilter.N were all ignored, so the operation
only worked while every record fitted in one response and a caller using
filters got unrelated integrations back. MaxRecords honours the documented
20 to 100 range, the marker is the last ARN already returned rather than an
offset, and no Marker is emitted on the terminal page. The four modelled
filter names are implemented: integration-arn, source-arn, source-types and
status. An unrecognised name is rejected rather than ignored.
CreateIntegration advertises Description and AdditionalEncryptionContext.
Both are now parsed, stored and rendered, with the documented rule that the
encryption context is only valid alongside a KMSKeyId, and Description
capped at the modelled 1000 characters.
* test(redshift): cross a real page boundary in the marker regression
The previous test created three integrations and asked for twenty, so it
only proved the terminal case: no Marker when everything fits. It never
forced a second page, never asserted a non-terminal page carries a Marker,
and never sent one back.
It now creates twenty-one records against the smallest legal page size and
walks every page, asserting that a full page carries exactly MaxRecords
records and a Marker, that no record appears on two pages, that the final
page omits the Marker, and that the traversal returns the same set as a
single large page. Other tests in this class share the store, so the
assertions are about the traversal rather than absolute counts.
* feat(redshift): validate IntegrationName against the modelled pattern
CreateIntegration only checked IntegrationName for non-blank, so a name
real AWS refuses was accepted: the member is modelled min 1, max 63,
pattern ^[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*$. A leading digit or
hyphen, an underscore, a doubled hyphen and a trailing hyphen all got
through, as did a name over 63 characters.
Validate both constraints in createIntegration, alongside the existing
Description length and encryption-context rules.
Three regressions cover the rejected shapes, the over-length case and
acceptance at the 63 character boundary.
* refactor(redshift): deduplicate RedshiftContainerManager startup and adoption sequence
Extract the shared post-acquisition initialization and registration sequence into a private helper method used by both start() and adoptOrStart().
Add unit test coverage verifying log streamer attachment and failure tolerance across both container startup paths.
Closes#3653
* test(redshift): use static Mockito answer import
* fix(apigateway,appsync): sandbox VTL rendering with SecureUberspector and execution limits
VtlTemplateEngine and AppSyncVtlEngine rendered templates with Velocity's
default UberspectImpl introspector, which allows arbitrary reflection
through any context object (e.g. $util.getClass().forName('java.lang.Runtime')),
and had no cap on #foreach iterations, output size, or execution time,
making them vulnerable to both sandbox escapes and denial of service via
runaway loops or #set string doubling.
Add a shared VtlSandbox helper that both engines call to switch to
SecureUberspector and restrict introspection on java.lang.Class,
ClassLoader, Runtime, ProcessBuilder, System, Thread, java.io.File and
related reflection/scripting/process packages, plus three independent
limit layers: a native #foreach loop cap that truncates the loop without
failing the template, a cooperative execution deadline checked from a new
SandboxedForeach directive before each loop iteration, and a BoundedWriter
output-size cap. The latter two throw the new VtlLimitExceededException,
an unchecked RuntimeException that flows through each engine's existing
error handling exactly like any other Velocity evaluation failure, with
no new error shape. Limits are configurable via EmulatorConfig
(vtlMaxLoops, vtlMaxOutputChars, vtlTimeoutMillis; application.yml keys
vtl-max-loops, vtl-max-output-chars, vtl-timeout-millis), mirroring the
project's existing per-service numeric-tunable config pattern, and
documented in api-gateway.md and appsync.md.
The classpath-shadowed velocity.properties resource is kept for any
embedding that resolves it normally, but is not the actual enforcement
point: under this project's test/runtime classloader, Velocity's own
getResourceAsStream lookup for that exact resource path can resolve to
the copy bundled inside the velocity-engine-core jar instead of this
project's shadowed copy, silently leaving the insecure UberspectImpl
active even with a correct properties file on disk. VtlSandbox configures
SecureUberspector and swaps in SandboxedForeach directly via the
VelocityEngine Java API instead, which is unaffected by that ambiguity.
* docs(apigateway): correct foreach registration documentation
* fix(s3): support virtual-hosted routing via X-Forwarded-Host and prevent unintended bucket creation
- Respect X-Forwarded-Host when resolving host for reverse proxy compatibility
- Support tail-agnostic .s3.<region>.<domain> qualifier and fallback lookup against existing buckets
- Reroute misplaced single-segment object/multipart uploads or reject with InvalidBucketName/MalformedXML
- Add unit and integration tests for virtual-hosted requests forwarded through proxies
* docs(s3): translate virtual host routing comment
* fix(apigateway): reject method request parameter names AWS refuses
API Gateway restricts a method request parameter name to
^[a-zA-Z0-9:._$-]+$. floci applied no validation, so a spec that real AWS
refuses imported cleanly against the emulator and only failed on deploy,
which is the direction that costs the most to discover.
The limitation is undocumented. Measured against real AWS (us-west-2),
both entry points reject a name outside the set:
PutMethod
BadRequestException: Invalid mapping expression specified:
Validation Result: warnings : [], errors : [Parameter name should
match the following regular expression: ^[a-zA-Z0-9:._$-]+$]
ImportRestApi
BadRequestException: Errors found during import: Unable to put
method 'GET' on resource at path '/items': <the message above>
$ : . _ - are inside the set, so a JSON:API style filter[a] cannot be
imported while filter.a can, which is the workaround applications adopt.
The rule covers query string, header and path parameters alike, and
applies whether or not the parameter is required.
Validation lives in putMethod, the choke point both entry points share.
The import path rethrows it under the envelope AWS uses there, naming the
method and resource path.
Only the declared name is restricted. At runtime a request carrying
?filter[a]=1 reaches a proxy integration with the brackets intact, so
this is not a general ban on the character in a query string, and nothing
on the execute path changes.
* docs(apigateway): attach the parameter-name javadoc to the method it describes
The javadoc for validateRequestParameterNames sat above
importParameterNameFailure, which carried its own javadoc directly
beneath it. Move it down onto the method it documents.
No behavior change.
* fix(ec2): honor RunInstances dry run before provisioning
* fix(ec2): validate launch input before dry-run success
* fix(ec2): validate dry runs through the launch service