Files
floci/compatibility-tests/compat-cdk/test/cdk.bats
T
Alessandro Lattao 85e0061a6f feat(cloudformation): provision AWS::ApiGatewayV2::DomainName and ApiMapping (#5038)
* refactor(apigateway): move the v2 domain and API mapping rules into the service

CreateDomainName and CreateApiMapping on /v2/domainnames kept their rules in
ApiGatewayController: the one-configuration check, the refusal of inputs Floci
does not emulate, the flattening onto the shared custom-domain store, the API
and stage existence check, the mapping key conflict check, the API type the
mapping is routed as, and the mapping id. A CloudFormation provisioner cannot
reach a controller, so it would have had to copy them.

They now live in ApiGatewayService. createV2DomainName validates the body and
creates the domain; createApiMapping checks the API and stage, refuses a key
that is taken and routes the mapping as the API's protocol type; getApiMapping,
deleteApiMapping and apiMappingId follow. ApiGatewayService takes
ApiGatewayV2Service for the API and stage lookup, so the whole rule sits in one
place and a caller needs one service. Nothing on the v2 side depends on the v1
service, so this adds no cycle. Leaving the lookup in ApiGatewayV2Service was
tried first, but then every caller had to resolve the API before calling into
ApiGatewayService, and the rule was split across two classes again.

The code is moved, not rewritten: messages, error codes, the order of the
checks and the id scheme are unchanged, and the controller delegates.

* feat(cloudformation): provision AWS::ApiGatewayV2::DomainName and ApiMapping

Both types were left to the stub arm. A stack reported CREATE_COMPLETE, but no
domain or mapping existed, Fn::GetAtt on the domain resolved to literals such
as DomainResource.RegionalDomainName (so a Route 53 alias built from it pointed
nowhere), and with allow-stub-unsupported-resource-types off the stack rolled
back.

ApiGatewayV2DomainCfnProvisioner creates them through the v2 rules in
ApiGatewayService and injects only that service. Ref on a domain is its name
and Fn::GetAtt returns DomainNameArn, RegionalDomainName and
RegionalHostedZoneId as GetDomainName reports them. Ref on a mapping is its
ApiMappingId, which is also its only attribute.

Updates follow AWS. DomainName is the only createOnly property of either type,
and everything else changes in place: the domain's configuration is replaced as
a whole, as DomainNameConfigurations is on AWS, and a mapping's ApiId, Stage and
ApiMappingKey change without a new id. To keep the id across a key change, a
mapping now stores the apiMappingId it was given instead of deriving it from
its key on every read. A record persisted before is still read under the
derived id, and a new mapping gets the id it always had unless another mapping
holds it. Deriving the id and documenting the difference was the first version;
it was dropped because Ref changed where AWS keeps it, and the change set
already reported the key change as an update.

A replacement creates the new entity and leaves the displaced one to
ReplacementCleanup, so it is deleted in UPDATE_COMPLETE_CLEANUP_IN_PROGRESS,
kept under UpdateReplacePolicy: Retain, and put back when a later resource
fails the update. The first version deleted the old domain inside provision, as
the v1 provisioner does, and a failed rename then ended in
UPDATE_ROLLBACK_FAILED with the original domain and its mappings already gone.
A mapping moved to another domain gets an id the displaced mapping does not
hold, since two mappings under one physical id cannot be told apart, and the
domain of each displaced id is recorded beside the cleanup. An in-place update
snapshots what it changes, so a failed stack update restores it instead of
ending in UPDATE_ROLLBACK_FAILED.

CDK templates needed the v2 rules to match AWS in two more places.
apigateway.DomainName with a multi-level basePath maps a REST API through
AWS::ApiGatewayV2::ApiMapping, so a mapping now accepts a REST API stage. And
the restrictions AWS documents for API mappings are enforced, in the API and in
templates alike: no v2 call on an edge-optimized domain, with AWS's message;
TLS_1_2 for an HTTP API or a multi-level key, which also keeps such a domain on
TLS_1_2; no WebSocket API beside an HTTP or REST API; and AWS's key characters
and length.

The id-only delete accepts <ApiMappingId>|<DomainName>, the type's primary
identifier, which is how Cloud Control names a mapping; a bare id still answers
NotFoundException, so Cloud Control cannot report a delete that did not happen.
The integration test deploys two templates aws-cdk-lib 2.272.0 synthesized,
checked in with the app that produced them, and compat-cdk deploys the same
shapes.

* fix(apigateway): answer v2 domain and API mapping calls as API Gateway does

The review of this PR found four places where Floci answered differently
from API Gateway. Each was measured against API Gateway in eu-west-1 on
2026-10-04, with an imported certificate on a throwaway domain.

An HTTP API custom domain is regional. CreateDomainName and
UpdateDomainName with an endpoint type of PRIVATE, or one API Gateway does
not know, give a REGIONAL domain, where Floci refused the first and stored
the type on an update. EDGE is refused with "EDGE endpoint type is not
supported for APIGatewayV2 domainName", not the message for v2 calls on an
existing edge-optimized domain.

API mapping keys are checked as API Gateway checks them, with its messages:
a key does not end with '/', does not start with '/' or hold '//', holds
letters, digits and $-_.+!*'(), between its levels, and is at most 300
characters. No key, an empty one, or on a create one of whitespace only, is
the root; an update refuses whitespace only. Floci took "/" for the root and
had its own message for the characters, without the comma.

UpdateApiMapping and UpdateDomainName answer over the v2 HTTP API, not only
from CloudFormation. What an UpdateApiMapping leaves out keeps its value.

Cloud Control identifies an AWS::ApiGatewayV2::ApiMapping by the type's
primary identifier, <ApiMappingId>|<DomainName>, while CloudFormation's Ref
stays the bare id: CloudControlService derives the identifier from the
desired state, as it already names primary identifier fields by type, and
the provisioner deletes by it with the create-time attributes too.

* fix(apigateway): refuse a v2 update of an edge domain, and recover a compound identifier whole

The second review pass found three gaps in the previous commit.

UpdateDomainName through the v2 API converted a v1-created edge-optimized
domain to REGIONAL. The v2 API does not manage an edge-optimized domain, so
the update is refused with the message every other v2 call on one gets, and
the CloudFormation in-place update goes through the same check.

A v2 UpdateDomainName without a configuration returned the domain unchanged
without looking at the rest of the body, so a mutual TLS request was
silently dropped. ApiGatewayService.updateV2DomainName now refuses what
Floci does not emulate, and the edge-optimized domain, either way.

Cloud Control's recovery of a create that finished just before a restart
took the identifier after the last '|' of its key, which for an API
mapping's <ApiMappingId>|<DomainName> left only the domain. It now takes
everything after the key's third separator.

A later review pass found four more points.
UpdateApiMapping fills in what its body leaves out under the lock the update
takes, so two partial updates of one mapping cannot write back each other's
old values. A v2 domain's certificate is stored as the v1 API's regional
certificate, which is what a regional domain reports through both APIs; a
domain the v2 API wrote before still reports the one it holds until its
configuration is replaced. The domain ARN both APIs and both CloudFormation
provisioners build comes from ApiGatewayService.domainNameArn, the Cloud
Control test waits with the awaitSuccess helper main has since gained, and
requireMappingAllowed's javadoc is back on it.
2026-10-12 11:28:04 -04:00

281 lines
10 KiB
Bash

#!/usr/bin/env bats
# CDK Compatibility Tests for floci
setup_file() {
load 'test_helper/common-setup'
cd "$CDK_DIR"
echo "# === CDK Compatibility Test ===" >&3
echo "# Endpoint: $FLOCI_ENDPOINT" >&3
echo "# --- Bootstrap ---" >&3
run cdklocal bootstrap --force
if [ "$status" -ne 0 ]; then
echo "# Bootstrap failed: $output" >&3
return 1
fi
echo "# --- Deploy ---" >&3
run cdklocal deploy --require-approval never
if [ "$status" -ne 0 ]; then
echo "# Deploy failed: $output" >&3
return 1
fi
}
teardown_file() {
load 'test_helper/common-setup'
cd "$CDK_DIR"
echo "# --- Destroy ---" >&3
cdklocal destroy --force || true
}
setup() {
load 'test_helper/common-setup'
}
# --- Spot Checks ---
@test "CDK: S3 bucket exists" {
run aws_cmd s3 ls
assert_success
bucket_count=$(echo "$output" | wc -l)
[ "$bucket_count" -gt 0 ]
}
@test "CDK: SQS queue exists" {
run aws_cmd sqs list-queues
assert_success
queue_count=$(json_get "$output" '.QueueUrls | length')
[ "$queue_count" -gt 0 ]
}
@test "CDK: DynamoDB table exists" {
run aws_cmd dynamodb list-tables
assert_success
table_count=$(json_get "$output" '.TableNames | length')
[ "$table_count" -gt 0 ]
}
@test "CDK: DynamoDB GSI exists on index table" {
run aws_cmd dynamodb describe-table --table-name floci-cdk-index-table
assert_success
gsi_count=$(json_get "$output" '.Table.GlobalSecondaryIndexes | length')
[ "$gsi_count" -eq 1 ]
}
@test "CDK: DynamoDB GSI name is gsi-1" {
run aws_cmd dynamodb describe-table --table-name floci-cdk-index-table
assert_success
gsi_name=$(json_get "$output" '.Table.GlobalSecondaryIndexes[0].IndexName')
[ "$gsi_name" = "gsi-1" ]
}
@test "CDK: DynamoDB GSI projection ALL" {
run aws_cmd dynamodb describe-table --table-name floci-cdk-index-table
assert_success
gsi_proj=$(json_get "$output" '.Table.GlobalSecondaryIndexes[0].Projection.ProjectionType')
[ "$gsi_proj" = "ALL" ]
}
@test "CDK: DynamoDB LSI exists on index table" {
run aws_cmd dynamodb describe-table --table-name floci-cdk-index-table
assert_success
lsi_count=$(json_get "$output" '.Table.LocalSecondaryIndexes | length')
[ "$lsi_count" -eq 1 ]
}
@test "CDK: DynamoDB LSI name is lsi-1" {
run aws_cmd dynamodb describe-table --table-name floci-cdk-index-table
assert_success
lsi_name=$(json_get "$output" '.Table.LocalSecondaryIndexes[0].IndexName')
[ "$lsi_name" = "lsi-1" ]
}
@test "CDK: DynamoDB LSI projection KEYS_ONLY" {
run aws_cmd dynamodb describe-table --table-name floci-cdk-index-table
assert_success
lsi_proj=$(json_get "$output" '.Table.LocalSecondaryIndexes[0].Projection.ProjectionType')
[ "$lsi_proj" = "KEYS_ONLY" ]
}
@test "CDK: CloudFormation stack CREATE_COMPLETE" {
run aws_cmd cloudformation describe-stacks --stack-name FlociTestStack
assert_success
stack_status=$(json_get "$output" '.Stacks[0].StackStatus')
[ "$stack_status" = "CREATE_COMPLETE" ]
}
@test "CDK: Secrets Manager generated secret exists" {
run aws_cmd secretsmanager describe-secret --secret-id floci-cdk-generated-secret
assert_success
secret_name=$(json_get "$output" '.Name')
[ "$secret_name" = "floci-cdk-generated-secret" ]
}
@test "CDK: GeneratedSecret username is admin" {
run aws_cmd secretsmanager get-secret-value --secret-id floci-cdk-generated-secret
assert_success
username=$(json_get "$output" '.SecretString' | jq -r '.username')
[ "$username" = "admin" ]
}
@test "CDK: GeneratedSecret password length is 24" {
run aws_cmd secretsmanager get-secret-value --secret-id floci-cdk-generated-secret
assert_success
password=$(json_get "$output" '.SecretString' | jq -r '.password')
password_len=${#password}
[ "$password_len" -eq 24 ]
}
@test "CDK: GeneratedSecret password excludes abc" {
run aws_cmd secretsmanager get-secret-value --secret-id floci-cdk-generated-secret
assert_success
password=$(json_get "$output" '.SecretString' | jq -r '.password')
# Check that password does not contain a, b, or c
[[ ! "$password" =~ [abc] ]]
}
# --- DockerImageFunction (ECR + Lambda end-to-end) ---
@test "CDK: DockerImageFunction was created" {
run aws_cmd lambda get-function --function-name floci-cdk-docker-hello
assert_success
package_type=$(json_get "$output" '.Configuration.PackageType')
[ "$package_type" = "Image" ]
image_uri=$(json_get "$output" '.Code.ImageUri')
[ -n "$image_uri" ]
# The stored ImageUri preserves the AWS-shaped form (CDK assets use this);
# Floci's Lambda launcher rewrites it to the loopback registry at pull time.
[[ "$image_uri" == *"dkr.ecr."*"amazonaws.com"* ]]
[[ "$image_uri" == *"cdk-hnb659fds-container-assets"* ]]
}
@test "CDK: DockerImageFunction invokes successfully" {
# End-to-end invocation requires the Lambda runtime API server (host port range
# floci.services.lambda.runtime-api-base-port) to be reachable from inside the
# Lambda container. On native Linux Docker without Docker Desktop, this depends
# on host firewall rules permitting traffic from the docker bridge to the host.
# If your host blocks this, the test fails with Function.TimedOut — this is a
# pre-existing Lambda networking constraint, not an ECR issue (it affects
# Zip-packaged Lambdas too).
payload_b64=$(printf '{"name":"world"}' | base64 -w 0 2>/dev/null || printf '{"name":"world"}' | base64)
run aws_cmd lambda invoke \
--function-name floci-cdk-docker-hello \
--payload "$payload_b64" \
/tmp/floci-cdk-docker-hello.out
assert_success
status_code=$(json_get "$output" '.StatusCode')
[ "$status_code" = "200" ]
body=$(cat /tmp/floci-cdk-docker-hello.out)
[[ "$body" == *"Hello, world!"* ]]
[[ "$body" == *"emulated ECR"* ]]
}
@test "CDK: DockerImageFunction asset image is in emulated ECR" {
# CDK pushes to a bootstrap repo named cdk-hnb659fds-container-assets-<account>-<region>
run aws_cmd ecr describe-repositories
assert_success
repos=$(echo "$output" | jq -r '.repositories[].repositoryName')
[[ "$repos" == *"cdk-hnb659fds-container-assets"* ]]
}
# --- VPC + ALB (regression: issue #1297) ---
#
# CloudFormation must create the CDK-generated AWS::EC2::VPC/Subnet resources for
# real (in EC2). Before the fix they were stubbed, so describe-subnets did not
# return them and the ALB referencing them failed with "The subnet ID '...' does
# not exist". https://github.com/floci-io/floci/issues/1297
@test "CDK: VPC subnets were created in EC2" {
run aws_cmd ec2 describe-subnets
assert_success
# The CDK VPC adds 4 subnets (2 public + 2 isolated) on top of the defaults.
custom_subnets=$(echo "$output" | jq '[.Subnets[] | select(.DefaultForAz != true)] | length')
[ "$custom_subnets" -ge 4 ]
}
@test "CDK: internal ALB is active" {
run aws_cmd elbv2 describe-load-balancers --names floci-cdk-alb
assert_success
state=$(json_get "$output" '.LoadBalancers[0].State.Code')
[ "$state" = "active" ]
scheme=$(json_get "$output" '.LoadBalancers[0].Scheme')
[ "$scheme" = "internal" ]
}
@test "CDK: ALB subnets exist in EC2" {
run aws_cmd elbv2 describe-load-balancers --names floci-cdk-alb
assert_success
s1=$(json_get "$output" '.LoadBalancers[0].AvailabilityZones[0].SubnetId')
s2=$(json_get "$output" '.LoadBalancers[0].AvailabilityZones[1].SubnetId')
[[ "$s1" == subnet-* ]]
[[ "$s2" == subnet-* ]]
run aws_cmd ec2 describe-subnets --subnet-ids "$s1" "$s2"
assert_success
count=$(json_get "$output" '.Subnets | length')
[ "$count" -eq 2 ]
}
# --- Cloud Map namespace + service (regression: issue #4596) ---
#
# CloudFormation must create the CDK-generated AWS::ServiceDiscovery::PrivateDnsNamespace
# and AWS::ServiceDiscovery::Service in Cloud Map instead of stubbing them.
# https://github.com/floci-io/floci/issues/4596
@test "CDK: Cloud Map namespace and service exist" {
run aws_cmd servicediscovery list-namespaces
assert_success
ns_id=$(json_get "$output" '.Namespaces[] | select(.Name == "floci-cdk.internal") | .Id')
[[ "$ns_id" == ns-* ]]
run aws_cmd servicediscovery list-services \
--filters "Name=NAMESPACE_ID,Values=$ns_id,Condition=EQ"
assert_success
svc_name=$(json_get "$output" '.Services[] | select(.Name == "floci-cdk-svc") | .Name')
[ "$svc_name" = "floci-cdk-svc" ]
}
# --- API Gateway custom domains ---
#
# CloudFormation must create the CDK-generated AWS::ApiGatewayV2::DomainName and
# AWS::ApiGatewayV2::ApiMapping instead of stubbing them, both for an HTTP API and for a REST API
# mapped under a key with several levels, and Fn::GetAtt on the domain must feed the alias record
# real values.
@test "CDK: HTTP API is mapped at the root of its v2 custom domain" {
run aws_cmd apigatewayv2 get-api-mappings --domain-name http.floci-cdk-api.example.com
assert_success
[ "$(json_get "$output" '.Items | length')" = "1" ]
[ "$(json_get "$output" '.Items[0].ApiMappingKey')" = "" ]
[ "$(json_get "$output" '.Items[0].Stage')" = '$default' ]
}
@test "CDK: alias record targets the v2 custom domain's regional name" {
run aws_cmd apigatewayv2 get-domain-name --domain-name http.floci-cdk-api.example.com
assert_success
regional=$(json_get "$output" '.DomainNameConfigurations[0].ApiGatewayDomainName')
[ -n "$regional" ]
run aws_cmd route53 list-hosted-zones-by-name --dns-name floci-cdk-api.example.com
assert_success
zone_id=$(json_get "$output" '.HostedZones[0].Id')
run aws_cmd route53 list-resource-record-sets --hosted-zone-id "$zone_id"
assert_success
alias=$(json_get "$output" '.ResourceRecordSets[] | select(.Name == "http.floci-cdk-api.example.com." and .Type == "A") | .AliasTarget.DNSName')
[ "${alias%.}" = "$regional" ]
}
@test "CDK: REST API is mapped under a key with several levels" {
run aws_cmd apigatewayv2 get-api-mappings --domain-name rest.floci-cdk-api.example.com
assert_success
[ "$(json_get "$output" '.Items[0].ApiMappingKey')" = "orders/v1" ]
[ "$(json_get "$output" '.Items[0].Stage')" = "prod" ]
}