mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
ea1231b8b464fab61e013403eb6ebd69d81aee04
971
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ea1231b8b4 |
fix(rds): restore Terraform RDS and RabbitMQ compatibility (#1951)
* fix(rds): support dbi resource id filter * fix(mq): omit RabbitMQ users from broker response |
||
|
|
a5daab6fb7 |
fix(lambda): reconcile code volumes against real Docker state and clean up superseded ones (#2208)
* fix(lambda): reconcile code volumes against real Docker state and clean up superseded ones Fixes #2164 Three problems in ContainerLauncher's per-function-version code volume management, all stemming from the same root cause: the "populated" bookkeeping was purely in-memory, never checked against or reconciled with Docker's actual state. - Stale volumes were never cleaned up on redeploy, only ever reclaimed by a user manually running docker volume prune. Now tracks each function's current volume and queues the superseded one for cleanup. - The in-memory "already populated" flag was trusted without ever re-checking Docker, so a volume removed out of band (manual docker volume rm, or an out-of-band prune) would silently mount an empty /var/task into the next container. ensureCodeVolume now also checks lifecycleManager.volumeExists() before trusting the flag. - Both of the above are really the same problem: no reconciliation against real Docker state. Fixed together by the same change. Cleanup is deferred rather than immediate: Docker auto-creates an empty named volume for a container mount that doesn't reference an existing one rather than failing, so a launch that resolved the old volume name just before a redeploy, but hasn't created its container yet, could be handed an empty /var/task by an immediate delete. A 60-second grace period, swept by a scheduled background task, crosses that window safely; removeVolume() also no-ops if the volume is still genuinely in use by then. * fix(lambda): rescue rolled-back code volumes and retry failed cleanup Addresses two review findings on the volume reconciliation fix: - The fast-path early return in ensureCodeVolume skipped the bookkeeping update entirely, so rolling back to a previous code version (v1 -> v2 -> v1) resolved v1's already-populated volume without pulling it back out of the pending-cleanup queue or marking it current again. The next sweep would delete the volume the function was actively using again. The bookkeeping reconciliation now always runs, whether or not the volume needed repopulating. - cleanupSupersededVolumes discarded a pending-cleanup entry unconditionally before attempting deletion, so a volume that Docker refused to remove (still in use by a slow-draining container that outlived the grace period) was silently dropped with no later sweep ever retrying it, permanently orphaning it. Now re-checks volumeExists after the delete attempt and re-queues with a fresh timestamp if the volume is still there. * fix(lambda): close the cleanup-vs-rollback race on code volumes Addresses a review finding: ensureCodeVolume's bookkeeping reconciliation and cleanupSupersededVolumes' claim-and-delete both touched volumesPendingCleanup with no mutual exclusion between them. If cleanup atomically claimed a superseded volume's entry a moment before a concurrent rollback resolved that same volume, the rollback would mark it current and hand it to a new container while cleanup proceeded to delete the real Docker volume out from under that launch - the exact empty /var/task failure mode the grace period exists to prevent, reached through the rescue path instead. Both methods now synchronize on the same per-volume-name lock (codeVolumeLocks) for their full resolve-or-claim-and-reconcile section, not just the expensive populate step. Whichever side wins the race, the other reliably observes the result under the lock rather than acting on stale state. Added a deterministic concurrency test using latches to force cleanup to block mid-deletion while still holding the lock, and assert a concurrent rollback blocks too rather than racing past it. Confirmed it fails against the previous commit (rollback completes immediately, racing past cleanup) and passes with this fix. * fix(lambda): stop pruning code-volume locks, closing a lock-identity race Addresses a review finding on the mutual-exclusion fix: pruning a volume's entry from codeVolumeLocks while a waiter elsewhere still held a reference to the removed entry's lock object let a third caller's computeIfAbsent create a replacement lock object for the same volume name. The original waiter (once granted the old lock) and that third caller (holding the new one) could then run their supposedly mutually-exclusive sections concurrently, reintroducing the exact cleanup-vs-rescue race the previous commit closed. The map is now never pruned. Each entry is a single Object keyed by volume name, bounded by the number of distinct function+code-version combinations ever launched, and negligible next to the disk space the rest of this fix reclaims - not worth the correctness risk of trying to bound it. Added a direct test verifying the actual invariant this depends on: a volume's lock entry survives a full populate-then-cleanup-delete cycle unchanged. The real interleaving that triggers this race needs precise JVM thread-scheduling control that isn't reliably forceable in a test, so this proves the fix by construction instead - confirmed it fails (both by compile error, since the accessor is new, and by a genuine runtime assertion failure when the removal is surgically reintroduced) without the fix and passes with it. * fix(lambda): give removeVolume a definitive success signal for cleanup retry Addresses a review finding: cleanupSupersededVolumes decided whether a deletion actually succeeded by making a second, separate call to volumeExists() afterward. That call's own exception handling treats a transient Docker API failure (a network blip, the daemon momentarily busy) the same as "confirmed does not exist", so a transient failure during that specific verification call, following an in-use no-op from removeVolume, would make cleanup wrongly conclude the volume was gone and drop it from the retry queue for good - the same permanent-loss bug fixed two commits ago, reachable through a different trigger. ContainerLifecycleManager.removeVolume now returns whether the volume is confirmed gone (removed, or already absent) rather than void. cleanupSupersededVolumes uses that return value directly instead of a second ambiguous check, so the failure mode described above can no longer happen: any removal attempt that isn't positively confirmed successful, for any reason, correctly retries on the next sweep. The other three real callers (EksClusterManager, MwaaEnvironmentManager, ContainerStorageHelper) all treat the call as fire-and-forget and don't need any changes; a void-to-boolean change doesn't break callers that ignore the return value. Verified with the full lambda and core.common.docker packages (550 tests, only the same pre-existing unrelated failures) plus the eks/mwaa/rds packages that call the other real usages of this method (one pre-existing, unrelated failure in RdsContainerManagerTest, confirmed identical against an unmodified upstream/main baseline in a throwaway worktree). * fix(lambda): protect in-flight code volumes from premature cleanup A launch that resolves its code volume name (ensureCodeVolume returns and releases the volume's lock) but hasn't yet called lifecycleManager.create() has no real Docker container-to-volume reference for removeVolume()'s own in-use check to protect. The fixed grace period isn't a safe upper bound on that gap either: create() itself has no proven bound on its duration (this file's own history notes it observed taking ~80s under daemon load, longer than the default 60s grace period). If a redeploy supersedes that volume and the grace period elapses while the original launch is still stuck before create(), a sweep can delete the volume out from under it, handing the container an empty /var/task once create() finally runs (Docker auto-creates an empty volume for a mount referencing a name that no longer exists rather than failing). Adds true in-flight reference counting instead of relying on elapsed time: ensureCodeVolume increments a per-volume counter before returning (still under the volume's lock, so a concurrent sweep that acquires the same lock next is guaranteed to observe it), and the caller releases it in launch() once create() succeeds - or in the existing catch-all failure handler if it never gets that far. cleanupSupersededVolumes re-queues rather than deletes any volume whose count is still nonzero, regardless of how long it's been queued. Verified: new test forces a second launch of an already-populated volume to block right before create() while a redeploy supersedes it and the grace period is made to elapse instantly; cleanup must skip it while the count is nonzero and only remove it once the delayed launch completes and releases its reference. Confirmed the test fails (cleanup deletes the volume mid-flight) with the guard temporarily disabled, and passes with it restored. Full lambda.launcher and core.common.docker package regression (174 tests) is green. * fix(lambda): serialize the current-volume transition per function pgermosen's review on this PR pointed out that functionCurrentVolume and volumesPendingCleanup are reconciled under the per-volume lock only. Two code versions of the same function resolve to two different volume names, so they acquire two different codeVolumeLocks entries and can run that reconciliation concurrently - which is fine for the populate work each guards, but not for this transition. Without a shared lock, a rapid back-to-back redeploy (v2 then v3) can have the two functionCurrentVolume.put() calls land out of order: whichever one happens to execute last wins as "current" regardless of which redeploy was actually latest, and the volume it displaces gets queued for cleanup using a "previous" value each thread captured locally right before its own put() - so if v2's full transition runs after v3's, v3 (briefly and correctly current) ends up queued for deletion while stale v2 is left recorded as current. Adds a per-function lock (functionVolumeTransitionLocks, keyed by function name rather than volume name) around just this transition. It doesn't and can't guarantee which redeploy "wins" when two race genuinely concurrently - that would need ordering information this method isn't given - but it does guarantee the bookkeeping itself stays self-consistent: whichever volume ends up current is never also left in the pending-cleanup set, and whatever it displaced is queued exactly once. Verified: the transition's three statements are plain map operations with no interception point inside them, so forcing the exact bad interleaving isn't reliably doable in a test. Instead added a test proving the fix's actual mechanism - a concurrent launch for a second code version of the same function blocks on the same per-function lock object while another launch holds it - the same style already used for the per-volume lock in cleanupAndAConcurrentRollback_areMutuallyExclusiveForTheSameVolume. Confirmed the test fails when the lock is swapped for an unshared one and passes with the real lock restored. Full lambda.launcher and core.common.docker package regression (175 tests) is green. |
||
|
|
6344852540 |
fix(lambda): reassemble container log lines split across Docker frames (#1953)
* fix(lambda): reassemble Docker log frames into complete lines Buffer stdout and stderr independently, emit complete UTF-8 lines, and finalize trailing tails only after Docker has stopped or its reader reaches a terminal state. * fix(codebuild): retain buildspec overrides when retrying builds Keep request-scoped buildspec overrides alongside transient build state so RetryBuild executes the same source-less build definition as the original request. * fix(ecs): finalize logs after force-removing tasks Keep Docker force removal available after stop failures and release task log handles once removal has terminated their transports. * fix(ecs): retain logs for containers that survive teardown Track ECS log handles by Docker ID so teardown finalizes only containers that have stopped, disappeared, or been force-removed. * fix(ecs): retry unresolved log stream teardown |
||
|
|
40e8aad55a |
feat(lambdamicrovms): AWS Lambda MicroVMs service module and its CloudFormation types (#2079)
* feat(lambdamicrovms): AWS Lambda MicroVMs service module Adds the Lambda MicroVMs control plane, a service AWS took GA on 2026-06-22: MicroVM images with a version and build lifecycle, the managed base-image catalog, MicroVM CRUD, and VPC egress network connectors. Two service models rather than one. Lambda Microvms (apiVersion 2025-09-09) carries images and MicroVMs under /2025-09-09; Lambda Core (2026-04-30) carries network connectors under /2026-04-04. Both sign as lambda, so their requests arrive under the existing lambda claim in ResolvedServiceCatalog and route by path. Neither prefix collides with anything LambdaController serves, and both are enabled by the lambda service rather than adding a toggle. Tagging rides the classic /2017-03-31/tags/ routes, so LambdaTagController learns the MicroVM ARN forms. Resources are stored per account and region. Floci resolves a per-request account in AccountContextFilter and these ARNs carry it, so region-only storage would let two accounts sharing a region read and mutate each other's images, MicroVMs and connectors. Wire shapes come from the vendored service models and, where the models are silent or disagree with the service, from responses recorded against live AWS. Several members the models mark optional are enforced in practice — a connector needs ClientToken, OperatorRole, NetworkProtocol and AssociatedComputeResourceTypes despite all four being optional in Smithy — and several resources are returned in a different projection per operation: an image in four shapes, a connector in four, with only the list summaries carrying Type. Builds converge instantly rather than on a timer, the usual emulator trade. Where that would otherwise produce an inconsistent body it is handled explicitly: a create or update reports the transitional state and does not name the version it is minting as active, because a client reading otherwise would launch a MicroVM off a version that does not exist yet. Auth tokens, the per-VM endpoint, and the idle and suspend timers are deliberately out of scope here; they belong to a full-fidelity MicroVMs emulator rather than to CloudFormation provisioning. Verified against a suite of responses recorded from live AWS (https://github.com/INTENTIUS/m80): 26 checks over the image, MicroVM and connector lifecycles, 0 failures. * feat(cloudformation): provision AWS::Lambda::MicrovmImage and AWS::Lambda::NetworkConnector Registers a CfnResourceProvisioner for the two MicroVM CloudFormation types against the LambdaMicrovmsService added alongside, so a template declaring either provisions and deletes rather than being skipped. Uses the CloudFormationResourceRegistry interface rather than the switch in CloudFormationResourceProvisioner, following SqsCfnProvisioner. * test(lambdamicrovms): AWS CLI compatibility coverage for images, MicroVMs and connectors * fix(lambdamicrovms): wire service state through StorageFactory Images, MicroVMs and connectors were held in plain in-memory maps, so in persistent mode a restarted Floci lost them while the CloudFormation stacks that created them survived. Those stacks then referenced resources that no longer existed and DeleteStack failed on the 404. The three stores are now StorageBackedMap over StorageFactory backends, keyed region/id. MicroVMs are delivered as part of the lambda service, so they share its storage key and therefore its configured mode and flush interval rather than declaring their own. The account half of the key is dropped from the service and left to the backend, which prefixes and strips the same account the RegionResolver returns, so region and account isolation are unchanged. StorageBackedMap only marks the backend dirty on put and remove, so every path that mutated a stored object in place now writes it back: image update, version status, version delete, rebuild, MicroVM settle and terminate, connector settle and update, and both tag paths. * style(core): import the lambda microvms controllers in the service catalog * fix(lambdamicrovms): register the persisted types for reflection Moving images, microvms and connectors into StorageBackedMap made their model classes persisted types, and PersistedModelReflectionTest fails on any that lack @RegisterForReflection because native-image persistence cannot rebuild them on restart. |
||
|
|
0cfffbea00 |
fix(kms): reject mismatched keys in decryption requests (#1893)
* fix(kms): reject mismatched keys in decryption requests * fix(kms): reject mismatched keys in reencryption requests * fix(kms): verify if key is usable for cryptographic operations |
||
|
|
15d6ce8429 |
fix(s3): DeleteObjects honours empty key list (#2201)
Fixes : #2198 Co-authored-by: Krishnan Mahadevan <kmahadevan-bidgely@users.noreply.github.com> |
||
|
|
f417164d42 |
fix(rds): advertise reachable endpoints (#2074)
RDS endpoints currently expose the proxy's container port even when Docker publishes it on a random host port. That works when the host can route to the container network, but fails with VM-backed Docker runtimes. Resolve the current container's published port when an external endpoint host is configured while preserving the internal proxy port used by the listener. |
||
|
|
28e9f6ed63 |
fix(apigatewayv2): encode binary Lambda request bodies (#2203)
* test(apigatewayv2): cover binary Lambda request payload Change-Id: Iae344954b576b49826164e0f5e68964f86198cd4 * fix(apigatewayv2): encode binary Lambda request bodies Change-Id: I5e32fe304c932878afdbf5be0c3c773595364ff0 * test(apigatewayv2): cover request body encoding matrix Change-Id: Id16e0cc81f6806afa50d8db8c6ac1cb7897af6f6 * fix(apigatewayv2): accept UTF-8 text media parameters Change-Id: Ibf82062b9345ebd80d722b497a15e60d62dce86d * test(apigatewayv2): make binary payload cleanup best effort Change-Id: Ib62dc80c73eb1836007b4492ccfda965da03f6ac * revert(apigatewayv2): keep measured AWS media matrix Change-Id: Ibbf8d8bca8d9967bf84628773cc08a991ffea6a1 |
||
|
|
bd01c1a70b |
feat(ses): implement SendCustomVerificationEmail for v1 and v2 (#2191)
* feat(ses): implement SendCustomVerificationEmail for v1 and v2
Add the SendCustomVerificationEmail action on both the v1 Query API and the v2 REST
JSON API (POST /v2/email/outbound-custom-verification-emails). The service renders the
stored custom-verification-email template into the inspection mailbox and the SMTP
relay, returns a MessageId, and registers the recipient as a pending-verification
identity, matching AWS. A missing template is the v1-native
CustomVerificationEmailTemplateDoesNotExist (remapped to NotFoundException on v2), with
the v1 send message ("Template <name> does not exist") verified against AWS.
* test(ses): log custom-verification compat cleanup failures instead of swallowing them
The @AfterAll cleanup deleted templates and identities in best-effort try/catch
blocks that swallowed every exception, so a real deletion failure would leave
state behind with no diagnostic. Log the affected template/identity and the
exception message, per AGENTS.md's rule against silently discarding exceptions.
|
||
|
|
ac4b865a34 |
feat(ec2): support managed prefix lists (#2105)
* feat(ec2): support managed prefix lists Implement CreateManagedPrefixList, DescribeManagedPrefixLists, GetManagedPrefixListEntries, ModifyManagedPrefixList and DeleteManagedPrefixList. Entries are versioned: a list starts at version 1 and every modification that changes entries stores a new version, so GetManagedPrefixListEntries can serve an earlier TargetVersion. Renaming or raising MaxEntries does not create a version, CurrentVersion makes a modification conditional, and removals apply before additions so one call can replace an entry's description. The AWS-managed gateway-endpoint lists are now built once and served by both DescribeManagedPrefixLists and the existing DescribePrefixLists, so the two surfaces cannot report different CIDRs for the same list. They are read-only. Closes #2100 * fix(ec2): validate prefix list input and keep tag copies in sync Three defects in the managed prefix list surface: ModifyManagedPrefixList only checked the resulting entry count against MaxEntries, so a zero or negative MaxEntries on an empty list passed the check and persisted an impossible capacity. CreateTags and DeleteTags update the generic tag store and then mirror the result onto the resource, but updateResourceTags had no arm for prefix lists, leaving the copy on the model stale for describe responses and tag filters. MaxEntries and TargetVersion were converted with Integer/Long.valueOf, so malformed input escaped as an unchecked NumberFormatException and became a 500 rather than a structured EC2 client error. * fix(ec2): reject a missing PrefixListId and infer the prefix-list tag type A null PrefixListId reached List.of() inside describeManagedPrefixLists and threw NullPointerException, so DeleteManagedPrefixList, GetManagedPrefixListEntries and ModifyManagedPrefixList answered a request that never named a list with a 500 rather than a client error. Guard the lookup and raise MissingParameter. inferResourceType had no pl- arm, so tags on a prefix list were stored but reported as resourceType "unknown" and were invisible to a DescribeTags filter on resource-type. The existing test only covered describe and tag: filters, which is why this went unnoticed. Also cover the accepting branch of the address-family check, which until now was only reached by the rejecting case. * fix(ec2): treat a blank numeric parameter as malformed rather than absent intOrNull and longOrNull returned null for a present but blank value, which the callers read as "parameter not supplied". For CurrentVersion that silently downgraded a conditional ModifyManagedPrefixList to an unconditional one, so a request that asked to be gated on a version was applied anyway. Only an absent parameter is null now; a blank one reaches the parse and surfaces as InvalidParameterValue. * fix(ec2): report PrefixListVersionMismatch for a stale CurrentVersion A conditional ModifyManagedPrefixList that loses the version check returns PrefixListVersionMismatch on AWS, not IncorrectState; verified against a live account, which also supplies the message. The Terraform provider keys its retry handling on that code, so the previous one would have left a caller unable to recognise a losing conditional update. --------- Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com> |
||
|
|
3ce5041c71 |
fix(cognito): reject invalid refresh tokens in InitiateAuth REFRESH_TOKEN_AUTH (#2132)
* fix(cognito): reject invalid refresh tokens in InitiateAuth REFRESH_TOKEN_AUTH InitiateAuth with AuthFlow=REFRESH_TOKEN_AUTH silently fell back to minting fresh tokens for a fake "unknown" user whenever the supplied REFRESH_TOKEN failed to parse or didn't resolve to a real user, instead of failing like GetTokensFromRefreshToken already does. Fixes #2113 * test(cognito): add regression tests for invalid refresh token rejection Cover InitiateAuth REFRESH_TOKEN_AUTH with a garbage token and with a well-formed token encoding a nonexistent user; both must fail with NotAuthorizedException rather than returning an AuthenticationResult. * test(cognito): add regression test for non-numeric refresh token issued-at Covers a well-formed refresh token whose issued-at field is not a number; must fail with 400 NotAuthorizedException rather than the 500 NumberFormatException that surfaced before the parse was guarded. * fix(ec2): make network interface pagination tests order-independent describeNetworkInterfacesWithMaxResultsNoNextToken and describeNetworkInterfacesMultipagePagination assumed a fixed/low ENI count, but other tests in this class are not isolated and can leave ENIs behind depending on JUnit's tie-breaking order among tests sharing @Order(92). Use MaxResults=1000 for the single-page case and measure the actual ENI baseline before asserting page counts for the multipage case. |
||
|
|
50fe67dde6 |
feat(eventbridge): deliver events to event-bus targets (#1814)
* feat(eventbridge): deliver events to event-bus targets * fix(eventbridge): skip null resources when republishing to event-bus targets * fix(eventbridge): validate Detail and resolve account for bus targets readTree accepts any well-formed JSON value, so an input override producing "hello" or [1,2] passed the guard and reached the target bus as a scalar detail, with putEvents reporting success — a silent malformation rather than the intended warn-and-drop. The pass-through arm had the same hole. Both arms now share one isObject() check. Bus targets also went through the two-arg putEvents overload, which passes a null accountId, so a cross-account bus ARN resolved in the caller's account and surfaced only as a warning. Thread the ARN's account through, as SQS targets already do via the queue URL. Same-account and account-less ARNs still forward null: only that path carries the legacy-key fallback in AccountAwareStorageBackend.get(). * docs(eventbridge): document event-bus target behavior and limits * fix(eventbridge): cap bus-to-bus forwarding at one hop, matching AWS |
||
|
|
f34e0b5655 |
fix(apigateway): create the stage when CreateDeployment carries a stageName (#2130)
CreateDeployment ignored the stageName parameter: the deployment was created but no stage was, so GetStages stayed empty and invoking the deployed API returned {"message":"Stage not found"}. Calling CreateStage explicitly afterwards was the only way to make the API reachable.
CreateDeployment creates the named stage pointing at the new deployment. When the stage already exists, repoint it while preserving its other settings so repeated Terraform applies remain usable. The API does not document this collision behavior. Stage variables from the request are applied either way, and omitting stageName still creates no stage.
Adds ApiGatewayDeploymentStageNameIntegrationTest (7 cases) following the reproduction from the report: the stage appears in GetStages, the deployed route answers 200 instead of "Stage not found", a redeploy moves the same single stage to the new deployment id, and no-stageName is unchanged.
|
||
|
|
7e5afae61b |
feat(eks): support IRSA with a real OIDC issuer and JWT validation (#2108)
* feat(eks): support IRSA with a real OIDC issuer and JWT validation
Every EKS cluster now gets an OIDC identity provider, so the full IRSA flow
works end to end without mocked or hardcoded tokens.
CreateCluster generates an RSA-2048 keypair and an AWS-shaped issuer URL,
returned by DescribeCluster as identity.oidc.issuer. The issuer is a faithful
string for building trust policies but is never dereferenced: STS resolves the
signing key in-process via a new OidcIssuerKeyLookup port, declared in
core.common so services.iam does not depend on services.eks.
Key material lives in storage separate from the Cluster model. Cluster is
serialized straight onto the DescribeCluster wire response, so a private key
carried there would leak; @JsonIgnore would instead lose it across restarts and
break tokens minted earlier.
sts:AssumeRoleWithWebIdentity previously accepted any non-blank token and
returned a hardcoded subject. It now verifies, but only for issuers Floci hosts:
- RS256 signature against the cluster's public key
- iss matches the issuer exactly
- aud contains sts.amazonaws.com
- exp / nbf, with 60s of clock-skew tolerance
- the role's trust policy, via a new WebIdentityTrustPolicyEvaluator matching
Principal.Federated and the Condition block
The response now carries the token's real claims in
SubjectFromWebIdentityToken, Provider, and Audience. Bad tokens return
InvalidIdentityToken (400); a trust policy that does not permit the subject
returns AccessDenied (403) — a check the web-identity path was missing entirely.
Tokens from an issuer Floci does not host stay permissive, since Floci cannot
verify a third-party signature. Existing behaviour is therefore unchanged and no
configuration flag is required.
WebIdentityTrustPolicyEvaluator is a sibling of AssumeRolePolicyEvaluator rather
than an extension of it: that evaluator serves sts:AssumeRole, hardcodes that
action, reads only Principal.AWS, and ignores conditions. Condition values are
compared with exact, case-sensitive equality instead of the existing
globMatches, which lowercases both operands — case-folding an OIDC subject would
silently admit a different service account.
Because Floci has no kubelet to project a token into a pod, a local-dev harness
can mint one via POST _floci/eks/clusters/{name}/oidc-token and write it to the
file named by AWS_WEB_IDENTITY_TOKEN_FILE. Signing stays server-side so the
private key never leaves Floci. OIDC discovery and JWKS routes are served under
the same _floci namespace, for fidelity rather than because anything fetches
them; the AWS-shaped issuer path is not resolvable by Floci's embedded DNS and
would collide with S3's path-style catch-all.
Adds 51 tests: unit coverage for the verifier, the trust-policy evaluator, and
the OIDC service, plus an end-to-end integration test covering the mint ->
assume -> credentials path and its negative cases (wrong service account,
tampered signature, wrong audience, expired, alg:none).
* fix(iam): close two web-identity validation gaps and backfill cluster OIDC state
Three defects found in review of the IRSA change.
An unsigned "header.payload." token bypassed validation entirely. verify()
split with a -1 limit so a trailing empty segment was preserved, but
parseClaims() — which backs peekIssuer() — did not. Java drops trailing empty
strings by default, so such a token split into two parts, its issuer went unseen,
and STS classified it as an opaque third-party token: signature, claim, and
trust-policy checks were all skipped and credentials were issued for a JWT that
was never signed. Both split sites now pass -1.
StringLike and StringNotLike on an OIDC condition key folded case. They
delegated to IamPolicyEvaluator.globMatches, which lowercases both operands, so
a trust policy scoped to one service account or namespace would admit another
differing only in case — the exact hazard the StringEquals branch was written to
avoid. Adds a case-sensitive glob and uses it for both operators. Action matching
still uses globMatches, which is correctly case-insensitive.
Clusters persisted before this feature never gained an issuer or key, so after an
upgrade DescribeCluster reported no identity.oidc.issuer, minting returned 400,
and the JWKS routes 404'd until the cluster was recreated. EksService now
backfills on startup, and re-runs ensureKey for clusters that already have an
issuer so a restart cannot leave a known issuer without its signing key.
Each fix has a regression test confirmed to fail without it.
* fix(eks): keep IRSA OIDC state scoped to the cluster's owning account
The startup backfill read clusters across every account via scanAllAccounts() but
wrote them back with the request-scoped put(), which resolves to the default
account outside a request context. A cluster owned by any other account kept its
issuer-less record while a duplicate appeared under the default account, leaving
DescribeCluster and the IRSA endpoints broken for the owner. The backfill now
takes the account from the cluster record and writes with putForAccount, per the
pattern StorageFactory documents for work running outside a request.
The same root cause affected key lookup more seriously. findVerificationKey used
the account-scoped scan(), so an issuer owned by a non-default account went
unresolved — and an unresolved issuer is treated as a third-party provider, so
STS accepted the token with no signature, claim, or trust-policy check at all.
It now scans every account, which is correct regardless: an issuer URL is
globally unique, and the account calling AssumeRoleWithWebIdentity need not be
the one that owns the cluster.
deleteKey and findKeyByCluster stay account-scoped; both are only reached from
request-scoped paths (DeleteCluster and the JWKS route), where the caller's
account is the right scope.
Both fixes have a regression test confirmed to fail without them.
|
||
|
|
4a5fae4dcd |
fix(cloudformation): apply AssumeRolePolicyDocument when adopting an existing IAM role on update (#2143)
provisionIamRole's adoption path (triggered by EntityAlreadyExists when a same-stack UpdateStack retries against a role that already exists) fetched the existing role via getRole() but never applied the template's current AssumeRolePolicyDocument. A changed trust policy was silently dropped while the stack still reported UPDATE_COMPLETE. Routes the adoption path through the existing IamService.updateAssumeRolePolicy helper, mirroring how createRole() already applies the document on first create. If a later step in the same attempt fails (e.g. a bad ManagedPolicyArns entry), the whole resource update fails and CloudFormation reports UPDATE_ROLLBACK_COMPLETE - the trust policy must actually roll back too, not stay on the new value. Captures the role's prior trust policy before applying the update and restores it in the existing failure-cleanup path alongside policy detachment. Does not re-fetch the role after applying the trust policy: nothing downstream reads anything affected by that update (Arn, RoleId, AttachedPolicyArns are unchanged by it), and a failing re-fetch there would escape before the restoration catch block, leaving the new trust policy active despite a rolled-back update. Adds an ID-verified updateAssumeRolePolicy(name, doc, expectedRoleId) overload in IamService: a role deleted and recreated under the same name between the earlier identity check and this write would otherwise silently receive an update meant for the role this stack actually owns. Both the primary write and the failure-triggered restore use this overload - restoring a trust policy is just as consequential as applying one, so both directions get the same identity guarantee. Fixes #2084. |
||
|
|
a2b20cc085 |
fix(dynamodb): compare Value when legacy Expected supplies Exists (#2125)
* fix(dynamodb): compare Value when legacy Expected supplies Exists
A legacy Expected entry that supplies both Exists:true and a Value was
evaluated as an existence check only — the supplied Value was silently
discarded, so any stale value passed the condition.
This is the wire form emitted by version-guarded writes, where the caller
pairs Exists:true with the version it last read:
"Expected": {"version": {"Exists": true, "Value": {"N": "5"}}}
Because the guard was present on every request and ignored on every
request, conflicting writes were accepted with no visible symptom.
Per the documented ExpectedAttributeValue semantics, Exists:true always
carries a Value and means the attribute must exist AND equal it, which is
the same check as a bare Value. Only Exists:false is a pure absence check.
The three combinations DynamoDB documents as invalid now raise
ValidationException instead of being silently accepted:
- Exists:true with no Value
- Exists:false alongside a Value
- Exists combined with ComparisonOperator / AttributeValueList
Validation runs over the whole Expected map before any condition is
evaluated. PutItem, DeleteItem and UpdateItem all route through
evaluateLegacyExpected, so the change applies to all three.
* fix(dynamodb): compare collection values in legacy EQ conditions
The EQ comparison used by legacy Expected, QueryFilter and ScanFilter
reduced a non-scalar attribute value to an empty string, so any two
values of the same collection type compared as equal. A stale
expectation on an SS, NS, BS, L or M value was therefore always
satisfied and the guarded write was applied.
EQ now delegates to the existing attributeValuesEqual helper — the same
one the ConditionExpression path uses. It is type-strict, compares
numbers via BigDecimal, recurses into M and L, and treats set types as
unordered.
* fix(dynamodb): compare number set members numerically in equality
Number set equality put the members in a HashSet<BigDecimal>, so
membership went through BigDecimal.equals, which is scale-sensitive: 1
and 1.0 were treated as different members. Because NS elements are
normalized on write while a supplied condition value is not, an
otherwise valid condition on a numerically equivalent set was rejected
and the guarded write blocked.
Membership now goes through a TreeSet, whose contains uses compareTo, so
members compare numerically. Applies to both the legacy Expected /
QueryFilter / ScanFilter EQ path and ConditionExpression, which share
this helper.
* fix(dynamodb): compare collection values in legacy NE conditions
NE had the inverse of the collapse the previous commit fixed for EQ: it
compared the scalar projections of both values, which are empty strings
for non-scalar types, so any two collections of the same type looked
equal and NE was always false. A condition asserting an attribute
differs from a set it genuinely differs from blocked the write.
NE now negates attributeValuesEqual, mirroring EQ. Null handling is
unchanged: a missing attribute or a missing comparison value still
satisfies NE.
* test(dynamodb): pin type-strict equality in legacy conditions
EQ and NE compare attribute types as well as values, so a string "5"
does not match a stored number 5. Nothing pinned that, which left room
for a refactor to reintroduce equality via scalar string projections
without any test failing.
* fix(dynamodb): match DynamoDB validation for legacy Expected entries
Verified the legacy Expected rules against DynamoDB itself and aligned
the validation with what the service actually returns.
Error messages now carry the "1 validation error detected: " prefix and
the exact wording, including "Exists and ComparisonOperator cannot be
used together", which differed from the message used before.
Two rules were missing:
- AttributeValueList without a ComparisonOperator is rejected, and
that check takes precedence over the Exists rules. It applies
whether or not Exists is present.
- An entry with neither Exists nor Value is rejected as well,
reported as "Value must be provided when Exists is null".
DynamoDB reports only the first offending entry even when several are
invalid, so validation still stops at the first error.
|
||
|
|
91b6a40bc7 |
fix(elasticache): clean up container by id on readiness-timeout rollback (#2090)
* fix(elasticache): clean up container by id on readiness-timeout rollback start() registers the container in activeContainers before its waitForBackendReady() probe, and that probe throws on timeout. When it does, start() propagates without ever returning a handle, so the service's rollback saw handle == null, skipped the container stop, and left it running (only reaped at shutdown). A readiness timeout is the most likely provisioning failure, not an edge case. Add an idempotent stopByGroupId(groupId) that looks the container up in activeContainers, falling back to the deterministic container name for one that failed before registration. Call it unconditionally from rollbackReplicationGroup instead of gating containerManager.stop(handle) on handle != null. Mirrors the same fix already merged for Neptune in #1742. * fix(elasticache): stop by handle when known, only fall back to stopByGroupId Greptile flagged (PR #2090 review): rollbackReplicationGroup called containerManager.stopByGroupId(groupId) unconditionally, even when the handle from this request's own start() was already known. If a concurrent CreateReplicationGroup for the same group id raced ahead and overwrote the activeContainers entry before this rollback ran, stopByGroupId's fresh lookup would fetch and stop the other request's container instead of this one's. Restore the precise containerManager.stop(handle) path whenever handle is non-null (the common case — every failure after the container itself started successfully) and only use stopByGroupId as the by-id fallback for the one case that actually needs it: a readiness timeout, where start() never returns a handle at all. * fix(elasticache): guard against concurrent creates for the same group id Reviewer follow-up on PR #2090: the handle-less rollback path (a readiness timeout, where start() never returns a handle) still cleans up by looking up whatever containerManager currently has registered for the group id. If a second CreateReplicationGroup for that same id raced in and started its own container before the first request's rollback ran, that lookup would fetch and stop the second request's container instead of the first's — the existing "already exists" check only guards against a *persisted* group, not one still being provisioned, so nothing previously prevented two concurrent creates for the same not-yet-existing id from both proceeding. Add a provisioningGroupIds guard: claim the id before provisioning starts and hold it until createReplicationGroup returns or throws (rollback included), rejecting a concurrent second create for the same id with the same ReplicationGroupAlreadyExistsFault used for an already-persisted group. This closes the race at its root rather than narrowing it — a second request for the same id can never reach containerManager.start() while the first is still in flight, so the by-id rollback fallback can never observe a container it doesn't own. Added a concurrency test using real threads + latches to prove a second create for an in-flight id is rejected immediately rather than racing ahead. * refactor(elasticache): trim comments to one-liners |
||
|
|
11d527547a |
fix(memorydb): clean up container by id on readiness-timeout rollback (#2092)
* fix(memorydb): clean up container by id on readiness-timeout rollback start() registers the container in activeContainers before its waitForBackendReady() probe, and that probe throws on timeout. When it does, start() propagates without ever returning a handle, so the service's rollback saw handle == null, skipped the container stop, and left it running (only reaped at shutdown). A readiness timeout is the most likely provisioning failure, not an edge case. Add an idempotent stopByClusterName(name) that looks the container up in activeContainers, falling back to the deterministic container name for one that failed before registration. rollbackBackend now calls it unconditionally instead of gating containerManager.stop(handle) on handle != null. Fixing this also required splitting the proxy-stop and container-stop steps into isolated try/catch blocks (previously shared one try, so a throwing stopProxy skipped the container cleanup entirely) and guarding the proxy stop with the same handle != null precondition the container stop already had. Without that isolation, the by-name cleanup could still be skipped in the exact scenario it exists to handle. Mirrors the same fix already merged for Neptune in #1742. * fix(memorydb): stop by handle when known, only fall back to stopByClusterName Same issue flagged by greptile on the sibling ElastiCache PR (#2090): rollbackBackend called containerManager.stopByClusterName(name) unconditionally, even when the handle from this request's own start() was already known. If a concurrent createCluster for the same name raced ahead and overwrote the activeContainers entry before this rollback ran, stopByClusterName's fresh lookup would fetch and stop the other request's container instead of this one's. Restore the precise containerManager.stop(handle) path whenever handle is non-null (the common case — every failure after the container itself started successfully) and only use stopByClusterName as the by-name fallback for the one case that actually needs it: a readiness timeout, where start() never returns a handle at all. * fix(memorydb): guard against concurrent creates for the same cluster name Same fix as PR #2090 for ElastiCache: the handle-less rollback path looks up whatever containerManager currently has registered for the name, which a concurrent createCluster for the same name could overwrite first. Claim the name for the whole provisioning attempt so a second concurrent create is rejected immediately instead. |
||
|
|
2594705f9c | feat(elbv2): honor preserve_host_header parameter (#2109) | ||
|
|
c8403ac6fc |
feat(iam): add service-linked role create, delete and deletion status (#2179)
* feat(iam): add service-linked role create, delete and deletion status aws_iam_service_linked_role calls CreateServiceLinkedRole directly, and one unsupported operation fails a whole account-bootstrap module. Delete and GetServiceLinkedRoleDeletionStatus come with it, because create alone leaves terraform destroy broken. The role lands under /aws-service-role/<principal>/ with a trust policy for that principal, and is readable by GetRole afterwards, which is what the issue asks for. The role NAME is a deterministic stand-in, not AWS's. The prefix is chosen by the linked service and is not computable from the principal — AWS turns lex.amazonaws.com into AWSServiceRoleForLexBots — so this derives a name from the principal's labels instead: es.amazonaws.com becomes AWSServiceRoleForEs. Every label contributes, because rds.amazonaws.com and rds.application-autoscaling.amazonaws.com are separate roles on AWS and a config declaring both must not collide on one name. A CustomSuffix is joined with an underscore, which is the separator callers parse back out; Terraform recovers custom_suffix by splitting the role name on it, and that attribute forces replacement, so any other join never converges. Deletion is synchronous, so the returned task id is already complete and its status is SUCCEEDED. Task ids use the documented task/aws-service-role/<principal>/<role>/<uuid> shape and are held in a StorageFactory-backed store, so they are account-scoped and survive a restart like every other IAM record. Closes #2122 * fix(iam): classify service-linked roles by origin, not by path CreateRole accepts the /aws-service-role/ prefix, so a role sitting at a well-formed service-linked path is not necessarily one. Path-based classification let DeleteServiceLinkedRole delete an ordinary role that merely lived there. Roles minted by CreateServiceLinkedRole now carry a marker, and the delete path keys on that instead. The field is additive, so a role persisted before this change reads as not service-linked, which is correct. * fix(iam): protect service-linked roles from ordinary role mutations DeleteServiceLinkedRole could answer 409 DeleteConflict, a code absent from that action's published error list (LimitExceeded, NoSuchEntity, ServiceFailure). It got there by routing through deleteRole, which refuses a role that still has policies attached — and nothing stopped a caller from attaching one to a service-linked role first. AWS never reaches that state. It publishes UnmodifiableEntity (400) on twelve role actions, and the message names the linked service to go through instead. So refuse the mutation rather than handle the conflict it would otherwise cause. This guards the eleven the emulator implements — AttachRolePolicy, DetachRolePolicy, PutRolePolicy, DeleteRolePolicy, Put/DeleteRolePermissionsBoundary, UpdateRole, UpdateAssumeRolePolicy, Add/RemoveRoleFromInstanceProfile and DeleteRole; UpdateRoleDescription is the twelfth and has no handler here. Several were silent: DeleteRole removed a service-linked role at 200, UpdateAssumeRolePolicy rewrote its trust policy, and AddRoleToInstanceProfile attached it to an instance profile. TagRole and UntagRole stay open, matching AWS. DeleteServiceLinkedRole now removes the role directly, since deleteRole refuses it. Also validate CreateServiceLinkedRole's own inputs. CustomSuffix must match [\w+=,.@-]{1,64}, as AWS constrains it — a suffix containing '/' previously produced a role name outside RoleName's own pattern, leaving an ARN whose name segment cannot be recovered. And a derived name over 64 characters is rejected, because AWS caps RoleName at 64 on every action that takes one and on the Role this action returns. Document the three deviations that remain: the role name is derived locally and will not match AWS for most services, deletion is synchronous so the deletion status is always SUCCEEDED, and CreateRole accepts the /aws-service-role/ path that AWS reserves. |
||
|
|
d78520d5cb |
feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2) (#1914)
* feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2)
Adds the kinesisanalyticsv2 service (X-Amz-Target KinesisAnalytics_20180523.*):
a control-plane state machine plus a real Apache Flink JobManager container spun up
as a sidecar on StartApplication, modeled on the AmazonMQ->RabbitMQ pattern.
- CreateApplication -> READY, StartApplication -> STARTING -> RUNNING via a readiness
poller, StopApplication -> READY, DeleteApplication -> removed
- Container image chosen from the requested RuntimeEnvironment (FLINK-1_15..1_20 ->
apache/flink:1.x) via KinesisAnalyticsRuntimes, with an optional operator override;
unsupported runtimes (SQL / Zeppelin) rejected with InvalidArgumentException
- Container naming via ContainerStorageHelper.resourceName (floci-kinesisanalytics-<name>)
- Registered in ResolvedServiceCatalog, dispatched by AwsJson11Controller; container
teardown wired into EmulatorLifecycle.onStop
- Tests: service + handler unit tests, @QuarkusTest integration, Java SDK compatibility test
- Docs: service page, services index, README, environment-variable reference
* fix(kinesisanalytics): enforce delete/update state and version/timestamp guards
Addresses review feedback (self-review + Greptile) on the Managed Flink service:
- DeleteApplication rejects a non-READY (RUNNING/STARTING) application with
ResourceInUseException; the caller must StopApplication first (Greptile P1)
- DeleteApplication validates the required CreateTimestamp against the stored value
- UpdateApplication validates CurrentApplicationVersionId (ConcurrentModificationException
on mismatch, InvalidArgumentException when absent)
- StopApplication error message reads 'RUNNING or STARTING' to match the guard
- Readiness poller @PreDestroy awaits termination (bounded) before returning so a
mid-flight write cannot race the shutdown storage flush
- Drop the unused Tags field from FlinkApplication (full tag support tracked as a follow-up)
- Compat test @AfterAll logs tolerated teardown failures (AGENTS.md) and stops before delete
Tests updated accordingly and verified live against the packaged jar.
* feat(kinesisanalytics): deploy and run the application JAR on the Flink cluster
Implements real job submission for Managed Service for Apache Flink, so the AWS
'deploy a JAR' flow actually runs the job (previously only a bare JobManager reached RUNNING):
- CreateApplication parses and stores ApplicationConfiguration (ApplicationCodeConfiguration
S3ContentLocation + ParallelismConfiguration); DescribeApplication echoes it back as
ApplicationConfigurationDescription
- StartApplication reads the JAR from Floci's local S3 (via S3Service), starts a JobManager plus a
TaskManager (sharing the JobManager network namespace for localhost RPC), then uploads and runs the
JAR via the Flink REST API (new FlinkRestClient); the app reaches RUNNING when the Flink job is RUNNING
- StopApplication cancels the job and tears down both containers
- Applications created without code still come up as a bare cluster
- Docs + README updated; unit tests for config round-trip; verified live end-to-end against the
packaged jar (S3 JAR -> RUNNING Flink job -> stop/delete cleanup)
Not yet emulated: EnvironmentProperties injection, snapshots/savepoints, in-place code updates.
* fix(kinesisanalytics): align Flink runtimes with AWS and add the 2.x line
The runtime map now mirrors the runtimes AWS Managed Service for Apache Flink actually offers:
- Add FLINK-2_0 / 2_1 / 2_2 / 2_3 -> apache/flink:2.0/2.1/2.2/2.3 (the Flink 2.x line; FLINK-2_2 is in
the AWS SDK RuntimeEnvironment enum and the whole 2.x line has published apache/flink images)
- Remove FLINK-1_16 / FLINK-1_17 -> AWS does not offer these runtimes, so Floci should reject them too
rather than accept versions real AWS refuses
Supported set: FLINK-1_15, 1_18, 1_19, 1_20, 2_0, 2_1, 2_2, 2_3. Tests + docs + README updated.
* test(kinesisanalytics): cover both Flink 1.18 and 2.3 in the SDK compat test
Refactor the single-runtime compat test into an abstract ordered lifecycle run against two
runtimes, so the suite guards both the Flink 1.x and 2.x lines (Flink 2.0 changed the config
system and boots slower):
- AbstractKinesisAnalyticsV2LifecycleTest: PER_CLASS instance state + the create->start->RUNNING->
list->stop->unsupported->delete lifecycle, parameterized on an abstract runtime()
- KinesisAnalyticsV2Flink118Test (FLINK-1_18) and KinesisAnalyticsV2Flink23Test (FLINK-2_3)
- FLINK-2_3 is passed as a string (newer than the pinned SDK 2.44.14 enum) and asserted via
runtimeEnvironmentAsString(); RUNNING wait bumped to 300s for Flink 2.x's slower boot
Verified live: both subclasses boot real apache/flink:1.18 and :2.3 clusters and reach RUNNING
(0 skipped). CI now exercises two clusters; both skip gracefully when Docker is unavailable.
* fix(kinesisanalytics): preserve AwsException from a bad application-code S3 location
StartApplication's catch(RuntimeException) wrapped every failure from startCluster into
InternalFailureException (HTTP 500) — including the AwsException that readJar throws when the
application-code S3 object is missing/empty/unreadable. A client's bad S3 code location therefore
surfaced as a 500 server error instead of the intended InvalidArgumentException (400).
Now AwsException propagates as-is (preserving its error code and message); only unexpected
RuntimeExceptions (e.g. Docker unavailable) become InternalFailureException. Addresses Greptile P1.
* feat(kinesisanalytics): add resource tagging (TagResource/UntagResource/ListTagsForResource)
Adds Tags support to CreateApplication plus TagResource, UntagResource, and
ListTagsForResource, dispatched as regular JSON1.1 actions under the same
KinesisAnalytics_20180523 target prefix as every other action — verified
against the real botocore kinesisanalyticsv2 model that this API has no
separate REST tagging endpoint (protocol is pure "json"/1.1 with all
operations on POST /), unlike REST-JSON services (EKS, MWAA) that use the
shared /tags/{arn} controller.
Tags is a list of {Key, Value} objects on the wire (not a map), same shape
MemoryDB's handler already uses for its own tagging actions; mirrored that
parse/build pattern rather than the map-shaped TagHandler interface. Tags
are stored on FlinkApplication but, matching the real API, never echoed in
ApplicationDetail (CreateApplication/DescribeApplication) — only
ListTagsForResource returns them. TagResource enforces AWS's 50
user-defined-tag ceiling (TooManyTagsException) on both CreateApplication
and TagResource.
docs/services/kinesisanalytics.md's action table is auto-generated from the
handler source (tools/docs/regen_action_docs.py) — regenerated it and filled
in the three new rows' hand-written descriptions.
* feat(kinesisanalytics): inject EnvironmentProperties into the Flink cluster
CreateApplication now accepts ApplicationConfiguration.EnvironmentProperties
.PropertyGroups and writes them to /etc/flink/application_properties.json in
both the JobManager and TaskManager containers before the job runs — the
same well-known path and JSON shape (a list of {PropertyGroupId, PropertyMap}
objects, matching the AWS API's own PropertyGroups shape) real Managed
Service for Apache Flink uses, so a JAR written against
KinesisAnalyticsRuntime.getApplicationProperties() picks them up unmodified
against Floci. DescribeApplication echoes them back under
ApplicationConfigurationDescription.EnvironmentPropertyDescriptions
.PropertyGroupDescriptions.
/etc/flink does not exist in the stock apache/flink image, and the
container's non-root "flink" user (uid 9999) can't create it directly under
/etc (confirmed live: mkdir -p /etc/flink fails with permission denied as
that user). The fix, also verified live: name the tar entry
"flink/application_properties.json" and extract into the existing /etc
rather than targeting /etc/flink directly — the daemon-level copy API can
create the missing subdirectory as part of unpacking the archive even
though the in-container user couldn't, landing as root:root 775 (so it's
still world-readable by the flink user). A real apache/flink:1.18 container
was used to verify both the failure mode and the fix before writing the
Java implementation.
* feat(kinesisanalytics): add application snapshot (savepoint) support
Adds CreateApplicationSnapshot/DescribeApplicationSnapshot/ListApplicationSnapshots/
DeleteApplicationSnapshot. Triggers a real Flink savepoint of the running job and
polls it to completion the same way StartApplication polls job readiness. Snapshot
files land on a persistent named Docker volume mounted at /opt/flink/savepoints in
the JobManager container, so they survive a Stop/Start cycle; the volume is only
removed on DeleteApplication.
* feat(kinesisanalytics): support in-place application code updates
UpdateApplication with a new ApplicationCodeConfigurationUpdate (or
ParallelismConfigurationUpdate) now redeploys onto an already-running application
without tearing down its JobManager/TaskManager containers: the current job is
cancelled and the new JAR is uploaded and run on the same cluster, transitioning
RUNNING -> STARTING -> RUNNING the same way StartApplication submits a fresh job.
Updating a READY application just stores the new code location for the next
StartApplication. Attaching code to a running bare cluster for the first time is
not yet supported and is rejected with InvalidRequestException.
* fix(kinesisanalytics): use AWS's documented generic InternalFailure code
startApplication and updateApplication's redeploy-code path threw an invented
"InternalFailureException" for unexpected Docker provisioning failures — not a
shape kinesisanalyticsv2's model declares (no operation in this API declares any
5xx shape at all). AWS documents "InternalFailure" (no "Exception" suffix, HTTP
500) as the generic error common to every service's API; it's also already the
default used elsewhere in this codebase (JsonErrorResponseUtils, KMS, Pricing,
SES, CloudControl, EventBridge, and others).
* feat(kinesisanalytics): add CreateApplicationPresignedUrl and SnapshotsEnabled
CreateApplicationPresignedUrl returns a URL to the running application's Flink
Dashboard (UrlType: FLINK_DASHBOARD_URL only; Zeppelin/Studio isn't supported).
Floci has no real session/proxy layer for this, so it returns the JobManager
container's own REST/dashboard URL directly, while still validating UrlType and
SessionExpirationDurationInSeconds against AWS's documented constraints.
ApplicationSnapshotConfiguration.SnapshotsEnabled (default true, matching real
AWS) is now honored on CreateApplication and toggleable via UpdateApplication's
ApplicationSnapshotConfigurationUpdate; CreateApplicationSnapshot rejects the
request with InvalidRequestException while disabled.
* fix(kinesisanalytics): persist flinkJobId as soon as the job is submitted
The readiness poller only called putApplication when advanceToRunning reported
RUNNING, not when it merely assigned flinkJobId after submitting the job (which
returns false until the job state catches up). pendingJars — a separate,
in-process-only cache — is already cleared by that point, so an emulator
restart between job submission and reaching RUNNING would leave the
application stuck: no persisted flinkJobId to resume polling, and no cached
JAR left to resubmit.
|
||
|
|
3b760bd8e5 |
fix(kinesis): resolve LATEST shard iterator position at GetShardIterator time (#1901)
* fix(kinesis): resolve LATEST shard iterator position at GetShardIterator time A LATEST iterator recomputed its start position as the shard tip on every GetRecords call, so records written between obtaining the iterator and the first poll were skipped forever. Snapshot the tip once when the iterator is created (matching DynamoDbStreamService) and encode it in the iterator's index slot. GetShardIterator now also fails fast with ResourceNotFoundException for an unknown shard, as on AWS. Fixes #1900 * test(kinesis): add regression tests for tailing with a LATEST iterator Reproduce issue #1900: a record written after the iterator is obtained must be returned, both on the first GetRecords call and when polling via NextShardIterator. * test(kinesis): cover unknown shard validation for LATEST iterators GetShardIterator must return ResourceNotFoundException when the shard does not exist instead of deferring the failure to GetRecords. * docs(kinesis): document shard iterator semantics Describe the supported iterator types and the LATEST tip-snapshot behavior; remove a stray empty Examples heading. * fix(kinesis): validate shard existence for all iterator types in GetShardIterator AWS rejects an unknown shard at GetShardIterator time for every iterator type, not just LATEST. Apply the shard lookup unconditionally instead of deferring the failure to GetRecords. Addresses review feedback on #1901. * test(kinesis): cover unknown shard validation across all iterator types |
||
|
|
c4f4181c3d |
fix(cognito): HMAC-sign refresh tokens to prevent forgery (#2139)
* fix(cognito): HMAC-sign refresh tokens to prevent forgery Refresh tokens were plain poolId|username|clientId|issuedAt|familyId strings, base64-encoded with no signature or encryption. Anyone who knew a pool id, client id, and a valid username could hand-craft a token accepted by InitiateAuth REFRESH_TOKEN_AUTH / GetTokensFrom RefreshToken, unlike real Cognito, which documents refresh tokens as encrypted and opaque. buildRefreshToken now appends an HmacSHA256 signature over the payload, keyed by a random secret generated and persisted per pool (mirroring the existing lazy RSA JWT signing key pattern). parse RefreshToken verifies that signature with a constant-time comparison before returning any decoded field, and rejects the token (same as today's null-parse contract) on any mismatch, tampering, or unknown pool. * fix(cognito): reject invalid refresh tokens in REFRESH_TOKEN_AUTH instead of impersonating "unknown" handleRefreshToken fell through to minting real, correctly-signed AccessToken/IdToken JWTs for a hardcoded "unknown" user whenever parseRefreshToken returned null (or adminGetUser failed). With refresh tokens now HMAC-verified, every forged/tampered/garbage token takes that null path, so this fallback would have kept handing out valid signed tokens for exactly the forgery attempts this fix is meant to close off. parseRefreshToken returning null is now treated the same way it already is in getTokensFromRefreshToken: NotAuthorizedException / "Invalid Refresh Token". * fix(cognito): guard non-numeric issued-at and drop unused variable in handleRefreshToken Static analysis flagged two issues in the handleRefreshToken rewrite: Long.parseLong(parts[3]) could throw an uncaught NumberFormatException, and tokenClientId was parsed but never read. Wrap the parse and reject with the same NotAuthorizedException/"Invalid Refresh Token" used elsewhere in this method, and drop the dead variable. |
||
|
|
8d2a5bdd46 |
fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them (#1969)
* fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them CreateStack now applies each entry of an IAM role's Policies array as an inline role policy (PutRolePolicy semantics), resolving intrinsics inside the policy document. Failures propagate so a policy that cannot be created fails the stack instead of reporting CREATE_COMPLETE without it. Fixes #1952 * refactor(cloudformation): move AWS::IAM::Role into its own provisioner Continues the per-service decomposition started with SQS (#1825) by taking the resource type this branch touches out of the CloudFormationResourceProvisioner switch, carrying the #1952 inline-Policies fix with it. - IamRoleCfnProvisioner owns provision and delete for AWS::IAM::Role: name resolution and same-stack adoption, managed-policy attachment with its rollback, the inline Policies of #1952, and the former deleteRoleSafe, whose only caller was the role delete arm. - CfnRollback holds what both halves of the migration need instead of duplicating it: the __FlociRollbackOwned attribute that CloudFormationService reads to decide rollback deletion, and attemptIamCleanup, still used by the AWS::IAM::Policy and AWS::IAM::ManagedPolicy arms. - ProvisionContext gains resolveStringList next to the resolveOptional and generatePhysicalName it already lifts from the monolith. - IamRoleCfnProvisionerTest covers the inline policies and the delete path with one mocked service; the existing role rollback tests keep running through the public provision entry point, now with the provisioner registered. Role provisioning behavior is otherwise unchanged. * fix(cloudformation): inline role policies fail loudly and unwind on failure Three review findings on the IAM role provisioner. A Policies entry with a null or absent PolicyDocument was skipped, so the stack reached CREATE_COMPLETE without the declared inline policy — the same silent drop this PR set out to fix, one level in. It is a ValidationError now. The inline-policy loop sat outside the block that unwinds a failed provision. When putRolePolicy failed after createRole succeeded, the resource went CREATE_FAILED, and because rollback only deletes resources that reached CREATE_COMPLETE, the role, its managed attachments and any inline policies already written were left behind. The loop now runs inside that block. A failed update that adopted an existing role kept whatever the half-applied attempt had granted. Inline writes are recorded with the value they replaced, so unwinding restores the previous document, or removes the policy when this attempt introduced the name. A role the stack did not create is not deleted. * fix(cloudformation): reconcile role policies an update stopped declaring An inline policy or managed attachment written by a previous execution and absent from the new template stayed on the role while the stack still reported UPDATE_COMPLETE. Both sets are now recorded on the resource and reconciled on the success path, so what the template drops is removed. Only names a previous execution recorded are touched, which leaves out-of-band policies alone. PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same policy a fresh name on every execution, so an update accumulated copies instead of replacing it. A missing PolicyName is now a ValidationError, matching what this resource already does for a missing PolicyDocument. * fix(cloudformation): skip reconciliation of a role policy already removed deleteRolePolicy and detachRolePolicy both raise NoSuchEntity on an absent target, so a tracked policy removed out of band between executions failed an update whose desired end state already held. Reconciliation now skips what the role no longer carries. |
||
|
|
6d829ff7a4 |
feat(s3): resolve index documents for static-website directory requests (#1815)
* feat(s3): resolve static website index documents * fix(s3): drop the query string from the website folder redirect Verified against a live S3 website endpoint in us-east-1 rather than inferred: a bucket with photos/index.html answers GET /photos?code=abc&state=xyz -> 302, Location: /photos/ with a bare Location. Same for HEAD and for nested prefixes (/a/b?x=1 -> /a/b/). An earlier commit added query-string preservation on the strength of a review comment asserting AWS behaved that way; the probe shows it does not, and LocalStack's website_hosting.py agrees with the probe. An SPA whose OAuth callback lands on a slash-less folder loses its parameters on real AWS too, so the emulator matches rather than improving on it. |
||
|
|
cb06a73b78 |
fix(lambda): disable HTTP/2 cleartext on the runtime API server (#2181)
RuntimeApiServerTest.extensionRegister_racedAgainstStop_eventuallyDeliversShutdown flaked intermittently with an EOFException from the JDK HTTP/2 client, surviving #2156's fix for the write-vs-close ordering bug. stop() already waits for each parked write's flush to complete before closing the httpServer, but that only confirms the bytes were locally flushed, not that the peer received them before the connection is torn down - multiplexed HTTP/2 stream-completion bookkeeping on the same connection can still race that close. Real AWS's Runtime/Extensions API is plain HTTP/1.1; nothing here needs HTTP/2. Disabling h2c removes the class of multiplexed-connection races entirely and the JDK HttpClient falls back to HTTP/1.1 automatically, no client-side change required. Fixes #2180. |
||
|
|
fa8f8d78a4 |
fix(sqs): delayed FIFO message no longer blocks its message group (#2112)
Only in-flight messages (claimed, within their visibility timeout) lock a FIFO message group. claimFifo() used !isVisible() as the lock predicate, which also matches messages still waiting out DelaySeconds, so a newly sent delayed message made already-visible messages in its group unreceivable. Require a receipt handle as well, the same delayed-vs-in-flight discriminator messageCounts() already uses. Fixes #2104 |
||
|
|
cd3c6b54b2 |
fix(dynamodb): order Query by full composite sort key (#2114)
* fix(dynamodb): order Query by full composite sort key Query ordered results using only the first RANGE attribute returned by getSortKeyName(). For an index with a composite sort key (more than one RANGE attribute, e.g. "state RANGE, createdAt RANGE"), the remaining components were ignored: when the first component tied across rows, the stable sort left items in base-table storage order and ScanIndexForward =false merely reversed that order, so the secondary component (e.g. createdAt) never drove ordering. Sort by the full sort key instead, comparing each RANGE attribute in key-schema order and short-circuiting on the first non-equal component, then reverse for ScanIndexForward=false. Single-sort-key indexes are unaffected (one-element list preserves previous behavior). Adds getSortKeyNames() to GlobalSecondaryIndex, LocalSecondaryIndex and TableDefinition, and a regression test whose base-key order deliberately disagrees with the secondary sort component. Fixes #1675 * fix(dynamodb): paginate composite sort-key Query by full key The composite-sort-key ordering fix sorted by every RANGE attribute, but pagination still used only the first RANGE component (getSortKeyName()). LastEvaluatedKey construction and ExclusiveStartKey matching therefore dropped the later components, so a cursor no longer uniquely identified the row a page stopped on — rows sharing the first RANGE value could be skipped or duplicated across pages. Thread the full sort-key list (getSortKeyNames()) through buildKeyNode() and buildItemKeyFromNode(): the emitted cursor now carries every sort-key component, and cursor matching compares the full composite key. Single sort-key indexes and the scan/table-key paths keep the previous behavior via the retained single-key overloads. Addresses PR review comment r3710297799 ("Composite pagination loses key identity"). Adds paginated regression tests over the composite index that fail without this change. Refs #1675. --------- Co-authored-by: Nikola Gencic <nikola.gencic@centiglobe.com> |
||
|
|
02288abc11 |
fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe* (#1740)
* fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe* DescribeDBInstances/DescribeDBClusters returned an empty 200 when the identifier parameter matched nothing; real AWS faults for the parameter form and returns an empty list only for the Filters form. Track whether the identifier came from the parameter and fault when it matched nothing, with error codes, messages, and 404 status matching live AWS. * fix(rds,docdb,neptune): ARN identifiers and Filters-form parity for Describe* Review follow-ups: - RDS, DocDB, and Neptune list methods accept an ARN (the identifier parameter and the db-instance-id/db-cluster-id filters both allow ARNs per the AWS model). The ARN is matched against each resource's stored ARN, so a cross-account or cross-region ARN does not resolve a same-named local resource. - DocDbQueryHandler and NeptuneQueryHandler fault only for the identifier parameter, not the Filters form, which returns an empty list (mirror of the RDS fix). * test(rds): expect NotFound faults after delete in SDK compat tests The Go and Java compat suites asserted the old emulator behavior — an empty 200 when describing a deleted instance/cluster by identifier. Real AWS faults DBInstanceNotFound/DBClusterNotFoundFault there, which is what the deletion waiters key on, and the emulator now does the same. |
||
|
|
d943e09a73 |
feat(ec2): add ReplaceRoute (#2178)
Terraform calls ReplaceRoute whenever an existing route changes target, so route tables could be created but never updated; the only workaround was to destroy and recreate the table. The action replaces the target of the route matching DestinationCidrBlock. AWS takes exactly one target per call, so the target a request does not name is cleared rather than carried over; a merge would leave a route holding two targets at once, which AWS cannot produce. Only GatewayId and NatGatewayId are modelled by Route, plus LocalTarget, which needs no new field because `local` is the gateway id a route table's built-in route already carries. The other ten AWS targets keep the UnsupportedOperation they returned before this action existed rather than being accepted and silently clearing the route they were meant to repoint. Errors follow the EC2 reference: InvalidRoute.NotFound when no route matches the destination, MissingParameter when DestinationCidrBlock is absent (an IPv6 or prefix-list request), and InvalidParameterCombination for two targets or none. Closes #2087 |
||
|
|
8b8f837728 |
fix(ecs): report service deployments and MISSING failures on DescribeServices (#2176)
* fix(ecs): report service deployments and MISSING failures on DescribeServices DescribeServices omitted services[].deployments entirely and always returned an empty failures list. Both are read by AWS's own ServicesStable waiter, which accepts on length(services[?!(length(deployments) == `1` && runningCount == desiredCount)]) == `0` and fails fast on failures[].reason == "MISSING" (botocore ecs/2014-11-13/waiters-2.json). Because that file is codegen'd into every SDK, `aws ecs wait services-stable` and every SDK waiter polled for the full 40 x 15s before giving up, and Terraform's aws_ecs_service never converged (terraform-provider-aws internal/service/ecs/service.go:2206 applies the same len(Deployments) == 1 test). Evaluating the acceptor against the old payload raises JMESPathTypeError, so it could not even be evaluated. An ACTIVE service now reports exactly one PRIMARY deployment derived from its current state, with rolloutState COMPLETED once runningCount reaches desiredCount. The deployment id is derived from the service ARN and task definition rather than generated per request, so it is stable across calls and restarts and rolls over when the task definition changes. An unresolvable service reference is returned as a MISSING failure carrying the ARN it would have had, instead of being dropped. Known deviations are documented in docs/services/ecs.md: a single deployment with no draining ACTIVE alongside it, no deploymentController gating, and pendingCount always 0. Closes #2174 * fix(ecs): stamp a deployment with its own start time, not the service's A task-definition change mints a new deployment id, but both deployment timestamps were still taken from the service's creation time, so the payload contradicted itself: a new deployment claiming to have been created when the service was. botocore documents Deployment.createdAt as "the time when the service deployment was created", and moto stamps it at deployment construction (moto/ecs/models.py:540) rather than reusing the service's. Track when the current deployment began on the service model, set at creation and on every task-definition change, and report that. Services persisted before this field existed fall back to the service creation time. Raised in review on #2176. |
||
|
|
aed50cc2b2 |
feat(ses): implement custom verification email templates for v1 and v2 (#1840)
* feat(ses): implement custom verification email templates for v1 and v2 Add the SES custom-verification-email-template CRUD APIs across both protocols, backed by one shared StorageFactory store (key cvet::<region>::<name>): - v1 Query: Create/Get/List/Update/DeleteCustomVerificationEmailTemplate. - v2 REST JSON: the same five operations under /v2/email/custom-verification-email-templates. Behaviour and error shapes were verified against real AWS: duplicate create is AlreadyExistsException, missing is NotFoundException, the FromEmailAddress must be a verified identity (NotFoundException otherwise), an invalid redirection URL is BadRequestException, the template body is not content-validated, List omits TemplateContent, and the store is shared between v1 and v2. SendCustomVerification- Email is left as a follow-up. * fix(ses): serialize custom-verification-template mutations under one lock Guard the check-then-write of updateCustomVerificationEmailTemplate and deleteCustomVerificationEmailTemplate on the same lock as create (renamed cvetCreateLock -> cvetMutationLock) so a concurrent delete can't slip between an update's existence check and its put and resurrect the just-deleted template. Also clean up the shared template left by the v1 integration test. * fix(ses): validate custom-verification-template fields before the existence check on update UpdateCustomVerificationEmailTemplate ran the existence check before validating required fields, so omitting TemplateName (possible on the v1 Query API) returned NotFoundException instead of the required-field InvalidParameterValue (v2 BadRequestException). Validate first, matching CreateCustomVerificationEmailTemplate. Also drop an unused Hamcrest import in the v2 integration test. * test(ses): give the custom-verification-template cleanup a unique last order update_missingTemplateName and cleanup_deleteSharedTemplate both used @Order(8); with OrderAnnotation equal values have no guaranteed order and the suite is stateful. Move the cleanup to @Order(9) so it runs last deterministically. * fix(ses): throw v1 error codes for custom-verification-template not-found/duplicate The CVET service methods threw the v2 codes (NotFoundException/404, AlreadyExistsException/400) directly, so remapV1Exception was a no-op and the v1 Query path returned the wrong codes: the v1 SDK's typed CustomVerificationEmailTemplate* exceptions never fired, and not-found used 404 instead of AWS's 400. Throw the v1-native codes (CustomVerificationEmailTemplateDoesNotExist / CustomVerificationEmailTemplateAlreadyExists, both 400, verified against AWS) and map them in remapV1Exception, so v1 is correct while v2 still returns NotFoundException/404 and AlreadyExistsException/400. Also wrap the get/delete CVET endpoints in remapV1Exception (the only two that lacked it) and pin the v1 codes with integration assertions. * fix(ses): throw the v1 code for an unverified custom-verification-template sender An unverified FromEmailAddress threw NotFoundException/404 from the shared CVET validator, so the v1 Query wire carried a v2 code. AWS classic SES returns FromEmailAddressNotVerified/400 (verified); throw that v1-native code and map it in remapV1Exception, so v1 is correct while v2 still returns NotFoundException/404. Pin the v1 code with an integration assertion. |
||
|
|
d039780e3a |
fix(s3): validate FULL_OBJECT checksum on CompleteMultipartUpload (#1980)
* fix(s3): validate FULL_OBJECT checksum on CompleteMultipartUpload * fix(s3): align FULL_OBJECT checksum validation with AWS's CRC-only support - Reject SHA1/SHA256 combined with ChecksumType=FULL_OBJECT on multipart completion with InvalidRequest, since AWS only supports full-object checksums for CRC32/CRC32C/CRC64NVME (SHA is composite-only). - Report ChecksumType=FULL_OBJECT instead of COMPOSITE once a requested full-object checksum has been validated. - Abort the multipart upload left dangling by the mismatched-checksum test, and add regression coverage for both fixes above. |
||
|
|
fa9ed9100e |
feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2) (#1875)
* feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2)
SendEmail now honors ListManagementOptions (ContactListName / TopicName):
Opt-out suppression — recipients opted out of the named contact list are
suppressed as a Bounce, reusing the existing relay-exclusion and Bounce-event
path. A contact is opted out when UnsubscribeAll is set; with a TopicName, an
explicit OPT_OUT preference (or the topic's OPT_OUT DefaultSubscriptionStatus
when no explicit preference) suppresses; without a TopicName, only
UnsubscribeAll contacts are suppressed. A recipient that is not yet a contact
is created on the list automatically; an unknown contact list fails the send.
Unsubscribe handling — a single-recipient list-managed send gets a functional
unsubscribe link: the {{amazonSESUnsubscribeUrl}} body placeholder is replaced
and List-Unsubscribe / List-Unsubscribe-Post headers are added. The link points
at Floci's own /_aws/ses/unsubscribe endpoint (GET/POST), which applies the
opt-out (topic -> OPT_OUT, no topic -> UnsubscribeAll), auto-creating the
contact if needed. The link uses readable query parameters rather than AWS's
opaque token, and its scheme follows Floci's base URL. Raw sends do not get
link injection yet.
* fix(ses): apply list-management unsubscribe headers to relay + inspection, override duplicates, preserve placeholder in templates
Addresses three review findings on the unsubscribe handling:
- The List-Unsubscribe / List-Unsubscribe-Post headers now reach the SMTP relay
message (relay() takes the additional headers and applies them) and are stored
on SentEmail so GET /_aws/ses surfaces them under Headers — previously they
only appeared in published events.
- withUnsubscribeHeaders now overrides a caller-supplied List-Unsubscribe /
List-Unsubscribe-Post rather than appending a duplicate, matching AWS.
- applyTemplateData leaves the reserved {{amazonSESUnsubscribeUrl}} placeholder
intact instead of failing with MissingRenderingAttribute, so a templated body
can carry it (replacement still happens post-render in the send path).
* fix(ses): sanitize relayed headers against SMTP injection and avoid double-slash unsubscribe URLs
User-supplied SendEmail Headers reach the SMTP relay, where a name or value containing
CR/LF could inject extra headers (e.g. Bcc) into the delivered message. Skip any header
with a blank name or CR/LF in its name/value before adding it to the relay message, and
log the drop. Also trim a trailing slash from the configured base URL when building the
List-Unsubscribe URL so a base-url ending in "/" no longer yields "//_aws/...".
* fix(ses): make the unsubscribe GET a no-mutation confirmation page
The unsubscribe endpoint applied the opt-out on both GET and POST. A GET is a browser
click that AWS answers with a landing page, and treating it as a mutation is the RFC 8058
prefetch hazard: mail clients, scanners and link-preview bots that fetch the URL would
silently unsubscribe the contact. GET now renders a confirmation form that POSTs back;
only the POST (the RFC 8058 one-click request) applies the opt-out. Adds GET test
coverage and updates the docs.
* test(ses): add an SDK compat test for SendEmail with ListManagementOptions
Send with ListManagementOptions through the SES v2 SDK client to prove the nested structure
(ContactListName + optional TopicName) marshals as a real client sends it, and that Floci
actually applies it — an absent recipient is auto-created as a contact on the list. Also note
in the docs that {{amazonSESUnsubscribeUrl}} is left verbatim on a send without
ListManagementOptions (Floci behavior, not verified against real SES).
* fix(ses): harden the unsubscribe confirmation page and document its trust model
Escape '&' as '&' in the confirmation form's action attribute (valid HTML), and add the
RFC 8058 one-click hidden field so the form's POST body matches the advertised
List-Unsubscribe-Post header. Also document — in the controller Javadoc and the SES docs — that
the endpoint carries the target in readable query parameters and, like the rest of Floci, is
unauthenticated, so it is only safe on a trusted dev/test network.
* fix(ses): filter unsafe headers once so all send surfaces stay consistent
The SMTP relay dropped user-supplied headers with a blank name or CR/LF, but the stored
SentEmail (GET /_aws/ses) and published events kept the raw list — so inspection and events
could show headers the relay dropped and retain CR/LF injection payloads. Move the safety
check to MessageHeader.isSafe(), filter the headers once in the send path, and use that
sanitized list for storage, relay, and event publishing alike.
* fix(ses): reject SES v2 message headers that omit a required Name or Value
Content.Simple.Headers / Content.Template.Headers entries declare Name and
Value as required members. A header object missing either member was parsed
leniently and later silently dropped, which is surprising when the request is
otherwise accepted. Reject it at parse time the way AWS does — BadRequestException
with the Smithy "Member must not be null" constraint message anchored at the
offending header path and 1-based index.
|
||
|
|
66fd109ad6 |
fix(eks): validate subnet IDs exist before creating a cluster (#1943)
* fix(eks): validate subnet IDs exist before creating a cluster CreateCluster previously accepted any subnet ID, including ones that don't exist, and returned a successful cluster with an empty vpcId. Real EKS validates resourcesVpcConfig.subnetIds against EC2 and rejects the request with InvalidParameterException if a subnet is not found. EksService now delegates to Ec2Service.requireSubnet for each subnet ID given at cluster creation, mirroring the pattern RdsService already uses for DB subnet groups. * fix(eks): resolve subnet validation against the request's region Subnet validation in createCluster used config.defaultRegion() instead of the region the request actually targeted, so a cluster created in a non-default region with real, existing subnets would be wrongly rejected as InvalidParameterException. RegionResolver gains getRegion(), mirroring the existing getAccountId() pattern (reads the per-request region set by AccountContextFilter, falling back to the configured default outside request scope). EksService.createCluster now uses regionResolver.getRegion() instead of config.defaultRegion(), which also fixes the cluster ARN's region to match the actual request. Found via review feedback on #1943. * fix(eks): pin the region test properly and resolve vpcId from the subnets Addresses both blocking points from review. 1. The region regression test could not fail. It used subnet-default-a, and requireSubnet() calls ensureDefaultResources() on whatever region it is handed, which seeds subnet-default-a/b/c there on the spot. The subnet therefore resolves in every region, so validation passed with or without the fix and only the ARN assertion discriminated — exactly as pointed out. Verified by reverting `regionResolver.getRegion()` back to `config.defaultRegion()` and re-running: the old test failed at the ARN assertion on line 276, which means createCluster had already returned without throwing. Validation was never being exercised. Split into two honestly named tests: createClusterBuildsArnFromRequestRegionNotDefaultRegion what the old test actually pinned createClusterValidatesSubnetsInRequestRegionNotDefaultRegion creates a subnet explicitly in us-east-1 and requests a cluster in eu-west-2 with that id. An explicitly created subnet is not seeded elsewhere, so this is the only shape that discriminates. With the fix reverted it now fails with "Expected AwsException to be thrown, but nothing was thrown" — the cluster is created from a subnet in the wrong region, which is the bug. With the fix it passes. 2. resourcesVpcConfig.vpcId was still blank (the other half of #1942). CreateCluster carries no vpcId; real EKS derives it from the subnets. requireSubnet already returns the resolved Subnet, and validateSubnets threw it away. It now carries the vpcId through to buildVpcConfigResponse, with a caller-supplied value still taking precedence. New test createClusterResolvesVpcIdFromTheSubnets fails before the change with "expected: <vpc-default> but was: <>". EksServiceTest 28 pass, Ec2ServiceTest 17 pass. Other failures in a full run are pre-existing on this machine and unrelated — confirmed by stashing these changes and reproducing ZipExtractorTest's backslash-path failure on the untouched tree. Leaving the `catch (AwsException e)` narrowing for the separate PR as suggested. |
||
|
|
42363886d5 |
fix(apigateway): preserve trailing slash in proxy event path (#1863)
* fix(apigateway): preserve trailing slash in proxy event path
The REST proxy event path was built from the JAX-RS {proxy} path param, which strips a trailing slash, so a request to /thing/ produced event.path "/thing" instead of "/thing/". A trailing slash is significant to backends that treat /thing and /thing/ as distinct routes. Recover it from the raw request URI for the event path, requestContext.path and the proxy path parameter, while resource matching and path-parameter extraction keep using the normalized path (AWS routes /thing/ to the /thing resource but preserves the slash in the delivered event).
Fixes #1557
* fix(apigateway): preserve trailing slash in the authorizer event path
buildProxyEvent recovers the trailing slash the JAX-RS {proxy} binding
strips, but toAuthorizerEvent still used the normalized path. A CUSTOM
authorizer therefore gated /admin/special while the Lambda received
/admin/special/, so path-based access control in the authorizer and the
handler operated on different strings. Real API Gateway gives both the
raw path.
Use preserveTrailingSlash for the authorizer event's path, methodArn and
requestContext.path; path-parameter extraction still uses the normalized
path, matching buildProxyEvent. Adds an end-to-end regression asserting
the authorizer event path keeps the slash while pathParameters do not.
* fix(apigateway): keep proxy path param and methodArn normalized
Review feedback: pathParameters come from the matcher, which runs on the
normalized path, so the greedy {proxy+} value carries no trailing slash on
real AWS even when event.path keeps one. Independent reports of the AWS
behaviour agree that event.path preserves the slash while
pathParameters.proxy does not.
methodArn is matched against IAM-style policy resources, where a stray
trailing slash would silently fail wildcards an authorizer returns. No AWS
behaviour was found pinning it either way, so it keeps the normalized path.
event.path and requestContext.path still preserve the slash, which is the
part of the original fix the evidence supports.
|
||
|
|
1150cfc657 |
fix(iam): include policy description in GetPolicy/ListPolicies/CreatePolicy responses (#2155)
* fix(iam): include policy description in GetPolicy/ListPolicies/CreatePolicy responses policyXml() built the response for CreatePolicy, GetPolicy, and ListPolicies but never emitted the Description element, even though IamPolicy stores it correctly and the sibling roleXml() includes it for roles. Callers (e.g. Terraform's AWS provider) that set a policy description see it as permanently missing on every read, which forces destroy+recreate since IAM policy descriptions are immutable. Fixes #2154 * fix(iam): stop ListPolicies from returning Description policyXml() is shared by CreatePolicy, GetPolicy, and ListPolicies — the previous fix added Description to all three, but AWS's own Policy model documents that Description "is included in the response to the GetPolicy operation. It is not included in the response to the ListPolicies operation." CreatePolicy documents neither inclusion nor exclusion, so it's treated the same as GetPolicy. policyXml() now takes an explicit includeDescription flag: true at the CreatePolicy/GetPolicy call sites, false in ListPolicies' member loop. Adds a ListPolicies test asserting no member response ever carries a Description element, so folding it back into the shared helper unconditionally — the exact way this would regress — fails loudly. Addresses review feedback from @pgermosen. * fix(iam): make listPoliciesOmitsDescription assert the element, not the word Match "<Description>" rather than the bare word "Description" to avoid a false failure if a future policy's name/path happens to contain that substring, and assert the created policy is actually present in the response first, so the absence check can't pass vacuously against an empty (or wrongly-filtered) member list. |
||
|
|
c0f36ea604 |
fix(lambda): drain parked extensions before closing the runtime API server (#2156)
RuntimeApiServer.stop() called httpServer.close() before the vertx.runOnContext(...) loops that write the 204 wake-ups and SHUTDOWN events to parked extensions. Because close() begins tearing down connections immediately — and is not guaranteed to run on the same event-loop context as those writes — a parked extension's SHUTDOWN response could be lost when close won the race, orphaning the extension. That surfaced as the intermittent EOFException failing RuntimeApiServerTest in CI across unrelated PRs. Close the HTTP server only after every parked 204/SHUTDOWN response has been fully flushed: each write is scheduled on the event loop and its end() future is awaited, decrementing a shared counter that fires the close once the last response has actually reached the wire. Chaining on the end() future — rather than on the scheduled handler merely returning — matters because response.end() is asynchronous, so the bytes are not yet flushed when the handler returns (the connection could still be torn down mid-write). Fixes #2142. |
||
|
|
ff8d6efdf3 |
feat(ses): implement v1 receipt rule set actions (stored-but-inert) (#2128)
* feat(ses): implement v1 receipt rule set actions (stored-but-inert)
Add the SES v1 receipt-rule-set management actions: CreateReceiptRuleSet,
DescribeReceiptRuleSet, ListReceiptRuleSets, DeleteReceiptRuleSet,
SetActiveReceiptRuleSet, and DescribeActiveReceiptRuleSet. Floci has no inbound-mail
endpoint, so rule sets are stored inertly — a set never holds any receipt rules and
routes no mail — but the management API round-trips so tools like Terraform can declare
a rule set during bootstrap without hitting UnsupportedOperation.
Behavior matches AWS (verified): RuleSetDoesNotExist for a missing set, AlreadyExists
for a duplicate name, idempotent DeleteReceiptRuleSet, and an empty
DescribeActiveReceiptRuleSet when no rule set is active. Individual receipt rules and
receipt filters are out of scope.
* fix(ses): reject deleting the active receipt rule set and read active state under lock
DeleteReceiptRuleSet removed the active rule set unconditionally; AWS rejects it with
CannotDelete/400 (verified), so reject it and preserve the set. DescribeActiveReceiptRuleSet
read without the lock, so a concurrent set-active replacement (clear-then-set) could expose
its intermediate no-active state; read under receiptRuleSetLock so the reader sees the old or
new active set, never the gap.
* fix(ses): validate the receipt rule set name against AWS's constraints
RuleSetName was only checked for non-blank, so Floci accepted names AWS rejects. Validate
it as AWS does (verified): a character outside ^[a-zA-Z0-9_.-]+$ is a ValidationError, and a
name over 64 characters or that does not start and end with an alphanumeric is an
InvalidParameterValue ("Not a valid ruleSetName"). Applied on create/describe/delete and on
set-active when a name is given.
* chore(ses): tidy receipt rule set import order and record the RuleSetName probe provenance
Address review nits: move the ReceiptRuleSet import into alphabetical position in
SesQueryHandler, and expand the RuleSetName validation comment to record that the
constraints come from probing live SES (the botocore model has no pattern), so the
next reader can re-verify rather than treat them as settled.
|
||
|
|
b31cbb9231 |
fix(rds): resolve AWS-managed default DB cluster parameter groups on reference (#1805)
* fix(rds): resolve AWS-managed default DB cluster parameter groups on reference AWS ships a managed default DB cluster parameter group per engine family (e.g. default.aurora-postgresql16) that always exists. A cluster that uses the engine default — as the CDK emits when no cluster parameter group is specified — referenced default.<family>, which getDbClusterParameterGroup rejected with DBClusterParameterGroupNotFound, so CreateDBCluster failed. Materialize a default.<family> cluster parameter group on first reference (family = the segment after "default."), reproducing AWS's always-present managed defaults. Non-default unknown names still raise DBClusterParameterGroupNotFound. * fix(rds): materialize named default cluster groups * fix(rds): catalog managed cluster parameter groups * fix(rds): validate managed cluster parameter families * fix(rds): protect managed cluster parameter groups * test(rds): lock cluster listing error message * chore: re-run CI The Build and Test failure on the previous head was RuntimeApiServerTest's extension/stop race, a pre-existing flake unrelated to this change — it also failed on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it). Reproduced locally under `--cpus=1` and fixed separately. |
||
|
|
10048adced |
fix(apigateway): match Content-Type case-insensitively in Lambda proxy responses (#2150)
* fix(apigateway): match Content-Type case-insensitively in Lambda proxy responses
buildProxyResponse re-derives the response Content-Type with an exact-case
JSON field lookup (node.path("headers").path("Content-Type")), even though
the header-copy loop just above it already handles arbitrary casing
correctly by iterating every field. Lambda proxy integrations commonly
return lowercased header names - e.g. the AWS Lambda Web Adapter sidecar
returns "content-type", not "Content-Type" - which the exact-case lookup
misses, silently falling back to "application/json" regardless of what the
Lambda actually set. HTTP header names are case-insensitive on the wire
(RFC 7230 §3.2), so this affected every response whose handler didn't
happen to use the exact AWS-console casing, most visibly every RFC 9457
application/problem+json error response.
Confirmed via debug logging of the raw Lambda payload before fixing:
{"statusCode":404,"headers":{"content-type":"application/problem+json",...
Replaces the exact-case lookup with a case-insensitive scan
(findHeaderIgnoreCase) reusing the already-fetched headers node.
* test(apigateway): cover case-insensitive Content-Type matching in proxy responses
Widens buildProxyResponse to package-private (matching dispatch()'s existing
visibility, which exists for the same reason: direct unit testing from
ApiGatewayExecuteControllerTest without standing up a full Lambda invoke).
Covers lowercase, exact-case, and mixed-case Content-Type header names, plus
the pre-existing default-to-application/json behavior when no Content-Type
header is present at all.
Verified by reverting findHeaderIgnoreCase to the old exact-case lookup:
the lowercase and mixed-case tests fail (2 of 13) while the exact-case and
no-header tests keep passing, confirming none of the four are vacuous.
* fix(apigateway): preserve JSON-null Content-Type fallback in findHeaderIgnoreCase
findHeaderIgnoreCase called JsonNode#asText() unconditionally on a matched
header, so a Lambda proxy response with an explicit "Content-Type": null
produced the literal string "null" instead of falling through to the
application/json default the old exact-case lookup preserved (it checked
!ctNode.isNull() before using the value). Response.Builder#type("null")
throws, turning what used to be a 200 with the JSON default into a 502 with
the raw Lambda payload.
Also adds braces to the two new conditionals in findHeaderIgnoreCase per the
project's Java style (AGENTS.md).
Both caught by Greptile review on #2150. Verified the regression test fails
against the un-braced, null-unguarded version before this fix.
* chore: trigger CI
* fix(apigateway): scan multiValueHeaders for Content-Type, preferring it over headers
* chore: retrigger CI (previous run hit 20m job timeout)
|
||
|
|
9b451ccc82 |
fix(iot): match topic rules outside the default region (#2169)
* fix(iot): match topic rules outside the default region Topic rules are stored per region — topicRuleKey(region, ruleName) — but handlePublish looked them up with a hardcoded config.defaultRegion(). A rule created in any other region was stored, gettable and listable yet never evaluated: republish/SQS/SNS/Kinesis/DynamoDB/Lambda actions were silently dropped while Publish still returned 200. IotDataController.publish now resolves the region from the request's SigV4 credential, as the shadow endpoints in that controller already do, and threads it through IotService.publish into handlePublish. A publish that carries no region — MQTT, or an unsigned data-plane request — evaluates every region's rules, mirroring the fallback ApiGatewayService.resolveRestApiRegion applies to unsigned REST API invocations. executeTopicRule derives the rule's own region from its ARN and targets the action sinks with it instead of the default region, so a rule created in eu-west-1 delivers to eu-west-1 resources. Closes #2065 * fix(iot): treat a non-SigV4 publish header as an unresolved region IotDataController.publish skipped region resolution only for a missing or blank Authorization header. Any other non-SigV4 value — a bearer JWT, say — fell through to resolveRegionFromAuth, whose miss path returns the configured default region. So a publish carrying such a header evaluated only the default region's rules, while one carrying no header at all evaluated every region's: the same absence of region information, two different outcomes. RegionResolver.resolveRegionFromAuthOrNull returns the credential's region, or null when there is nothing to parse, and publish threads that through — so every publish that names no region is treated the same way. |
||
|
|
0203bc7f7e |
feat(cognito): add AdminLinkProviderForUser (#2166)
* feat(cognito): add AdminLinkProviderForUser Linking a federated identity to an existing user pool user returned 400 UnsupportedOperation, because the action had no arm in the CognitoJsonHandler switch and fell through to the default case. Add the action to the handler and service. The link is recorded as an entry in the destination user's `identities` attribute, matching the JSON array AWS documents: userId, providerName, providerType, issuer, primary and dateCreated. CognitoUser.attributes is already a free-form map and AdminGetUser emits every attribute as a UserAttribute, so the linked identity surfaces without a model change. dateCreated is stored in epoch milliseconds. That differs from the seconds this service uses for its own user timestamps, but it is what AWS emits in the identities attribute and the ID token claim. providerType is only set when the source provider name is one of the provider types AWS also uses as a name (Facebook, Google, LoginWithAmazon, SignInWithApple). SAML and OIDC types, and issuer, are properties of a registered IdP, which the emulator does not model, so they stay null rather than being guessed. A source identity may be linked to at most one user per pool; a conflicting link throws AliasExistsException, a documented error of this operation. Source provider names are not validated against a configured IdP, and the five-identity cap is not enforced. Both are noted as deliberate divergences in the pull request. Closes #1563 * fix(cognito): validate link fields and serialize the uniqueness check AdminLinkProviderForUser accepted requests with a missing SourceUser ProviderName or ProviderAttributeValue: path().asText() turns absent fields into empty strings, so a bad request returned 200 and persisted an identity with an empty providerName or userId. Require the three fields up front and answer InvalidParameterException, matching how this service already reports missing required input. The uniqueness check and the write could also interleave: two concurrent links of the same source identity to different users could both pass the scan before either wrote. Wrap the check and the write in synchronized (pool), the pattern the tag operations already use. * fix(cognito): serialize identity links on a stable monitor The uniqueness check locked the UserPool object, but updateUserPool replaces the stored instance (convertValue copy + poolStore.put), so two links racing an update could hold different monitors and both pass the scan. Serialize on a dedicated lock instead, declared beside the one method it guards. Dropping the describeUserPool lookup also changes the unknown-pool error source: adminGetUser reports it as ResourceNotFoundException 400, which is how every sibling admin user mutator already reports it. Verified with an 8-thread probe linking the same source identity to eight users: one winner and seven AliasExistsException with the lock, eight winners without it. |
||
|
|
7d9b9aedd2 |
feat(cloudformation): honor resource-level DeletionPolicy (#2167)
A resource's DeletionPolicy attribute was never read off the template, so every managed resource was deleted regardless of what it declared: deleteStackResources and rollbackCreatedResources both called provisioner.delete unconditionally. Read DeletionPolicy alongside Type in executeTemplate and apply it at both delete sites. Retain keeps the resource on every stack operation. RetainExceptOnCreate keeps it too, except when the create that made it is rolled back — deleting it there is the entire meaning of that value, and rollbackCreatedResources runs only for a failed create. A retained resource is reported as DELETE_SKIPPED, on the resource and as a stack event, and is not counted as a failed delete, so the stack still reaches DELETE_COMPLETE. That also lets a stack owning a non-empty S3 bucket be deleted, which otherwise fails on the objects. Any other value falls through to the existing delete. That includes Snapshot: floci cannot take the snapshots AWS supports for those types, and AWS does delete the resource under Snapshot, so Delete is the faithful half. The docs record that and the other divergences. The policy is set on the resource after the provisioner returns, because provision() and executeNestedStack() both return a fresh StackResource that replaces the map entry. Closes #1555 |
||
|
|
1795e131a2 |
feat(applicationautoscaling): add Application Auto Scaling control plane (#2159)
* feat(applicationautoscaling): add Application Auto Scaling control plane Adds a services/applicationautoscaling package emulating the Application Auto Scaling API (JSON 1.1, AnyScaleFrontendService. target prefix, application-autoscaling signing name). This is a distinct service from the existing EC2 Auto Scaling package, which speaks Query under the autoscaling signing name. Implements the nine actions Terraform exercises: RegisterScalableTarget, DescribeScalableTargets, DeregisterScalableTarget, PutScalingPolicy, DescribeScalingPolicies, DeleteScalingPolicy, and the ListTagsForResource / TagResource / UntagResource trio. Notable behaviours: - Identity is the (ServiceNamespace, ResourceId, ScalableDimension) triple; RegisterScalableTarget upserts on it and leaves unsupplied parameters unchanged, matching AWS. - ScalableTargetARN uses the application-autoscaling service name while PolicyARN uses plain autoscaling and embeds the resource path and policy name — the two ARN families genuinely differ. - Tagging resolves by ScalableTargetARN because the Terraform provider's transparent-tagging interceptor calls ListTagsForResource on every read, keyed on the ARN it reads from DescribeScalableTargets. - Target-tracking policies create the real pair of CloudWatch alarms AWS creates on the caller's behalf; deregistering a scalable target deletes its policies and their alarms. - Optional configuration fields are only echoed back when supplied, so Terraform never sees a value it did not configure. Scaling policies are stored and described but inert: nothing evaluates them and no capacity is adjusted, mirroring EC2 Auto Scaling's existing PutScalingPolicy. This is documented in docs/services/applicationautoscaling.md. Closes #2157 * refactor(applicationautoscaling): stop exposing the scalable target's tag map getTags() handed out the live internal map, and the service mutated it in place at three call sites. listTagsForResource also returned that same live reference out to the handler layer, so a caller could alter stored state without going through the service. getTags() now returns an unmodifiable view, with putTags/removeTags for the mutations the service actually needs, and a test pins the read-only contract. Reported by github-code-quality on #2159. |
||
|
|
b1f953efb1 |
fix(iam): seed AmazonAPIGatewayPushToCloudWatchLogs managed policy (#2147)
* fix(iam): seed AmazonAPIGatewayPushToCloudWatchLogs managed policy Floci seeded 52 AWS-managed policies at boot but none matched API Gateway, so AttachRolePolicy for this standard service-role policy returned NoSuchEntity. It's the policy attached to the API Gateway CloudWatch-logs role that aws_api_gateway_account depends on, so this blocked the first apply of any Terraform config that enables API Gateway access logging. Fixes #2121 * test(iam): add regression test for AmazonAPIGatewayPushToCloudWatchLogs seeding Reproduces #2121: GetPolicy for the API Gateway CloudWatch-logs managed policy returned 404 NoSuchEntity before the fix. |
||
|
|
76b264f667 |
fix(cloudformation): reconcile AWS::Logs::LogGroup in place on UpdateStack (#2152)
* fix(cloudformation): reconcile AWS::Logs::LogGroup in place on UpdateStack Fixes #1965 Root cause: provisionLogGroup called CreateLogGroup unconditionally on every provision, including updates to a stack whose log group already existed and was untouched. CloudWatchLogsService.createLogGroup throws ResourceAlreadyExistsException in that case, so any UpdateStack on a stack with a log group resource rolled back with "The specified log group already exists", even when nothing about the resource changed. Fix: on update, reconcile retention and tags in place instead of recreating, matching the pattern already used for Lambda functions. LogGroupName isn't updatable in place on real AWS, so a name change still deletes the old group and creates a new one (replacement). Also fixed a related gap: auto-generated LogGroupName (no explicit name in the template) called generatePhysicalName, which mints a new random name on every call, so an auto-named log group was replaced on every single update even when unchanged. It now reuses the existing physical name across updates, matching how auto-generated Lambda function names are handled. * fix(cloudformation): fix LogGroup replacement ordering and name-mode tracking Addresses two review findings on the reconciliation fix: - A LogGroupName rename deleted the old log group before confirming the new name could actually be created. If the new name collided with an existing group, CreateLogGroup failed and the update rolled back, but the old group was already gone and rollback does not restore it - permanent data loss. Now creates the new group first, matching the existing create-before-delete pattern already used for Lambda function replacement, and only deletes the old group once the new one exists. - Removing an explicit LogGroupName from the template fell through to the "no explicit name" branch, which reused the prior physical id - the old explicit name - instead of generating a fresh name for the new auto-generated mode. Now tracks whether the current name is explicit or generated (mirroring FlociLambdaFunctionNameMode) and forces a fresh generated name when an explicit name is removed. * fix(cloudformation): infer LogGroup name mode for pre-fix persisted stacks A log group persisted by a floci version before FlociLogGroupNameMode was tracked has no recorded mode, so explicitNameRemoved could never be detected for it even when it should be. Fixes it by backfilling the mode from the physical id's shape: generatePhysicalName always produces <stackName>-<logicalId>-<12 hex chars>, so anything else must have been an explicit LogGroupName. Doesn't attempt to un-truncate the (practically unreachable at a 512-character limit) truncation path, conservatively treating that edge case as explicit. Added a dedicated unit test exercising both legacy cases directly against the provisioner, since simulating "created by an older floci version" isn't reachable through the black-box HTTP integration tests. * refactor(cloudformation): rename shared name-mode constants off the Lambda prefix NAME_MODE_EXPLICIT/NAME_MODE_GENERATED are generic mode-value labels shared by both the Lambda and LogGroup name-mode tracking, not Lambda-specific, so the LAMBDA_ prefix was misleading now that a second resource type uses them. LAMBDA_NAME_MODE_ATTR is unchanged, since that one is a genuinely Lambda-specific attribute key. |
||
|
|
f6faf0ffe5 | fix(s3): Ensure tags are added on multipart s3 uploads. (#2151) | ||
|
|
e3c180b952 |
fix(ecs): resolve Secrets Manager JSON-key selectors in task definition secrets (#2133)
* fix(ecs): resolve Secrets Manager JSON-key selectors in task definition secrets containerDefinitions[].secrets[].valueFrom now supports the ECS selector suffix (:json-key:version-stage:version-id) that CDK emits for Secret.fromSecretsManager with a field. Parsing mirrors the real ECS agent: the ARN resource is split on colons and disambiguated by segment count (2 = plain reference passed through verbatim, 5 = selector with empty segments meaning unset, anything else is the agent's invalid-ARN error surfaced in stoppedReason). The base ARN is rebuilt before lookup so partial-ARN resolution keeps working, JSON keys are extracted top-level-only after the fetch, and SecretsManagerService now validates that a supplied VersionId and VersionStage name the same version. Closes #1912 * fix(ecs): document and pin JSON serialization of object selector values Review follow-up: object/array json-key values serializing as JSON (rather than Go's map[a:1 b:2] rendering from the agent's %v) is now recorded as the third deliberate divergence in the javadoc and pinned by a test. |
||
|
|
760115db14 |
feat(kms): implement ListKeyPolicies (#2046)
* feat(kms): implement ListKeyPolicies
ListKeyPolicies failed with UnsupportedOperation, so clients enumerating
policy names before a GetKeyPolicy call could not proceed. GetKeyPolicy
and PutKeyPolicy were already supported, so this was a hole in an
otherwise complete area.
Returns the single `default` policy name, which is what the model
prescribes ("The only valid value is default"), with Truncated false and
NextMarker omitted rather than serialized as null, since AWS only emits
NextMarker when Truncated is true.
Limit and Marker are accepted and ignored. One policy name cannot be
paginated, and ListKeyPolicies is the one KMS list operation that does
not declare InvalidMarkerException, unlike ListKeys, ListAliases,
ListGrants, ListKeyRotations, ListResourceTags, ListRetirableGrants and
DescribeCustomKeyStores. There is therefore no marker it could
legitimately reject, and no undeclared error code is invented for one.
Closes #1528
Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
* chore: drop hand-written ListKeyPolicies changelog entry (semantic-release owns CHANGELOG.md)
* fix(kms): drop unused ListKeyPolicies pagination params and fix test claims
Review follow-up, validated against the local AWS references: Limit/Marker are
accepted at the wire by never being read (matching moto's list_key_policies), so
the service signature drops the dead parameters and the structurally vacuous
paging unit test goes with them; the integration test remains the real coverage.
The javadoc justification now states the leniency honestly: SDKs do not fully
enforce LimitType [1..1000] client-side (botocore validates only the minimum),
so out-of-range values can arrive and are deliberately tolerated. The ARN
resolution test no longer claims alias coverage the operation does not have.
---------
Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
|