mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
5afb60d0f55e00aeb555a08ecc7d9ce8305bc545
1317
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
5afb60d0f5 |
fix(kinesis): reject records over the 1 MiB size limit (#1896)
* fix(kinesis): reject records over the 1 MiB size limit PutRecord and PutRecords accepted records of any size; real Kinesis rejects a record whose data blob plus partition key exceeds the stream's maximum record size (1 MiB by default). Floci doesn't implement UpdateMaxRecordSize, so every stream sits at the default. Validate in putRecordWithShardId, covering both operations. An oversized record in PutRecords fails the whole request up front, before anything is written: the per-record ErrorCode field is reserved for ProvisionedThroughputExceededException and InternalFailure, so a size violation cannot be reported per record. Closes #1755 * refactor(kinesis): decode batch entries once and resolve stream first Review round: cache successful Data decodes for the write loop (malformed entries keep their per-record failure), resolve the stream before the size check so a missing stream reports ResourceNotFoundException, and add a wire-level PutRecords over-limit test. * test(kinesis): cover PutRecords per-record failure and unknown stream Two paths the size-limit change touched had no coverage: no test produced a non-zero FailedRecordCount for Kinesis, and none covered PutRecords against a missing stream. Malformed per-record Data must stay a per-record InternalFailure rather than a whole-batch failure. Collapsing the decode fallback to entry.data() drops FailedRecordCount to 0 and stores a record with a null blob, since validateRecordSize only counts the partition key; the next GetRecords then fails on the encode. Resolving the stream up front turns PutRecords against a missing stream into ResourceNotFoundException instead of a per-record InternalFailure. |
||
|
|
8ef71d6930 |
fix(cloudformation): honor resource-level conditions (#2255)
* fix(cloudformation): honor resource-level conditions * fix: handle condition deletion failures * fix(cloudformation): fail on unresolved condition dependencies instead of skipping A resource that will be created must not depend on a resource excluded by a false condition. Real CloudFormation rejects such a template synchronously at CreateStack/UpdateStack with "Template format error: Unresolved resource dependencies [X]" and provisions nothing, rather than silently skipping the dependent (verified against AWS for DependsOn and Ref/Fn::Sub). Validate the condition dependency graph in createChangeSet before any stack state is created, and throw the same ValidationError from topologicalSort as a safety net for nested/direct executions. Fn::If-guarded references remain valid because dependency collection only walks the selected branch. Tests cover: DependsOn and Ref/Fn::Sub unresolved dependencies fail; an Fn::If-guarded false-branch reference is created; and a false->true condition update creates the previously-skipped resource. * fix: evaluate stackset conditions in target account * fix(cloudformation): retain failed cleanup resources |
||
|
|
3fe836aa16 |
fix(s3): verify SigV4 signature on presigned URLs when enforce-auth is enabled (#1842)
* fix(s3): verify SigV4 signature on presigned URLs when enforce-auth is enabled * test(s3): use real SigV4 signatures in presigned URL auth enforcement tests * test(s3): assert tampered presigned signature is rejected * fix(s3): construct presigned canonical query per SigV4 encoding rules * test(s3): cover presigned canonical query edge cases Extract canonical query construction into a package-private buildCanonicalQueryString method and add unit tests for the SigV4 encoding, ordering, empty-value, duplicate-name, and signature-exclusion branches. * test(s3): add SDK-signed presigned URL regression tests Add integration tests that generate presigned URLs with the AWS SDK S3Presigner (an independent signer) under enforce-auth: both original URLs succeed, transplanting object A's path onto object B's query is rejected with 403 SignatureDoesNotMatch, reordered and special-character queries still verify, expired URLs and malformed credentials are rejected, and an IAM-issued access key verifies. Adds the aws-sdk s3 test dependency. * fix(s3): collapse sequential spaces in signed header values per SigV4 Canonical values for non-host signed headers were only trimmed. SigV4 also collapses sequential spaces to a single space, so a valid presigned request carrying such a header could be rejected. Extract canonicalizeHeaderValue and add unit coverage. * style(s3): log caught exception in presigned SigV4 verification The catch block silently returned false. Log at debug per repo style so a swallowed exception can be diagnosed. * test(s3): move SDK presigned URL tests to compatibility-tests Move S3PresignedUrlSdkIntegrationTest from the main project to compatibility-tests/sdk-test-java and remove the aws-sdk s3 test dependency from the main pom.xml per CONTRIBUTING.md guidelines. * fix(s3): read X-Amz-Content-Sha256 instead of hardcoding UNSIGNED-PAYLOAD * fix(s3): reject presigned URLs with X-Amz-Expires outside 1-604800 * fix(s3): reject presigned URLs with unsupported X-Amz-Algorithm |
||
|
|
e4010ec12f |
feat(rds): model DB proxies and their target groups (#1813)
* feat(rds): model DB proxies and their target groups Add DB proxies as first-class RDS resources for both the RDS Query API and CloudFormation: - RdsService: two persisted stores plus the proxy lifecycle (create/register-targets/describe/delete). A proxy exposes a bare-host endpoint on the engine family's default port; in non-mock mode registering a target starts an auth relay (via RdsProxyManager) that forwards 1:1 to the target cluster/instance, re-armed on restart. - RdsQueryHandler: CreateDBProxy, DeleteDBProxy, RegisterDBProxyTargets, DescribeDBProxyTargetGroups, DescribeDBProxyTargets, and a real DescribeDBProxies listing (2014-10-31 XML shapes). - AwsQueryController: route the six DBProxy actions to RDS. - CloudFormation: provision/delete AWS::RDS::DBProxy and AWS::RDS::DBProxyTargetGroup. This models DB proxies for provisioning and discovery; it does not add real connection pooling (the relay forwards 1:1), so it does not close #1679. * fix(rds): reserve DB proxy port so same-engine proxies get distinct ports createDbProxy used the engine family's default port (5432/3306/1433) directly without reserving it, so two proxies for the same engine got the identical port and the second relay failed to bind in non-mock mode. Reserve the default port via reserveOrAllocateProxyPort, falling back to an allocated pool port when it is already taken — the first proxy keeps the clean bare-host default port, later ones get a distinct port, and the persisted port stays canonical across restarts. * fix(rds): harden DB proxy lifecycle compatibility * fix(rds): complete DB proxy compatibility hardening * fix(rds): make DB proxy lifecycle rollback-safe * fix(rds): default omitted proxy target group * test(dynamodb): retain Quarkus port for cleanup --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com> |
||
|
|
42a79a7fd7 |
feat(ec2): DescribeVpcEndpointServices returns the common interface services with AZs (#2007)
* feat(ec2): DescribeVpcEndpointServices returns the common interface services with AZs The empty service set aborted CDK InterfaceVpcEndpoint synthesis (lookupSupportedAzs calls this at synth time). Now returns the standard com.amazonaws.<region>.<service> interface services (ec2, ssm, logs, sts, secretsmanager, kms, ecr, ecs, lambda, iot.data, ...) plus s3, each with the region's AZs and serviceType, honoring a ServiceName filter. Fixes #2004 * fix(ec2): DescribeVpcEndpointServices echoes an explicit ServiceName with all AZs An explicit ServiceName filter (CDK InterfaceVpcEndpoint queries a specific, often custom, service name) now returns exactly that service in every AZ, instead of an empty AZ set when the name isn't in the built-in list — which failed synth with 'lookupSupportedAzs returned <> but subnets have AZs ...'. * test(ec2): pin the s3-Gateway and ecr.api-Interface pairing in the endpoint-services test * fix(ec2): report both endpoint types for S3 and update the SDK compatibility test Two gaps flagged in review. S3 is the one service with both a Gateway and an Interface offering, and AWS reports both on its single service detail. The handler emitted Gateway only, despite the comment above the loop saying otherwise, so an interface-endpoint lookup for S3 found nothing. The Java SDK compatibility suite still asserted that serviceNames and serviceDetails come back empty, which the populated response violates. It now asserts what the endpoint actually returns: the S3 detail carrying both types, an interface-only service, and non-empty availability zones. |
||
|
|
4058dfae00 |
fix(ec2): type a security group rule's tags as security-group-rule (#2272)
* fix(ec2): type a security group rule's tags as security-group-rule inferResourceType had no sgr- case, so DescribeTags reported a rule's tags as resourceType "unknown" and a resource-type filter never matched them. The tags themselves were already correct: createTags stores them and updateResourceTags mirrors them onto the rule, so only the aggregation surface was wrong. Closes #2270 * fix(ec2): brace inferResourceType and tag the group in its test Bracing only the new arm would have left it the single braced line among thirteen, so the whole method is braced rather than just the addition. The test tagged only the rule, so the security-group assertion read an empty result and fell back to the expected value through orElse, passing without exercising the sg- classification at all. Tag the group too and assert on the result directly; removing the sg- arm now fails the test. --------- Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl> |
||
|
|
58129108bf |
fix(cloudformation): expand AWS::Serverless::HttpApi via SAM transform (#2146)
* fix(cloudformation): expand AWS::Serverless::HttpApi via SAM transform
SamTransformProcessor's switch on SAM resource types only handled
AWS::Serverless::Function, AWS::Serverless::SimpleTable, and
AWS::Serverless::Api (REST, v1) — AWS::Serverless::HttpApi fell into the
default branch and was silently dropped from the expanded template, along
with any Auth.Authorizers/DefaultAuthorizer config and any HttpApi-typed
Events on a sibling Function. A stack using AWS::Serverless::HttpApi
reported CREATE_COMPLETE with a synthesized physical id for the resource,
but no AWS::ApiGatewayV2::Api ever existed.
Adds expandServerlessHttpApi, mirroring the existing explicit-API pattern
(expandServerlessApi for REST v1) rather than the implicit-API path
(generateImplicitApi/collectApiRoutes), scoped to the explicit
AWS::Serverless::HttpApi + Function Events ApiId: {Ref: ...} form. For
each explicit HttpApi resource this synthesizes a real
AWS::ApiGatewayV2::Api, a $default auto-deploy Stage, one
AWS::ApiGatewayV2::Authorizer per Auth.Authorizers entry (mapping SAM's
mixed-case JwtConfiguration.issuer/audience onto the PascalCase
Issuer/Audience the raw CFN resource expects), and — for every Function
event bound to that API — an AWS_PROXY Integration, a Route wired to
Auth.DefaultAuthorizer when present, and a Lambda::Permission.
Implicit HttpApi (a Function's HttpApi event with no ApiId, where SAM
auto-creates the API) is intentionally out of scope here, matching how
this file already keeps generateImplicitApi/collectApiRoutes as a separate
concern from expandServerlessApi's explicit-resource handling.
Full JWT-authorizer enforcement additionally requires #1758
(AWS::ApiGatewayV2::Authorizer CloudFormation provisioning) — without it,
the Authorizer resource this transform synthesizes is itself dropped by
the provisioner's default branch, the same way it is for a raw (non-SAM)
template. Verified locally with both fixes applied together; #1758 is a
separate PR since the bugs are independent (raw-CFN provisioning vs. SAM
transform expansion) even though a SAM+JWT-authorizer template needs both.
Fixes #1759.
* fix(cloudformation): honor per-event Auth: {Authorizer: NONE} on HttpApi events
expandServerlessHttpApi applied the HttpApi's Auth.DefaultAuthorizer to every
route uniformly, ignoring SAM's documented per-event override
(Events.<Name>.Properties.Auth.Authorizer: NONE) that lets a specific route
opt out of the default authorizer — e.g. a route whose auth is handled
inside the application itself and needs a missing/invalid token to still
reach the handler rather than being rejected by the gateway.
HttpApiRoute now carries whether its event declared Auth.Authorizer: NONE,
collected in collectHttpApiRoutes alongside the existing path/method
fields, and expandHttpApiRoute skips wiring the default authorizer for
routes that opted out.
Found while validating #1759's fix against a template with this exact
pattern (one route using the default JWT authorizer, a second explicitly
set to Authorizer: NONE) — the original fix would have silently applied
the default authorizer to both.
* fix(cloudformation): forward SAM authorizer IdentitySource for HttpApi JWT authorizers
expandServerlessHttpApi's buildHttpApiAuthorizer hardcoded IdentitySource to
$request.header.Authorization regardless of what the SAM template's
Authorizers.<Name>.IdentitySource declared, silently overriding any
non-default source (e.g. $request.querystring.token) with the header form.
CloudFormationResourceProvisioner.resolveIdentitySource and
ApiGatewayExecuteController already support arbitrary identity sources,
including querystring, for raw (non-SAM) AWS::ApiGatewayV2::Authorizer
resources — this closes the same gap for the SAM transform, accepting either
the documented array form or a scalar string, matching the raw provisioner's
leniency.
Verified by reverting the fix and confirming
createStack_samHttpApiAuthorizerHonorsCustomIdentitySource fails.
* fix(cloudformation): reject SAM JWT authorizer with no IdentitySource
Real sam deploy rejects a JWT authorizer that omits IdentitySource
(_validate_jwt_authorizer in samtranslator/model/apigatewayv2.py) rather
than defaulting it. This transform was silently defaulting to
$request.header.Authorization instead, so a template real SAM refuses
would pass here quietly.
* fix(cloudformation): reject SAM HttpApi authorizer with no JwtConfiguration, honor case-insensitive Issuer/Audience
SAM's _validate_jwt_authorizer checks JwtConfiguration before IdentitySource,
rejecting a template that omits it. buildHttpApiAuthorizer treated it as
optional, silently producing an authorizer that would never validate a token
for real sam deploy. It now rejects in the same order SAM does.
SAM's _get_jwt_configuration also lower-cases every JwtConfiguration key
before reading it, so any casing of issuer/audience is accepted, not just the
two spellings the docs happen to show. Only the lowercase form was read here,
so a template using another casing silently produced an authorizer with an
empty JwtConfiguration instead of an error.
|
||
|
|
80d1dc732e |
feat(ses): implement PutAccountVdmAttributes and return VdmAttributes from GetAccount (v2) (#2265)
* feat(ses): implement PutAccountVdmAttributes and return VdmAttributes from GetAccount (v2) Add the SES v2 PutAccountVdmAttributes action (PUT /v2/email/account/vdm) and surface the account's VDM settings in GetAccount under VdmAttributes. The settings (VdmEnabled, DashboardAttributes.EngagementMetrics, GuardianAttributes.OptimizedSharedDelivery — each an ENABLED/DISABLED FeatureStatus) are stored per region and round-trip through GetAccount. VDM is opt-in, so each flag defaults to DISABLED. An invalid FeatureStatus value is a BadRequestException, matching AWS; Floci stores the settings but does not run VDM analytics. * fix(ses): reject non-string FeatureStatus values in PutAccountVdmAttributes parseFeatureStatus coerced any JSON node via asText(), so a boolean or object VdmEnabled produced a misleading enum error instead of being rejected as a type mismatch. Guard on isTextual() before matching the ENABLED/DISABLED enum, consistent with the other SES v2 parsers. * fix(ses): match AWS GetAccount VdmAttributes shape GetAccount always emitted VdmAttributes with the nested Dashboard/Guardian objects. AWS instead omits VdmAttributes entirely until VDM has been configured for the region, and once present adds the Dashboard/Guardian sub-objects only while VdmEnabled is ENABLED. Return VdmAttributes only when the region has stored VDM state, and gate the nested objects on the stored VdmEnabled flag. * test(ses): record live-AWS confirmation that unconfigured VDM omits VdmAttributes eu-west-1 and ap-northeast-1 (never configured) omit the VdmAttributes key, while a configured-then-disabled region reports VdmEnabled DISABLED. |
||
|
|
a985fa4640 |
feat(cloudformation): provision AWS::EC2::VPCEndpoint (#1995)
* feat(cloudformation): provision AWS::EC2::VPCEndpoint Maps VpcId/ServiceName/VpcEndpointType and the RouteTableIds/SubnetIds/ SecurityGroupIds reference lists onto the existing Ec2Service.createVpcEndpoint; DeleteStack removes the endpoint. Fixes #1994 * refactor(cloudformation): move VPCEndpoint into the per-service provisioner structure Ec2VpcEndpointCfnProvisioner implements CfnResourceProvisioner for AWS::EC2::VPCEndpoint and injects only Ec2Service. The registry discovers it via CDI, so the provision and delete switch arms plus the resolveIdList helper come out of CloudFormationResourceProvisioner. Two review fixes carried in with the move: - PrivateDnsEnabled now resolves through the template engine instead of props.path(...).asBoolean(false), so a Ref or parameter no longer collapses to false. An absent property passes null and Ec2Service applies the AWS default (true for Interface endpoints). - An update deletes the endpoint it replaced, so re-deploys no longer leave orphaned endpoints behind. A missing prior endpoint is tolerated. Adds an isolated unit test for the new provisioner; the existing CloudFormationVpcEndpointIntegrationTest still covers the end-to-end path. * feat(cloudformation): VPCEndpoint sets the CreationTimestamp attribute The registry schema lists Id, CreationTimestamp, NetworkInterfaceIds and DnsEntries as Fn::GetAtt attributes, and only Id was set. An unset attribute resolves to the literal "LogicalId.CreationTimestamp" rather than failing, so a template asking for it got a wrong value with nothing to signal it. Ec2Service already stamps the timestamp at create, so the provisioner renders it with the same format DescribeVpcEndpoints uses. NetworkInterfaceIds and DnsEntries are not modelled yet and stay unset. |
||
|
|
105a8eeb7e |
feat(cloudformation): provision AWS::Lambda::Permission and fix Version and Alias updates (#1997)
* feat(cloudformation): provision AWS::Lambda::Permission, Version, and Alias Maps the three Lambda addressing resources onto the existing LambdaService APIs: Permission -> addPermission (statement id = logical id, SourceArn/SourceAccount carried), Version -> publishVersion (Ref = version-qualified ARN, Version/FunctionArn attributes), Alias -> createAlias (Ref = alias ARN). Fixes #1996 * refactor(cloudformation): move Lambda addressing into a per-service provisioner Moves AWS::Lambda::Permission, Version and Alias out of the CloudFormationResourceProvisioner switch into LambdaAddressingCfnProvisioner, following the SqsCfnProvisioner pattern. CloudFormationResourceProvisioner is now byte-identical to main again. The provisioner implements delete(), so the three resource types no longer survive stack deletion. Physical ids double as delete handles: a Permission stores <functionName>|<statementId>, a Version its version-qualified function ARN, an Alias its alias ARN. Also fixes two behaviors the switch arms did not cover: - Alias RoutingConfig.AdditionalVersionWeights is now parsed and passed to LambdaService instead of being discarded. - Stack updates no longer recreate these resources. A Permission replaces its previous statement rather than colliding on the duplicate Sid, a Version keeps the version it already published, and an Alias updates in place, deleting the old alias when a rename retargets it. Adds LambdaService#deleteVersion (and the matching store method) so a single published version can be removed without taking $LATEST with it. * fix(lambda): a rejected permission replacement puts the previous statement back A stack update re-provisions every resource, and AddPermission rejects a duplicate Sid, so the provisioner removed the previous statement before adding its replacement. When the replacement was then rejected the function was left with neither: CloudFormation reported UPDATE_ROLLBACK_COMPLETE while every service that could invoke the function before the update had lost access. The statement is now captured before it is removed and put back if AddPermission fails, with the restore failure attached as suppressed so the stack still reports the original error. LambdaService gained restorePermissionStatement for this, which takes the stored statement shape rather than an AddPermission request so what goes back is exactly what came out. * fix(cloudformation): narrow the provisioner to AWS::Lambda::Permission upstream #1961 added LambdaVersionAliasCfnProvisioner, which claims AWS::Lambda::Version and AWS::Lambda::Alias. This provisioner claimed the same two, and the registry rejects a duplicate claim, so every stack rolled back with "Duplicate CloudFormation provisioner for AWS::Lambda::Version". Version and Alias provisioning is dropped here in favour of that one, which sets the same physical id and attributes. What is left is AWS::Lambda::Permission, which nothing else provisions. Delete now tolerates a statement or function that is already gone, so a DeleteStack retry does not fail a resource for work already done. * fix(cloudformation): a stack update keeps its Lambda version and applies alias routing Two gaps in LambdaVersionAliasCfnProvisioner, both reachable from a plain UpdateStack. provisionVersion called publishVersion unconditionally, so every update minted a new version and repointed every Ref to it. Version resources are immutable in CloudFormation, so the version this resource already published is kept while it still exists, and a new one is published only when it is gone or the FunctionName property moved to a different function. RoutingConfig was not carried over, on the grounds that nothing emitted it. The CloudFormation path does, so AdditionalVersionWeights is parsed and passed to create and update. A template that declares no RoutingConfig clears the weights rather than keeping them, which is why the existing alias test now expects an empty map instead of null. |
||
|
|
30a61646ac |
feat(ec2): support CreateImage (create AMI from instance) (#1979)
* feat(ec2): support CreateImage from an instance Validates the source instance exists, then registers an image the same way RegisterImage does. Unblocks AMI-baking flows (e.g. CDK AwsCustomResource calling ec2:CreateImage on a stack-created instance). Fixes #1978 * fix(ec2): CreateImage reboots the source and produces a launchable AMI Two review findings. CreateImage ignored the default reboot. AWS reboots the source instance unless NoReboot=true so the image is captured from a quiesced file system; the action only checked that the instance existed. NoReboot is now parsed and the reboot runs by default. The resulting AMI kept nothing of what it was captured from. registerImage was called with null architecture, root device and block device mappings, so DescribeImages reported a generic x86_64 /dev/sda1 image with no devices, and RunInstances on the new id fell through to the catalog default guest because a generated ami-* is not in the catalog. The image now inherits architecture, root device name and block device mappings from the source instance's image, and records the launchable ancestor so RunInstances starts the same guest. CreateImage on an instance launched from a created AMI follows the chain back. Tests: unit coverage for the reboot default and its NoReboot opt-out, and for chained images resolving to the catalog ancestor rather than the generated id; integration coverage that an arm64 source yields an arm64 AMI that launches. * fix(ec2): a capture of a catalog AMI reports its root device CreateImage inherits the source image's block device mappings, but a catalog entry describes only its root device name and carries no mappings, so an AMI captured from a catalog-launched instance was registered with no devices and DescribeImages reported none. The root device is now rebuilt from the catalog entry, with a snapshot registered through the existing RegisterImage path. * fix(ec2): a capture takes its own snapshot of each device CreateImage handed the source AMI's mappings straight to RegisterImage, so the captured image reported the source's snapshot ids and the two images shared one snapshot. The mappings are now copied with fresh snapshot ids, keeping the device name, size, type and encryption. * fix(ec2): a capture includes the volumes attached after launch CreateImage read only the mappings of the AMI the instance was launched from, so a data volume attached afterwards was missing from the captured image. AWS records block device mapping information for those volumes as well. The instance's attached volumes are now added to the capture, each with its device name, size, type and a fresh snapshot. The root volume is skipped because the source AMI already describes that device. Also lists CreateImage and RegisterImage in the AMIs action table. That table is hand-maintained because Ec2QueryHandler is a deferred handler. * fix(ec2): a capture reports the root volume type the source actually has The catalog-source fallback in sourceImageMappings recorded the rebuilt root device as gp2, while RunInstances creates the source instance's root volume as gp3. DescribeImages therefore reported a type the instance never had. Both sites now read one DEFAULT_ROOT_VOLUME_TYPE constant, alongside the existing DEFAULT_ROOT_VOLUME_SIZE_GIB, so the two cannot drift apart again. |
||
|
|
58112b1f3b |
fix(cloudformation): map FIFO and redrive attributes for AWS::SQS::Queue (#1939)
* test(cloudformation): reproduce dropped DeduplicationScope and FifoThroughputLimit in SqsCfnProvisioner * test(cloudformation): reproduce dropped RedrivePolicy in SqsCfnProvisioner * fix(cloudformation): pass DeduplicationScope and FifoThroughputLimit to CreateQueue * fix(cloudformation): serialize RedrivePolicy with resolved DLQ ARN for CreateQueue * test(cloudformation): cover FifoQueue mapping for queues without an explicit QueueName * fix(cloudformation): map FifoQueue and suffix generated FIFO queue names with .fifo * test(cloudformation): verify CFN FIFO queue attributes end-to-end via CreateStack * refactor(cloudformation): resolve FifoQueue once in SqsCfnProvisioner * fix(cloudformation): unwrap already-serialized RedrivePolicy strings RedrivePolicy in a template is usually a JSON object, but CDK commonly emits it as an already-serialized JSON string via Fn::Join. resolveNode collapses that to a TextNode, and calling toString() on it re-encodes (quotes/escapes) the string a second time, so SqsService.createQueue receives an unparseable value and the redrive silently doesn't work. Reported on #1939. * test(cloudformation): add regression test for string-form RedrivePolicy Reproduces the double-encoding bug reported on #1939: when RedrivePolicy is supplied as an already-serialized JSON string (CDK's common Fn::Join form), resolveNode collapses it to a TextNode and TextNode#toString() re-quotes/escapes it, so SqsService receives an unparseable value. * chore: retrigger CI (transient base-image layer pull failure) --------- Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> |
||
|
|
0971cf6f64 |
fix(cloudformation): resolve ASG launch templates by id and MixedInstancesPolicy (#2005) (#2019)
An AWS::AutoScaling::AutoScalingGroup that pointed at its launch template any way other than by LaunchTemplateName failed with "The specified launch template does not exist." provisionAutoScalingGroup collapsed LaunchTemplateId into the launch template name argument, and Auto Scaling matches names exactly, so a valid lt- id — including one that a Ref to an in-stack AWS::EC2::LaunchTemplate resolves to — never matched. The id and name are now passed to createAutoScalingGroup separately. MixedInstancesPolicy was never read from template properties, so a mixed-instances group reached Auto Scaling with no launch source and failed validation. It is now built in the same shape the Query API parser produces, including Overrides[].InstanceType and InstancesDistribution; a non-integer distribution value fails the stack rather than being silently dropped. CloudFormationAsgLaunchTemplateIntegrationTest covers resolution by name, by id, through a Ref to an in-stack launch template, and through MixedInstancesPolicy. Closes #2005 Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> |
||
|
|
7d66bf087a |
fix(cloudformation): expand SAM AutoPublishAlias into Version + Alias (#1961)
* fix(cloudformation): expand SAM AutoPublishAlias
AutoPublishAlias was read nowhere in the codebase, so the SAM transform
silently dropped it: the stack reached CREATE_COMPLETE, the function
deployed with only $LATEST, and an alias-qualified invoke then failed
with "Alias not found" far from the deploy that caused it. The
"Unsupported SAM resource type" debug arm only covers unknown resource
types, not unknown properties, so nothing was logged either.
Expand it into the AWS::Lambda::Version + AWS::Lambda::Alias pair real
SAM generates, and provision those two types. Both halves are needed:
the transform alone emits resources the provisioner ignores, and the
provisioner alone is unreachable from a SAM template.
The Lambda service already implements publishVersion and the alias APIs,
so this is plumbing rather than new service behavior. The new types go
through CfnResourceProvisioner rather than the legacy switch, following
the registry migration. Ref/GetAtt on the emitted properties give the
function -> version -> alias ordering that topologicalSort already
follows, so no explicit DependsOn is needed.
An intrinsic alias name (e.g. !Ref StageName) is passed through to Name
for the engine to resolve at provision time; only the generated logical
id needs a literal and drops the suffix in that case.
* test(cloudformation): cover Version/Alias provisioner directly
The SAM integration test drives provisioning end to end but cannot reach
two paths: the already-exists fallback (createAlias conflicting with an
alias that outlived a stack delete) and delete(), which its @AfterEach
invokes but never asserts on — a broken delete was silent.
Add LambdaVersionAliasCfnProvisionerTest alongside the existing Sqs and
Rds provisioner tests: attribute wiring for both types, the conflict
fallback, non-conflict failures still propagating, alias delete parsed
out of the ARN, delete idempotency when the alias is already gone,
version delete as a no-op, and a physical id that is not an alias ARN
(the generic fallback's shape on stacks predating this provisioner).
Also stop pinning the alias's FunctionVersion to a literal "1" in the
integration test: assert it is a number and not $LATEST, which is what
the assertion is actually for. Pinning the first version fails
confusingly when an earlier run leaks the function and its counter.
* fix(cloudformation): point the SAM alias at $LATEST
Real SAM points AutoPublishAlias at the published version, and the first
revision of this change did the same. Floci cannot invoke a published
version: the snapshot carries no code path, so a version-qualified
invoke times out on a cold start (#1987), and silently runs $LATEST's
code when a warm container happens to exist (#1988). Emitting the
faithful form therefore broke the alias-qualified invoke this expansion
exists to enable — strictly worse than not expanding the property.
Point the alias at $LATEST instead. The Version resource is still
emitted, so the resource set and GetAtt still match SAM; only the
alias target differs, and it flips back to the version in one line once
#1987 lands.
The integration test asserted the alias record existed with a numeric
FunctionVersion, which the broken form satisfied — so it passed while
the behavior was broken. It now invokes through the alias and asserts
the function actually runs, which fails against the version-pointing
form (verified by reverting it with the record assertion relaxed).
* fix(cloudformation): point the SAM alias at $LATEST
Restores the change
|
||
|
|
0cbfba82dd |
fix(cloudformation): infer Lambda FunctionName mode for pre-fix persisted stacks (#2177)
* fix(cloudformation): infer Lambda FunctionName mode for pre-fix persisted stacks
Fixes #2163
A Lambda function persisted before FlociLambdaFunctionNameMode was
tracked has no recorded mode, so removing an explicit FunctionName
from the template silently kept reconciling under the old explicit
name instead of triggering the replacement AWS requires - the same
bug already fixed for AWS::Logs::LogGroup in #1965/#2152.
Generalizes the LogGroup fix's isGeneratedLogGroupName into a shared
isGeneratedName(physicalId, stackName, logicalId, maxLength), reused
by both resource types instead of duplicated. Made it properly
truncation-aware in the process: at Lambda's 64-character limit,
generatePhysicalName's truncation path is actually reachable (unlike
LogGroup's 512, where CloudFormation's 128+255 character stack
name/logical id limits make it provably unreachable), so the shared
helper now reconstructs the exact expected prefix generatePhysicalName
would produce, truncation included, rather than only matching the
untruncated shape.
* docs(cloudformation): document isGeneratedName's lowercase and maxLength assumptions
Found while re-verifying #2163: several other generatePhysicalName
callers use lowercase=true (S3 bucket, some IAM resources, ECR repo)
or could theoretically use a very small maxLength, neither of which
isGeneratedName accounts for. Not a live bug since both current
callers (LogGroup at 512, Lambda at 64) use lowercase=false and a
maxLength comfortably above the point where the truncated prefix could
go empty, but worth spelling out for whoever reuses this next.
* fix(cloudformation): warn when legacy Lambda name inference is ambiguous
greptile flagged a real gap in the legacy FunctionName mode backfill:
isGeneratedName() can't distinguish a legacy explicit name that
deliberately matches the generated-name shape (e.g. a name copied from
an earlier auto-generated deploy and then pinned) from one that really
was auto-generated all along. If Floci gets it wrong, removing
FunctionName from the template silently keeps the old name instead of
triggering the replacement AWS would perform.
Checked whether this is actually closeable: LAMBDA_NAME_MODE_ATTR is
already written on every successful provision based on that deploy's
real hasExplicitName, so from a resource's second update onward the
mode is exact, no heuristic involved. The heuristic only ever runs
once, on a legacy resource's first update after this attribute was
introduced - and for that one-time backfill, there's no stored history
of the previous template's actual FunctionName property to consult;
Floci never persisted it. No additional data captured now can recover
what was never recorded then, so this can't be made more accurate.
What it can be is observable. Adds a warning logged specifically when
the inference is consequential - a legacy resource, no recorded mode,
the physical ID matches the generated shape, and the current template
also has no FunctionName - so an operator relying on that removal to
trigger a replacement has a chance to notice it silently didn't,
instead of this being an invisible guess. The other inference
direction (name doesn't match the generated shape) isn't ambiguous -
an auto-generated name always has the deterministic shape, so anything
else genuinely was explicit - and correctly doesn't warn.
Verified: two new tests confirm the warning fires for the ambiguous
case and stays silent for the unambiguous one. Confirmed the positive
test fails with the warning temporarily disabled and passes with it
restored. Full cloudformation package regression is green (one
pre-existing, unrelated ECR/Docker-dependent failure, confirmed
against a clean upstream/main baseline earlier this session).
* fix(test): pass the CloudFront service argument in the legacy name mode test
CloudFormationLambdaLegacyNameModeTest calls the CloudFormationResourceProvisioner
constructor with the parameter list it had before #1831 added the CloudFrontService
store, so the merge with current main does not compile. The call goes straight from
the trailing nulls to CloudFormationResourceRegistry, missing CloudFrontService
between them.
This branch predates #1831 (merged as
|
||
|
|
5156095f01 |
fix(apigateway): fall back to REST API region scan for non-SigV4 Authorization headers (#2149)
* fix(apigatewayv2): resolve HTTP API region across regions like REST APIs do Unsigned requests (and requests carrying a non-SigV4 Authorization header, e.g. a Cognito bearer JWT) resolve to RegionResolver's configured default region rather than a region the caller specified. For v1 REST APIs, resolveRestApiRegion already falls back to scanning all regions for the apiId when that happens. HTTP API (v2) dispatch had no equivalent, so any HTTP API deployed outside the default region returned 404 "Invalid API id specified" for every unsigned or bearer-token-authenticated request - which is effectively every request a browser, curl, or non-SigV4 client sends. Adds ApiGatewayV2Service#resolveHttpApiRegion, mirroring ApiGatewayService#resolveRestApiRegion exactly (same region::apiId key shape), and RegionResolver#isRegionUnresolved to give dispatch() a single correct signal for "region resolution silently fell back to the default" that covers both the blank-header and non-SigV4-header cases the previous blank-check missed. * test(apigateway): cover HTTP API cross-region resolution and non-SigV4 fallback Adds unit coverage for the dispatch() region-resolution fix: - An unsigned request for a v2 HTTP API deployed outside the default region must fall back to resolveHttpApiRegion and find it there. - A correctly-resolved (signed) request must not pay for the fallback scan. - A non-SigV4 Authorization header (e.g. a Cognito bearer JWT) on a v1 REST API must also trigger the region scan, not just a blank/missing header — using a real RegionResolver rather than a mock so the test exercises the actual header-parsing logic in isRegionUnresolved. Verified each test fails when the corresponding fix is reverted: the v2 test and the bearer-JWT test both fail (2 of 12) when dispatch()'s region-fallback logic is rolled back to the pre-fix version, confirming they aren't vacuously passing. * chore: trigger CI * refactor(apigateway): drop duplicate RegionResolver.isRegionUnresolved #2169 (merged) added resolveRegionFromAuthOrNull, the same predicate as isRegionUnresolved added here. Collapse onto the former per hectorvent's review note on #2169 rather than let both live in core/common. * test(apigateway): update mocks for merged v1-first dispatch flow Finish resolving the PR #2149 merge conflict — the test file's edits for the merged dispatch() ordering weren't included in the merge commit. * test(apigateway): note that v2 region tests pin #2054, not this PR Per review feedback on #2149: unsignedRequestFindsV2ApiDeployedOutsideDefaultRegion and signedV2RequestDoesNotConsultRegionFallback exercise v2 cross-region dispatch behavior that landed independently in #2054, not the v1 Authorization-header fix this PR makes. Kept as the only controller-level coverage of that behavior, with a comment so they aren't read as regression guards for this change. |
||
|
|
12154297b5 |
feat(iam): support account aliases (#2103)
* feat(iam): support account aliases Implement ListAccountAliases, CreateAccountAlias and DeleteAccountAlias. An account holds at most one alias: creating a second returns EntityAlreadyExists, and deleting requires the current alias by name so a stale value cannot silently clear it. FLOCI_SERVICES_IAM_ACCOUNT_ALIAS seeds an alias at startup for callers that expect to read one without creating it first. Closes #2101 * fix(iam): make account alias create and delete atomic Concurrent CreateAccountAlias calls could all pass the emptiness check and write, reporting success to every caller while keeping only one value. Unlike a named resource, where racing creates carry the same name and either winner is equivalent, racing alias creates carry different values, so a loser is told their alias was set when another is stored. Guard the check-then-write on both create and delete, and cover it with a concurrency trial asserting exactly one winner. Also track the alias created by the bats delete case in ACCOUNT_ALIAS so teardown clears it if the test fails midway. * fix(iam): match verified AWS account alias semantics and unbreak the test fixture IamServiceTestHelper resolves the package-private IamService constructor reflectively against a hardcoded parameter list, so the extra storage backend broke it at run time with no compile-time signal. Every test using that fixture errored, and one of them hangs on a socket read rather than failing, which is what exhausted the CI job. Extend both lookups to the new arity. Checking the error message against a live AWS account showed the operation itself was modelled wrongly: CreateAccountAlias does not reject a second alias, it replaces the current one. EntityAlreadyExists means the requested name is taken, which for a single-account store is only the alias already held. Create now replaces and rejects just that case, which also makes the message name the alias the caller asked for. DeleteAccountAlias applies the same pattern constraint as create, so a malformed value is a ValidationError. Concurrent creates therefore all succeed with last-write-wins; the trial now asserts the store settles on one of the requested values. Seeding logs when it skips because an alias is already stored, which is otherwise invisible under persistent storage. * fix(test): repair iam.bats after the merge fused test bodies Resolving the merge by keeping both sides concatenated the OIDC and account alias cases as text, which left the create_oidc_provider helper nested inside an alias test and dropped a closing brace, so bats could not parse the file and produced no report at all. Rebuild it from main plus the alias cases, with the alias tracked in setup and teardown. * test(iam): pin account alias isolation, and document the two-dash rule The alias is the only IAM entity keyed by a constant rather than a caller-supplied name, so every account shares one storage key and the separation rests entirely on AccountAwareStorageBackend prefixing. Every integration test here signs as the same account, so that prefixing was never exercised for aliases. The new case pins it: handing both services the store unwrapped fails it. The docs still described the pre-fix constraint. They now carry the consecutive-hyphen rule and note that the ValidationError message, reproduced from AWS verbatim, does not itself mention it. --------- Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com> Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl> |
||
|
|
a6f5f12295 |
fix(ec2): keep the source on security group rules (#2266)
* fix(ec2): keep the source on security group rules AuthorizeSecurityGroupIngress and -Egress read only IpPermissions.N.IpRanges.M.CidrIp, so a rule whose source is another security group was accepted and then silently stripped: it came back with no source at all on the authorize response, on DescribeSecurityGroups and on DescribeSecurityGroupRules. "Allow traffic from security group X" is how an ALB is wired to its backend tasks, so that whole class of wiring could be created against Floci but never asserted afterwards. Parse the source types the permission actually carries: group references, which the EC2 Query protocol serializes under the wire name Groups rather than the SDK-facing UserIdGroupPairs, and IPv6 ranges. A reference made by group name resolves to its group id within the target group's VPC, since names are unique per VPC and ReferencedSecurityGroup has no name field. Flatten one SecurityGroupRule per source entry, each keeping its own description, matching the AWS invariant that a rule holds exactly one source. A permission with no source at all still yields a single sourceless rule, as before. The reference is returned as referencedGroupInfo on DescribeSecurityGroupRules and as UserIdGroupPairs on DescribeSecurityGroups. An IPv6-only TCP ingress rule now publishes its host port, which it could not do while the ranges were dropped at the parse; Ec2PortForwardManager already treats IPv6 ranges as a CIDR source, and group references stay unpublished. Revoke still matches on protocol and port range alone and ignores sources, unchanged by this. Closes #2190 * style(ec2): brace the conditionals in the new source parsing AGENTS.md requires braces on every conditional. The new IPv6 and group source loops and the group-reference resolution used the unbraced form the surrounding parse loop happens to use. |
||
|
|
ecad6acf58 |
feat(swf): add Simple Workflow Service emulation (#2257)
* feat(swf): add Simple Workflow Service emulation
Implements all 39 SWF operations over the JSON 1.0 protocol
(X-Amz-Target: SimpleWorkflowService.*): domain and type registration,
the workflow execution state machine, and the decider/worker task
lifecycle.
Behaviour was derived from botocore's swf-2012-01-25 model and verified
against the live service, which drove several details that are easy to
get wrong from the model alone:
- Faults carry a namespaced __type (com.amazonaws.swf.base.model#Fault)
in the body but the bare fault name in x-amzn-query-error. botocore
prefers the header, so a namespaced value there makes the CLI print
"com.amazonaws.swf.base.model#UnknownResourceFault" where SWF prints
"UnknownResourceFault". SwfException keeps the two spellings apart.
- Timestamps are epoch-second numbers, not ISO strings.
- Void operations answer 200 with an empty body rather than {}.
- An idle poll returns taskToken "" rather than omitting the member;
the SDKs read the empty token as "no task".
- ActivityTaskTimedOut reports startedEventId 0 for a task that never
started, and WorkflowExecutionStarted reports parentInitiatedEventId 0
on root executions, rather than omitting either member.
State machine:
- One decision task outstanding per execution. Events arriving while one
is outstanding set a pending flag that is satisfied when it completes,
so a signal cannot produce two concurrent decision tasks.
- Decisions apply in order; a decision after a closing decision is
dropped. A decision that cannot be applied appends its *Failed event
with the AWS cause and gives the decider a fresh task instead of
failing the request.
- Closing with open activities, timers, or children appends
UNHANDLED_DECISION and leaves the execution open.
- Timeouts (activity schedule-to-start, start-to-close,
schedule-to-close, heartbeat; decision start-to-close; execution
start-to-close; timers) expire from one background sweep rather than a
timer per task, so a restart leaves nothing to reconcile.
- Child executions link to their parent and report their outcome back;
the closing parent's childPolicy is applied to open children.
Tests: 29 unit tests drive timeout expiry through a controllable clock,
32 integration tests assert the wire shapes and fault strings captured
from the live service, and a compatibility suite exercises the same
flows through the AWS SDK v2 client so responses must deserialize into
the generated model and faults into typed exceptions.
Long polling, ScheduleLambdaFunction invocation, and retention-based
pruning are not implemented; docs/services/swf.md records each.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): report the child-started event id on ChildWorkflowExecution* events
A ChildWorkflowExecution* event carries two correlation ids, and they point at
different events in the parent's history: initiatedEventId is the
StartChildWorkflowExecutionInitiated id, startedEventId is the
ChildWorkflowExecutionStarted id. Both were reported as the initiated id, so a
decider correlating a child's outcome on startedEventId matched the wrong event.
Verified against the live service, where a parent that starts one child and sees
it complete produces:
5 StartChildWorkflowExecutionInitiated
6 ChildWorkflowExecutionStarted {initiatedEventId: 5}
8 ChildWorkflowExecutionCompleted {initiatedEventId: 5, startedEventId: 6}
The child now records the parent's ChildWorkflowExecutionStarted id at start
time and reports it back on every ChildWorkflowExecution* event.
The integration test asserts both ids against the events they name rather than
against a "greater than zero" placeholder, and fails on the previous behaviour
with "startedEventId Expected: <6> Actual: <5>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): reject a decision batch whose closing decision is not last
RespondDecisionTaskCompleted accepted a batch with decisions after a closing
decision and silently dropped the remainder. The live service rejects the whole
batch instead:
HTTP 400
{"__type":"com.amazon.coral.validate#ValidationException",
"message":"Close must be last decision in list"}
Silently accepting it hides a decider bug and diverges on both the status code
and the response body, so a decider that ships a malformed batch sees success
locally and a 400 against AWS.
The batch is now validated before any state is mutated, matching the live
service's behaviour of leaving the decision task outstanding so the decider can
retry with a corrected batch. Note this fault is namespaced
com.amazon.coral.validate rather than com.amazonaws.swf.base.model.
Tests assert the status code, both fault spellings, the message, that no
DecisionTaskCompleted event is appended, and that the same task token still
works afterwards. They fail on the previous behaviour with "Expected status code
<400> but was <200>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): name the scheduled event when an activity task has already closed
An activity task token that resolves to a task which is no longer open reported
"Unknown or expired task token". The live service distinguishes the two cases: a
genuine token whose task has closed names the scheduled event instead, because
the token itself was valid.
Captured from the live service, heartbeating a task that a cancel had already
closed:
HTTP 400
{"__type":"com.amazonaws.swf.base.model#UnknownResourceFault",
"message":"Unknown activity, scheduledEventId = 5"}
Both cases are UnknownResourceFault, so SDK error typing was already correct and
only the message diverged — but a worker that logs or matches on the message sees
a different string locally than against AWS.
A token that never existed still reports the bad token; only a resolved token on
a closed task reports the scheduled event. This required keeping the token's map
entry when an activity closes, since removing it made both cases indistinguishable;
reuse is still refused by the existing open-state check.
Test asserts both branches and fails on the previous behaviour with "expected:
<Unknown activity, scheduledEventId = 5> but was: <Unknown or expired task token>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): serialize execution mutation per domain and guard the sweep interval
Addresses three review findings.
Concurrent StartWorkflowExecution calls for one workflowId all scanned for an
open run before any of them inserted, so each persisted its own run key. Eight
concurrent starts produced eight open runs where SWF admits one, and later
operations without a runId then selected an arbitrary run. The open-run check
and the insert are now one atomic step.
A closing execution mutates its parent (ChildWorkflowExecution* events) and its
children (childPolicy), but held only its own lock, so event-id allocation and
the history list raced. Six children closing against one parent reproduced
ConcurrentModificationException.
Both come from the same mismatch: the lock was per execution while the
invariants span an execution family. The lock is now per domain. A parent and a
child always share a domain, so one lock covers the family and never has to be
nested — nesting would deadlock, since a closing child takes its parent while a
closing parent takes its children. Per-domain granularity is sufficient here:
the emulator serves a single developer's workload, not production concurrency.
A zero or negative timeout-sweep interval reached scheduleWithFixedDelay, which
threw IllegalArgumentException out of the StartupEvent observer and stopped the
whole emulator becoming ready — one bad SWF setting taking down every other
service. A non-positive interval now falls back to 1s with a warning.
Tests fail on the previous behaviour with "expected: <1> but was: <8>",
ConcurrentModificationException, and IllegalArgumentException respectively.
Verified over the wire too: eight concurrent starts yield one success, seven
WorkflowExecutionAlreadyStartedFault, and one open run.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): report the live service's TypeNotDeprecatedFault message
DeleteWorkflowType/DeleteActivityType against a still-registered type
reported the type descriptor, e.g. "WorkflowType=[name=W, version=1]". The
live service answers with prose instead, and uses the same wording for both
type kinds:
{"__type":"com.amazonaws.swf.base.model#TypeNotDeprecatedFault",
"message":"The type is currently registered and cannot be deleted in its
current state"}
Since both variants are identical, the two fault factories collapse into one.
The descriptor form is still correct for the other type faults
(TypeDeprecatedFault, TypeAlreadyExistsFault, UnknownResourceFault), which were
verified unchanged in the same probe.
Also adds integration coverage for the five actions that had none at either
test layer: DeprecateActivityType, UndeprecateActivityType, DeleteActivityType,
ListWorkflowTypes, and RespondActivityTaskFailed. Every assertion is taken from
a live-service capture, including that scheduling a deprecated activity type
appends ScheduleActivityTaskFailed with cause ACTIVITY_TYPE_DEPRECATED and
leaves the execution open, that ListWorkflowTypes filters by registration
status and name, and that a second RespondActivityTaskFailed on the same token
reports "Unknown activity, scheduledEventId = 5".
The message tests fail on the previous behaviour with "Expected: The type is
currently registered ... Actual: WorkflowType=[name=TestWf, version=1.0]".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* feat(swf): invoke real Lambda functions for ScheduleLambdaFunction
The decision was recorded as ScheduleLambdaFunctionFailed with cause
LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION rather than invoking anything. SWF is
otherwise a pure coordination service — deciders and activity workers are the
user's own processes, so there is no user code for the emulator to run — but
ScheduleLambdaFunction is the one decision where SWF itself executes something,
and Floci already runs Lambda functions in containers. A decider that fans work
out to Lambda could not be exercised locally at all.
Floci now invokes the function through its own Lambda service, the same way the
EventBridge and Scheduler invokers do, and records the outcome. Verified against
the live service:
5 LambdaFunctionScheduled {control, id, input, name, startToCloseTimeout}
6 LambdaFunctionStarted {scheduledEventId: 5}
7 LambdaFunctionCompleted {result, scheduledEventId: 5, startedEventId: 6}
8 DecisionTaskScheduled
Four behaviours came from that capture and are easy to get wrong:
- A function that cannot be resolved is LambdaFunctionFailed with Lambda's own
error code as reason (ResourceNotFoundException) — not
ScheduleLambdaFunctionFailed — and it still reports Started first.
- An execution with no lambdaRole never starts the function at all: Scheduled is
followed by StartLambdaFunctionFailed with cause ASSUME_ROLE_FAILED and the
message "No IAM role is attached to the current workflow execution."
- lambdaRole resolves from StartWorkflowExecution's lambdaRole, falling back to
the workflow type's defaultLambdaRole, and is echoed in the started event.
- An absent input reaches the handler as {}, and reusing an id is accepted —
there is no ID_ALREADY_IN_USE for Lambda the way there is for activity ids.
SwfService takes a LambdaInvoker seam rather than LambdaService directly, so the
unit tests keep running without a Docker daemon while SwfLambdaInvoker wires the
real thing at runtime. The invocation is RequestResponse because the response
body is what gets recorded as result; the fire-and-forget invokers use Event for
the opposite reason.
The Lambda region comes from the execution's domain ARN, so a workflow in one
region does not invoke a function in another.
Tests: SwfServiceTest covers all four paths against a recording invoker and
fails on the previous behaviour with "the function must actually be invoked
==> expected: <1> but was: <0>". SwfLambdaIntegrationTest and the SDK
compatibility SwfLambdaTest deploy a real function and assert the recorded
result is what the container returned, so neither passes against a synthesised
event. Docker-backed cases live in their own class so a Docker-less run loses
only them rather than the whole SWF wire suite.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): scope state by region and paginate the registration lists
Addresses two AWS compatibility gaps from review.
SWF names are unique per region, but storage keys were the bare name, so
registering a domain in us-east-1 made the same name in eu-west-1 fail as a
duplicate, and describe/list could return the first region's domain and ARN.
Verified against the live service: the same name registers in both regions with
independent descriptions and retention periods, each ARN naming its own region;
a type registered in one region answers UnknownResourceFault in the other; and
executions, including their runIds, do not cross.
Keys are now region-qualified — `<region>:<domain>` for domains,
`<region>:<domain>/<name>/<version>` for types, and
`<region>:<domain>/<workflowId>/<runId>` for executions — and every store scan
is prefixed by region. The region reaches the service on each call and is stored
on the execution, which is also what task tokens resolve through, so a token
issued in one region cannot address another's execution. The per-domain
mutation lock is region-qualified too; leaving it bare would have let two
regions serialize against each other, and would have disagreed with the
sweeper's own lock derived from the storage key.
ListDomains, ListWorkflowTypes and ListActivityTypes ignored maximumPageSize and
nextPageToken and returned everything. They now share one paging helper with the
history and execution listings. Details taken from live captures rather than the
docs: nextPageToken is absent on the final page even when that page is exactly
full, a maximumPageSize of 0 or absent means "no caller limit", above 1000 is
rejected rather than clamped, and a corrupt token answers
`ValidationException: Invalid token` instead of silently restarting at the first
page — which would make a paging loop repeat forever.
Adds AWS SDK regression tests (SwfRegionPaginationTest) driving two clients at
different regions against the same emulator, plus wire-level integration
coverage. Against the previous implementation those SDK tests fail with
DomainAlreadyExists on the second region, "maximumPageSize must cap the page: 5",
and nothing thrown for an oversized page size.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* test(swf): pin reverseOrder as applying before pagination
The registration lists reverse the whole result set and then page it, so with
maximumPageSize=3 and reverseOrder=true the first page is the tail of the
ascending order. That was already the behaviour but nothing asserted it, and the
shared paging helper makes "page first, then reverse the page" an easy
regression to introduce.
Measured against the live service: 5 types at page size 3 reversed returns
Paged4, Paged3, Paged2 and then Paged1, Paged0. Injecting the page-then-reverse
ordering fails the new test with
"Expected: <[Paged4, Paged3, Paged2]>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* test(swf): cover region scoping at the wire level
The region-scoping tests went in at the service and SDK layers, but every
SwfIntegrationTest request omitted an Authorization header, so nothing asserted
that the region is read from the SigV4 credential scope — the step that decides
which region's state a call addresses.
Adds a wire test that sends a credential scope naming the region, covering the
same name registering in two regions with independent descriptions, retentions
and ARNs, a type being unknown in the other region, and a same-region
re-registration still faulting.
Against
|
||
|
|
12cf6e2fd8 | fix(cloudwatch): reject invalid log event tokens (#2249) | ||
|
|
2d003b52f2 |
fix(ec2): reject prefix list names AWS reserves for its own lists (#2274)
* fix(ec2): reject prefix list names AWS reserves for its own lists CreateManagedPrefixList accepted names beginning com.amazonaws., com.amazon. or com.aws., which AWS refuses with InvalidParameterValue, so a customer list could shadow a seeded gateway-endpoint one. The trailing dot is part of each prefix. Checked against a live account: com.amazonaws-probe and comamazonaws.probe are both accepted there, so matching without the dot would refuse names AWS allows. Closes #2273 * fix(ec2): apply the reserved-name rule to a prefix list rename too ModifyManagedPrefixList persisted any nonblank name, so a list could be renamed to com.amazonaws.us-east-1.s3 and returned alongside the seeded AWS-managed list of that name. AWS applies the same rule to a rename, verified against a live account, and leaves the existing name in place when it rejects one. Create and rename now share the check. --------- Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl> |
||
|
|
62ff490619 |
fix(test): pass the managed prefix list store in Ec2PublicIpOnLaunchTest (#2288)
The test calls the package-private Ec2Service constructor with the parameter list it had before #2105 added the managed prefix list store, so main does not compile. #2023 was written before that landed and merged after it. Closes #2287 Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl> |
||
|
|
5657e35007 |
feat(cloudfront): enforce signed private content (#1831)
* feat(cloudfront): serve distribution requests from S3 and custom origins * feat(cloudfront): enforce signed private content * 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. * fix(cloudfront): wildcard aliases match exactly one subdomain level wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the wildcard at that level only: "you can't add alternate domain names that are at levels higher or lower than the wildcard. For example, you can't add the alternate domain names example.com or marketing.product.example.com." https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html Practical effect: a distribution owning "*.example.com" would answer for a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to nobody. Require the label standing in for the wildcard to contain no dot. wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour (a.b.example.test resolving to the *.example.test distribution); it now asserts no match, plus the same for a deeper wildcard. * test(dynamodb): retain Quarkus port for cleanup * fix(cloudfront): isolate mocked storage backends * fix(cloudfront): match wildcards in signed policy queries |
||
|
|
2ab795c6dc |
fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#2023)
* fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#1984) Every instance was given PublicIpAddress 127.0.0.1 unconditionally in Ec2ContainerManager, so a private-subnet instance wrongly reported an internet-facing address (breaks the ssh-reachability / public-vs-private distinction). runInstances now flags the instance (associatePublicIp) from its subnet's MapPublicIpOnLaunch, and the container manager exposes a public address only when that flag is set. Private-subnet instances get no PublicIpAddress — DescribeInstances omits the element (XmlBuilder skips nulls), matching real EC2. The value for public instances stays the host-reachable 127.0.0.1 (unchanged). Unit test covers the public-vs-private flag. Supports the aws-bench project: un-excludes the ssh-reachability scenario. * fix(ec2): honor the launch-time AssociatePublicIpAddress override * fix(ec2): honor the top-level AssociatePublicIpAddress and an explicit-false launch configuration Two gaps left by the previous commit, both flagged in review. RunInstances only read the override off the primary network-interface spec (NetworkInterface.1.AssociatePublicIpAddress), so the legacy top-level AssociatePublicIpAddress parameter — what the CLI and older SDKs send — was silently dropped and the subnet default decided instead. It is now read as a fallback; AWS rejects both shapes at once, so the interface spec wins when present. The launch-configuration path was worse than before. LaunchConfiguration stored a primitive boolean, so an absent flag and an explicit false were indistinguishable, and the reconciler could only forward an explicit true. An LC that set AssociatePublicIpAddress=false in a MapPublicIpOnLaunch subnet still got a public address. The field is now a nullable Boolean the whole way through (service, query handler, CFN provisioner), so false overrides the subnet and only null falls back to it. DescribeLaunchConfigurations omits the element when it was never set, as AWS does. Tests: a handler-level test pins all four parse cases (top-level, interface spec, both present, absent), and the reconciler test pins true/false/null reaching runInstances unchanged. |
||
|
|
188588b4eb |
fix(s3): derive S3 host suffix matching from DNS config (#1843)
* fix(s3): derive S3 host suffix matching from DNS config
S3VirtualHostFilter hardcoded the wildcard-DNS suffixes (localhost.floci.io,
localhost.localstack.cloud) in two places: the bare service-host check
(isS3ServiceEndpointHost) and the virtual-hosted bucket fallback (isAwsS3Domain).
Both now derive their suffix set from the embedded DNS source of truth plus any
configured floci.dns.extra-suffixes, so a custom DNS suffix is recognised the same
way the builtins are.
Why: the two literal lists duplicated what the DNS server already knows and could
drift from it silently. Deriving from EmbeddedDnsServer.BUILTIN_SUFFIXES keeps them
in lockstep, and folding in extra-suffixes means a user migrating from LocalStack
via a custom suffix gets consistent S3 host handling (bucket routing and service
endpoint detection), not just the DNS resolution they get today.
How:
- buildServiceHostSuffixes() computes {localhost} + BUILTIN_SUFFIXES + extra-suffixes
once per instance; isS3ServiceEndpointHost() checks membership instead of literals.
- matchesConfiguredSuffixHost() routes the virtual-hosted forms bucket.<suffix>,
bucket.s3.<suffix> and bucket.s3.<region>.<suffix> for every configured suffix,
replacing the hardcoded localstack/floci branches in isAwsS3Domain.
- EmbeddedDnsServer.BUILTIN_SUFFIXES widened to public so the filter reuses the list.
The virtual-host match now requires the full builtin suffix (.localhost.localstack.cloud)
rather than the bare parent domain (.localstack.cloud), matching LocalStack's actual
wildcard DNS (*.localhost.localstack.cloud).
* test(s3): derive DEFAULT_SUFFIXES from the production factory
The test constant hardcoded a copy of the builtin suffix set, which would
silently drift if a new builtin were added to EmbeddedDnsServer.BUILTIN_SUFFIXES.
Widen buildServiceHostSuffixes() to package-private and reuse it in the test so
the two stay in sync automatically.
* fix(s3): include the configured hostname in the derived suffix set
EmbeddedDnsServer resolves builtins + floci.hostname + floci.dns.extra-suffixes,
but the derived service-host set carried only two of the three. The configured
hostname reaches the filter as baseHostname, and matchesEndpointHost excludes the
bare s3.<host> remainder by design, so the bucket form one level down
(bucket.s3.<hostname>) matched nothing. DNS still resolves that host, so the
request reached Floci and was then handled path-style, binding the first path
segment as the bucket, rather than being refused.
Carry the hostname into buildServiceHostSuffixes so all three DNS inputs are
mirrored and a host that resolves by wildcard DNS routes under the same rules.
|
||
|
|
97ac3cabb5 |
feat(stepfunctions): add UpdateStateMachine and update in place on stack updates (#1867)
* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates * test(dynamodb): retain Quarkus port for cleanup * chore: rerun CI after download outage * fix(cloudformation): preserve log group on failed rename * fix(cloudformation): scope update rollback to attempted resources * fix(cloudformation): delete resources after stack updates * test(cloudformation): wire cloudfront fixture dependency * fix: include Step Functions update date in describe response * fix: preserve Step Functions describe response shape * fix: preserve generated Step Functions names |
||
|
|
da5ff910b4 |
fix(ec2): start sshd even when run-instances omits a key pair (#2245)
* fix(ec2): start sshd even when run-instances omits a key pair Reported in #2184: run-instances without --key-name left every container with no SSH daemon listening at all, "connection refused" regardless of image (alpine, Amazon Linux 2023, Ubuntu all affected). The cause: startSshd() only ran inside the same conditional as injectSshKey(), so no key pair meant sshd never started. Real AWS AMIs run sshd as part of normal boot regardless of whether a key pair is attached - the daemon is always there, it just has nothing to authenticate an unattached client with. Floci's behavior diverged by not running the daemon at all in that case, rather than running it and correctly having no way in. Splits the two: injectSshKey still only runs when a key was actually provided (nothing to inject otherwise), but startSshd now always runs. It's fully self-contained already (installs openssh-server if absent, generates host keys, starts the daemon) and never depended on anything injectSshKey sets up, so making it unconditional needed no other changes. Verified: new test launches an instance with no public key and asserts sshd still starts (and confirms nothing gets written to authorized_keys, since there's no key to inject). Confirmed it fails with the fix reverted (no /usr/sbin/sshd invocation happens without a key) and passes with it restored. Full ec2 package regression is green (268 tests) - including the several existing tests that already launched with no key pair and needed no changes to keep passing. * fix(ec2): stop silently claiming sshd started when it never actually did Follow-up on a comment from duytanisme on #2245: sshd not starting even when an SSH key IS provided, requiring a manual exec-in or a custom user-data script to work around it. Root cause: startSshd() ran every step through execInContainer(), which discards the exec's exit code entirely and only throws if the Docker API call itself fails. The install step's shell script is an if/elif chain with no matching branch, or whose install command itself failed (no network yet, apt lock held, etc.) - and a bash if/elif with no matching branch and no else clause exits 0 by convention. So a container without a package manager, or one where the install call failed for any reason, still reported success, ssh-keygen and sshd then both ran anyway against a daemon that was never installed, and "Started sshd in EC2 instance" got logged regardless. Switches every step to execInContainerForResult and checks its exit code explicitly, following the exact pattern already used by configureLinkLocalMetadataEndpoint for the same class of problem: bail out and log a specific warning with the actual command output at whichever step actually failed, instead of silently proceeding. Also adds an explicit "command -v sshd" as the last statement of the install script, so its own exit code is the real source of truth for whether sshd is actually available afterward, and switches the start command from a hardcoded /usr/sbin/sshd to a bare "sshd" resolved via PATH (matching how ssh-keygen is already invoked two lines above), since not every image installs it to that exact path. Verified: new test forces the install probe to fail and asserts ssh-keygen and the start command are never even attempted. Confirmed it fails (proceeds anyway) with the exit-code check disabled and passes with it restored. Updated the existing no-key-pair test for the new bare "sshd" command. Full ec2 package regression is green (269 tests). |
||
|
|
a0adea9073 |
fix(cloudwatch): return logStreamName on FilterLogEvents results (#2259)
FilterLogEvents is the cross-stream search API, so a match is only attributable if the response names the stream that emitted it. Floci served FilterLogEvents and GetLogEvents from one serializer emitting eventId, timestamp, message and ingestionTime, so a caller searching a whole log group could tell which group a hit came from but not which stream, and tooling written against real AWS lost that attribution without any error. Derive the stream from the event's storage key rather than persisting it on the event. Keys are already <region>::<group>::<stream>::<timestamp>::<uuid>, so the key is an authoritative record of the emitter for every event in the store, including ones written before this change. Storing the name on LogEvent instead would leave every already-persisted event with a null logStreamName and need a backfill pass to repair it. The stream is read back between the group prefix and the trailing timestamp and uuid, both generated here, so a stream name is recovered whole even though nothing stops a caller from creating one that holds a ':'. filterLogEvents walks the keyset once and pairs each event with its stream, which also collapses the stream-restricted branch: it previously ran one full keyset scan per requested stream, since a scan walks every key regardless of the prefix it filters on. GetLogEvents keeps its existing shape. Real AWS returns OutputLogEvent there, which carries no logStreamName, because the caller named the stream in the request. Closes #2210 |
||
|
|
a49c3e57f6 |
fix(apigateway): apply MOCK integration response headers (#1822)
* fix(apigateway): apply mock response headers for OPTIONS * refactor(apigateway): drop the OPTIONS route in favour of #1955 Both this PR and #1955 added an @OPTIONS method on the same @Path in ApiGatewayExecuteController and ApiGatewayUserRequestController, so whichever merged second would not have compiled. #1955's version is the more complete one: it covers ApiGatewayAwsExecuteController (the /_aws/execute-api path) as well, forwards the request body, and skips GlobalCorsFilter for deployed-API paths -- without which a real browser preflight is short-circuited before it ever reaches the route. This PR keeps only its own contribution: invokeMock returned early on the empty-response-template path and dropped static method.response.header.* mappings. ApiGatewayMockCorsHeadersTest now exercises that over GET, since the dropped-header bug is verb-agnostic, leaving the two PRs independently mergeable in either order. * test(dynamodb): retain Quarkus port for cleanup * chore: rerun CI after autoscaling test flake --------- Co-authored-by: abanna <abanna@users.noreply.github.com> |
||
|
|
5d61e95239 |
perf(lambda): reuse a populated code volume across restarts via a completion marker (#1827)
* perf(lambda): reuse populated code volumes across restarts * test(dynamodb): retain Quarkus port for cleanup * chore: rerun CI after download outage * ci: retry transient gosu downloads --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com> |
||
|
|
a7da1b9856 |
feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency (#1810)
* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency A Map state ran its iterations one after another. AWS runs them concurrently up to MaxConcurrency (default 0 = unlimited), which is a correctness requirement, not just a speed-up: a Map whose iterations coordinate — e.g. a dependency-ordered fan-out where one child blocks until a sibling completes — deadlocks when the iterations are serialised. Run each iteration on the shared executor under the execution's account, gated by a Semaphore sized to MaxConcurrency (unlimited when 0). Results are written into per-index slots so the output array preserves input order regardless of completion order, MaxConcurrency=1 stays strictly sequential, and a failed iteration cancels the rest and fails the Map (fail-fast, matching the default ToleratedFailureCount of 0). * fix(stepfunctions): cap Map worker threads with a bounded pool + handle interruption Address review: submitting every iteration to the shared cached pool behind a Semaphore spawned one thread per item (a 1000-item Map with MaxConcurrency=5 created ~1000 threads, ~995 parked). Run iterations on a fixed-size per-Map ThreadPoolExecutor sized to MaxConcurrency so live threads are capped and the rest queue. shutdownNow() in finally stops the iterations on any exit, and an InterruptedException from the driver now preserves the interrupt status. * fix(stepfunctions): make Map concurrency bounded and fail-fast * docs(stepfunctions): document map concurrency * test(dynamodb): retain Quarkus port for cleanup * chore: rerun CI after OpenTofu registry flake * test(stepfunctions): pin Map item selection order |
||
|
|
9e7cdad29a | fix(rds): preserve configured database images (#2035) | ||
|
|
45bb37f1fb |
feat(apigatewayv2): route execute-api hosts to WebSocket $connect and @connections (#2188)
Consolidates AWS-style execute-api virtual-host support for WebSocket APIs onto the existing ApiGatewayExecuteApiHostFilter (added in #2054) plus the WebSocket handler, instead of adding a second host filter. - @connections (#1846): ApiGatewayExecuteApiHostFilter now also rewrites a WebSocket API's @connections management calls (.../{stage}/@connections/{id}) to the canonical /execute-api/{apiId}/{stage}/... route, behind the same disableExecuteApiEndpoint->404 check. It previously bailed for non-HTTP APIs, so @connections on the execute-api host was swallowed by the S3 controller. - $connect (#1871): WebSocketHandler accepts the execute-api host for the WS handshake and resolves the API region -- from the host's region label when present, else a cross-region apiId lookup (ApiGatewayV2Service.resolveApiRegion) -- fixing the 403 for APIs created in a non-default region. - Widen the filter host regex to accept the region-bearing AWS form ({apiId}.execute-api.{region}.localhost|amazonaws.com) alongside Floci's regionless built-in suffixes (.execute-api.localhost.floci.io / .localstack.cloud). - Fix RegionResolver.resolveRegionFromHost to treat only a real region label as the region and return null for the built-in suffixes -- the old pattern parsed "localhost" as the region and broke the lookup. - Remove the separate ExecuteApiSubdomainFilter; host parsing is shared via ApiGatewayExecuteApiHostFilter.extractApiId. - Update docs and add Java unit + Node SDK compatibility coverage for both host forms. Closes #1871 Closes #1846 |
||
|
|
9ebf9feb54 |
fix(lambda): propagate image inspection failures (#2268)
Co-authored-by: Moroshani <208086089+moroshani@users.noreply.github.com> |
||
|
|
b911ccd013 |
fix(lambda): SIGTERM container before closing runtime API socket (#2098)
* fix(lambda): SIGTERM container before closing runtime API socket
Real AWS Lambda tears an execution environment down by sending SIGTERM
to the runtime while the runtime API stays responsive; the runtime
library (awslambdaric, Node.js RIC, ...) sees the signal and exits
cleanly on the OS default handler. Floci closed the runtime API socket
first, causing the parked /invocation/next long-poll to wake with a
network error before SIGTERM could reach the process — the runtime
library treated that as a fault and printed a ~40-line traceback on
every clean invocation.
Split RuntimeApiServer.stop() into quiesce() (settle bookkeeping,
notify extensions, complete pending/in-flight invocations) and close()
(release the httpServer socket). Reorder ContainerLauncher.stop() to
quiesce → docker stop → close, so the runtime process receives SIGTERM
against a still-bound socket and exits cleanly. Parked runtime pollers
now stay parked through quiesce() rather than receiving an
AWS-undocumented 204, matching real Lambda behaviour where a shutting
runtime is expected to exit on SIGTERM without the API side responding.
Docker's stop timeout is now selected from AWS's documented
Shutdown-phase grace tiers: 2s when at least one extension is
registered, 1s (rounding up AWS's 300ms runtime sub-budget) otherwise.
Closes #2091
* fix(lambda): populate inFlight under lock to close teardown race
enqueue() and the /invocation/next handler polled the parked ctx or
pending invocation inside the server lock, then dispatched
sendInvocation() asynchronously on the Vert.x context. inFlight was
populated inside sendInvocation, after the lock had been released — so
a concurrent quiesce() could sweep pendingQueue and inFlight (both
empty at that instant) and miss an invocation that was already in
flight from the caller's perspective. The invocation's future would
then never complete, and the caller would hang until the function's
deadline.
Move inFlight.put(...) into the same synchronized block as the poll,
so quiesce()'s sweep and enqueue's dispatch are ordered by the lock.
sendInvocation still does its inFlight.put — now a same-value overwrite
in the fast path, and the source of truth for the slow path where
inFlight.put runs earlier than the ctx write does.
Add two property tests exercising the race window: one where enqueue()
hands the invocation to a parked poller, one where NEXT_PATH polls
from pendingQueue, both followed by an immediate stop().
* fix(lambda): drop deferred dispatch if quiesce completed the invocation
After enqueue() records an invocation in inFlight and hands it to a
parked poller, the actual sendInvocation() runs on a deferred Vert.x
context. If quiesce() lands between the two, it sweeps inFlight and
completes the caller's future with ContainerStopped — but the deferred
callback would still deliver the invocation to the runtime, which
would execute the handler (side effects) and POST /response into a
future that's already completed. CompletableFuture silently discards
the second complete(), so the caller sees an error even though the
function ran and succeeded.
Re-check `stopped && inFlight.get(requestId) == null` inside the lock
before dispatching, and skip the dispatch if so. Applies to both entry
points: enqueue()'s deferred sendInvocation and NEXT_PATH's
synchronous-but-post-lock-release sendInvocation.
Add a property test that parks a poller, enqueues, immediately stops,
and asserts the poller does NOT receive a 200 with the invocation
payload — only a socket close from close() is acceptable.
* fix(lambda): make quiesce's inFlight sweep atomic under lock
The dispatch guards in enqueue()'s deferred callback and NEXT_PATH read
`stopped` under the server lock. Their correctness relies on the
invariant: once quiesce() releases its lock, stopped=true implies
inFlight is empty. The prior code cleared inFlight *outside* the lock,
which left a window where a dispatch could observe stopped=true while
an inFlight entry it's about to deliver was still present — the guard
would let the delivery through, quiesce would then complete the future
with ContainerStopped, and the runtime's /response would be silently
discarded.
Snapshot inFlight inside the lock (symmetric with pendingQueue two
lines above), complete futures outside. Dispatch guards simplified to
just `stopped` since the atomicity now holds by construction. Drop
sendInvocation's redundant inFlight.put — both entry points pre-insert
under the lock.
Also:
- Narrow ContainerLauncher.stop()'s timeout comment: docker's --time is
a max wait for PID 1, not a grace floor. Extensions run as sibling
`docker exec`s and are killed with the container; the 2s ceiling
doesn't back the deadlineMs advertised to extensions.
- Fix javadoc placement: hasRegisteredExtensions() had accidentally
inherited isFaulted()'s comment. Give each its own doc.
Add quiesceAtomicallyClearsInFlightWithStopped test: multiple in-flight
invocations → quiesce → all futures must complete with ContainerStopped.
* fix(lambda): reconcile with #2156 write-flush + trim comments
#2156 landed the "await parked writes before httpServer.close" pattern
for extension SHUTDOWN dispatches. Reconcile our teardown split with
that: quiesce() schedules extension SHUTDOWN dispatches and records
their aggregate flush completion in a new field extensionWritesFlushed;
close() awaits that field before dropping the httpServer.
Preserves both behaviours: SIGTERM-before-socket-close ordering (this
PR's core value) and the write-flush guarantee (#2156's contribution).
Runtime pollers still stay parked — no 204 — matching real AWS Lambda's
teardown. Trim design-doc-shaped comments to reviewer-friendly length
in the same file.
* test(lambda): add deterministic race tests via test-specific subclass
The three sleep-based race tests (removed here) don't distinguish the
fix from the pre-fix code — they exercise the interleaving with
Thread.sleep and pass either way. Replace them with two latch-gated
tests that reproduce the exact interleaving hampsterx flagged
(enqueue's deferred dispatch, and NEXT_PATH's synchronous dispatch,
each racing against a partially-swept quiesce) and prove the guards
plus atomic inFlight sweep close the silent-discard bug.
The tests use the "test-specific subclass" pattern (Meszaros, xUnit
Test Patterns) rather than a settable-field hook on the production
class: quiesce() and the two dispatch sites call three empty
`protected void` methods that a test subclass overrides to gate on
CountDownLatches. Production has no mutable state, no volatile reads,
and matches Floci's existing `Test-only:` javadoc convention
(ContainerLauncher, LambdaService, LambdaConcurrencyLimiter, ...).
Verified: reverting the atomic-sweep-in-lock fix AND the guard
simplification causes both new tests to fail with the expected
"parked poller received the invocation" assertion. Restoring either
fix alone is enough for the tests to pass, confirming they gate on
the invariant that matters (stopped=true ⇒ inFlight empty).
* fix(lambda): commit enqueue dispatch/requeue decision atomically
Per @abanna's review of #2098. enqueue()'s deferred callback read
waitingCtx.response().ended() twice — once inside `synchronized(lock)`
deciding requeue, once outside deciding send. A client disconnect
between the two reads left neither branch firing and the invocation
stranded in inFlight until the function deadline.
Read ended() exactly once inside the lock and commit dispatch/requeue
before releasing. Adds a deterministic latch-gated race test (two new
Test-only protected seams) that fails on the double-read shape and
passes on the fix. 50/50 tests pass.
* fix(lambda): requeue invocation when sendInvocation's write fails
Per Greptile's P1 review of
|
||
|
|
a235b76835 |
feat(cloudformation): implement GetTemplateSummary (#2148)
* feat(cloudformation): implement GetTemplateSummary (#1964) Adds the missing action to the CloudFormation Query allowlist and computes Parameters, ResourceTypes, Version, DeclaredTransforms and an informational Capabilities/CapabilitiesReason (derived from AWS::IAM:: resource types) from a stack's existing template, an inline TemplateBody, or a TemplateURL. Without this, tools like sam deploy that call GetTemplateSummary before UpdateStack failed with UnsupportedOperation. * fix(cloudformation): correct GetTemplateSummary for SAM stacks and named IAM resources Addresses two review findings: - StackName lookups summarized the persisted post-transform template, so an existing SAM stack lost its Transform declaration and reported expanded resource types (AWS::Lambda::Function) instead of the original submitted ones (AWS::Serverless::Function). Stack now keeps the pre-transform template body alongside the existing post-transform one, and GetTemplateSummary prefers it. - Capabilities always reported CAPABILITY_IAM for any IAM resource, even ones with an explicit name (e.g. RoleName). CloudFormation requires CAPABILITY_NAMED_IAM for those; GetTemplateSummary now checks the relevant name property per IAM resource type. * fix(cloudformation): detect named IAM resources set via intrinsic functions The CAPABILITY_NAMED_IAM check only looked for a literal string value on the name property, so a real-world RoleName/UserName/etc. set via Ref, Fn::Sub, Fn::Join or another intrinsic (the common shape in SAM and CDK output) was missed entirely, misclassifying the template as only needing CAPABILITY_IAM. CloudFormation requires NAMED_IAM whenever the property is present at all, regardless of how its value resolves, so the check now looks for presence instead of a textual value. * docs(cloudformation): clarify GetTemplateSummary's originalTemplateBody fallback Spells out why the fallback to the post-transform templateBody exists (originalTemplateBody has no data for stacks persisted before this field was added) and that it self-heals on the stack's next CreateChangeSet/UpdateStack call, in response to review feedback. |
||
|
|
4ba854ab8c |
fix(stepfunctions): publish execution status after its terminal fields (#2234)
* fix(stepfunctions): publish execution status after its terminal fields DescribeExecution returns the live Execution instance from the store, and the executor mutated it in place with the status set before the fields that describe it. A client polling for a terminal status could therefore observe SUCCEEDED with a null output, which real Step Functions never returns. This is what reddened main in run 31457665686: the poll in StepFunctionsPassParametersIntegrationTest landed inside the window and Jackson rejected the null document with IllegalArgumentException: argument "content" is null. It is intermittent (one failure in the last fifteen main runs), because the window is two adjacent field writes wide. Set the terminal fields first and the status last on every terminal path, so the status is the publication point: SUCCEEDED, both FAILED paths, failExecution, TIMED_OUT, and ABORTED in stopExecution. The outer catch in doExecute was worse than a race. It set only the status, so an execution failing there reported FAILED with a null error and cause permanently. It now records both. No new test. The window is a few instructions wide while an HTTP round trip is milliseconds, so a black box test cannot land in it, and onUpdate fires after every setter so there is no seam to observe from. A concurrent polling test was written and discarded after it passed against the unfixed code. Existing coverage does guard the fields themselves: StepFunctionsJsonataIntegrationTest asserts error and cause on failed executions in several places. * test(stepfunctions): cover terminal error and cause on the outer catch The outer catch in doExecute previously set only the status, leaving error and cause null on an execution DescribeExecution reports as FAILED. That path had no coverage: no test referenced the "State not found" throw, and the existing States.Runtime assertions all go through the inner catch. A missing state reaches it deterministically, since the throw sits outside the per-state try and unwinds the whole execution loop. Verified as a real guard rather than a green one: against the pre-fix outer catch these fail with "expected: <States.Runtime> but was: <null>". Field ordering is deliberately not asserted. The window between two adjacent setters is a few instructions wide, so a black box test cannot land in it. |
||
|
|
c48c062117 |
fix(docker): fall back to Windows named pipe when docker-host is at its unix-socket default (#2030)
Floci defaults docker-host to unix:///var/run/docker.sock, which has no equivalent on native Windows. Since this hardcoded default always overrides docker-java's own OS-aware detection, every Docker-backed operation failed at container-start time on Windows with a low-level socket error — including Lambda-invoked CloudFormation custom resources such as CDK's Custom::S3BucketNotifications. When docker-host is still unmodified and DOCKER_HOST isn't set, fall back to Docker Desktop's named pipe (npipe:////./pipe/docker_engine) on Windows, mirroring what docker-java already does correctly on its own. Linux/macOS behavior is unchanged. An explicit docker-host or DOCKER_HOST always takes priority over the fallback. Verified end-to-end: a CDK-shaped stack (S3 bucket + Lambda + Custom::S3BucketNotifications) went from CREATE_FAILED to CREATE_COMPLETE after this fix. Fixes #2006. |
||
|
|
cfbae88fca |
feat(apigateway): derive SQS QueueUrl from path-style integration URI when absent from template (#1903)
* feat(apigateway): derive SQS QueueUrl from path-style integration URI when absent from template * fix(apigateway): derive SQS QueueUrl from the queue name |
||
|
|
907a2dfbf3 |
feat(cloudformation): provision AWS::ECS::CapacityProvider and ClusterCapacityProviderAssociations (#1999)
* feat(cloudformation): provision AWS::ECS::CapacityProvider and ClusterCapacityProviderAssociations Maps both onto the existing EcsService.createCapacityProvider / putClusterCapacityProviders — provider name generation follows the other provisioners, associations carry the provider list and default strategy (weight/base). Fixes #1998 * refactor(cloudformation): move ECS capacity provisioning into a per-service provisioner The new resource types from #1998 landed as two more arms of CloudFormationResourceProvisioner's switch. Move them into the per-service structure introduced in #1825 so the monolith stops growing: - EcsCapacityCfnProvisioner owns AWS::ECS::CapacityProvider and AWS::ECS::ClusterCapacityProviderAssociations and injects only EcsService. It is picked up by CloudFormationResourceRegistry through CDI, so both switch arms and their provisionEcsCapacity* methods are gone. Two review findings are fixed along the way: - Delete is implemented. Previously stack deletion and create rollback hit the default arm of the delete dispatch, so a stack could report DELETE_COMPLETE while the capacity provider stayed registered and the cluster kept its associations. Deleting the associations resource now detaches the providers from the cluster, and deleting a capacity provider deregisters it. Both are idempotent for the already-gone case (rollback, a persistent restore that dropped the record) and propagate every other AwsException so a genuine failure still settles the stack into DELETE_FAILED. - Capacity provider properties are no longer discarded. Only AutoScalingGroupArn was forwarded and tags were replaced with an empty map, so ManagedScaling, ManagedTerminationProtection and ManagedDraining silently vanished. The whole AutoScalingGroupProvider sub-tree is now carried across with intrinsics resolved and keys decapitalized, which is the shape CreateCapacityProvider stores, so a provider created by a stack holds the same state as one created through the ECS API. Tags are parsed from the standard Key/Value list. EcsCapacityCfnProvisionerTest covers both types against a single mocked EcsService, including the full ASG configuration, tags and every delete path. CloudFormationEcsCapacityIntegrationTest additionally asserts the tags reach DescribeCapacityProviders and that deleting the stack deregisters the provider. * fix(cloudformation): update an existing ECS capacity provider instead of recreating it UpdateStack re-executes every resource with the physical id it got at create time, and createCapacityProvider rejects a name that already exists, so an unchanged provider failed the whole update. With no Name declared the provisioner also minted a fresh generated name on every pass and left the previous provider behind. An existing provider is now reused through updateCapacityProvider, an unnamed one keeps the name its first execution generated, and a provider removed out of band is recreated rather than reported as a failure. Name and AutoScalingGroupArn are createOnly, so a change to either is reported as an unsupported replacement, matching how AWS::IAM::Role handles RoleName. updateCapacityProvider carries only the Auto Scaling settings, so Tags are applied separately and a tag the template dropped is removed. |
||
|
|
43f47a3c96 |
feat(cloudcontrol): implement CreateResource / DeleteResource / GetResource (#2037)
* feat(cloudcontrol): implement CreateResource / DeleteResource / GetResource Floci's Cloud Control handler implemented only ListResources; CreateResource and the rest returned "unsupported". Tools that drive AWS through the Cloud Control API (rather than the individual service APIs) therefore could not provision against Floci at all. Wire the write operations to the existing CloudFormationResourceProvisioner — the same 114-type provisioning that CloudFormation stacks already use — via two standalone helpers (no enclosing stack; Cloud Control DesiredState carries resolved values, so a minimal template engine suffices). Cloud Control is async, so CreateResource/DeleteResource return a terminal ProgressEvent and the request token resolves via GetResourceRequestStatus. GetResource reads a single resource by identifier off the existing read side. Any resource type a CloudFormation stack can create, Cloud Control can now create too. Integration test covers CreateResource(AWS::EC2::VPC) → listable → token round-trip. * fix(cloudcontrol): read back every created type and stop reporting SUCCESS for no-op deletes CreateResource provisions the whole CloudFormation type set while the read side lists six types, so GetResource threw ResourceNotFoundException for anything outside that list — a successful create was unreadable. CreateResource now records what it provisioned, and GetResource falls back to that record when the read side does not carry the type. DeleteResource went through deleteStandalone with empty attributes. Custom resources, EKS nodegroups and IAM inline policies cannot be deleted from type and physical id alone, so their delete silently no-opped while DeleteResource still returned SUCCESS. The create-time attributes are now passed through, and when they are absent for one of those types the operation reports FAILED with the reason rather than claiming to have deleted something that is still there. Also the two lifecycle gaps: the executor gets a @PreDestroy shutdown so its threads do not outlive the bean, and the request-token map is bounded, evicting the oldest finished tokens while never dropping one a client is still polling. * feat(cloudcontrol): read EC2 instances, launch templates and instance profiles ListResources covered six types. AWS::EC2::Instance, AWS::EC2::LaunchTemplate and AWS::IAM::InstanceProfile were not among them, so a caller that provisions one through Cloud Control could not read it back — and a tool whose AWS provider reaches these types only through its Cloud Control proxy could not see its own estate at all. Cloud Control reports a resource's current model rather than an echo of the desired state, so an instance carries what only the running resource knows: its private and public addresses, its state, its availability zone, and the subnet and security groups it actually landed in. A property with no value is omitted rather than reported as null, as Cloud Control does. This is also what GetResource needs to resolve these types, since it reads through the same list. * fix(cloudcontrol): report InvalidRequestException and require DesiredState Cloud Control declares InvalidRequestException for a malformed request. ValidationException and InvalidRequest are not in the service model, so an SDK could not map either onto a typed exception. Both now report the declared code. DesiredState is a required member of CreateResourceInput. An absent or blank one became an empty object and provisioned a resource the caller never described, so it is now rejected. * fix(cloudcontrol): GetResourceRequestStatus reports RequestTokenNotFoundException GetResourceRequestStatus does not declare InvalidRequestException. Its only declared error is RequestTokenNotFoundException, so an absent RequestToken now reports that instead of the code the other operations share. |
||
|
|
45811768b2 |
fix(stepfunctions): wrap optimized lambda:invoke result in the Invoke envelope (#2165)
A Task using the arn:aws:states:::lambda:invoke integration returned the Lambda function's return value directly as the task result, with no ExecutedVersion, Payload or StatusCode key. Real Step Functions nests the function output inside the Invoke response metadata for this integration, which is why $.Payload and the JSONata $states.result.Payload are the documented ways to read a Lambda result. Against the unwrapped result those references resolved to nothing, the state still succeeded, and the execution finished SUCCEEDED carrying silently-empty data — a pipeline accumulating results across stages looked healthy while producing an empty result. Both the direct-ARN branch and the optimized branch shared one block in invokeResource(), so the parsed function output was returned raw for both. Gate the wrap to the optimized branch: it now returns ExecutedVersion (from the resolved function's version, matching what LambdaService.invoke already reports), Payload (the parsed function output) and StatusCode (from the invoke result). A directly specified function ARN keeps returning only the function output, which is the documented behavior for that form. SdkHttpMetadata and SdkResponseMetadata are deliberately not emitted. Their contents are artifacts of a real HTTPS call to the Lambda service — Date, X-Amzn-Trace-Id, RequestId, Content-Length — and floci invokes in process, so any value it put there would be invented. The .waitForTaskToken flow is unaffected: executeTaskState overwrites the task result with the callback payload, so the envelope is discarded for that pattern, as it should be. Closes #2110 |
||
|
|
988696b057 | fix(firehose): return Kinesis source in stream description (#2025) | ||
|
|
486be8f5b0 |
feat(kinesis): add local inspection endpoints for UI (#1880)
* feat(kinesis): add local inspection endpoints for UI
* fix(kinesis): limit local record inspection
* fix(kinesis): include shard id in inspected records
* fix(kinesis): address reviewer comments on inspection endpoint
- Comment 1 (fix): sort order for Limit — already using a min-heap
PriorityQueue (oldestFirst comparator) that evicts the oldest record
when size > resolvedLimit, so the queue retains the newest N records.
Records are then re-sorted ascending before return. Limit=2 on
[oldest, middle, newest] now returns [middle, newest], not
[oldest, middle]. The previous ascending-sort+limit path was replaced
in the prior commit; this commit pins the behaviour in the test.
- Comment 2 (minor): unify error shapes on the /records endpoint.
Moved the Limit <= 0 guard from KinesisService into
KinesisInspectionController next to the StreamName guard so both
query-parameter validations use the same plain {"message": ...} shape
instead of the AwsException {"__type": ...} shape.
- Comment 3 (minor): consistent clamping policy. Removed the throw for
limit <= 0 from resolveInspectionRecordLimit; both bounds are now
clamped silently via Math.max/min, matching the behaviour of the
sibling getRecords / getRecordsForAccount methods. Added Javadoc
noting the 1000-record hard ceiling with no pagination cursor.
- Test: strengthened recordsEndpointHonorsLimit to assert which two
records are returned (pk-2 and pk-3, the newest), not just hasSize(2).
Added recordsEndpointRejectsNonPositiveLimit to cover the controller-
level Limit=0 validation.
|
||
|
|
93b6f5e2b0 |
fix(s3): preserve literal '+' in object keys and support encoding-type=url in list-objects (#1736)
* fix(s3): preserve literal '+' in object keys and support encoding-type=url in list-objects Object keys containing a literal '+' (for example Airflow task-log keys such as run_id=2026-06-26T00:00:00+00:00/f.log) came back from ListObjectsV2 with the '+' turned into a space, so a list-then-get round trip failed with NoSuchKey. '+' only means space in form-encoded query strings, never in URL paths, so every URLDecoder.decode call site on a path or copy source now escapes it first. Also adds encoding-type=url support to ListObjects, ListObjectsV2 and ListObjectVersions: Key, Prefix, Delimiter, StartAfter, Marker/NextMarker and KeyMarker/NextKeyMarker are percent-encoded through a new maybeEncode helper, while the opaque ContinuationToken/NextContinuationToken stay verbatim per the S3 spec. Query parameters the JAX-RS layer has already decoded are not decoded a second time, so keys holding literal percent escapes survive a list round trip. ListObjectVersions honours delimiter, returning CommonPrefixes and the encoded Delimiter, and pages the combined version/prefix result set. Closes #1589 * fix(s3): page ListObjectVersions by entry and honour version-id-marker max-keys grouped every version of a key into a single slot, so a bucket holding two versions of log.txt answered ?versions&max-keys=1 with both Version entries and IsTruncated=false. AWS counts each Version, each DeleteMarker and each CommonPrefixes group as one entry, so a page can stop part-way through a key. Version entries are now emitted one slot at a time, merged with common prefixes in key order. A truncated response carries NextVersionIdMarker beside NextKeyMarker, ListObjectVersions accepts version-id-marker to resume inside a key, and the echoed VersionIdMarker stays verbatim because version ids are opaque. A version-id-marker sent without a key-marker is rejected with InvalidArgument, as on AWS. |
||
|
|
fc74987bd3 |
fix(ec2): delete key pairs by name through the storage backend (#2187)
DeleteKeyPair with KeyName mutated the detached list returned by StorageBackend.scan, which is documented not to affect the store — so the call reported success while leaving the key pair in place. Resolve matching key pairs to their store key and delete through the backend instead. The only existing DeleteKeyPair test passed KeyPairId, the branch that already worked, and asserted just a 200; DeleteKeyPair always returns true, so the no-op was invisible. Cover the by-name path and assert removal rather than status. Closes #2185 |
||
|
|
4215006fe2 |
feat(logs): support log group deletion protection (#2256)
* fix(logs): accept log group deletion protection lifecycle * feat(logs): support log group deletion protection |
||
|
|
6ca7d44af0 |
fix(cloudformation): pass the CloudFront service argument in the provisioner tests (#2261)
#1820 added a CloudFrontService parameter to the CloudFormationResourceProvisioner constructor. Three tests that construct it directly landed from other branches around the same time and were never updated: the two EventBus ownership tests from #1807, and DynamoDbReplicaCfnProvisionerTest from #1811. None of those PRs touched #1820's files, so each passed CI on its own branch and main stopped compiling once they had all landed. All three supplied 33 arguments to a 34-parameter constructor. Adds the missing null in the cloudFrontService position, immediately before the resource registry. Swept every remaining `new CloudFormationResourceProvisioner(` call site in the tree; the other six already match, so nine of nine now agree with the constructor. Test sources only; no production behaviour changes. |
||
|
|
a29464abc7 |
feat(dynamodb): global-table v2 replicas (UpdateTable ReplicaUpdates + Custom::DynamoDBReplica) (#1811)
* feat(dynamodb): support global table replicas * fix(dynamodb): validate replica updates before mutation * fix(dynamodb): align replica compatibility behavior * chore: rerun CI after download outage * fix(dynamodb): document replica update semantics --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com> |
||
|
|
d9e4447aeb |
feat(cloudformation): resolve dynamic references in RDS credentials (#1809)
* feat(cloudformation): resolve dynamic references in RDS credentials * test(cloudformation): pin secret resolution failures --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com> |