mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
4215006fe29c781e2af60dfcaed8577dcc18f478
994
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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>
|
||
|
|
7f51c746cd |
fix(cloudformation): provision AWS::ApiGatewayV2::Authorizer and wire Route.AuthorizerId (#1760)
* fix(cloudformation): provision AWS::ApiGatewayV2::Authorizer and wire Route.AuthorizerId CloudFormationResourceProvisioner had no case for AWS::ApiGatewayV2::Authorizer, so the resource fell through the default stub branch and never reached ApiGatewayV2Service — the same failure mode #788/#796 fixed for the v1 AWS::ApiGateway::Authorizer type. Stacks reported CREATE_COMPLETE, but apigatewayv2 get-authorizers came back empty and routes referencing the authorizer carried no authorizerId, so a JWT-authorized route silently served every request unauthenticated. Adds provisionApiGatewayV2Authorizer, modeled on the neighboring v2 Route/Integration/Stage provisioners, mapping the CFN PascalCase properties (Name, AuthorizerType, IdentitySource, JwtConfiguration, AuthorizerUri, AuthorizerPayloadFormatVersion, AuthorizerResultTtlInSeconds, EnableSimpleResponses) onto the existing ApiGatewayV2Service.createAuthorizer camelCase request shape. Also fixes provisionApiGatewayV2Route, which built its request map without reading AuthorizerId at all even though ApiGatewayV2Service.createRoute/updateRoute already handle it. Fixes #1758. * fix(cloudformation): accept scalar IdentitySource on ApiGatewayV2 Authorizer resolveStringListOrEmpty silently returned an empty list when a template supplied IdentitySource as a bare scalar string rather than the documented array form, dropping the identity source instead of persisting it. ApiGatewayV2Service.createAuthorizer/updateAuthorizer already accept a scalar string for identitySource (identitySourceRaw instanceof String), so the CFN provisioner was stricter than the service it calls. Adds resolveIdentitySource, a local resolver that accepts both a scalar string and an array. Adds a regression test asserting the scalar form is persisted, alongside strengthening the existing test to assert IdentitySource itself (previously unchecked). Addresses review feedback on #1760. * fix(cloudformation): populate AuthorizerId attribute, add scoped delete for AWS::ApiGatewayV2::Authorizer - Fn::GetAtt Authorizer.AuthorizerId now resolves: provisionApiGatewayV2Authorizer only set the physical id, never the resource's attributes map, so GetAtt (which reads a separate map from Ref) fell back to a literal placeholder string. - Stack deletion now actually removes the authorizer: the generic type/physicalId delete switch had no case for AWS::ApiGatewayV2::Authorizer at all and silently no-op'd. Added a scoped case in delete(StackResource, region) following the same shape already used for AWS::EKS::Nodegroup (a resource needing extra context beyond type+physicalId, stored as an attribute during provisioning). Both fixes store ApiId as a resource attribute during provisioning, since it's needed by the new delete path and wasn't previously retained anywhere. * fix(apigateway): support $request.querystring.* identity sources for JWT authorizers extractToken only checked HttpHeaders — it had no query-parameter access at all, so any IdentitySource entry like $request.querystring.token was silently unusable, and a request using a valid token there always 401'd. Threads UriInfo through enforceJwtAuthorizer/extractToken and adds a $request.querystring. branch mirroring the one enforceRequestAuthorizerV2 already has for Lambda REQUEST authorizers. * chore: retrigger CI The Build and Test job failed on a single flaky error in RuntimeApiServerTest.extensionRegister_racedAgainstStop_eventuallyDeliversShutdown (EOFException on an HTTP/2 read while racing extension registration against server stop) — 1 of 8325 tests. This branch changes no Lambda code; that test is from #1773 and lives on main independently. Passes locally on repeat runs. |
||
|
|
f71903379c |
fix(cloudformation): AWS::IAM::ManagedPolicy exposes PolicyArn for Fn::GetAtt (#2056)
CloudFormation documents PolicyArn as the attribute for this type, so a template written against AWS reads it back with Fn::GetAtt [<policy>, PolicyArn]. The provisioner only recorded the value under "Arn", so that GetAtt did not resolve and the unresolved literal propagated into whatever consumed it — typically a role's ManagedPolicyArns, which then failed with "Policy <logicalId>.PolicyArn does not exist" and rolled the stack back, several resources away from the cause. Both keys are now recorded; "Arn" stays for anything already reading it. |
||
|
|
875e0f2d3b |
feat(bedrock): add proxy backend for real LLM responses via OpenAI-compatible API (#1789)
* feat(bedrock): add proxy backend for real LLM responses via OpenAI-compatible API * fix(bedrock): preserve leading text when a tool call response also has content OpenAI-compatible backends can return assistant text alongside tool_calls in the same response (e.g. a preamble before invoking a tool). The Converse translation only emitted the toolUse block in that case, silently dropping the text. * fix(bedrock): use InternalServerException for proxy serialization failures InternalFailure isn't a bedrock-runtime error shape in botocore/the Java SDK, so clients couldn't map it; InternalServerException is the declared 500 for this API. * fix(bedrock): map proxy backend timeouts to ModelTimeoutException (408) HttpTimeoutException (connect or request timeout) was falling into the generic catch and surfacing as ModelErrorException/424, which the AWS SDKs treat as terminal. Bedrock's dedicated 408 shape is retryable under the default SDK retry strategy, so this distinction is load-bearing, not cosmetic. Also makes the request timeout configurable (proxy.request-timeout-seconds, default 60s) since larger models on CPU-backed backends may need more headroom than the default. * fix(bedrock): fail fast on InvokeModel under the proxy backend Falling back to StubBackend's canned response meant a caller who configured a real proxy backend and called InvokeModel got a plausible-looking, entirely fabricated completion with no signal beyond a server-side log line. That's inconsistent with Converse, which already fails loudly on misconfiguration, and worse: InvokeModel is still the default entry point for many SDK wrappers, so this could silently mask a broken integration. Also fixes the streaming-endpoint error messages, which blamed "the Floci stub" for a limitation that's actually unconditional (streaming isn't implemented for any backend). |
||
|
|
e048e52ce0 |
test(lambda): wait for the parked poll instead of sleeping in extension stop race (#2131)
extensionRegister_racedAgainstStop_eventuallyDeliversShutdown slept 5ms to let the extension's /event/next poll connect and park before racing stop() against it, then asserted SHUTDOWN came back on that request. The sleep asserts the poll has parked without checking. On a loaded machine it expires first, so stop() closes the listening socket while the request is still in flight: the poll never reaches the handler, stop()'s SHUTDOWN fan-out finds no waiting context to hand the event to, and the client sees the connection die instead of the SHUTDOWN the test is about. That surfaces as an EOFException (connection accepted, then torn down) or a ConnectException (lost the race before the connect even landed) out of asyncNext.get(), and it failed CI this way once in 8325 tests. Replace the sleep with awaitExtensionParked(), polling a new package-private RuntimeApiServer.isExtensionParked() until the poll has provably parked, so the race the test sets up is the one it means to test. isExtensionParked reads under the same lock as the rest of the extension state, per the class's documented locking discipline; RegisteredExtension.hasWaitingContext() peeks without consuming, unlike takeWaitingContext(). The test still fails if the "poll pendingEvents before checking stopped" fix in the /event/next handler is reverted, so this removes the flake without weakening the regression it covers. Verified by breaking that fix and watching this test go red, and by reproducing the original failure under CPU saturation before and after the change. |
||
|
|
62a576c8d4 |
feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment (#1804)
* feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment AWS::SecretsManager::SecretTargetAttachment previously fell through the default branch, so its Ref yielded a generated placeholder rather than the secret ARN. Per the CloudFormation resource reference, this resource's Ref returns the ARN of the secret named in SecretId, and consumers such as Secret.fromSecretCompleteArn(...) require the complete ARN (with the trailing -6char suffix). Resolve SecretId (a Ref to the Secret, a friendly name, or a raw ARN) to the canonical complete ARN via describeSecret and expose it as the resource's physical id / Arn attribute, falling back to SecretId as-given if the lookup fails. Deleting the attachment is a detach no-op — it must not delete the underlying secret. * fix(cloudformation): require SecretId on SecretTargetAttachment SecretId is a required property of AWS::SecretsManager::SecretTargetAttachment. Resolving it as optional let a template omit it and still create (falling back to the logical id); reject a missing SecretId instead. Adds a regression test. * fix(cloudformation): complete secret target attachment lifecycle * fix(cloudformation): require attachment metadata on delete * fix(cloudformation): tolerate detached secret overwrites * fix(cloudformation): align secret target attachment behavior * docs(cloudformation): document secret target attachments --------- Co-authored-by: abanna <abanna@users.noreply.github.com> |
||
|
|
bdad066694 |
fix(cloudformation): resolve Fn::GetAtt [Vpc, DefaultSecurityGroup] (#1977)
* fix(cloudformation): resolve Fn::GetAtt [Vpc, DefaultSecurityGroup] provisionVpc now records the VPC's default security group id as the DefaultSecurityGroup attribute, so GetAtt resolves to the real sg-* id instead of passing the literal 'LogicalId.DefaultSecurityGroup' string to downstream resources (breaks CDK's Custom::VpcRestrictDefaultSG handler). Fixes #1976 * refactor(cloudformation): extract AWS::EC2::VPC into a per-service provisioner |
||
|
|
4e0a815f20 |
feat(cloudformation): provision AWS::EC2::LaunchTemplate (#1973)
* feat(cloudformation): provision AWS::EC2::LaunchTemplate Create the launch template in Ec2Service from LaunchTemplateData (ImageId, InstanceType, KeyName, SecurityGroupIds, UserData, IamInstanceProfile). Ref resolves to the launch template id and Fn::GetAtt exposes LatestVersionNumber/DefaultVersionNumber, which CDK ASGs and instances reference. DeleteStack removes the template. Fixes #1971 * feat(cloudformation): resolve EC2 instance config from its LaunchTemplate reference An AWS::EC2::Instance that sets LaunchTemplate instead of direct properties now fills ImageId/InstanceType/KeyName from the referenced template's data (AWS resolution order), so instances launched from a launch template no longer fail with 'The request must contain the parameter ImageId'. * refactor(cloudformation): move AWS::EC2::LaunchTemplate into a per-service provisioner Follows the CfnResourceProvisioner pattern instead of growing the monolithic switch: Ec2LaunchTemplateCfnProvisioner injects only Ec2Service and is picked up by CloudFormationResourceRegistry via CDI. Provision and delete arms for AWS::EC2::LaunchTemplate are removed from CloudFormationResourceProvisioner along with the now-unused private provisionLaunchTemplate method. EC2 instance resolution against a referenced launch template stays put, since AWS::EC2::Instance is not extracted yet. An IamInstanceProfile given only by Name is now normalized to its instance-profile ARN, matching the EC2 query API path; previously the bare name was stored as if it were an ARN. Adds unit coverage for the new provisioner (attributes, generated name, profile ARN normalization, security groups, delete). * test(cloudformation): delete the launch-template instance stack so EC2 state stays clean The instance case left its stack standing, so a running instance (and its network interface) leaked into the shared emulator state for the rest of the suite. That pushed the total interface count past the MaxResults=5 boundary Ec2IntegrationTest's DescribeNetworkInterfaces pagination cases assert on, and they failed in full-suite runs while passing in isolation. Deleting the stack terminates the instance, which describeNetworkInterfaces skips. * fix(cloudformation): update a launch template in place instead of recreating it UpdateStack re-provisions every resource, and the provisioner called createLaunchTemplate unconditionally. An explicit LaunchTemplateName therefore hit InvalidLaunchTemplateName.AlreadyExistsException on every update, and an omitted one generated a fresh random name, creating a second template and orphaning the first. A template whose name has not changed is now updated by publishing a new version and keeping its physical id, which is how AWS::EC2::LaunchTemplate behaves when only its LaunchTemplateData changes. An unnamed template keeps the name generated at create time rather than minting a new one. A changed name is a replacement: the new template is created first and the previous one deleted only after that succeeds. |
||
|
|
1a99721ae0 |
feat(cloudformation): provision AWS::EC2::VPCGatewayAttachment (#1972)
* feat(cloudformation): provision AWS::EC2::VPCGatewayAttachment Attach the internet gateway to the VPC via Ec2Service so route tables pointing at the IGW behave like AWS. The physical id encodes vpc|igw so stack deletion can detach. The VpnGatewayId variant records the attachment without an attach call (no VPN gateway model). Fixes #1970 * refactor(cloudformation): move VPCGatewayAttachment into a per-service provisioner The monolithic switch in CloudFormationResourceProvisioner is being split into per-service CfnResourceProvisioner implementations, so AWS::EC2::VPCGatewayAttachment lands in the new structure instead of growing the switch. Ec2VpcGatewayAttachmentCfnProvisioner injects only Ec2Service and is picked up by CloudFormationResourceRegistry through CDI, no registration needed. The provision logic and the physical-id encoding (vpcId|gatewayId) carry over unchanged, and delete() detaches the internet gateway so stack deletion no longer leaves the attachment orphaned. Removes the AWS::EC2::VPCGatewayAttachment arms from the provision and delete switches along with provisionVpcGatewayAttachment and detachVpcGatewayAttachmentSafe, leaving CloudFormationResourceProvisioner identical to main. * fix(cloudformation): validate VPCGatewayAttachment and make its delete type-safe Four review findings on the attachment provisioner. A template that omitted VpcId still reported CREATE_COMPLETE: the null went into attachInternetGateway, so DescribeInternetGateways exposed an attachment with no VPC and every later detach on that gateway threw on the null compare. VpcId is now required, as is exactly one of InternetGatewayId or VpnGatewayId. The VpnGatewayId form recorded a physical id and did nothing else, so CloudFormation reported CREATE_COMPLETE for an attachment that does not exist and cannot be observed — there is no VPN gateway model behind it. It now fails the resource with an explicit message instead of claiming success. Updates orphaned the previous pair. The new pair is attached first and the old one detached only after that succeeds, so a failed update leaves the previous attachment intact; an unchanged update no longer re-attaches and duplicates. Deletion classified the gateway by the id's igw- prefix, so an igw-* value supplied as VpnGatewayId could detach a gateway the stack never attached. The physical id now carries a kind tag (igw|<vpcId>|<gatewayId>) and delete acts only on ids this provisioner wrote. |
||
|
|
5cb26ff117 |
fix(cloudformation): treat delete of an already-removed DynamoDB table or Lambda function as idempotent (#1803)
* fix(cloudformation): treat delete of an already-removed DynamoDB table or Lambda function as idempotent When a stack is torn down after a rollback has already deleted some of its resources, CloudFormation re-issues the delete against resources that no longer exist. DynamoDB DeleteTable and Lambda DeleteFunction both raise ResourceNotFoundException in that case, which flipped the stack to DELETE_FAILED and wedged the stack name against a later create. Route the AWS::DynamoDB::Table and AWS::Lambda::Function delete cases through deleteDynamoTableSafe / deleteLambdaFunctionSafe, which swallow ResourceNotFoundException (treating an absent resource as already deleted, as AWS does) while still re-throwing any other AwsException so genuine conflicts continue to surface as DELETE_FAILED. * test(cloudformation): cover idempotent delete boundaries * chore(ci): retrigger flaky checks |
||
|
|
48b2139b4f |
fix(cloudformation): keep uniqueness suffix when truncating generated resource names (#1802)
* fix(cloudformation): keep uniqueness suffix when truncating generated resource names
CloudFormation auto-generates a physical name as
`{stackName}-{logicalId}-{random}` for resources declared without an
explicit name. When that string exceeded the resource type's name-length
cap, generatePhysicalName truncated the whole string with
`substring(0, maxLength)`, which dropped the trailing random token. Every
auto-named resource in a long-named stack then collapsed onto the same
truncated name, breaking Ref/GetAtt lookups — most visibly a
`Custom::LogRetention` whose `ServiceToken` (a GetAtt of its provider
Lambda's Arn) resolved to a different, colliding function.
Truncate only the descriptive prefix and always keep the random suffix,
matching how CloudFormation shortens a generated name while preserving its
uniqueness token, so distinct logical resources keep distinct physical names.
* fix(cloudformation): preserve uniqueness suffix in extracted ProvisionContext name generator
The #1825 registry refactor lifted generatePhysicalName into ProvisionContext
verbatim, so migrated resource types (SQS) once again truncated the trailing
uniqueness token when a stack name neared the length limit. Apply the same
suffix-preserving truncation there so extracted provisioners stay consistent
with the monolith.
* fix(cloudformation): harden generated name regression test
|
||
|
|
91e06ebebf | fix(apigateway): import authorizers and security requirements from OpenAPI (#1798) | ||
|
|
7e4e3e8c50 |
feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor) (#2086)
* feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor)
Adds a new services/mwaa package following the EKS lifecycle pattern
(Controller/Service/EnvironmentManager, one Docker container-set per
resource, readiness polling) and the Neptune/ElastiCache proxy pattern
(MwaaWebProxy/MwaaProxyManager: Floci owns the host-facing port, the
backing container stays internal-only).
Each environment is backed by two real containers — postgres:16-alpine
for the metadata DB and apache/airflow:<version>-python3.12 running
LocalExecutor — with AirflowVersion genuinely selecting the image tag
(validated against a configured allow-list), unlike EKS's cosmetic-only
version field. MwaaWebProxy fronts the real Airflow webserver and
intercepts POST /aws_mwaa/cli, bridging it to a docker-exec'd `airflow`
CLI call and returning the documented {stdout, stderr} shape.
DAGs and requirements.txt sync from S3 on a poller, reusing the existing
S3Service in-process rather than a new AWS-facing surface. The Airflow
container is pointed back at Floci via LaunchedContainerAwsEnv (the same
mechanism Lambda/ECS containers already use), so a DAG's own boto3 calls
resolve against Floci instead of real AWS.
StartupScriptS3Path is supported end-to-end: fetched from S3 at create
time, injected before the container starts (create -> inject -> start,
mirroring EksClusterManager's config-injection sequencing), sourced
before migrate/scheduler/webserver so exported vars propagate. The
airflow user gets a passwordless sudo grant (verified against the real
image — sudo ships but isn't passwordless by default, and AWS's own
startup-script examples assume sudo just works), and a fixed set of
Floci-critical env vars (Fernet key, DB DSN, executor, AWS-SDK-redirection
vars) are snapshotted before and restored after the script runs, mirroring
real MWAA's reserved-environment-variable protection.
Verified end-to-end against real Docker (not just the mock=true unit
suite): environment reaches AVAILABLE, proxy pass-through and the CLI
bridge both work with real output, a DAG uploaded to S3 syncs and parses,
a second environment on a different AirflowVersion pulls a genuinely
distinct image, and delete tears down both containers/volumes and the
proxy cleanly.
45 new tests (unit + RestAssured integration, all against mock=true in
the default suite so Docker is never required for `mvnw test`); full
suite otherwise unchanged.
* fix(mwaa): hard-fail startup-script injection failures, release proxy ports on delete
Two issues from review:
copyFileIntoContainer swallowed every failure identically, including the
one case where that's wrong: a configured StartupScriptS3Path that fails
to copy into the container. The entrypoint's "if [ -f /startup.sh ]"
guard would silently skip it and the environment would reach AVAILABLE
having never applied the requested setup, contradicting the documented
intent of gating environment creation on startup-script failure (matching
real MWAA). copyFileIntoContainer now reports success/failure; the
startup-script call site checks it and throws, while DAG sync and the
best-effort sudoers grant keep their existing soft-fail behavior.
deleteEnvironment allocated a proxy port via PortAllocator on create but
never released it on delete, unlike every other service that uses
PortAllocator (Lambda, MSK, EC2, ECR) — repeated create/delete cycles
would eventually exhaust the configured proxy port range even with zero
MWAA proxies actually running.
* fix(mwaa): roll back allocated proxy port and containers on create failure
If startEnvironment() succeeded (containers running) but PortAllocator.allocate
or MwaaProxyManager.startProxy failed afterward, createEnvironment's catch
block set CREATE_FAILED without releasing the reserved port or stopping the
containers that had already started — leaking both on every such failure.
Mirrors NeptuneService.createDbCluster/rollbackDbCluster's already-proven
shape for this exact class of problem (container + proxy + port, partial
failure must roll back everything): a provisioned flag set only after every
step succeeds, and a try/finally that runs rollbackFailedCreate whenever it
doesn't — stopping the proxy (a no-op if it never started), stopping any
containers that did start (MwaaEnvironmentManager.stopEnvironment already
null-checks each container id, so it's safe for partial startup too), and
always releasing the port.
* fix(mwaa): correct CreateEnvironment error shape, namespace container names, add docs
Two items from maintainer review:
- Duplicate CreateEnvironment threw ResourceAlreadyExistsException, a shape the
operation doesn't declare (verified against the real botocore mwaa/2020-07-01
model: CreateEnvironment's only errors are ServiceUnavailableException,
ValidationException, InternalServerException) — SDK clients couldn't map it.
Now throws ValidationException.
- dbContainerName/airflowContainerName built names via raw string concatenation
instead of routing through ContainerStorageHelper.dockerName like every other
Docker-backed service (EKS, RDS, ...), so MWAA alone didn't participate in the
FLOCI_DOCKER_RESOURCE_NAMESPACE convention that keeps multiple Floci instances
sharing one Docker daemon from colliding. Both static methods now take the
EmulatorConfig and route through the shared helper; volume names inherit the
fix automatically since they're built by extending the container name.
Also adds docs/services/mwaa.md (mkdocs nav updated) following eks.md's
structure — operations table, mock/real mode, the web/CLI proxy, startup-script
behavior (sudo grant, reserved-variable protection), config reference, ARN
format, CLI/SDK examples, and an honest "Not Implemented" section covering the
known gaps already discussed on the PR (PluginsS3Path, cross-account container
naming, restart restoration).
|
||
|
|
5f7d4d2dc8 |
fix(s3): recognize virtual-hosted-style requests over HTTP/2 (#1954)
* fix(s3): recognize virtual-hosted-style requests over HTTP/2
Browsers negotiate HTTP/2 via ALPN over HTTPS, and HTTP/2 (RFC 9113) has no
Host header — the authority is carried in the :authority pseudo-header.
S3VirtualHostFilter read only getHeaderString("Host"), which is null over
HTTP/2, so virtual-hosted-style requests fell through to path-style handling:
the bucket label in the authority was ignored and the first path segment was
treated as the bucket instead.
Resolve the effective authority from the request URI (populated from
:authority) when the Host header is absent, so bucket routing works on both
HTTP/1.1 and HTTP/2.
Closes #1866
* fix(s3): detect website requests over HTTP/2 via request-URI authority
Over HTTP/2 there is no Host header, so S3Controller.isWebsiteRequest saw a null host and served API XML instead of website HTML for virtual-hosted website buckets. Resolve the effective authority from the request URI (reusing S3VirtualHostFilter.resolveHost) so website index/error-document handling works on HTTP/2 too; the filter's path rewrite preserves the s3-website authority for this.
Tests: isWebsiteRequest detection over HTTP/1.1 and HTTP/2 (S3ControllerWebsiteRequestTest), and that the filter rewrite keeps the s3-website authority downstream (S3VirtualHostFilterTest).
|
||
|
|
79031a240a |
fix(s3): apply CreateBucketConfiguration tags on bucket creation (#2115)
CreateBucket accepted a <Tags> array in the request body but ignored it.
The body was parsed for LocationConstraint only, so tags supplied at
creation were silently dropped: the request returned 200, and a
following GetBucketTagging or S3 Control ListTagsForResource reported an
empty tag set.
AWS applies these tags. The CreateBucket API reference documents Tags
inside CreateBucketConfiguration as "an array of tags that you can apply
to the bucket that you're creating", gated on the s3:TagResource
permission.
The gap is visible through the AWS Terraform provider, which sends
bucket tags this way rather than via a separate PutBucketTagging call.
Against Floci an aws_s3_bucket with a tags map applies cleanly but lands
with tags = {} in state, so every subsequent plan proposes to add them
again -- a diff that never converges.
Parse the same <Tag> key/value pairs handlePutBucketTagging already
parses, and route them through the existing s3Service.putBucketTagging
once the bucket exists.
Verified end to end: with this change a terraform apply of a tagged
aws_s3_bucket records the tag in state, get-bucket-tagging returns it,
and the next plan reports no changes. The unpatched image, same config
and provider version, still reports tags = {} and a pending change.
|
||
|
|
b543aa4baa |
feat(lambda): support extra /etc/hosts entries on Lambda launch (#2073)
* feat(lambda): support extra /etc/hosts entries via FLOCI_SERVICES_LAMBDA_EXTRA_HOSTS * feat(lambda): support ipv6 addresses. --------- Co-authored-by: Florian Overfelt <joverfelt@meso-scale.com> |
||
|
|
fa96b791b4 | fix(codebuild): stabilize start and retry responses (#2052) | ||
|
|
88408d8574 |
fix(ec2): return AWS-parity MissingParameter for CreateSubnet without VpcId (#2094)
* fix(ec2): return AWS-parity MissingParameter for CreateSubnet without VpcId CreateSubnet passed a null VpcId straight into the VPC lookup, producing "The vpc ID 'null' does not exist" instead of the MissingParameter error real EC2 returns for a required-but-absent parameter (#2089). * test(ec2): cover CreateSubnet missing VpcId at unit level Asserts createSubnet(null vpcId) throws MissingParameter rather than InvalidVpcID.NotFound with a literal "null" in the message. * test(ec2): cover CreateSubnet missing VpcId over the wire Exercises the Query API handler directly (no VpcId form param) to pin the AWS-parity MissingParameter response end-to-end. * test(ec2): cover blank VpcId for CreateSubnet at unit level Greptile flagged that isBlank() also covers empty/whitespace VpcId, a branch the original tests didn't exercise directly. * test(ec2): cover blank VpcId for CreateSubnet over the wire Companion to the unit-level blank VpcId case, exercised through the Query API handler. |
||
|
|
6a214e84d6 | fix(apigateway): use last duplicate header value (#1806) | ||
|
|
733c72d02a | fix(cognito): reject unconfirmed users in SRP auth (#2027) | ||
|
|
76f602fafa |
feat(cloudformation): support AWS::Events::EventBus and EventBusPolicy (#1794)
* feat(cloudformation): support AWS::Events::EventBus provisioning and deletion * fix(cloudformation): delete EventBridge rules against their own event bus on stack teardown * test(cloudformation): verify custom event bus rule delivers to SQS end to end * feat(cloudformation): support AWS::Events::EventBusPolicy (Action/Principal form) * feat(cloudformation): support AWS::Events::EventBusPolicy Statement form with merge by Sid * fix(cloudformation): route CREATE rollback through resource-aware delete so custom-bus rules are cleaned up * chore(cloudformation): warn instead of debug when a stack event bus cannot be deleted |
||
|
|
58743487a7 |
feat(iam): seed Amazon Bedrock managed policies (#2034)
* feat(iam): seed Amazon Bedrock managed policies AmazonBedrockFullAccess and AmazonBedrockReadOnly were absent from the seeded AWS-managed policy catalog. CloudFormation attaches managed policies inline when creating a role, so it never noticed; Terraform (and the raw IAM API) call AttachRolePolicy, which validates the policy exists and 404'd with NoSuchEntity on these two. Seed them alongside the existing Bedrock AgentCore policy, matching the pattern used for the RDS (#1559) and EKS (#1216) additions. * fix(iam): match the AWS-published Bedrock policy descriptions |
||
|
|
43aea0983d |
feat(iam): seed the managed policies CDK bootstrap and the scenario stacks attach (#2064)
* feat(iam): seed the managed policies CDK bootstrap and the scenario stacks attach Four AWS-managed policies were missing from the catalog, and each surfaced the same way: "Policy arn:aws:iam::aws:policy/<name> does not exist" reported on the role that consumed it, rolling the whole stack back several resources from the cause. - AWSCloudFormationReadOnlyAccess — attached by the roles `cdk bootstrap` creates, so CDKToolkit rolled back and no CDK application could deploy at all. - AmazonAthenaFullAccess, AmazonRedshiftFullAccess, AmazonS3TablesReadOnlyAccess — attached by the QA roles the aws-bench ec2-multiregion scenario deploys. Supersedes #2059, which carried only the first of the four. * fix(iam): drop the AWSCloudFormationReadOnlyAccess duplicate landed by #2057 * fix(iam): match the AWS-published descriptions for two seeded policies Both verified with iam:GetPolicy against real AWS. AWSCloudFormationReadOnlyAccess was seeded by #2057 as "Provides read only access to Cloud Control and CloudFormation."; AWS returns "Provides access to AWS CloudFormation via the AWS Management Console." AmazonS3TablesReadOnlyAccess said "Provides read-only access to Amazon S3 Tables."; AWS returns "Provides read only access to all S3 table buckets." |
||
|
|
78ba5b3457 | feat(iam): list entities attached to managed policies (#1808) | ||
|
|
a8ed218c57 |
fix(s3): accept a percent-encoded bucket/key separator in copy sources (#2060)
* fix(s3): accept a percent-encoded bucket/key separator in copy sources
The AWS SDK for .NET percent-encodes the whole x-amz-copy-source value, so a
v4 client sends `bucket%2Ffolder%2Fkey.txt` with no literal slash anywhere.
Splitting the raw header on indexOf('/') found no separator there, so every
CopyObject and UploadPartCopy from that SDK failed with 400 InvalidArgument,
including copies of top-level keys.
Treat whichever comes first, a literal '/' or an encoded %2F, as the
bucket/key separator. Bucket names admit neither '/' nor '%', so the first
occurrence of either is unambiguously the separator and never part of the
bucket name. The split still happens before decoding, so an encoded slash
inside a key stays key content and a literal '?' is still preserved.
Both handlers now share one parseCopySource helper rather than duplicating
the split.
Adds regression coverage for the fully-encoded .NET wire format, a lowercase
%2f, a leading encoded separator, the mixed encoded-separator/literal-slash
form, UploadPartCopy, and malformed encoding reached through an encoded
separator.
Closes #2038
* test(s3): verify the bytes copied through an encoded separator
The encoded-separator UploadPartCopy part was uploaded but left out of
CompleteMultipartUpload, so the test only proved the request returned 200,
not that the encoded source resolved to the same object.
Complete the part and assert the trailing slice, so a parse that resolved the
wrong key would fail on content rather than pass on status.
|
||
|
|
2889fbdef8 | fix(lambda): report resolved executed version (#2026) | ||
|
|
3baf4f4849 |
feat(ec2): return an empty set for DescribeVpnGateways (#1975)
* feat(ec2): return an empty set for DescribeVpnGateways There is no VPN gateway model, so an empty vpnGatewaySet is AWS-accurate for an account without VPN gateways. Unblocks the CDK CLI's VPC context provider (Vpc.fromLookup), which always issues this describe and aborts the whole lookup on UnsupportedOperation. Fixes #1974 * test(ec2): assert the vpn gateway set is empty, not merely present The substring check passed for any response containing <vpnGatewaySet, including a non-empty one, so it did not pin the empty-result contract. Uses the item count, matching the other empty EC2 collection tests. |
||
|
|
a01b707bdc |
feat(sqs): retain MessageGroupId on standard queue messages (#1891)
* feat(sqs): retain MessageGroupId on standard queue messages Standard queues dropped MessageGroupId on SendMessage, so ReceiveMessage never returned it. Since the July 2025 fair-queues launch, standard queues accept MessageGroupId and return it as a message system attribute. Store the value in the standard-queue branch of sendMessage; both protocol handlers already parse it on send and return it on receive, covering single and batch sends. Delivery is unchanged: group locking only applies in the FIFO claim path, so same-group standard messages still deliver in parallel, matching AWS. Closes #1496 * test(sqs): give the new test a unique @Order * chore: retrigger ci |