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.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-12 11:28:04 -04:00
1 parent b1bb016b6e
commit 85e0061a6f
27 files changed
+3729 -169

No files matched your search

@@ -10,6 +10,12 @@ const lambda = require("aws-cdk-lib/aws-lambda");
const ec2 = require("aws-cdk-lib/aws-ec2");
const elbv2 = require("aws-cdk-lib/aws-elasticloadbalancingv2");
const servicediscovery = require("aws-cdk-lib/aws-servicediscovery");
const apigateway = require("aws-cdk-lib/aws-apigateway");
const apigwv2 = require("aws-cdk-lib/aws-apigatewayv2");
const apigwv2Integrations = require("aws-cdk-lib/aws-apigatewayv2-integrations");
const acm = require("aws-cdk-lib/aws-certificatemanager");
const route53 = require("aws-cdk-lib/aws-route53");
const route53Targets = require("aws-cdk-lib/aws-route53-targets");
const path = require("path");
class FlociTestStack extends cdk.Stack {
constructor(scope, id, props) {
@@ -96,6 +102,37 @@ class FlociTestStack extends cdk.Stack {
dnsRecordType: servicediscovery.DnsRecordType.A,
dnsTtl: cdk.Duration.seconds(30),
});
// API Gateway custom domains: an HTTP API mapped at the root of an AWS::ApiGatewayV2::DomainName
// with an alias record to it, and a REST API under a key with several levels, which CDK maps
// with AWS::ApiGatewayV2::ApiMapping because a base path mapping takes one level only.
const apiZone = new route53.PublicHostedZone(this, 'ApiZone', { zoneName: 'floci-cdk-api.example.com' });
const httpApiDomain = new apigwv2.DomainName(this, 'HttpApiDomain', {
domainName: 'http.floci-cdk-api.example.com',
certificate: new acm.Certificate(this, 'HttpApiCertificate', {
domainName: 'http.floci-cdk-api.example.com',
validation: acm.CertificateValidation.fromDns(apiZone),
}),
});
const httpApi = new apigwv2.HttpApi(this, 'TestHttpApi', {
defaultIntegration: new apigwv2Integrations.HttpUrlIntegration('Backend', 'https://example.com'),
defaultDomainMapping: { domainName: httpApiDomain },
});
new route53.ARecord(this, 'HttpApiAlias', {
zone: apiZone,
recordName: 'http.floci-cdk-api.example.com',
target: route53.RecordTarget.fromAlias(new route53Targets.ApiGatewayv2DomainProperties(httpApiDomain.regionalDomainName, httpApiDomain.regionalHostedZoneId)),
});
const restApi = new apigateway.RestApi(this, 'TestRestApi');
restApi.root.addResource('items').addMethod('GET', new apigateway.HttpIntegration('https://example.com'));
new apigateway.DomainName(this, 'RestApiDomain', {
domainName: 'rest.floci-cdk-api.example.com',
certificate: new acm.Certificate(this, 'RestApiCertificate', {
domainName: 'rest.floci-cdk-api.example.com',
validation: acm.CertificateValidation.fromDns(apiZone),
}),
mapping: restApi,
basePath: 'orders/v1',
});
new cdk.CfnOutput(this, 'BucketName', { value: bucket.bucketName });
new cdk.CfnOutput(this, 'QueueUrl', { value: queue.queueUrl });
new cdk.CfnOutput(this, 'TableName', { value: table.tableName });
@@ -105,7 +142,9 @@ class FlociTestStack extends cdk.Stack {
new cdk.CfnOutput(this, 'AlbArn', { value: alb.loadBalancerArn });
new cdk.CfnOutput(this, 'NamespaceId', { value: namespace.namespaceId });
new cdk.CfnOutput(this, 'ServiceId', { value: service.serviceId });
new cdk.CfnOutput(this, 'HttpApiId', { value: httpApi.apiId });
new cdk.CfnOutput(this, 'RestApiId', { value: restApi.restApiId });
}
}
exports.FlociTestStack = FlociTestStack;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZmxvY2ktc3RhY2suanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJmbG9jaS1zdGFjay50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSxtQ0FBbUM7QUFDbkMseUNBQXlDO0FBQ3pDLDJDQUEyQztBQUMzQyxxREFBcUQ7QUFDckQsaUVBQWlFO0FBQ2pFLGlEQUFpRDtBQUNqRCwyQ0FBMkM7QUFDM0MsZ0VBQWdFO0FBQ2hFLHFFQUFxRTtBQUNyRSw2QkFBNkI7QUFHN0IsTUFBYSxjQUFlLFNBQVEsR0FBRyxDQUFDLEtBQUs7SUFDM0MsWUFBWSxLQUFnQixFQUFFLEVBQVUsRUFBRSxLQUFzQjtRQUM5RCxLQUFLLENBQUMsS0FBSyxFQUFFLEVBQUUsRUFBRSxLQUFLLENBQUMsQ0FBQztRQUV4QixNQUFNLE1BQU0sR0FBRyxJQUFJLEVBQUUsQ0FBQyxNQUFNLENBQUMsSUFBSSxFQUFFLFlBQVksRUFBRTtZQUMvQyxhQUFhLEVBQUUsR0FBRyxDQUFDLGFBQWEsQ0FBQyxPQUFPO1NBQ3pDLENBQUMsQ0FBQztRQUVILE1BQU0sS0FBSyxHQUFHLElBQUksR0FBRyxDQUFDLEtBQUssQ0FBQyxJQUFJLEVBQUUsV0FBVyxFQUFFO1lBQzdDLFNBQVMsRUFBRSxzQkFBc0I7WUFDakMsaUJBQWlCLEVBQUUsR0FBRyxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsRUFBRSxDQUFDO1NBQzVDLENBQUMsQ0FBQztRQUVILE1BQU0sS0FBSyxHQUFHLElBQUksUUFBUSxDQUFDLE9BQU8sQ0FBQyxJQUFJLEVBQUUsV0FBVyxFQUFFO1lBQ3BELFNBQVMsRUFBRSxzQkFBc0I7WUFDakMsWUFBWSxFQUFFLEVBQUUsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsUUFBUSxDQUFDLGFBQWEsQ0FBQyxNQUFNLEVBQUU7WUFDakUsYUFBYSxFQUFFLEdBQUcsQ0FBQyxhQUFhLENBQUMsT0FBTztTQUN6QyxDQUFDLENBQUM7UUFFSCxnRkFBZ0Y7UUFDaEYsTUFBTSxVQUFVLEdBQUcsSUFBSSxRQUFRLENBQUMsT0FBTyxDQUFDLElBQUksRUFBRSxnQkFBZ0IsRUFBRTtZQUM5RCxTQUFTLEVBQUUsdUJBQXVCO1lBQ2xDLFlBQVksRUFBRSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsSUFBSSxFQUFFLFFBQVEsQ0FBQyxhQUFhLENBQUMsTUFBTSxFQUFFO1lBQ2pFLE9BQU8sRUFBRSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsSUFBSSxFQUFFLFFBQVEsQ0FBQyxhQUFhLENBQUMsTUFBTSxFQUFFO1lBQzVELGFBQWEsRUFBRSxHQUFHLENBQUMsYUFBYSxDQUFDLE9BQU87WUFDeEMsc0JBQXNCLEVBQUU7Z0JBQ3RCO29CQUNFLFNBQVMsRUFBRSxPQUFPO29CQUNsQixZQUFZLEVBQUUsRUFBRSxJQUFJLEVBQUUsT0FBTyxFQUFFLElBQUksRUFBRSxRQUFRLENBQUMsYUFBYSxDQUFDLE1BQU0sRUFBRTtvQkFDcEUsT0FBTyxFQUFFLEVBQUUsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsUUFBUSxDQUFDLGFBQWEsQ0FBQyxNQUFNLEVBQUU7b0JBQzVELGNBQWMsRUFBRSxRQUFRLENBQUMsY0FBYyxDQUFDLEdBQUc7aUJBQzVDO2FBQ0Y7WUFDRCxxQkFBcUIsRUFBRTtnQkFDckI7b0JBQ0UsU0FBUyxFQUFFLE9BQU87b0JBQ2xCLE9BQU8sRUFBRSxFQUFFLElBQUksRUFBRSxPQUFPLEVBQUUsSUFBSSxFQUFFLFFBQVEsQ0FBQyxhQUFhLENBQUMsTUFBTSxFQUFFO29CQUMvRCxjQUFjLEVBQUUsUUFBUSxDQUFDLGNBQWMsQ0FBQyxTQUFTO2lCQUNsRDthQUNGO1NBQ0YsQ0FBQyxDQUFDO1FBRUgsTUFBTSxlQUFlLEdBQUcsSUFBSSxjQUFjLENBQUMsU0FBUyxDQUFDLElBQUksRUFBRSxpQkFBaUIsRUFBRTtZQUM1RSxJQUFJLEVBQUUsNEJBQTRCO1lBQ2xDLG9CQUFvQixFQUFFO2dCQUNwQixvQkFBb0IsRUFBRSxzQkFBc0I7Z0JBQzVDLGlCQUFpQixFQUFFLFVBQVU7Z0JBQzdCLGNBQWMsRUFBRSxFQUFFO2dCQUNsQixpQkFBaUIsRUFBRSxLQUFLO2FBQ3pCO1NBQ0YsQ0FBQyxDQUFDO1FBQ0gsZUFBZSxDQUFDLGtCQUFrQixDQUFDLEdBQUcsQ0FBQyxhQUFhLENBQUMsT0FBTyxDQUFDLENBQUM7UUFFOUQsbUVBQW1FO1FBQ25FLHlFQUF5RTtRQUN6RSxzRUFBc0U7UUFDdEUsZ0RBQWdEO1FBQ2hELElBQUksTUFBTSxDQUFDLG1CQUFtQixDQUFDLElBQUksRUFBRSxlQUFlLEVBQUU7WUFDcEQsWUFBWSxFQUFFLHdCQUF3QjtZQUN0QyxJQUFJLEVBQUUsTUFBTSxDQUFDLGVBQWUsQ0FBQyxjQUFjLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxTQUFTLEVBQUUsSUFBSSxFQUFFLFdBQVcsQ0FBQyxDQUFDO1lBQ3BGLE9BQU8sRUFBRSxHQUFHLENBQUMsUUFBUSxDQUFDLE9BQU8sQ0FBQyxFQUFFLENBQUM7WUFDakMsVUFBVSxFQUFFLEdBQUc7U0FDaEIsQ0FBQyxDQUFDO1FBRUgsa0ZBQWtGO1FBQ2xGLDJFQUEyRTtRQUMzRSx5RUFBeUU7UUFDekUsTUFBTSxHQUFHLEdBQUcsSUFBSSxHQUFHLENBQUMsR0FBRyxDQUFDLElBQUksRUFBRSxTQUFTLEVBQUU7WUFDdkMsT0FBTyxFQUFFLGVBQWU7WUFDeEIsTUFBTSxFQUFFLENBQUM7WUFDVCxXQUFXLEVBQUUsQ0FBQztZQUNkLG1CQUFtQixFQUFFO2dCQUNuQixFQUFFLElBQUksRUFBRSxRQUFRLEVBQUUsVUFBVSxFQUFFLEdBQUcsQ0FBQyxVQUFVLENBQUMsTUFBTSxFQUFFLFFBQVEsRUFBRSxFQUFFLEVBQUU7Z0JBQ25FLEVBQUUsSUFBSSxFQUFFLFVBQVUsRUFBRSxVQUFVLEVBQUUsR0FBRyxDQUFDLFVBQVUsQ0FBQyxnQkFBZ0IsRUFBRSxRQUFRLEVBQUUsRUFBRSxFQUFFO2FBQ2hGO1NBQ0YsQ0FBQyxDQUFDO1FBRUgsTUFBTSxHQUFHLEdBQUcsSUFBSSxLQUFLLENBQUMsdUJBQXVCLENBQUMsSUFBSSxFQUFFLFNBQVMsRUFBRTtZQUM3RCxnQkFBZ0IsRUFBRSxlQUFlO1lBQ2pDLEdBQUc7WUFDSCxjQUFjLEVBQUUsS0FBSztZQUNyQixVQUFVLEVBQUUsRUFBRSxVQUFVLEVBQUUsR0FBRyxDQUFDLFVBQVUsQ0FBQyxnQkFBZ0IsRUFBRTtTQUM1RCxDQUFDLENBQUM7UUFFSCwrRkFBK0Y7UUFDL0YsTUFBTSxTQUFTLEdBQUcsSUFBSSxnQkFBZ0IsQ0FBQyxtQkFBbUIsQ0FBQyxJQUFJLEVBQUUsZUFBZSxFQUFFO1lBQ2hGLElBQUksRUFBRSxvQkFBb0I7WUFDMUIsR0FBRztTQUNKLENBQUMsQ0FBQztRQUNILE1BQU0sT0FBTyxHQUFHLFNBQVMsQ0FBQyxhQUFhLENBQUMsYUFBYSxFQUFFO1lBQ3JELElBQUksRUFBRSxlQUFlO1lBQ3JCLGFBQWEsRUFBRSxnQkFBZ0IsQ0FBQyxhQUFhLENBQUMsQ0FBQztZQUMvQyxNQUFNLEVBQUUsR0FBRyxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsRUFBRSxDQUFDO1NBQ2pDLENBQUMsQ0FBQztRQUVILElBQUksR0FBRyxDQUFDLFNBQVMsQ0FBQyxJQUFJLEVBQUUsWUFBWSxFQUFFLEVBQUUsS0FBSyxFQUFFLE1BQU0sQ0FBQyxVQUFVLEVBQUUsQ0FBQyxDQUFDO1FBQ3BFLElBQUksR0FBRyxDQUFDLFNBQVMsQ0FBQyxJQUFJLEVBQUUsVUFBVSxFQUFFLEVBQUUsS0FBSyxFQUFFLEtBQUssQ0FBQyxRQUFRLEVBQUUsQ0FBQyxDQUFDO1FBQy9ELElBQUksR0FBRyxDQUFDLFNBQVMsQ0FBQyxJQUFJLEVBQUUsV0FBVyxFQUFFLEVBQUUsS0FBSyxFQUFFLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyxDQUFDO1FBQ2pFLElBQUksR0FBRyxDQUFDLFNBQVMsQ0FBQyxJQUFJLEVBQUUsZ0JBQWdCLEVBQUUsRUFBRSxLQUFLLEVBQUUsVUFBVSxDQUFDLFNBQVMsRUFBRSxDQUFDLENBQUM7UUFDM0UsSUFBSSxHQUFHLENBQUMsU0FBUyxDQUFDLElBQUksRUFBRSxxQkFBcUIsRUFBRSxFQUFFLEtBQUssRUFBRSxlQUFlLENBQUMsSUFBSSxJQUFJLDRCQUE0QixFQUFFLENBQUMsQ0FBQztRQUNoSCxJQUFJLEdBQUcsQ0FBQyxTQUFTLENBQUMsSUFBSSxFQUFFLE9BQU8sRUFBRSxFQUFFLEtBQUssR Line truncated
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZmxvY2ktc3RhY2suanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJmbG9jaS1zdGFjay50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSxtQ0FBbUM7QUFDbkMseUNBQXlDO0FBQ3pDLDJDQUEyQztBQUMzQyxxREFBcUQ7QUFDckQsaUVBQWlFO0FBQ2pFLGlEQUFpRDtBQUNqRCwyQ0FBMkM7QUFDM0MsZ0VBQWdFO0FBQ2hFLHFFQUFxRTtBQUNyRSx5REFBeUQ7QUFDekQsd0RBQXdEO0FBQ3hELGlGQUFpRjtBQUNqRiwwREFBMEQ7QUFDMUQsbURBQW1EO0FBQ25ELGtFQUFrRTtBQUNsRSw2QkFBNkI7QUFHN0IsTUFBYSxjQUFlLFNBQVEsR0FBRyxDQUFDLEtBQUs7SUFDM0MsWUFBWSxLQUFnQixFQUFFLEVBQVUsRUFBRSxLQUFzQjtRQUM5RCxLQUFLLENBQUMsS0FBSyxFQUFFLEVBQUUsRUFBRSxLQUFLLENBQUMsQ0FBQztRQUV4QixNQUFNLE1BQU0sR0FBRyxJQUFJLEVBQUUsQ0FBQyxNQUFNLENBQUMsSUFBSSxFQUFFLFlBQVksRUFBRTtZQUMvQyxhQUFhLEVBQUUsR0FBRyxDQUFDLGFBQWEsQ0FBQyxPQUFPO1NBQ3pDLENBQUMsQ0FBQztRQUVILE1BQU0sS0FBSyxHQUFHLElBQUksR0FBRyxDQUFDLEtBQUssQ0FBQyxJQUFJLEVBQUUsV0FBVyxFQUFFO1lBQzdDLFNBQVMsRUFBRSxzQkFBc0I7WUFDakMsaUJBQWlCLEVBQUUsR0FBRyxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsRUFBRSxDQUFDO1NBQzVDLENBQUMsQ0FBQztRQUVILE1BQU0sS0FBSyxHQUFHLElBQUksUUFBUSxDQUFDLE9BQU8sQ0FBQyxJQUFJLEVBQUUsV0FBVyxFQUFFO1lBQ3BELFNBQVMsRUFBRSxzQkFBc0I7WUFDakMsWUFBWSxFQUFFLEVBQUUsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsUUFBUSxDQUFDLGFBQWEsQ0FBQyxNQUFNLEVBQUU7WUFDakUsYUFBYSxFQUFFLEdBQUcsQ0FBQyxhQUFhLENBQUMsT0FBTztTQUN6QyxDQUFDLENBQUM7UUFFSCxnRkFBZ0Y7UUFDaEYsTUFBTSxVQUFVLEdBQUcsSUFBSSxRQUFRLENBQUMsT0FBTyxDQUFDLElBQUksRUFBRSxnQkFBZ0IsRUFBRTtZQUM5RCxTQUFTLEVBQUUsdUJBQXVCO1lBQ2xDLFlBQVksRUFBRSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsSUFBSSxFQUFFLFFBQVEsQ0FBQyxhQUFhLENBQUMsTUFBTSxFQUFFO1lBQ2pFLE9BQU8sRUFBRSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsSUFBSSxFQUFFLFFBQVEsQ0FBQyxhQUFhLENBQUMsTUFBTSxFQUFFO1lBQzVELGFBQWEsRUFBRSxHQUFHLENBQUMsYUFBYSxDQUFDLE9BQU87WUFDeEMsc0JBQXNCLEVBQUU7Z0JBQ3RCO29CQUNFLFNBQVMsRUFBRSxPQUFPO29CQUNsQixZQUFZLEVBQUUsRUFBRSxJQUFJLEVBQUUsT0FBTyxFQUFFLElBQUksRUFBRSxRQUFRLENBQUMsYUFBYSxDQUFDLE1BQU0sRUFBRTtvQkFDcEUsT0FBTyxFQUFFLEVBQUUsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsUUFBUSxDQUFDLGFBQWEsQ0FBQyxNQUFNLEVBQUU7b0JBQzVELGNBQWMsRUFBRSxRQUFRLENBQUMsY0FBYyxDQUFDLEdBQUc7aUJBQzVDO2FBQ0Y7WUFDRCxxQkFBcUIsRUFBRTtnQkFDckI7b0JBQ0UsU0FBUyxFQUFFLE9BQU87b0JBQ2xCLE9BQU8sRUFBRSxFQUFFLElBQUksRUFBRSxPQUFPLEVBQUUsSUFBSSxFQUFFLFFBQVEsQ0FBQyxhQUFhLENBQUMsTUFBTSxFQUFFO29CQUMvRCxjQUFjLEVBQUUsUUFBUSxDQUFDLGNBQWMsQ0FBQyxTQUFTO2lCQUNsRDthQUNGO1NBQ0YsQ0FBQyxDQUFDO1FBRUgsTUFBTSxlQUFlLEdBQUcsSUFBSSxjQUFjLENBQUMsU0FBUyxDQUFDLElBQUksRUFBRSxpQkFBaUIsRUFBRTtZQUM1RSxJQUFJLEVBQUUsNEJBQTRCO1lBQ2xDLG9CQUFvQixFQUFFO2dCQUNwQixvQkFBb0IsRUFBRSxzQkFBc0I7Z0JBQzVDLGlCQUFpQixFQUFFLFVBQVU7Z0JBQzdCLGNBQWMsRUFBRSxFQUFFO2dCQUNsQixpQkFBaUIsRUFBRSxLQUFLO2FBQ3pCO1NBQ0YsQ0FBQyxDQUFDO1FBQ0gsZUFBZSxDQUFDLGtCQUFrQixDQUFDLEdBQUcsQ0FBQyxhQUFhLENBQUMsT0FBTyxDQUFDLENBQUM7UUFFOUQsbUVBQW1FO1FBQ25FLHlFQUF5RTtRQUN6RSxzRUFBc0U7UUFDdEUsZ0RBQWdEO1FBQ2hELElBQUksTUFBTSxDQUFDLG1CQUFtQixDQUFDLElBQUksRUFBRSxlQUFlLEVBQUU7WUFDcEQsWUFBWSxFQUFFLHdCQUF3QjtZQUN0QyxJQUFJLEVBQUUsTUFBTSxDQUFDLGVBQWUsQ0FBQyxjQUFjLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxTQUFTLEVBQUUsSUFBSSxFQUFFLFdBQVcsQ0FBQyxDQUFDO1lBQ3BGLE9BQU8sRUFBRSxHQUFHLENBQUMsUUFBUSxDQUFDLE9BQU8sQ0FBQyxFQUFFLENBQUM7WUFDakMsVUFBVSxFQUFFLEdBQUc7U0FDaEIsQ0FBQyxDQUFDO1FBRUgsa0ZBQWtGO1FBQ2xGLDJFQUEyRTtRQUMzRSx5RUFBeUU7UUFDekUsTUFBTSxHQUFHLEdBQUcsSUFBSSxHQUFHLENBQUMsR0FBRyxDQUFDLElBQUksRUFBRSxTQUFTLEVBQUU7WUFDdkMsT0FBTyxFQUFFLGVBQWU7WUFDeEIsTUFBTSxFQUFFLENBQUM7WUFDVCxXQUFXLEVBQUUsQ0FBQztZQUNkLG1CQUFtQixFQUFFO2dCQUNuQixFQUFFLElBQUksRUFBRSxRQUFRLEVBQUUsVUFBVSxFQUFFLEdBQUcsQ0FBQyxVQUFVLENBQUMsTUFBTSxFQUFFLFFBQVEsRUFBRSxFQUFFLEVBQUU7Z0JBQ25FLEVBQUUsSUFBSSxFQUFFLFVBQVUsRUFBRSxVQUFVLEVBQUUsR0FBRyxDQUFDLFVBQVUsQ0FBQyxnQkFBZ0IsRUFBRSxRQUFRLEVBQUUsRUFBRSxFQUFFO2FBQ2hGO1NBQ0YsQ0FBQyxDQUFDO1FBRUgsTUFBTSxHQUFHLEdBQUcsSUFBSSxLQUFLLENBQUMsdUJBQXVCLENBQUMsSUFBSSxFQUFFLFNBQVMsRUFBRTtZQUM3RCxnQkFBZ0IsRUFBRSxlQUFlO1lBQ2pDLEdBQUc7WUFDSCxjQUFjLEVBQUUsS0FBSztZQUNyQixVQUFVLEVBQUUsRUFBRSxVQUFVLEVBQUUsR0FBRyxDQUFDLFVBQVUsQ0FBQyxnQkFBZ0IsRUFBRTtTQUM1RCxDQUFDLENBQUM7UUFFSCwrRkFBK0Y7UUFDL0YsTUFBTSxTQUFTLEdBQUcsSUFBSSxnQkFBZ0IsQ0FBQyxtQkFBbUIsQ0FBQyxJQUFJLEVBQUUsZUFBZSxFQUFFO1lBQ2hGLElBQUksRUFBRSxvQkFBb0I7WUFDMUIsR0FBRztTQUNKLENBQUMsQ0FBQztRQUNILE1BQU0sT0FBTyxHQUFHLFNBQVMsQ0FBQyxhQUFhLENBQUMsYUFBYSxFQUFFO1lBQ3JELElBQUksRUFBRSxlQUFlO1lBQ3JCLGFBQWEsRUFBRSxnQkFBZ0IsQ0FBQyxhQUFhLENBQUMsQ0FBQztZQUMvQyxNQUFNLEVBQUUsR0FBRyxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsRUFBRSxDQUFDO1NBQ2pDLENBQUMsQ0FBQztRQUVILGlHQUFpRztRQUNqRyw2RkFBNkY7UUFDN0YsdUZBQXVGO1FBQ3ZGLE1BQU0sT0FBTyxHQUFHLElBQUksT0FBTyxDQUFDLGdCQUFnQixDQUFDLElBQUksRUFBRSxTQUFTLEVBQUUsRUFBRSxRQUFRLEVBQUUsMkJBQTJCLEVBQUUsQ0FBQyxDQUFDO1FBQ3pHLE1BQU0sYUFBYSxHQUFHLElBQUksT0FBTyxDQUFDLFVBQVUsQ0FBQyxJQUFJLEVBQUUsZUFBZSxFQUFFO1lBQ2xFLFVBQVUsRUFBRSxnQ0FBZ0M7WUFDNUMsV0FBVyxFQUFFLElBQUksR0FBRyxDQUFDLFdBQVcsQ0FBQyxJQUFJLEVBQUUsb0JBQW9CLEVBQUU7Z0JBQzNELFVBQVUsRUFBRSxnQ0FBZ0M7Z0JBQzVDLFVBQVUsRUFBRSxHQUFHLENBQUMscUJBQXFCLENBQUMsT0FBTyxDQUFDLE9BQU8sQ0FBQzthQUN2RCxDQUFDO1NBQ0gsQ0FBQyxDQUFDO1FBQ0gsTUFBTSxPQUFPLEdBQUcsSUFBSSxPQUFPLENBQUMsT0FBTyxDQUFDLElBQUksRUFBRSxhQUFhLEVBQUU7WUFDdkQsa0JBQ Line truncated
@@ -7,6 +7,12 @@ import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import * as servicediscovery from 'aws-cdk-lib/aws-servicediscovery';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as apigwv2 from 'aws-cdk-lib/aws-apigatewayv2';
import * as apigwv2Integrations from 'aws-cdk-lib/aws-apigatewayv2-integrations';
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
import * as route53 from 'aws-cdk-lib/aws-route53';
import * as route53Targets from 'aws-cdk-lib/aws-route53-targets';
import * as path from 'path';
import { Construct } from 'constructs';
@@ -105,6 +111,39 @@ export class FlociTestStack extends cdk.Stack {
dnsTtl: cdk.Duration.seconds(30),
});
// API Gateway custom domains: an HTTP API mapped at the root of an AWS::ApiGatewayV2::DomainName
// with an alias record to it, and a REST API under a key with several levels, which CDK maps
// with AWS::ApiGatewayV2::ApiMapping because a base path mapping takes one level only.
const apiZone = new route53.PublicHostedZone(this, 'ApiZone', { zoneName: 'floci-cdk-api.example.com' });
const httpApiDomain = new apigwv2.DomainName(this, 'HttpApiDomain', {
domainName: 'http.floci-cdk-api.example.com',
certificate: new acm.Certificate(this, 'HttpApiCertificate', {
domainName: 'http.floci-cdk-api.example.com',
validation: acm.CertificateValidation.fromDns(apiZone),
}),
});
const httpApi = new apigwv2.HttpApi(this, 'TestHttpApi', {
defaultIntegration: new apigwv2Integrations.HttpUrlIntegration('Backend', 'https://example.com'),
defaultDomainMapping: { domainName: httpApiDomain },
});
new route53.ARecord(this, 'HttpApiAlias', {
zone: apiZone,
recordName: 'http.floci-cdk-api.example.com',
target: route53.RecordTarget.fromAlias(new route53Targets.ApiGatewayv2DomainProperties(
httpApiDomain.regionalDomainName, httpApiDomain.regionalHostedZoneId)),
});
const restApi = new apigateway.RestApi(this, 'TestRestApi');
restApi.root.addResource('items').addMethod('GET', new apigateway.HttpIntegration('https://example.com'));
new apigateway.DomainName(this, 'RestApiDomain', {
domainName: 'rest.floci-cdk-api.example.com',
certificate: new acm.Certificate(this, 'RestApiCertificate', {
domainName: 'rest.floci-cdk-api.example.com',
validation: acm.CertificateValidation.fromDns(apiZone),
}),
mapping: restApi,
basePath: 'orders/v1',
});
new cdk.CfnOutput(this, 'BucketName', { value: bucket.bucketName });
new cdk.CfnOutput(this, 'QueueUrl', { value: queue.queueUrl });
new cdk.CfnOutput(this, 'TableName', { value: table.tableName });
@@ -114,5 +153,7 @@ export class FlociTestStack extends cdk.Stack {
new cdk.CfnOutput(this, 'AlbArn', { value: alb.loadBalancerArn });
new cdk.CfnOutput(this, 'NamespaceId', { value: namespace.namespaceId });
new cdk.CfnOutput(this, 'ServiceId', { value: service.serviceId });
new cdk.CfnOutput(this, 'HttpApiId', { value: httpApi.apiId });
new cdk.CfnOutput(this, 'RestApiId', { value: restApi.restApiId });
}
}
@@ -240,3 +240,41 @@ setup() {
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" ]
}
+28 -3
View File
@@ -613,8 +613,8 @@ object places no condition on its statement, as in IAM.
| **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage |
| **Deployments** | CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment |
| **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName |
| **API Mappings** | CreateApiMapping, GetApiMapping, GetApiMappings, DeleteApiMapping |
| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName |
| **API Mappings** | CreateApiMapping, GetApiMapping, GetApiMappings, UpdateApiMapping, DeleteApiMapping |
| **VPC Links** | CreateVpcLink, GetVpcLink, GetVpcLinks, UpdateVpcLink, DeleteVpcLink |
| **Tags** | TagResource, UntagResource, GetTags |
@@ -622,6 +622,31 @@ object places no condition on its statement, as in IAM.
(`arn:<partition>:apigateway:<region>::/vpclinks/<vpcLinkId>`). `UpdateVpcLink` changes only the
name, as in the API model.
### Custom Domain Names and API Mappings
A custom domain created through either API is one record, routed by its `Host` header as
described under [Custom Domain Names](#custom-domain-names); an API mapping sends the request to
the mapped stage of an HTTP, WebSocket or REST API. A REST API can be mapped under a key with
several levels, such as `orders/v1`, which only the v2 API creates.
`CreateDomainName` and `UpdateDomainName` take exactly one domain name configuration and refuse
mutual TLS, ownership verification certificates, an IP address type other than `ipv4` and a routing
mode other than `API_MAPPING_ONLY`; an update replaces the configuration as a whole. As on AWS, a v2
domain is regional: the `EDGE` endpoint type is refused, and any other one, `PRIVATE` included,
gives a `REGIONAL` domain, whose certificate the v1 API reports as
`regionalCertificateArn`. The v2 API does not manage an edge-optimized domain, an HTTP API or a key
with several levels needs a domain on the `TLS_1_2` security policy (so such a domain cannot leave
it), and a WebSocket API cannot share a domain with an HTTP or REST API.
A mapping key holds letters, digits and `$-_.+!*'(),`, with `/` between its levels, at most 300
characters; it does not start or end with `/` or hold `//`. No key, an empty one, or on a create one
of whitespace only, is the root mapping. `UpdateApiMapping` changes only what it names, and a
mapping keeps its `apiMappingId` when its key changes. The keys and their messages were measured
against API Gateway.
Templates can create domains and mappings with `AWS::ApiGatewayV2::DomainName` and
`AWS::ApiGatewayV2::ApiMapping`; see [CloudFormation](cloudformation.md).
### WebSocket Data-Plane {#websocket-data-plane}
Floci supports real WebSocket connections for API Gateway v2 WebSocket APIs. Clients connect via:
@@ -681,7 +706,7 @@ DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Disconn
### Not Implemented
- `ExportApi`, `UpdateDomainName`, `UpdateApiMapping`
- `ExportApi`
### Examples
+4
View File
@@ -45,6 +45,10 @@ Cloud Control.
`ResourceDescriptions`. This applies to any type Floci does not enumerate on the
read side, whether or not the type is real in AWS, since Floci has no CloudFormation
type registry to tell the two apart.
- **Identifiers**: a resource is identified by its type's primary identifier, which for
most types is the physical id CloudFormation's `Ref` returns. A compound one joins its
parts with `|`, as Cloud Control does: an `AWS::ApiGatewayV2::ApiMapping` is
`<ApiMappingId>|<DomainName>`.
- **Delete needs create-time state**: types whose delete depends on attributes
captured at create time (currently `AWS::EKS::Nodegroup` and `AWS::IAM::Policy`, plus
any `Custom::*` / `AWS::CloudFormation::CustomResource`) fail `DeleteResource` with a
+1 -1
View File
@@ -148,7 +148,7 @@ cross-resource references.
| Route 53 | `HostedZone`, `RecordSet` |
| Cloud Map | `HttpNamespace`, `PrivateDnsNamespace`, `PublicDnsNamespace`, `Service` |
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` |
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment`, `VpcLink` |
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment`, `DomainName`, `ApiMapping`, `VpcLink` |
| AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey`. `Ref` on `GraphQLApi` and `ApiKey` returns the id where AWS returns the ARN. See [AppSync](appsync.md#cloudformation) for `Ref` and `Fn::GetAtt` compared with AWS. |
| Step Functions | `StateMachine` |
| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
@@ -5,9 +5,9 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
@@ -50,11 +50,9 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -1613,16 +1611,7 @@ public class ApiGatewayController {
public Response createV2DomainName(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
Map<String, Object> request = readJsonBody(body);
// HTTP APIs require exactly one configuration, where the REST API takes none at all. It has
// to be an object: a scalar or a list there is still a body AWS would not have accepted.
if (!(request.get("domainNameConfigurations") instanceof List<?> configurations)
|| configurations.size() != 1
|| !(configurations.getFirst() instanceof Map<?, ?> configuration)) {
throw new AwsException("BadRequestException",
"Invalid input. Expected one domain name configuration", 400);
}
rejectUnemulatedDomainInputs(request, configuration);
CustomDomain domain = service.createDomainName(region, toV1DomainRequest(request));
CustomDomain domain = service.createV2DomainName(region, request);
return Response.status(201).entity(toV2DomainNode(region, domain).toString())
.type(MediaType.APPLICATION_JSON).build();
}
@@ -1645,6 +1634,20 @@ public class ApiGatewayController {
return Response.ok(toV2DomainNode(region, domain).toString()).type(MediaType.APPLICATION_JSON).build();
}
/**
* {@code UpdateDomainName}: the body's configuration replaces the domain's as a whole, and a body
* without one changes nothing.
*/
@PATCH
@Path("/v2/domainnames/{domainName}")
public Response updateV2DomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName,
String body) {
String region = regionResolver.resolveRegion(headers);
Map<String, Object> request = readJsonBody(body);
CustomDomain domain = service.updateV2DomainName(region, domainName, request);
return Response.ok(toV2DomainNode(region, domain).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/v2/domainnames/{domainName}")
public Response deleteV2DomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) {
@@ -1667,26 +1670,11 @@ public class ApiGatewayController {
}
String apiId = String.valueOf(request.get("apiId"));
String stage = String.valueOf(request.get("stage"));
// A mapping to an API or stage that does not exist would route nowhere, so AWS refuses it
// rather than answering 201 with something unusable.
requireApiAndStageExist(region, apiId, stage);
String basePath = ApiGatewayService.canonicalBasePath(
request.get("apiMappingKey") == null ? null : String.valueOf(request.get("apiMappingKey")));
boolean keyTaken = service.basePathMappingsByStoredPath(region, domainName).keySet().stream()
.anyMatch(existing -> ApiGatewayService.canonicalBasePath(existing).equals(basePath));
if (keyTaken) {
throw new AwsException("ConflictException",
"ApiMapping key already exists for this domain name", 409);
}
Map<String, Object> v1Request = new HashMap<>();
v1Request.put("restApiId", apiId);
v1Request.put("stage", stage);
v1Request.put("basePath", basePath);
BasePathMapping mapping = service.createBasePathMapping(region, domainName, v1Request,
v2Service.getApi(region, apiId).getProtocolType());
return Response.status(201).entity(toApiMappingNode(basePath, mapping).toString())
String apiMappingKey = request.get("apiMappingKey") == null
? null
: String.valueOf(request.get("apiMappingKey"));
StoredMapping created = service.createApiMapping(region, domainName, apiMappingKey, apiId, stage);
return Response.status(201).entity(toApiMappingNode(created).toString())
.type(MediaType.APPLICATION_JSON).build();
}
@@ -1696,8 +1684,7 @@ public class ApiGatewayController {
String region = regionResolver.resolveRegion(headers);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("items");
service.basePathMappingsByStoredPath(region, domainName)
.forEach((storedPath, mapping) -> items.add(toApiMappingNode(storedPath, mapping)));
service.getApiMappings(region, domainName).forEach(mapping -> items.add(toApiMappingNode(mapping)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@@ -1707,21 +1694,34 @@ public class ApiGatewayController {
@PathParam("domainName") String domainName,
@PathParam("apiMappingId") String apiMappingId) {
String region = regionResolver.resolveRegion(headers);
StoredMapping found = findApiMapping(region, domainName, apiMappingId);
return Response.ok(toApiMappingNode(found.storedPath(), found.mapping()).toString())
StoredMapping found = service.getApiMapping(region, domainName, apiMappingId);
return Response.ok(toApiMappingNode(found).toString())
.type(MediaType.APPLICATION_JSON).build();
}
/**
* {@code UpdateApiMapping}: what the body leaves out keeps its value, as on AWS, and the mapping
* keeps its id through a change of key.
*/
@PATCH
@Path("/v2/domainnames/{domainName}/apimappings/{apiMappingId}")
public Response updateApiMapping(@Context HttpHeaders headers,
@PathParam("domainName") String domainName,
@PathParam("apiMappingId") String apiMappingId,
String body) {
String region = regionResolver.resolveRegion(headers);
Map<String, Object> request = readJsonBody(body);
StoredMapping updated = service.updateApiMapping(region, domainName, apiMappingId, request);
return Response.ok(toApiMappingNode(updated).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/v2/domainnames/{domainName}/apimappings/{apiMappingId}")
public Response deleteApiMapping(@Context HttpHeaders headers,
@PathParam("domainName") String domainName,
@PathParam("apiMappingId") String apiMappingId) {
String region = regionResolver.resolveRegion(headers);
// Deleted by the path the selected record is stored under, so the record that answered the
// lookup is the record that goes.
StoredMapping found = findApiMapping(region, domainName, apiMappingId);
service.deleteBasePathMappingRecord(region, domainName, found.storedPath());
service.deleteApiMapping(region, domainName, apiMappingId);
return Response.noContent().build();
}
@@ -2458,58 +2458,10 @@ public class ApiGatewayController {
}
}
/**
* Refuses the parts of a domain that floci does not emulate, rather than accepting them and
* answering with a domain that behaves differently from the one that was asked for.
*/
private static void rejectUnemulatedDomainInputs(Map<String, Object> request, Map<?, ?> configuration) {
Object routingMode = request.get("routingMode");
if (routingMode != null && !"API_MAPPING_ONLY".equals(routingMode)) {
throw new AwsException("BadRequestException",
"Only API_MAPPING_ONLY routing is supported", 400);
}
if (request.get("mutualTlsAuthentication") != null) {
throw new AwsException("BadRequestException",
"Mutual TLS authentication is not supported", 400);
}
Object ipAddressType = configuration.get("ipAddressType");
if (ipAddressType != null && !"ipv4".equals(ipAddressType)) {
throw new AwsException("BadRequestException",
"Only the ipv4 address type is supported", 400);
}
if (configuration.get("ownershipVerificationCertificateArn") != null) {
throw new AwsException("BadRequestException",
"Ownership verification certificates are not supported", 400);
}
}
/** Flattens the v2 request onto the keys the shared custom-domain store is written with. */
private Map<String, Object> toV1DomainRequest(Map<String, Object> request) {
Map<String, Object> v1Request = new HashMap<>();
v1Request.put("domainName", request.get("domainName"));
copyIfPresent(request, v1Request, "tags", "tags");
if (request.get("domainNameConfigurations") instanceof List<?> configurations
&& !configurations.isEmpty()
&& configurations.getFirst() instanceof Map<?, ?> configuration) {
copyIfPresent(configuration, v1Request, "certificateArn", "certificateArn");
copyIfPresent(configuration, v1Request, "certificateName", "certificateName");
copyIfPresent(configuration, v1Request, "endpointType", "endpointType");
copyIfPresent(configuration, v1Request, "securityPolicy", "securityPolicy");
}
return v1Request;
}
private static void copyIfPresent(Map<?, ?> source, Map<String, Object> target, String from, String to) {
Object value = source.get(from);
if (value != null) {
target.put(to, value);
}
}
private ObjectNode toV2DomainNode(String region, CustomDomain d) {
ObjectNode node = objectMapper.createObjectNode();
node.put("domainName", d.getDomainName());
node.put("domainNameArn", AwsArnUtils.Arn.of("apigateway", region, "", "/domainnames/" + d.getDomainName()).toString());
node.put("domainNameArn", ApiGatewayService.domainNameArn(region, d.getDomainName()));
node.put("apiMappingSelectionExpression", "$request.basepath");
// AWS reports both of these on every domain.
node.put("routingMode", "API_MAPPING_ONLY");
@@ -2520,11 +2472,13 @@ public class ApiGatewayController {
configuration.put("endpointType", d.getEndpointConfigurationType());
configuration.put("domainNameStatus", d.getDomainNameStatus());
configuration.put("ipAddressType", "ipv4");
if (d.getCertificateArn() != null) {
configuration.put("certificateArn", d.getCertificateArn());
String certificateArn = ApiGatewayService.v2CertificateArn(d);
if (certificateArn != null) {
configuration.put("certificateArn", certificateArn);
}
if (d.getCertificateName() != null) {
configuration.put("certificateName", d.getCertificateName());
String certificateName = ApiGatewayService.v2CertificateName(d);
if (certificateName != null) {
configuration.put("certificateName", certificateName);
}
if (d.getSecurityPolicy() != null) {
configuration.put("securityPolicy", d.getSecurityPolicy());
@@ -2537,65 +2491,24 @@ public class ApiGatewayController {
return node;
}
private ObjectNode toApiMappingNode(String storedPath, BasePathMapping mapping) {
private ObjectNode toApiMappingNode(StoredMapping stored) {
String storedPath = stored.storedPath();
BasePathMapping mapping = stored.mapping();
ObjectNode node = objectMapper.createObjectNode();
node.put("apiMappingId", apiMappingId(storedPath));
node.put("apiMappingId", stored.apiMappingId());
node.put("apiId", mapping.getRestApiId());
node.put("stage", mapping.getStage());
// v1 stores the root mapping as "(none)"; v2 expresses it as an empty key.
// The key reported is the one the record is stored under, so it matches its id.
// The key reported is the one the record is stored under, which is the path it routes on.
String canonical = ApiGatewayService.canonicalBasePath(storedPath);
node.put("apiMappingKey", "(none)".equals(canonical) ? "" : canonical);
return node;
}
/** Rejects a mapping whose API or stage does not exist, with the errors AWS gives for each. */
private void requireApiAndStageExist(String region, String apiId, String stage) {
try {
v2Service.getApi(region, apiId);
} catch (AwsException e) {
throw new AwsException("BadRequestException", "Invalid API identifier specified: " + apiId, 400);
}
try {
v2Service.getStage(region, apiId, stage);
} catch (AwsException e) {
throw new AwsException("BadRequestException", "Invalid stage identifier specified", 400);
}
}
/**
* Derives the mapping id from what identifies the mapping, so it survives a restart and is the
* same id whichever API created it. The base path is encoded rather than hashed: two base paths
* sharing a hash would share an id, and a read or delete by that id would pick between them.
*/
// Package-private so the identity property can be tested against records that only persisted
// state can hold: no API path creates a non-canonical base path any more.
static String apiMappingId(String storedPath) {
// Encoded from the key the record is stored under — not its canonical form, and not the
// record's own field, which BasePathMapping normalises on construction. State written
// before writes were canonicalised can sit under "" or "/" beside "(none)", and reading
// identity from anywhere but the key hands several records one id for a read or a delete
// to choose between. The prefix keeps an empty stored path from producing an empty id.
return "m" + HexFormat.of().formatHex(
(storedPath == null ? "" : storedPath).getBytes(StandardCharsets.UTF_8));
}
/** A mapping together with the base path it is stored under, which is what identifies it. */
private record StoredMapping(String storedPath, BasePathMapping mapping) {}
private StoredMapping findApiMapping(String region, String domainName, String apiMappingId) {
return service.basePathMappingsByStoredPath(region, domainName).entrySet().stream()
.filter(entry -> apiMappingId(entry.getKey()).equals(apiMappingId))
.map(entry -> new StoredMapping(entry.getKey(), entry.getValue()))
.findFirst()
.orElseThrow(() -> new AwsException("NotFoundException",
"Unable to find ApiMapping with ID " + apiMappingId, 404));
}
private ObjectNode toDomainNode(String region, CustomDomain d) {
ObjectNode node = objectMapper.createObjectNode();
node.put("domainName", d.getDomainName());
node.put("domainNameArn", AwsArnUtils.Arn.of("apigateway", region, "", "/domainnames/" + d.getDomainName()).toString());
node.put("domainNameArn", ApiGatewayService.domainNameArn(region, d.getDomainName()));
node.put("domainNameStatus", d.getDomainNameStatus());
node.put("endpointConfigurationType", d.getEndpointConfigurationType());
node.putObject("endpointConfiguration").putArray("types").add(d.getEndpointConfigurationType());
@@ -41,6 +41,7 @@ import io.github.hectorvent.floci.services.apigateway.model.Stage;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.github.hectorvent.floci.services.apigateway.model.VpcLink;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
@@ -55,6 +56,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
@@ -63,6 +65,7 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -117,6 +120,8 @@ public class ApiGatewayService implements ResourceProvider {
private final TlsCertificateManager certificateManager;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
/** The v2 APIs an API mapping can point at; a custom domain is shared by both APIs. */
private final ApiGatewayV2Service apiGatewayV2Service;
// Constants
private static final String EPC_KEY = "endpointConfiguration";
@@ -124,6 +129,21 @@ public class ApiGatewayService implements ResourceProvider {
private static final String EPC_VPC_IDS_KEY = "vpcEndpointIds";
private static final String EPC_TYPES_PATH = "/endpointConfiguration/types/";
private static final String EPC_VPC_IDS_PATH = "/endpointConfiguration/vpcEndpointIds";
private static final String TLS_1_2 = "TLS_1_2";
/** The API type a mapping to a REST API is stored with, beside a v2 API's protocol type. */
private static final String REST_API_TYPE = "REST";
/** What AWS answers for a v2 API mapping call on an edge-optimized domain. */
private static final String V2_EDGE_DOMAIN_MESSAGE = "Only REGIONAL domain names can be managed through the "
+ "API Gateway V2 API. For EDGE domain names, please use the API Gateway V1 API. Also note that only REST "
+ "APIs can be attached to EDGE domain names.";
/** What AWS answers for a v2 domain created or updated with the EDGE endpoint type. */
private static final String V2_EDGE_ENDPOINT_TYPE_MESSAGE =
"EDGE endpoint type is not supported for APIGatewayV2 domainName";
/** The characters AWS allows in an API mapping key, its level separator included, and the most it takes. */
private static final Pattern API_MAPPING_KEY = Pattern.compile("[A-Za-z0-9$\\-_.+!*'(),/]+");
private static final int MAX_API_MAPPING_KEY_LENGTH = 300;
private static final String MAPPING_KEY_SLASHES_MESSAGE =
"API mapping key should not start with a '/' or have consecutive '/'s.";
ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,
TlsCertificateManager certificateManager) {
@@ -131,12 +151,20 @@ public class ApiGatewayService implements ResourceProvider {
new RegionResolver(config.defaultRegion(), config.defaultAccountId()));
}
ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,
TlsCertificateManager certificateManager, RegionResolver regionResolver) {
this(storageFactory, config, certificateManager, regionResolver,
new ApiGatewayV2Service(storageFactory, config, regionResolver));
}
@Inject
public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,
TlsCertificateManager certificateManager, RegionResolver regionResolver) {
TlsCertificateManager certificateManager, RegionResolver regionResolver,
ApiGatewayV2Service apiGatewayV2Service) {
this.certificateManager = certificateManager;
this.config = config;
this.regionResolver = regionResolver;
this.apiGatewayV2Service = apiGatewayV2Service;
this.apiStore = storageFactory.create("apigateway", "apigateway-apis.json",
new TypeReference<>() {
});
@@ -2013,6 +2041,14 @@ public class ApiGatewayService implements ResourceProvider {
// ──────────────────────────── Custom Domains ────────────────────────────
/**
* A public custom domain's ARN, {@code arn:<partition>:apigateway:<region>::/domainnames/<name>},
* which both APIs report and CloudFormation's {@code DomainNameArn} returns.
*/
public static String domainNameArn(String region, String domainName) {
return AwsArnUtils.Arn.of("apigateway", region, "", "/domainnames/" + domainName).toString();
}
public CustomDomain createDomainName(String region, Map<String, Object> request) {
String domainName = (String) request.get("domainName");
if (domainName == null) throw new AwsException("BadRequestException", "domainName is required", 400);
@@ -2200,6 +2236,9 @@ public class ApiGatewayService implements ResourceProvider {
throw new AwsException("BadRequestException", "Unsupported path: " + path, 400);
}
}
if (!Objects.equals(newSecurityPolicy, domain.getSecurityPolicy())) {
requireMappingsAllowSecurityPolicy(region, domainName, newSecurityPolicy);
}
// Only a change of type is held to the partition: an EDGE domain stored before the rule
// existed must still take certificate or security-policy updates.
if (!Objects.equals(newEndpointConfigurationType, domain.getEndpointConfigurationType())) {
@@ -2228,11 +2267,11 @@ public class ApiGatewayService implements ResourceProvider {
}
public BasePathMapping createBasePathMapping(String region, String domainName, Map<String, Object> request) {
return createBasePathMapping(region, domainName, request, "REST");
return createBasePathMapping(region, domainName, request, REST_API_TYPE, Set.of());
}
BasePathMapping createBasePathMapping(String region, String domainName,
Map<String, Object> request, String apiType) {
private BasePathMapping createBasePathMapping(String region, String domainName, Map<String, Object> request,
String apiType, Set<String> excludedIds) {
String basePath = canonicalBasePath((String) request.get("basePath"));
String apiId = (String) request.get("restApiId");
String stage = (String) request.get("stage");
@@ -2245,6 +2284,8 @@ public class ApiGatewayService implements ResourceProvider {
if (basePathMappingStore.get(key).isPresent()) {
throw new AwsException("ConflictException", "Base path already exists for this domain name", 409);
}
requireProtocolTypesCompatible(region, domainName, apiType, null);
mapping.setApiMappingId(unusedApiMappingId(region, domainName, basePath, excludedIds));
basePathMappingStore.put(key, mapping);
}
LOG.infov("Created mapping for {0} path={1} -> API {2}", domainName, basePath, apiId);
@@ -2372,6 +2413,460 @@ public class ApiGatewayService implements ResourceProvider {
return mapping;
}
// ──────────────────────────── Custom Domains and API Mappings (v2) ────────────────────────────
//
// A custom domain is one resource in AWS, reachable through both APIs, so the v2 operations read
// and write the same records the v1 ones do. The rules live here rather than in the controller
// because CloudFormation's AWS::ApiGatewayV2 types go through them too.
/** {@code CreateDomainName} through the v2 API, from its request body. */
public CustomDomain createV2DomainName(String region, Map<String, Object> request) {
return createDomainName(region, toV1DomainRequest(request));
}
/**
* {@code UpdateDomainName} through the v2 API: a body with a configuration replaces the domain's
* as {@link #replaceV2DomainConfiguration} does. One without changes nothing, after the same
* refusals: of what Floci does not emulate, and of an edge-optimized domain, which the v2 API
* does not manage.
*/
public CustomDomain updateV2DomainName(String region, String domainName, Map<String, Object> request) {
if (request.get("domainNameConfigurations") != null) {
return replaceV2DomainConfiguration(region, domainName, request);
}
rejectUnemulatedDomainInputs(request, Map.of());
CustomDomain domain = getDomainName(region, domainName);
requireRegionalDomain(domain);
return domain;
}
/**
* Drives a domain's configuration to the one in a v2 {@code CreateDomainName} body, validated the
* same way. This is what an update of {@code DomainNameConfigurations} does on AWS: the list is
* replaced as a whole, so a certificate the body leaves out is cleared and a security policy it
* leaves out takes the {@code TLS_1_2} default. The domain is regional, so its certificate goes to
* the regional fields, and one left in the edge-optimized fields by an earlier v2 write is
* cleared with the rest. Tags are not touched.
*/
public CustomDomain replaceV2DomainConfiguration(String region, String domainName,
Map<String, Object> request) {
Map<String, Object> v1Request = toV1DomainRequest(request);
String securityPolicy = (String) v1Request.getOrDefault("securityPolicy", TLS_1_2);
synchronized (domainNameLock) {
CustomDomain domain = getDomainName(region, domainName);
requireRegionalDomain(domain);
if (!Objects.equals(securityPolicy, domain.getSecurityPolicy())) {
requireMappingsAllowSecurityPolicy(region, domainName, securityPolicy);
}
domain.setCertificateArn(null);
domain.setCertificateName(null);
domain.setRegionalCertificateArn((String) v1Request.get("regionalCertificateArn"));
domain.setRegionalCertificateName((String) v1Request.get("regionalCertificateName"));
domain.setSecurityPolicy(securityPolicy);
applyEndpointType(domain, endpointTypeOf(v1Request), region);
domainStore.put(domainKey(region, domainName), domain);
return domain;
}
}
/**
* Flattens a v2 {@code CreateDomainName} body onto the keys the shared custom-domain store is
* written with, after refusing what floci does not emulate.
*/
private static Map<String, Object> toV1DomainRequest(Map<String, Object> request) {
// HTTP APIs require exactly one configuration, where the REST API takes none at all. It has
// to be an object: a scalar or a list there is still a body AWS would not have accepted.
if (!(request.get("domainNameConfigurations") instanceof List<?> configurations)
|| configurations.size() != 1
|| !(configurations.getFirst() instanceof Map<?, ?> configuration)) {
throw new AwsException("BadRequestException",
"Invalid input. Expected one domain name configuration", 400);
}
if ("EDGE".equals(configuration.get("endpointType"))) {
throw new AwsException("BadRequestException", V2_EDGE_ENDPOINT_TYPE_MESSAGE, 400);
}
rejectUnemulatedDomainInputs(request, configuration);
Map<String, Object> v1Request = new HashMap<>();
v1Request.put("domainName", request.get("domainName"));
copyIfPresent(request, v1Request, "tags", "tags");
// An HTTP API domain is regional: API Gateway creates or keeps any other endpoint type it is
// given, PRIVATE or one it does not know, as REGIONAL (measured, eu-west-1, 2026-10-04). Its
// certificate is the regional one, which the v1 API reports as regionalCertificateArn.
copyIfPresent(configuration, v1Request, "certificateArn", "regionalCertificateArn");
copyIfPresent(configuration, v1Request, "certificateName", "regionalCertificateName");
v1Request.put("endpointType", "REGIONAL");
copyIfPresent(configuration, v1Request, "securityPolicy", "securityPolicy");
return v1Request;
}
/**
* Refuses the parts of a domain that floci does not emulate, rather than accepting them and
* answering with a domain that behaves differently from the one that was asked for.
*/
private static void rejectUnemulatedDomainInputs(Map<String, Object> request, Map<?, ?> configuration) {
Object routingMode = request.get("routingMode");
if (routingMode != null && !"API_MAPPING_ONLY".equals(routingMode)) {
throw new AwsException("BadRequestException",
"Only API_MAPPING_ONLY routing is supported", 400);
}
if (request.get("mutualTlsAuthentication") != null) {
throw new AwsException("BadRequestException",
"Mutual TLS authentication is not supported", 400);
}
Object ipAddressType = configuration.get("ipAddressType");
if (ipAddressType != null && !"ipv4".equals(ipAddressType)) {
throw new AwsException("BadRequestException",
"Only the ipv4 address type is supported", 400);
}
if (configuration.get("ownershipVerificationCertificateArn") != null) {
throw new AwsException("BadRequestException",
"Ownership verification certificates are not supported", 400);
}
}
private static void copyIfPresent(Map<?, ?> source, Map<String, Object> target, String from, String to) {
Object value = source.get(from);
if (value != null) {
target.put(to, value);
}
}
/** A v2 API mapping: the base path mapping record, with the base path it is stored under. */
public record StoredMapping(String storedPath, BasePathMapping mapping) {
/** The id stored on the record, or for a record persisted before ids were stored, the derived one. */
public String apiMappingId() {
return mapping.getApiMappingId() != null
? mapping.getApiMappingId()
: ApiGatewayService.apiMappingId(storedPath);
}
}
/** What a mapping routes to: an API, one of its stages, and the type of API it is routed as. */
private record MappingTarget(String apiId, String stage, String apiType) {}
/** The mappings of a domain, refused for an edge-optimized one as AWS refuses every v2 call on it. */
public List<StoredMapping> getApiMappings(String region, String domainName) {
requireRegionalDomain(getDomainName(region, domainName));
List<StoredMapping> mappings = new ArrayList<>();
basePathMappingsByStoredPath(region, domainName)
.forEach((storedPath, mapping) -> mappings.add(new StoredMapping(storedPath, mapping)));
return mappings;
}
/**
* Creates a v2 API mapping, stored as a base path mapping that remembers the type of API it
* routes to.
*/
public StoredMapping createApiMapping(String region, String domainName, String apiMappingKey,
String apiId, String stage) {
return createApiMapping(region, domainName, apiMappingKey, apiId, stage, Set.of());
}
/**
* As above, with ids the new mapping must not be given. A caller that still tracks a mapping on
* another domain under one of them would otherwise hold two mappings it cannot tell apart; on
* AWS a new mapping never takes the id of another.
*/
public StoredMapping createApiMapping(String region, String domainName, String apiMappingKey,
String apiId, String stage, Set<String> excludedIds) {
// A mapping to an API or stage that does not exist would route nowhere, so AWS refuses it
// rather than answering 201 with something unusable.
requireValidApiMappingKey(apiMappingKey, false);
MappingTarget target = requireMappingTarget(region, apiId, stage);
String basePath = canonicalBasePath(apiMappingKey);
synchronized (domainNameLock) {
requireMappingAllowed(getDomainName(region, domainName), basePath, target.apiType());
requireApiMappingKeyFree(region, domainName, basePath);
Map<String, Object> v1Request = new HashMap<>();
v1Request.put("restApiId", target.apiId());
v1Request.put("stage", target.stage());
v1Request.put("basePath", basePath);
return new StoredMapping(basePath,
createBasePathMapping(region, domainName, v1Request, target.apiType(), excludedIds));
}
}
/**
* The v2 {@code UpdateApiMapping} from its request body: what the body leaves out keeps its value,
* as on AWS. The values it keeps are read under the lock the update takes, so two updates naming
* different fields of one mapping cannot write back each other's old values.
*/
public StoredMapping updateApiMapping(String region, String domainName, String apiMappingId,
Map<String, Object> request) {
synchronized (domainNameLock) {
StoredMapping current = getApiMapping(region, domainName, apiMappingId);
String currentKey = canonicalBasePath(current.storedPath());
String apiMappingKey = request.containsKey("apiMappingKey")
? Objects.toString(request.get("apiMappingKey"), null)
: ("(none)".equals(currentKey) ? null : currentKey);
String apiId = Objects.toString(request.get("apiId"), current.mapping().getRestApiId());
String stage = Objects.toString(request.get("stage"), current.mapping().getStage());
return updateApiMapping(region, domainName, apiMappingId, apiMappingKey, apiId, stage);
}
}
/**
* Points a v2 API mapping at a new key, API and stage, the v2 {@code UpdateApiMapping}. The id
* names the mapping rather than its key, so it stays with the record when the key changes, as on
* AWS.
*/
public StoredMapping updateApiMapping(String region, String domainName, String apiMappingId,
String apiMappingKey, String apiId, String stage) {
requireValidApiMappingKey(apiMappingKey, true);
MappingTarget target = requireMappingTarget(region, apiId, stage);
String basePath = canonicalBasePath(apiMappingKey);
synchronized (domainNameLock) {
CustomDomain domain = getDomainName(region, domainName);
StoredMapping found = getApiMapping(region, domainName, apiMappingId);
requireMappingAllowed(domain, basePath, target.apiType());
requireProtocolTypesCompatible(region, domainName, target.apiType(), found.storedPath());
BasePathMapping mapping = found.mapping();
String storedPath = found.storedPath();
if (!basePath.equals(canonicalBasePath(storedPath))) {
requireApiMappingKeyFree(region, domainName, basePath);
// Pinned before the record leaves the path a legacy id was derived from.
mapping.setApiMappingId(found.apiMappingId());
basePathMappingStore.delete(mappingKey(region, domainName, storedPath));
mapping.setBasePath(basePath);
storedPath = basePath;
}
mapping.setRestApiId(target.apiId());
mapping.setStage(target.stage());
mapping.setApiType(target.apiType());
basePathMappingStore.put(mappingKey(region, domainName, storedPath), mapping);
return new StoredMapping(storedPath, mapping);
}
}
/**
* The API and stage a v2 API mapping points at. AWS takes a REST API here as well as an HTTP or
* WebSocket API, which is how a REST API gets a mapping with more than one level, and refuses an
* API or stage that does not exist rather than creating a mapping that routes nowhere. A v2 API
* answers first, as it did before REST APIs were accepted.
*/
private MappingTarget requireMappingTarget(String region, String apiId, String stageName) {
String apiType = v2ApiType(region, apiId);
boolean restApi = apiType == null && restApiExists(region, apiId);
if (apiType == null && !restApi) {
throw new AwsException("BadRequestException", "Invalid API identifier specified: " + apiId, 400);
}
try {
if (restApi) {
getStage(region, apiId, stageName);
} else {
apiGatewayV2Service.getStage(region, apiId, stageName);
}
} catch (AwsException e) {
throw new AwsException("BadRequestException", "Invalid stage identifier specified", 400);
}
return new MappingTarget(apiId, stageName, restApi ? REST_API_TYPE : apiType);
}
private String v2ApiType(String region, String apiId) {
try {
return apiGatewayV2Service.getApi(region, apiId).getProtocolType();
} catch (AwsException notAV2Api) {
LOG.debugv("{0} is not an HTTP or WebSocket API in {1}: {2}", apiId, region, notAV2Api.getMessage());
return null;
}
}
private boolean restApiExists(String region, String apiId) {
try {
getRestApi(region, apiId);
return true;
} catch (AwsException notARestApi) {
LOG.debugv("{0} is not a REST API in {1}: {2}", apiId, region, notARestApi.getMessage());
return false;
}
}
/**
* Refuses an API mapping key that API Gateway refuses, with its messages (measured, eu-west-1,
* 2026-10-04). No key or an empty one is the root mapping, and so is a key of whitespace only
* on a create; an update refuses that one.
*/
private static void requireValidApiMappingKey(String apiMappingKey, boolean update) {
if (apiMappingKey == null || apiMappingKey.isEmpty()) {
return;
}
if (apiMappingKey.isBlank()) {
if (update) {
throw new AwsException("BadRequestException", MAPPING_KEY_SLASHES_MESSAGE, 400);
}
return;
}
if (apiMappingKey.length() > MAX_API_MAPPING_KEY_LENGTH) {
throw new AwsException("BadRequestException",
"ApiMapping key length must be under " + MAX_API_MAPPING_KEY_LENGTH + " characters.", 400);
}
if (apiMappingKey.endsWith("/")) {
throw new AwsException("BadRequestException", "API mapping key should not end with a '/'.", 400);
}
if (apiMappingKey.startsWith("/") || apiMappingKey.contains("//")) {
throw new AwsException("BadRequestException", MAPPING_KEY_SLASHES_MESSAGE, 400);
}
if (!API_MAPPING_KEY.matcher(apiMappingKey).matches()) {
throw new AwsException("BadRequestException",
"An API mapping key may contain only letters, numbers and one of $-_.+!*'(), characters.", 400);
}
}
/**
* The restrictions AWS puts on an API mapping's domain: only a regional domain is reachable
* through the v2 API, and an HTTP API or a key with more than one level needs a domain on the
* TLS 1.2 security policy.
*/
private static void requireMappingAllowed(CustomDomain domain, String basePath, String apiType) {
requireRegionalDomain(domain);
boolean root = "(none)".equals(basePath);
if (!TLS_1_2.equals(securityPolicyOf(domain))) {
if ("HTTP".equals(apiType)) {
throw new AwsException("BadRequestException",
"HTTP APIs can only be mapped to a regional custom domain name with the TLS 1.2 security policy",
400);
}
if (!root && basePath.contains("/")) {
throw new AwsException("BadRequestException",
"API mappings with multiple levels require a regional custom domain name with the TLS 1.2 "
+ "security policy", 400);
}
}
}
private static void requireRegionalDomain(CustomDomain domain) {
if ("EDGE".equals(domain.getEndpointConfigurationType())) {
throw new AwsException("BadRequestException", V2_EDGE_DOMAIN_MESSAGE, 400);
}
}
/**
* A domain whose mappings need TLS 1.2, an HTTP API or a key with more than one level, cannot be
* moved to another security policy: the mappings AWS accepted would no longer be allowed on it.
*/
private void requireMappingsAllowSecurityPolicy(String region, String domainName, String securityPolicy) {
if (TLS_1_2.equals(securityPolicy == null ? TLS_1_2 : securityPolicy)) {
return;
}
for (Map.Entry<String, BasePathMapping> entry : basePathMappingsByStoredPath(region, domainName).entrySet()) {
String basePath = canonicalBasePath(entry.getKey());
if ("HTTP".equals(entry.getValue().getApiType())
|| (!"(none)".equals(basePath) && basePath.contains("/"))) {
throw new AwsException("BadRequestException", "Custom domain name " + domainName
+ " has HTTP API mappings or API mappings with multiple levels, which require the TLS 1.2 "
+ "security policy", 400);
}
}
}
/**
* AWS keeps WebSocket APIs off a custom domain name that an HTTP or REST API is mapped to, and the
* other way round. {@code ignoredStoredPath} is the mapping being changed, if any. A record
* persisted before mappings remembered their API type is not held against either.
*/
private void requireProtocolTypesCompatible(String region, String domainName, String apiType,
String ignoredStoredPath) {
boolean webSocket = "WEBSOCKET".equals(apiType);
for (Map.Entry<String, BasePathMapping> entry : basePathMappingsByStoredPath(region, domainName).entrySet()) {
String otherType = entry.getValue().getApiType();
if (otherType == null || entry.getKey().equals(ignoredStoredPath)) {
continue;
}
if (webSocket != "WEBSOCKET".equals(otherType)) {
throw new AwsException("BadRequestException",
"WebSocket APIs can't be mapped to the same custom domain name as an HTTP API or REST API",
400);
}
}
}
private static String securityPolicyOf(CustomDomain domain) {
return domain.getSecurityPolicy() == null ? TLS_1_2 : domain.getSecurityPolicy();
}
/** Whichever spelling an earlier record was written under, "" and an omitted key are one key. */
private void requireApiMappingKeyFree(String region, String domainName, String basePath) {
boolean keyTaken = basePathMappingsByStoredPath(region, domainName).keySet().stream()
.anyMatch(existing -> canonicalBasePath(existing).equals(basePath));
if (keyTaken) {
throw new AwsException("ConflictException",
"ApiMapping key already exists for this domain name", 409);
}
}
public StoredMapping getApiMapping(String region, String domainName, String apiMappingId) {
requireRegionalDomain(getDomainName(region, domainName));
return basePathMappingsByStoredPath(region, domainName).entrySet().stream()
.map(entry -> new StoredMapping(entry.getKey(), entry.getValue()))
.filter(stored -> stored.apiMappingId().equals(apiMappingId))
.findFirst()
.orElseThrow(() -> new AwsException("NotFoundException",
"Unable to find ApiMapping with ID " + apiMappingId, 404));
}
/**
* The id a new mapping on {@code basePath} is given: the one derived from the path, so a mapping
* gets the id it always had, unless a mapping whose key changed since it was created still holds
* it, or the caller excludes it. Then a numbered variant, so no two mappings on a domain share one.
*/
private String unusedApiMappingId(String region, String domainName, String basePath, Set<String> excludedIds) {
Set<String> taken = new HashSet<>(excludedIds);
basePathMappingsByStoredPath(region, domainName)
.forEach((storedPath, mapping) -> taken.add(new StoredMapping(storedPath, mapping).apiMappingId()));
String derived = apiMappingId(basePath);
String id = derived;
for (int n = 2; taken.contains(id); n++) {
id = derived + "-" + n;
}
return id;
}
public void deleteApiMapping(String region, String domainName, String apiMappingId) {
// Deleted by the path the selected record is stored under, so the record that answered the
// lookup is the record that goes.
StoredMapping found = getApiMapping(region, domainName, apiMappingId);
deleteBasePathMappingRecord(region, domainName, found.storedPath());
}
/**
* Derives a mapping id from the path the mapping is stored under. A new mapping is given this id
* and stores it, so the id outlives a later change of key; a record persisted before ids were
* stored is still read under it. The base path is encoded rather than hashed: two base paths
* sharing a hash would share an id, and a read or delete by that id would pick between them.
*/
public static String apiMappingId(String storedPath) {
// Encoded from the key the record is stored under: not its canonical form, and not the
// record's own field, which BasePathMapping normalises on construction. State written
// before writes were canonicalised can sit under "" or "/" beside "(none)", and reading
// identity from anywhere but the key hands several records one id for a read or a delete
// to choose between. The prefix keeps an empty stored path from producing an empty id.
return "m" + HexFormat.of().formatHex(
(storedPath == null ? "" : storedPath).getBytes(StandardCharsets.UTF_8));
}
/** The certificate a v2 domain configuration reports, see {@link #v2CertificateIsRegional}. */
public static String v2CertificateArn(CustomDomain domain) {
return v2CertificateIsRegional(domain) ? domain.getRegionalCertificateArn() : domain.getCertificateArn();
}
/** The certificate name a v2 domain configuration reports, see {@link #v2CertificateIsRegional}. */
public static String v2CertificateName(CustomDomain domain) {
return v2CertificateIsRegional(domain) ? domain.getRegionalCertificateName() : domain.getCertificateName();
}
/**
* The v1 model keeps an edge-optimized domain's certificate apart from a regional one's, and the
* v2 API reports whichever the domain uses. A regional domain the v2 API wrote before its
* certificate went to the regional fields still holds it in the edge-optimized ones, so those
* answer while the regional ones are empty.
*/
private static boolean v2CertificateIsRegional(CustomDomain domain) {
return !"EDGE".equals(domain.getEndpointConfigurationType())
&& (domain.getRegionalCertificateArn() != null || domain.getRegionalCertificateName() != null);
}
// ──────────────────────────── Custom Domain Resolution ────────────────────────────
/**
@@ -10,6 +10,11 @@ public class BasePathMapping {
private String restApiId;
private String stage;
private String apiType;
/**
* The v2 {@code apiMappingId}, given when the mapping is created and kept when its key changes.
* Null on a record persisted before ids were stored, whose id is derived from its stored path.
*/
private String apiMappingId;
public BasePathMapping() {
this.basePath = "(none)";
@@ -32,4 +37,7 @@ public class BasePathMapping {
public String getApiType() { return apiType; }
public void setApiType(String apiType) { this.apiType = apiType; }
public String getApiMappingId() { return apiMappingId; }
public void setApiMappingId(String apiMappingId) { this.apiMappingId = apiMappingId; }
}
@@ -149,8 +149,9 @@ public class CloudControlService {
String identifier = created.entrySet().stream()
.filter(resource -> resource.getValue() == recovered)
.map(Map.Entry::getKey)
.map(key -> key.substring((accountId + "|").length()))
.map(key -> key.substring(key.lastIndexOf('|') + 1))
// account|region|type|identifier: the identifier is everything after the
// third separator, since a compound one holds separators of its own.
.map(key -> key.split("\\|", 4)[3])
.findFirst().orElse(normalized.identifier());
normalized = new ProgressEvent(normalized.typeName(), identifier, normalized.requestToken(),
normalized.operation(), "SUCCESS", null, recovered.model(), accountId);
@@ -321,12 +322,13 @@ public class CloudControlService {
if (resource == null || resource.getPhysicalId() == null) {
recordCreateFailure(pending, "CreateResource is not supported for " + typeName + ".");
} else {
String identifier = identifierOf(typeName, resource.getPhysicalId(), props);
String model = resourceModel(region, typeName, resource.getPhysicalId(), props);
CreatedResource createdResource = new CreatedResource(token, accountId,
resource.getAttributes() == null ? Map.of() : Map.copyOf(resource.getAttributes()), model);
created.put(createdKey(accountId, region, typeName, resource.getPhysicalId()), createdResource);
persistCreated(accountId, region, typeName, resource.getPhysicalId(), createdResource);
record(new ProgressEvent(typeName, resource.getPhysicalId(),
created.put(createdKey(accountId, region, typeName, identifier), createdResource);
persistCreated(accountId, region, typeName, identifier, createdResource);
record(new ProgressEvent(typeName, identifier,
token, "CREATE", "SUCCESS", null, model, accountId));
}
} catch (Exception e) {
@@ -454,6 +456,20 @@ public class CloudControlService {
return propertiesString(model);
}
/**
* The identifier Cloud Control hands out for a created resource: the type's primary identifier,
* which for most types is the physical id. A compound one joins its parts with {@code |}, as
* Cloud Control does; an {@code AWS::ApiGatewayV2::ApiMapping} is {@code <ApiMappingId>|<DomainName>},
* where CloudFormation's {@code Ref} is the bare id.
*/
private static String identifierOf(String typeName, String physicalId, JsonNode desiredState) {
if ("AWS::ApiGatewayV2::ApiMapping".equals(typeName) && desiredState != null
&& desiredState.path("DomainName").isTextual()) {
return physicalId + "|" + desiredState.path("DomainName").asText();
}
return physicalId;
}
/** The read-only primary identifier property name for the common EC2/IAM types. */
private static String primaryIdentifierField(String typeName) {
return switch (typeName) {
@@ -464,6 +480,7 @@ public class CloudControlService {
case "AWS::EC2::InternetGateway" -> "InternetGatewayId";
case "AWS::EC2::RouteTable" -> "RouteTableId";
case "AWS::EC2::LaunchTemplate" -> "LaunchTemplateId";
case "AWS::ApiGatewayV2::ApiMapping" -> "ApiMappingId";
default -> "Id";
};
}
@@ -1,7 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
@@ -103,7 +102,7 @@ public class ApiGatewayDomainCfnProvisioner implements CfnResourceProvisioner {
}
r.setPhysicalId(domainName);
r.getAttributes().put("DomainNameArn",
AwsArnUtils.Arn.of("apigateway", ctx.region(), "", "/domainnames/" + domainName).toString());
ApiGatewayService.domainNameArn(ctx.region(), domainName));
r.getAttributes().put("RegionalDomainName", orEmpty(provisioned.getRegionalDomainName()));
r.getAttributes().put("RegionalHostedZoneId", orEmpty(provisioned.getRegionalHostedZoneId()));
r.getAttributes().put("DistributionDomainName", orEmpty(provisioned.getDistributionDomainName()));
@@ -0,0 +1,506 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Provisions {@code AWS::ApiGatewayV2::DomainName} and {@code AWS::ApiGatewayV2::ApiMapping}.
*
* <p>A custom domain is one resource in AWS, reachable through both APIs, so these write the same
* domain and base path mapping records as {@link ApiGatewayDomainCfnProvisioner}, through the rules
* the v2 API applies. A domain's physical id is its name and a mapping's is its {@code ApiMappingId},
* as in AWS. {@code DomainName} is the only createOnly property of either type: a new one replaces
* the resource, everything else is updated in place, and a mapping keeps its id when its key changes.
*
* <p>A replacement creates the new entity and leaves the displaced one to {@link ReplacementCleanup},
* which deletes it once the stack update commits, keeps it under {@code UpdateReplacePolicy: Retain},
* and puts it back when a later resource fails the update. An in-place update snapshots what it
* changes first, so a failed update can restore it.
*/
@ApplicationScoped
public class ApiGatewayV2DomainCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(ApiGatewayV2DomainCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String DOMAIN_NAME_TYPE = "AWS::ApiGatewayV2::DomainName";
private static final String API_MAPPING_TYPE = "AWS::ApiGatewayV2::ApiMapping";
private static final String NOT_FOUND = "NotFoundException";
/** The domain a mapping belongs to: its delete needs it, and its physical id does not carry it. */
private static final String MAPPING_DOMAIN_NAME_ATTR = "__FlociApiMappingDomainName";
/**
* The domain of each mapping this resource displaced and may still owe a delete, by id. A mapping
* id is unique only within its domain, so the cleanup and the rollback need both.
*/
private static final String MAPPING_DISPLACED_DOMAINS_ATTR = "__FlociApiMappingDisplacedDomains";
/** {@code <ApiMappingId>|<DomainName>}, the type's primary identifier, which Cloud Control names a mapping by. */
private static final String IDENTIFIER_SEPARATOR = "|";
private final ApiGatewayService apiGatewayService;
@Inject
public ApiGatewayV2DomainCfnProvisioner(ApiGatewayService apiGatewayService) {
this.apiGatewayService = apiGatewayService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(DOMAIN_NAME_TYPE, API_MAPPING_TYPE);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
case DOMAIN_NAME_TYPE -> provisionDomainName(r, props, ctx);
case API_MAPPING_TYPE -> provisionApiMapping(r, props, ctx);
default -> throw new IllegalStateException(
"ApiGatewayV2DomainCfnProvisioner cannot handle " + r.getResourceType());
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
switch (resourceType) {
case DOMAIN_NAME_TYPE -> deleteDomain(physicalId, region);
case API_MAPPING_TYPE -> deleteMappingByIdentifier(physicalId, region);
default -> throw new IllegalStateException(
"ApiGatewayV2DomainCfnProvisioner cannot handle " + resourceType);
}
}
@Override
public void delete(StackResource resource, String region) {
String physicalId = resource.getPhysicalId();
if (API_MAPPING_TYPE.equals(resource.getResourceType()) && physicalId != null
&& physicalId.contains(IDENTIFIER_SEPARATOR)) {
// What Cloud Control created, keyed by the primary identifier, <ApiMappingId>|<DomainName>.
deleteMappingByIdentifier(physicalId, region);
return;
}
if (API_MAPPING_TYPE.equals(resource.getResourceType()) && resource.getAttributes() != null) {
String domainName = resource.getAttributes().get(MAPPING_DOMAIN_NAME_ATTR);
if (!isBlank(domainName)) {
deleteMapping(domainName, resource.getPhysicalId(), region);
return;
}
}
delete(resource.getResourceType(), resource.getPhysicalId(), region);
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
// The update committed, so what an in-place change snapshotted for a rollback is spent.
resource.getAttributes().remove(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR);
resource.getAttributes().remove(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR);
if (DOMAIN_NAME_TYPE.equals(resource.getResourceType())) {
return ReplacementCleanup.complete(resource, this::delete);
}
UpdateCleanupResult result = ReplacementCleanup.complete(resource, mappingDeleter(resource));
forgetDisplacedDomainsOnceNothingIsOwed(resource);
return result;
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR);
resource.getAttributes().remove(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
forgetDisplacedDomainsOnceNothingIsOwed(resource);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
return switch (resource.getResourceType()) {
case DOMAIN_NAME_TYPE -> rollbackDomainUpdate(resource);
case API_MAPPING_TYPE -> rollbackMappingUpdate(resource);
default -> false;
};
}
// ──────────────────────────── DomainName ────────────────────────────
private void provisionDomainName(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
String domainName = ctx.resolveOptional(props, "DomainName");
if (isBlank(domainName)) {
throw new IllegalArgumentException("AWS::ApiGatewayV2::DomainName requires DomainName");
}
Map<String, String> tags = ctx.resolveTags(props, "Tags");
Map<String, Object> request = domainRequest(domainName, props, tags, ctx);
CustomDomain existing = ctx.isUpdate() ? findDomain(ctx.priorPhysicalId(), ctx.region()) : null;
CustomDomain provisioned;
if (existing != null && ctx.reusesPriorEntity(domainName)) {
// Snapshotted before the first change, so a later resource failing the update can put the
// domain back. The service validates before it writes, so a template the API would refuse
// changes nothing.
r.getAttributes().put(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR,
domainSnapshot(existing, ctx.region()));
provisioned = apiGatewayService.replaceV2DomainConfiguration(ctx.region(), domainName, request);
reconcileTags(provisioned, tags, ctx.region());
} else {
r.getAttributes().remove(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR);
provisioned = apiGatewayService.createV2DomainName(ctx.region(), request);
}
r.setPhysicalId(domainName);
r.getAttributes().put("DomainNameArn",
ApiGatewayService.domainNameArn(ctx.region(), domainName));
r.getAttributes().put("RegionalDomainName", orEmpty(provisioned.getRegionalDomainName()));
r.getAttributes().put("RegionalHostedZoneId", orEmpty(provisioned.getRegionalHostedZoneId()));
ReplacementCleanup.record(r, ctx, attributesBefore);
}
/** The template's domain in the shape of a v2 {@code CreateDomainName} body. */
private static Map<String, Object> domainRequest(String domainName, JsonNode props, Map<String, String> tags,
ProvisionContext ctx) {
Map<String, Object> request = new LinkedHashMap<>();
request.put("domainName", domainName);
JsonNode configurations = props.hasNonNull("DomainNameConfigurations")
? ctx.engine().resolveNode(props.get("DomainNameConfigurations"))
: null;
if (configurations != null && configurations.isArray()) {
List<Map<String, Object>> resolved = new ArrayList<>();
for (JsonNode configuration : configurations) {
Map<String, Object> entry = new LinkedHashMap<>();
putIfPresent(entry, "certificateArn", ctx.resolveOptional(configuration, "CertificateArn"));
putIfPresent(entry, "certificateName", ctx.resolveOptional(configuration, "CertificateName"));
putIfPresent(entry, "endpointType", ctx.resolveOptional(configuration, "EndpointType"));
putIfPresent(entry, "securityPolicy", ctx.resolveOptional(configuration, "SecurityPolicy"));
putIfPresent(entry, "ipAddressType", ctx.resolveOptional(configuration, "IpAddressType"));
putIfPresent(entry, "ownershipVerificationCertificateArn",
ctx.resolveOptional(configuration, "OwnershipVerificationCertificateArn"));
resolved.add(entry);
}
request.put("domainNameConfigurations", resolved);
}
JsonNode mutualTls = props.hasNonNull("MutualTlsAuthentication")
? ctx.engine().resolveNode(props.get("MutualTlsAuthentication"))
: null;
if (mutualTls != null && mutualTls.isObject()) {
Map<String, Object> truststore = new LinkedHashMap<>();
putIfPresent(truststore, "truststoreUri", ctx.resolveOptional(mutualTls, "TruststoreUri"));
putIfPresent(truststore, "truststoreVersion", ctx.resolveOptional(mutualTls, "TruststoreVersion"));
if (!truststore.isEmpty()) {
request.put("mutualTlsAuthentication", truststore);
}
}
putIfPresent(request, "routingMode", ctx.resolveOptional(props, "RoutingMode"));
if (!tags.isEmpty()) {
request.put("tags", tags);
}
return request;
}
private static String domainSnapshot(CustomDomain domain, String region) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("region", region);
snapshot.put("domainName", domain.getDomainName());
snapshot.put("certificateArn", ApiGatewayService.v2CertificateArn(domain));
snapshot.put("certificateName", ApiGatewayService.v2CertificateName(domain));
snapshot.put("endpointType", domain.getEndpointConfigurationType());
snapshot.put("securityPolicy", domain.getSecurityPolicy());
ObjectNode tags = snapshot.putObject("tags");
if (domain.getTags() != null) {
domain.getTags().forEach(tags::put);
}
return snapshot.toString();
}
private boolean rollbackDomainUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
return true;
}
String rawSnapshot = resource.getAttributes().remove(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR);
JsonNode snapshot = rawSnapshot == null ? null : readSnapshot(resource, rawSnapshot);
if (snapshot == null) {
return false;
}
String region = snapshot.path("region").asText();
String domainName = snapshot.path("domainName").asText();
Map<String, Object> configuration = new LinkedHashMap<>();
putIfPresent(configuration, "certificateArn", snapshot.path("certificateArn").asText(null));
putIfPresent(configuration, "certificateName", snapshot.path("certificateName").asText(null));
putIfPresent(configuration, "endpointType", snapshot.path("endpointType").asText(null));
putIfPresent(configuration, "securityPolicy", snapshot.path("securityPolicy").asText(null));
Map<String, Object> request = new LinkedHashMap<>();
request.put("domainName", domainName);
request.put("domainNameConfigurations", List.of(configuration));
CustomDomain restored = apiGatewayService.replaceV2DomainConfiguration(region, domainName, request);
Map<String, String> tags = new LinkedHashMap<>();
snapshot.path("tags").fields().forEachRemaining(tag -> tags.put(tag.getKey(), tag.getValue().asText()));
reconcileTags(restored, tags, region);
return true;
}
/** Drives the domain's tags to the template's: a dropped key is untagged, an unchanged set is left alone. */
private void reconcileTags(CustomDomain existing, Map<String, String> desired, String region) {
Map<String, String> current = existing.getTags() == null ? Map.of() : existing.getTags();
if (desired.equals(current)) {
return;
}
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
if (!stale.isEmpty()) {
apiGatewayService.untagDomainName(region, existing.getDomainName(), stale);
}
if (!desired.isEmpty()) {
apiGatewayService.tagDomainName(region, existing.getDomainName(), desired);
}
}
private CustomDomain findDomain(String domainName, String region) {
try {
return apiGatewayService.getDomainName(region, domainName);
} catch (AwsException e) {
if (!NOT_FOUND.equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Custom domain {0} from the previous execution is gone, creating it again", domainName);
return null;
}
}
private void deleteDomain(String domainName, String region) {
CfnDeletes.safeDelete("custom domain", domainName,
() -> apiGatewayService.deleteDomainName(region, domainName), NOT_FOUND);
}
// ──────────────────────────── ApiMapping ────────────────────────────
private void provisionApiMapping(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
String domainName = ctx.resolveOptional(props, "DomainName");
String apiId = ctx.resolveOptional(props, "ApiId");
String stage = ctx.resolveOptional(props, "Stage");
if (isBlank(domainName) || isBlank(apiId) || isBlank(stage)) {
throw new IllegalArgumentException(
"AWS::ApiGatewayV2::ApiMapping requires DomainName, ApiId and Stage");
}
String apiMappingKey = ctx.resolveOptional(props, "ApiMappingKey");
String priorDomainName = r.getAttributes().get(MAPPING_DOMAIN_NAME_ATTR);
StoredMapping existing = ctx.isUpdate() && domainName.equals(priorDomainName)
? findMapping(priorDomainName, ctx.priorPhysicalId(), ctx.region())
: null;
StoredMapping provisioned;
if (existing != null) {
// ApiId, Stage and ApiMappingKey update in place, and the mapping keeps its id. The
// snapshot comes first, so a later resource failing the update can put the mapping back.
r.getAttributes().put(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR,
mappingSnapshot(existing, domainName, ctx.region()));
provisioned = apiGatewayService.updateApiMapping(ctx.region(), domainName, existing.apiMappingId(),
apiMappingKey, apiId, stage);
} else {
r.getAttributes().remove(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR);
Set<String> excludedIds = Set.of();
if (ctx.isUpdate() && isBlank(priorDomainName)) {
// The stub arm's record from before this provisioner existed: nothing was created for
// it, so the cleanup and the rollback have no domain to delete it from.
rememberDisplacedDomain(r, ctx.priorPhysicalId(), "");
} else if (ctx.isUpdate() && !domainName.equals(priorDomainName)) {
// A new DomainName replaces the mapping. On AWS the replacement gets an id of its own;
// here it would derive the displaced mapping's id when the key is the same, and two
// mappings under one physical id cannot be told apart by the cleanup or the rollback.
excludedIds = Set.of(ctx.priorPhysicalId());
rememberDisplacedDomain(r, ctx.priorPhysicalId(), priorDomainName);
}
provisioned = apiGatewayService.createApiMapping(ctx.region(), domainName, apiMappingKey, apiId, stage,
excludedIds);
}
String apiMappingId = provisioned.apiMappingId();
r.setPhysicalId(apiMappingId);
r.getAttributes().put("ApiMappingId", apiMappingId);
r.getAttributes().put(MAPPING_DOMAIN_NAME_ATTR, domainName);
ReplacementCleanup.record(r, ctx, attributesBefore);
forgetDisplacedDomainsOnceNothingIsOwed(r);
}
private static String mappingSnapshot(StoredMapping existing, String domainName, String region) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("region", region);
snapshot.put("domainName", domainName);
snapshot.put("apiMappingId", existing.apiMappingId());
String key = ApiGatewayService.canonicalBasePath(existing.storedPath());
snapshot.put("apiMappingKey", "(none)".equals(key) ? null : key);
snapshot.put("apiId", existing.mapping().getRestApiId());
snapshot.put("stage", existing.mapping().getStage());
return snapshot.toString();
}
private boolean rollbackMappingUpdate(StackResource resource) {
// Rolling back a replacement deletes it through the domain it was created on, and one whose
// delete fails stays owed, so its domain is recorded before the attempt.
String replacement = resource.getPhysicalId();
String replacementDomain = resource.getAttributes().get(MAPPING_DOMAIN_NAME_ATTR);
boolean replacementAlreadyKnown = displacedDomains(resource).containsKey(replacement);
if (!replacementAlreadyKnown && !isBlank(replacementDomain)) {
rememberDisplacedDomain(resource, replacement, replacementDomain);
}
boolean rolledBack;
try {
rolledBack = ReplacementCleanup.rollback(resource, mappingDeleter(resource));
} finally {
// The prior mapping stands again even when deleting the replacement failed, so the
// resource names the prior mapping's domain from here on.
Map<String, String> domains = displacedDomains(resource);
if (!replacement.equals(resource.getPhysicalId()) && domains.containsKey(resource.getPhysicalId())) {
String priorDomain = domains.remove(resource.getPhysicalId());
if (isBlank(priorDomain)) {
resource.getAttributes().remove(MAPPING_DOMAIN_NAME_ATTR);
} else {
resource.getAttributes().put(MAPPING_DOMAIN_NAME_ATTR, priorDomain);
}
writeDisplacedDomains(resource, domains);
}
}
if (rolledBack) {
forgetDisplacedDomainsOnceNothingIsOwed(resource);
return true;
}
if (!replacementAlreadyKnown) {
Map<String, String> domains = displacedDomains(resource);
domains.remove(replacement);
writeDisplacedDomains(resource, domains);
}
String rawSnapshot = resource.getAttributes().remove(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR);
JsonNode snapshot = rawSnapshot == null ? null : readSnapshot(resource, rawSnapshot);
if (snapshot == null) {
return false;
}
apiGatewayService.updateApiMapping(snapshot.path("region").asText(), snapshot.path("domainName").asText(),
snapshot.path("apiMappingId").asText(), snapshot.path("apiMappingKey").asText(null),
snapshot.path("apiId").asText(), snapshot.path("stage").asText());
return true;
}
private StoredMapping findMapping(String domainName, String apiMappingId, String region) {
try {
return apiGatewayService.getApiMapping(region, domainName, apiMappingId);
} catch (AwsException e) {
if (!NOT_FOUND.equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("API mapping {0} on {1} from the previous execution is gone, creating it again",
apiMappingId, domainName);
return null;
}
}
/** Deletes a displaced or rolled-back mapping through the domain it was created on. */
private ReplacementCleanup.Deleter mappingDeleter(StackResource resource) {
return (type, apiMappingId, region) -> {
String domainName = displacedDomains(resource).getOrDefault(apiMappingId,
resource.getAttributes().get(MAPPING_DOMAIN_NAME_ATTR));
if (isBlank(domainName)) {
LOG.debugv("API mapping {0} has no domain, so nothing was created for it", apiMappingId);
return;
}
deleteMapping(domainName, apiMappingId, region);
};
}
/**
* The id-only delete, which Cloud Control reaches with the type's primary identifier,
* {@code <ApiMappingId>|<DomainName>}. A bare id names no domain to look in.
*/
private void deleteMappingByIdentifier(String identifier, String region) {
int separator = identifier == null ? -1 : identifier.indexOf(IDENTIFIER_SEPARATOR);
if (separator <= 0 || separator == identifier.length() - 1) {
throw new AwsException(NOT_FOUND, "Unable to find ApiMapping with ID " + identifier, 404);
}
deleteMapping(identifier.substring(separator + 1), identifier.substring(0, separator), region);
}
/** Tolerates a mapping already gone, including one removed together with its domain. */
private void deleteMapping(String domainName, String apiMappingId, String region) {
CfnDeletes.safeDelete("API mapping", apiMappingId,
() -> apiGatewayService.deleteApiMapping(region, domainName, apiMappingId), NOT_FOUND);
}
private static void rememberDisplacedDomain(StackResource resource, String apiMappingId, String domainName) {
Map<String, String> domains = displacedDomains(resource);
domains.put(apiMappingId, domainName);
writeDisplacedDomains(resource, domains);
}
private static void forgetDisplacedDomainsOnceNothingIsOwed(StackResource resource) {
if (!ReplacementCleanup.hasReplacement(resource)) {
resource.getAttributes().remove(MAPPING_DISPLACED_DOMAINS_ATTR);
}
}
private static Map<String, String> displacedDomains(StackResource resource) {
Map<String, String> domains = new LinkedHashMap<>();
String raw = resource.getAttributes().get(MAPPING_DISPLACED_DOMAINS_ATTR);
if (isBlank(raw)) {
return domains;
}
try {
MAPPER.readTree(raw).fields().forEachRemaining(e -> domains.put(e.getKey(), e.getValue().asText()));
} catch (JsonProcessingException e) {
LOG.warnv("Unreadable displaced API mapping domains on {0}, dropping them: {1}",
resource.getLogicalId(), e.getMessage());
}
return domains;
}
private static void writeDisplacedDomains(StackResource resource, Map<String, String> domains) {
if (domains.isEmpty()) {
resource.getAttributes().remove(MAPPING_DISPLACED_DOMAINS_ATTR);
return;
}
ObjectNode node = MAPPER.createObjectNode();
domains.forEach(node::put);
resource.getAttributes().put(MAPPING_DISPLACED_DOMAINS_ATTR, node.toString());
}
// ──────────────────────────── Shared ────────────────────────────
private static JsonNode readSnapshot(StackResource resource, String rawSnapshot) {
try {
return MAPPER.readTree(rawSnapshot);
} catch (JsonProcessingException e) {
LOG.errorv("Could not parse the update snapshot of {0}: {1}", resource.getLogicalId(), e.getMessage());
return null;
}
}
private static void putIfPresent(Map<String, Object> request, String key, String value) {
if (value != null) {
request.put(key, value);
}
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
private static String orEmpty(String value) {
return value == null ? "" : value;
}
}
@@ -134,6 +134,22 @@ public final class CfnRollback {
*/
public static final String INTEGRATION_CONNECTION_SNAPSHOT_ATTR = "__FlociIntegrationConnectionSnapshot";
/**
* Holds the certificate, security policy, endpoint type and tags an API Gateway v2 custom domain
* carried before an in-place update changed them, so a failed stack update can put them back.
* Written by {@code ApiGatewayV2DomainCfnProvisioner} before its first mutating call and spent
* by its {@code rollbackUpdate}.
*/
public static final String API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR = "__FlociApiGatewayV2DomainUpdateSnapshot";
/**
* Holds the key, API and stage an API Gateway v2 API mapping carried before an in-place update
* changed them, with the domain that addresses it, so a failed stack update can put them back.
* Written by {@code ApiGatewayV2DomainCfnProvisioner} before its update call and spent by its
* {@code rollbackUpdate}.
*/
public static final String API_MAPPING_UPDATE_SNAPSHOT_ATTR = "__FlociApiMappingUpdateSnapshot";
/**
* Holds the complete prior metric filter, identity, name mode and per-address mutation outcomes
* and ownership states.
@@ -47,12 +47,18 @@
"AWS::ApiGatewayV2::Api": [
"ProtocolType"
],
"AWS::ApiGatewayV2::ApiMapping": [
"DomainName"
],
"AWS::ApiGatewayV2::Authorizer": [
"ApiId"
],
"AWS::ApiGatewayV2::Deployment": [
"ApiId"
],
"AWS::ApiGatewayV2::DomainName": [
"DomainName"
],
"AWS::ApiGatewayV2::Integration": [
"ApiId"
],
@@ -0,0 +1,424 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The v2 custom domain and API mapping rules, over real services and in-memory stores: the id a
* mapping is given and keeps, the APIs it can point at, and the restrictions AWS documents for API
* mappings (a regional domain, the TLS 1.2 security policy for an HTTP API or a key with more than
* one level, no WebSocket API beside an HTTP or REST API, the characters and length of a key).
*/
class ApiGatewayV2ApiMappingServiceTest {
private static final String REGION = "us-east-1";
private static final String DOMAIN = "api.example.com";
private static final String OTHER_DOMAIN = "other.example.com";
private static final String CERTIFICATE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/abc";
private static final String EDGE_MESSAGE = "Only REGIONAL domain names can be managed through the API Gateway V2 "
+ "API. For EDGE domain names, please use the API Gateway V1 API. Also note that only REST APIs can be "
+ "attached to EDGE domain names.";
private static final String V2_EDGE_ENDPOINT_MESSAGE = "EDGE endpoint type is not supported for APIGatewayV2 "
+ "domainName";
private ApiGatewayService service;
private ApiGatewayV2Service v2Service;
@BeforeEach
void setUp() {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cloudfront().domainSuffix()).thenReturn("cloudfront.net");
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
v2Service = new ApiGatewayV2Service(storageFactory, config, regionResolver);
service = new ApiGatewayService(storageFactory, config, mock(TlsCertificateManager.class), regionResolver,
v2Service);
}
private void v2Domain(String name) {
service.createV2DomainName(REGION, Map.of("domainName", name,
"domainNameConfigurations", List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "REGIONAL"))));
}
/** A domain as the v1 API creates it, which can carry what the v2 API cannot. */
private void v1Domain(String name, String endpointType, String securityPolicy) {
Map<String, Object> request = new HashMap<>();
request.put("domainName", name);
request.put("regionalCertificateArn", CERTIFICATE_ARN);
request.put("certificateArn", CERTIFICATE_ARN);
request.put("endpointConfiguration", Map.of("types", List.of(endpointType)));
request.put("securityPolicy", securityPolicy);
service.createDomainName(REGION, request);
}
private String api(String protocolType, String stage) {
Map<String, Object> request = new HashMap<>();
request.put("name", protocolType.toLowerCase() + "-api");
request.put("protocolType", protocolType);
if ("WEBSOCKET".equals(protocolType)) {
request.put("routeSelectionExpression", "$request.body.action");
}
String apiId = v2Service.createApi(REGION, request).getApiId();
v2Service.createStage(REGION, apiId, Map.of("stageName", stage));
return apiId;
}
private String restApi(String stage) {
String apiId = service.createRestApi(REGION, Map.of("name", "rest-api")).getId();
service.createDeployment(REGION, apiId, Map.of("stageName", stage));
return apiId;
}
private static void assertBadRequest(String message, Runnable call) {
AwsException failure = assertThrows(AwsException.class, call::run);
assertEquals("BadRequestException", failure.getErrorCode());
assertEquals(400, failure.getHttpStatus());
if (message != null) {
assertEquals(message, failure.getMessage());
}
}
@Test
void aMappingKeepsItsIdWhenItsKeyChanges() {
v2Domain(DOMAIN);
String apiId = api("HTTP", "$default");
StoredMapping created = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default");
StoredMapping updated = service.updateApiMapping(REGION, DOMAIN, created.apiMappingId(), "v2", apiId, "$default");
assertEquals(created.apiMappingId(), updated.apiMappingId());
assertEquals("v2", updated.storedPath());
assertEquals("v2", service.getApiMapping(REGION, DOMAIN, created.apiMappingId()).storedPath());
assertEquals(1, service.getApiMappings(REGION, DOMAIN).size());
}
@Test
void aKeyAnotherMappingMovedOffGetsAnIdOfItsOwn() {
v2Domain(DOMAIN);
String apiId = api("HTTP", "$default");
String first = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default").apiMappingId();
service.updateApiMapping(REGION, DOMAIN, first, "v2", apiId, "$default");
String second = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default").apiMappingId();
assertNotEquals(first, second);
assertEquals("v2", service.getApiMapping(REGION, DOMAIN, first).storedPath());
assertEquals("v1", service.getApiMapping(REGION, DOMAIN, second).storedPath());
}
@Test
void anExcludedIdIsNotHandedOut() {
v2Domain(DOMAIN);
String apiId = api("HTTP", "$default");
String derived = ApiGatewayService.apiMappingId("v1");
String id = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default", Set.of(derived)).apiMappingId();
assertNotEquals(derived, id);
}
@Test
void aKeyChangeOntoATakenKeyConflicts() {
v2Domain(DOMAIN);
String apiId = api("HTTP", "$default");
String first = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default").apiMappingId();
service.createApiMapping(REGION, DOMAIN, "v2", apiId, "$default");
AwsException failure = assertThrows(AwsException.class,
() -> service.updateApiMapping(REGION, DOMAIN, first, "v2", apiId, "$default"));
assertEquals("ConflictException", failure.getErrorCode());
assertEquals("v1", service.getApiMapping(REGION, DOMAIN, first).storedPath());
}
@Test
void aRestApiCanBeMappedUnderAKeyWithSeveralLevels() {
v2Domain(DOMAIN);
String apiId = restApi("prod");
StoredMapping created = service.createApiMapping(REGION, DOMAIN, "orders/v1/items", apiId, "prod");
assertEquals("REST", created.mapping().getApiType());
assertEquals(apiId, service.resolveBasePathMapping(DOMAIN, "/orders/v1/items/123").getRestApiId());
}
@Test
void anApiOrStageThatDoesNotExistIsRefused() {
v2Domain(DOMAIN);
String httpApi = api("HTTP", "$default");
String restApi = restApi("prod");
assertBadRequest("Invalid API identifier specified: nope",
() -> service.createApiMapping(REGION, DOMAIN, "a", "nope", "$default"));
assertBadRequest("Invalid stage identifier specified",
() -> service.createApiMapping(REGION, DOMAIN, "b", httpApi, "missing"));
assertBadRequest("Invalid stage identifier specified",
() -> service.createApiMapping(REGION, DOMAIN, "c", restApi, "missing"));
}
@Test
void anEdgeDomainCannotBeManagedThroughTheV2Api() {
v1Domain(DOMAIN, "EDGE", "TLS_1_2");
String restApi = restApi("prod");
assertBadRequest(EDGE_MESSAGE, () -> service.createApiMapping(REGION, DOMAIN, "v1", restApi, "prod"));
assertBadRequest(EDGE_MESSAGE, () -> service.getApiMappings(REGION, DOMAIN));
assertBadRequest(V2_EDGE_ENDPOINT_MESSAGE, () -> service.createV2DomainName(REGION, Map.of("domainName",
OTHER_DOMAIN, "domainNameConfigurations", List.of(Map.of("endpointType", "EDGE")))));
}
/**
* Measured against API Gateway (eu-west-1, 2026-10-04): an HTTP API custom domain is regional.
* A create or update with an endpoint type of PRIVATE or one API Gateway does not know gives a
* REGIONAL domain; EDGE is refused.
*/
@Test
void aV2DomainIsRegionalWhateverOtherEndpointTypeItIsGiven() {
service.createV2DomainName(REGION, Map.of("domainName", DOMAIN, "domainNameConfigurations",
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "PRIVATE"))));
assertEquals("REGIONAL", service.getDomainName(REGION, DOMAIN).getEndpointConfigurationType());
service.replaceV2DomainConfiguration(REGION, DOMAIN, Map.of("domainNameConfigurations",
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "FOO"))));
assertEquals("REGIONAL", service.getDomainName(REGION, DOMAIN).getEndpointConfigurationType());
assertBadRequest(V2_EDGE_ENDPOINT_MESSAGE, () -> service.replaceV2DomainConfiguration(REGION, DOMAIN,
Map.of("domainNameConfigurations",
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "EDGE")))));
assertEquals("REGIONAL", service.getDomainName(REGION, DOMAIN).getEndpointConfigurationType());
}
/**
* UpdateDomainName through the v2 API is a v2 call like the others: refused on an
* edge-optimized domain, and refused for what Floci does not emulate even without a
* configuration to replace.
*/
@Test
void aV2UpdateRefusesAnEdgeDomainAndWhatIsNotEmulated() {
v1Domain(DOMAIN, "EDGE", "TLS_1_2");
assertBadRequest(EDGE_MESSAGE, () -> service.updateV2DomainName(REGION, DOMAIN, Map.of(
"domainNameConfigurations",
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "REGIONAL")))));
assertEquals("EDGE", service.getDomainName(REGION, DOMAIN).getEndpointConfigurationType());
v2Domain(OTHER_DOMAIN);
assertBadRequest("Mutual TLS authentication is not supported", () -> service.updateV2DomainName(REGION,
OTHER_DOMAIN, Map.of("mutualTlsAuthentication", Map.of("truststoreUri", "s3://bucket/key"))));
assertEquals(OTHER_DOMAIN, service.updateV2DomainName(REGION, OTHER_DOMAIN, Map.of()).getDomainName());
}
/** Measured against API Gateway (eu-west-1, 2026-10-04), its messages included. */
@Test
void anApiMappingKeyIsCheckedAsApiGatewayChecksIt() {
v2Domain(DOMAIN);
String httpApi = api("HTTP", "prod");
String endSlash = "API mapping key should not end with a '/'.";
String slashes = "API mapping key should not start with a '/' or have consecutive '/'s.";
String characters = "An API mapping key may contain only letters, numbers and one of $-_.+!*'(), characters.";
assertBadRequest(endSlash, () -> service.createApiMapping(REGION, DOMAIN, "/", httpApi, "prod"));
assertBadRequest(endSlash, () -> service.createApiMapping(REGION, DOMAIN, "a/", httpApi, "prod"));
assertBadRequest(slashes, () -> service.createApiMapping(REGION, DOMAIN, "/a", httpApi, "prod"));
assertBadRequest(slashes, () -> service.createApiMapping(REGION, DOMAIN, "a//b", httpApi, "prod"));
assertBadRequest(characters, () -> service.createApiMapping(REGION, DOMAIN, " a", httpApi, "prod"));
assertBadRequest(characters, () -> service.createApiMapping(REGION, DOMAIN, "a~b", httpApi, "prod"));
assertBadRequest("ApiMapping key length must be under 300 characters.",
() -> service.createApiMapping(REGION, DOMAIN, "a".repeat(301), httpApi, "prod"));
assertEquals("a,b$", service.createApiMapping(REGION, DOMAIN, "a,b$", httpApi, "prod").storedPath());
assertEquals("a".repeat(300),
service.createApiMapping(REGION, DOMAIN, "a".repeat(300), httpApi, "prod").storedPath());
// A key of whitespace only is the root on a create, and refused on an update.
assertEquals("(none)", ApiGatewayService.canonicalBasePath(
service.createApiMapping(REGION, DOMAIN, " ", httpApi, "prod").storedPath()));
String id = service.createApiMapping(REGION, DOMAIN, "v1", httpApi, "prod").apiMappingId();
assertBadRequest(slashes, () -> service.updateApiMapping(REGION, DOMAIN, id, " ", httpApi, "prod"));
assertBadRequest(endSlash, () -> service.updateApiMapping(REGION, DOMAIN, id, "/", httpApi, "prod"));
}
@Test
void anHttpApiNeedsTheTls12SecurityPolicy() {
v1Domain(DOMAIN, "REGIONAL", "TLS_1_0");
String httpApi = api("HTTP", "$default");
String restApi = restApi("prod");
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "http", httpApi, "$default"));
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "orders/v1", restApi, "prod"));
assertEquals("REST", service.createApiMapping(REGION, DOMAIN, "orders", restApi, "prod").mapping().getApiType());
}
@Test
void aDomainWithAnHttpApiMappingStaysOnTls12() {
v2Domain(DOMAIN);
String httpApi = api("HTTP", "$default");
service.createApiMapping(REGION, DOMAIN, null, httpApi, "$default");
assertBadRequest(null, () -> service.replaceV2DomainConfiguration(REGION, DOMAIN, Map.of("domainName", DOMAIN,
"domainNameConfigurations", List.of(Map.of("certificateArn", CERTIFICATE_ARN,
"endpointType", "REGIONAL", "securityPolicy", "TLS_1_0")))));
assertBadRequest(null, () -> service.updateDomainName(REGION, DOMAIN,
List.of(Map.of("op", "replace", "path", "/securityPolicy", "value", "TLS_1_0"))));
assertEquals("TLS_1_2", service.getDomainName(REGION, DOMAIN).getSecurityPolicy());
}
@Test
void aWebSocketApiDoesNotShareADomainWithAnHttpOrRestApi() {
v2Domain(DOMAIN);
v2Domain(OTHER_DOMAIN);
String webSocketApi = api("WEBSOCKET", "prod");
String httpApi = api("HTTP", "$default");
String restApi = restApi("prod");
service.createApiMapping(REGION, DOMAIN, "ws", webSocketApi, "prod");
service.createApiMapping(REGION, OTHER_DOMAIN, "http", httpApi, "$default");
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "http", httpApi, "$default"));
assertBadRequest(null, () -> service.createBasePathMapping(REGION, DOMAIN,
Map.of("basePath", "rest", "restApiId", restApi, "stage", "prod")));
assertBadRequest(null, () -> service.createApiMapping(REGION, OTHER_DOMAIN, "ws", webSocketApi, "prod"));
service.createApiMapping(REGION, DOMAIN, "ws2", webSocketApi, "prod");
}
@Test
void aKeyHoldsOnlyTheCharactersAwsAllowsUpTo300OfThem() {
v2Domain(DOMAIN);
String apiId = api("HTTP", "$default");
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "v1?x", apiId, "$default"));
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "a".repeat(301), apiId, "$default"));
service.createApiMapping(REGION, DOMAIN, "a".repeat(300), apiId, "$default");
service.createApiMapping(REGION, DOMAIN, "$-_.+!*'()/x", apiId, "$default");
}
@Test
void updatingAMappingOntoAnotherKindOfApiRoutesItAsThatKind() {
v2Domain(DOMAIN);
String httpApi = api("HTTP", "$default");
String restApi = restApi("prod");
String id = service.createApiMapping(REGION, DOMAIN, "v1", httpApi, "$default").apiMappingId();
StoredMapping updated = service.updateApiMapping(REGION, DOMAIN, id, "v1", restApi, "prod");
assertEquals("REST", updated.mapping().getApiType());
assertEquals(restApi, service.getApiMapping(REGION, DOMAIN, id).mapping().getRestApiId());
}
@Test
void replacingADomainConfigurationReplacesItAsAWhole() {
service.createV2DomainName(REGION, Map.of("domainName", DOMAIN, "domainNameConfigurations",
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "certificateName", "named",
"endpointType", "REGIONAL", "securityPolicy", "TLS_1_0"))));
CustomDomain replaced = service.replaceV2DomainConfiguration(REGION, DOMAIN, Map.of("domainName", DOMAIN,
"domainNameConfigurations", List.of(Map.of("certificateArn", CERTIFICATE_ARN))));
assertEquals(CERTIFICATE_ARN, replaced.getRegionalCertificateArn());
assertNull(replaced.getRegionalCertificateName(), "a field the configuration leaves out is cleared");
assertEquals("TLS_1_2", replaced.getSecurityPolicy(), "an omitted security policy takes the default");
assertEquals("REGIONAL", replaced.getEndpointConfigurationType());
}
@Test
void aV2DomainKeepsItsCertificateAsTheRegionalOne() {
service.createV2DomainName(REGION, Map.of("domainName", DOMAIN, "domainNameConfigurations",
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "certificateName", "named"))));
CustomDomain domain = service.getDomainName(REGION, DOMAIN);
assertEquals(CERTIFICATE_ARN, domain.getRegionalCertificateArn());
assertEquals("named", domain.getRegionalCertificateName());
assertNull(domain.getCertificateArn(), "the edge-optimized certificate is not the regional domain's");
assertNull(domain.getCertificateName());
assertEquals(CERTIFICATE_ARN, ApiGatewayService.v2CertificateArn(domain));
assertEquals("named", ApiGatewayService.v2CertificateName(domain));
}
@Test
void theV2ApiReportsTheCertificateOfTheDomainsEndpointType() {
Map<String, Object> regional = new HashMap<>();
regional.put("domainName", DOMAIN);
regional.put("regionalCertificateArn", CERTIFICATE_ARN);
regional.put("endpointConfiguration", Map.of("types", List.of("REGIONAL")));
service.createDomainName(REGION, regional);
Map<String, Object> edge = new HashMap<>();
edge.put("domainName", OTHER_DOMAIN);
edge.put("certificateArn", "arn:aws:acm:us-east-1:000000000000:certificate/edge");
edge.put("regionalCertificateArn", CERTIFICATE_ARN);
edge.put("endpointConfiguration", Map.of("types", List.of("EDGE")));
service.createDomainName(REGION, edge);
assertEquals(CERTIFICATE_ARN, ApiGatewayService.v2CertificateArn(service.getDomainName(REGION, DOMAIN)));
assertEquals("arn:aws:acm:us-east-1:000000000000:certificate/edge",
ApiGatewayService.v2CertificateArn(service.getDomainName(REGION, OTHER_DOMAIN)));
}
@Test
void aDomainTheV2ApiWroteToTheEdgeFieldsKeepsItsCertificateUntilItIsReplaced() {
// How a v2 create stored a regional domain's certificate before it went to the regional fields.
Map<String, Object> earlier = new HashMap<>();
earlier.put("domainName", DOMAIN);
earlier.put("certificateArn", CERTIFICATE_ARN);
earlier.put("certificateName", "earlier");
earlier.put("endpointConfiguration", Map.of("types", List.of("REGIONAL")));
service.createDomainName(REGION, earlier);
assertEquals(CERTIFICATE_ARN, ApiGatewayService.v2CertificateArn(service.getDomainName(REGION, DOMAIN)));
assertEquals("earlier", ApiGatewayService.v2CertificateName(service.getDomainName(REGION, DOMAIN)));
CustomDomain replaced = service.replaceV2DomainConfiguration(REGION, DOMAIN, Map.of("domainName", DOMAIN,
"domainNameConfigurations", List.of(Map.of("securityPolicy", "TLS_1_2"))));
assertNull(replaced.getCertificateArn(), "the configuration is replaced as a whole");
assertNull(replaced.getCertificateName());
assertNull(ApiGatewayService.v2CertificateArn(replaced));
}
@Test
void anUpdateBodyKeepsWhatItLeavesOut() {
v2Domain(DOMAIN);
String apiId = api("HTTP", "$default");
v2Service.createStage(REGION, apiId, Map.of("stageName", "beta"));
String id = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default").apiMappingId();
StoredMapping rekeyed = service.updateApiMapping(REGION, DOMAIN, id,
Map.of("apiId", apiId, "apiMappingKey", "v2"));
assertEquals("v2", rekeyed.storedPath());
assertEquals("$default", rekeyed.mapping().getStage(), "a stage the body leaves out is kept");
StoredMapping restaged = service.updateApiMapping(REGION, DOMAIN, id, Map.of("apiId", apiId, "stage", "beta"));
assertEquals("v2", restaged.storedPath(), "a key the body leaves out is kept");
assertEquals("beta", restaged.mapping().getStage());
Map<String, Object> toRoot = new HashMap<>();
toRoot.put("apiId", apiId);
toRoot.put("apiMappingKey", null);
assertEquals("(none)", service.updateApiMapping(REGION, DOMAIN, id, toRoot).storedPath(),
"a key the body names as null is the root");
assertEquals(id, service.getApiMapping(REGION, DOMAIN, id).apiMappingId());
}
}
@@ -13,6 +13,7 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* Custom domain names and API mappings over the HTTP API (v2) endpoints.
@@ -433,6 +434,243 @@ class ApiGatewayV2DomainNameIntegrationTest {
.statusCode(404);
}
@Test
@Order(11)
void aRestApiCanBeMappedUnderAKeyWithSeveralLevels() {
// AWS takes a REST API here too: the v2 API is how a REST API gets a multi-level mapping.
String restApiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"v2-mapped-rest-api\"}")
.when()
.post("/restapis")
.then()
.statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("{\"stageName\":\"prod\"}")
.when()
.post("/restapis/" + restApiId + "/deployments")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("""
{"domainName":"rest-multi-level.example.com","domainNameConfigurations":[
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc","endpointType":"REGIONAL"}]}
""")
.when()
.post("/v2/domainnames")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("{\"apiId\":\"%s\",\"stage\":\"prod\",\"apiMappingKey\":\"orders/v1/items\"}".formatted(restApiId))
.when()
.post("/v2/domainnames/rest-multi-level.example.com/apimappings")
.then()
.statusCode(201)
.body("apiId", is(restApiId))
.body("apiMappingKey", is("orders/v1/items"));
}
@Test
@Order(12)
void anEdgeDomainCannotBeManagedThroughTheV2Api() {
String message = "Only REGIONAL domain names can be managed through the API Gateway V2 API. For EDGE "
+ "domain names, please use the API Gateway V1 API. Also note that only REST APIs can be attached "
+ "to EDGE domain names.";
given()
.contentType(ContentType.JSON)
.body("""
{"domainName":"edge-only.example.com",
"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc",
"endpointConfiguration":{"types":["EDGE"]}}
""")
.when()
.post("/domainnames")
.then()
.statusCode(201);
given()
.when()
.get("/v2/domainnames/edge-only.example.com/apimappings")
.then()
.statusCode(400)
.body("message", is(message));
given()
.contentType(ContentType.JSON)
.body("""
{"domainName":"edge-v2.example.com","domainNameConfigurations":[{"endpointType":"EDGE"}]}
""")
.when()
.post("/v2/domainnames")
.then()
.statusCode(400)
// Measured against API Gateway (eu-west-1, 2026-10-04): a v2 create names the endpoint type.
.body("message", is("EDGE endpoint type is not supported for APIGatewayV2 domainName"));
}
@Test
@Order(13)
void anHttpApiIsMappedOnlyOntoADomainOnTls12() {
given()
.contentType(ContentType.JSON)
.body("""
{"domainName":"tls10.example.com",
"regionalCertificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc",
"endpointConfiguration":{"types":["REGIONAL"]},"securityPolicy":"TLS_1_0"}
""")
.when()
.post("/domainnames")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("{\"apiId\":\"%s\",\"stage\":\"$default\"}".formatted(apiId))
.when()
.post("/v2/domainnames/tls10.example.com/apimappings")
.then()
.statusCode(400)
.body(containsString("TLS 1.2"));
}
/** Measured against API Gateway (eu-west-1, 2026-10-04): what an update leaves out keeps its value. */
@Test
@Order(14)
void updateApiMappingChangesOnlyWhatItNames() {
String domain = "patch-mapping.example.com";
createRegionalDomain(domain);
given()
.contentType(ContentType.JSON)
.body("{\"stageName\":\"s2\"}")
.when()
.post("/v2/apis/" + apiId + "/stages")
.then()
.statusCode(201);
String id = given()
.contentType(ContentType.JSON)
.body("{\"apiId\":\"%s\",\"stage\":\"$default\",\"apiMappingKey\":\"patched\"}".formatted(apiId))
.when()
.post("/v2/domainnames/" + domain + "/apimappings")
.then()
.statusCode(201)
.extract().path("apiMappingId");
given()
.contentType(ContentType.JSON)
.body("{\"apiId\":\"%s\",\"stage\":\"s2\"}".formatted(apiId))
.when()
.patch("/v2/domainnames/" + domain + "/apimappings/" + id)
.then()
.statusCode(200)
.body("apiMappingId", is(id))
.body("apiMappingKey", is("patched"))
.body("stage", is("s2"));
given()
.contentType(ContentType.JSON)
.body("{\"apiId\":\"%s\",\"apiMappingKey\":\"patched-again\"}".formatted(apiId))
.when()
.patch("/v2/domainnames/" + domain + "/apimappings/" + id)
.then()
.statusCode(200)
.body("apiMappingId", is(id))
.body("apiMappingKey", is("patched-again"))
.body("stage", is("s2"));
given()
.contentType(ContentType.JSON)
.body("{\"apiId\":\"%s\"}".formatted(apiId))
.when()
.patch("/v2/domainnames/" + domain + "/apimappings/zzzzzz")
.then()
.statusCode(404);
}
/** Measured against API Gateway (eu-west-1, 2026-10-04): an HTTP API domain stays regional. */
@Test
@Order(14)
void updateDomainNameKeepsTheDomainRegional() {
String domain = "patch-domain.example.com";
createRegionalDomain(domain);
given()
.contentType(ContentType.JSON)
.body("""
{"domainNameConfigurations":[
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/def","endpointType":"PRIVATE"}]}
""")
.when()
.patch("/v2/domainnames/" + domain)
.then()
.statusCode(200)
.body("domainNameConfigurations[0].endpointType", is("REGIONAL"))
.body("domainNameConfigurations[0].certificateArn", containsString("certificate/def"));
given()
.contentType(ContentType.JSON)
.body("""
{"domainNameConfigurations":[
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/def","endpointType":"EDGE"}]}
""")
.when()
.patch("/v2/domainnames/" + domain)
.then()
.statusCode(400)
.body("message", is("EDGE endpoint type is not supported for APIGatewayV2 domainName"));
}
/** A domain is one resource: a regional one's certificate is the v1 API's regional certificate. */
@Test
@Order(15)
void aRegionalDomainsCertificateIsTheSameThroughBothApis() {
String v2Created = "cert-v2.example.com";
createRegionalDomain(v2Created);
given()
.when()
.get("/domainnames/" + v2Created)
.then()
.statusCode(200)
.body("regionalCertificateArn", containsString("certificate/abc"))
.body("certificateArn", nullValue());
String v1Created = "cert-v1.example.com";
given()
.contentType(ContentType.JSON)
.body("""
{"domainName":"%s",
"regionalCertificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/regional",
"regionalCertificateName":"regional-name",
"endpointConfiguration":{"types":["REGIONAL"]}}
""".formatted(v1Created))
.when()
.post("/domainnames")
.then()
.statusCode(201);
given()
.when()
.get("/v2/domainnames/" + v1Created)
.then()
.statusCode(200)
.body("domainNameConfigurations[0].certificateArn", containsString("certificate/regional"))
.body("domainNameConfigurations[0].certificateName", is("regional-name"));
}
private static void createRegionalDomain(String domain) {
given()
.contentType(ContentType.JSON)
.body("""
{"domainName":"%s","domainNameConfigurations":[
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc","endpointType":"REGIONAL"}]}
""".formatted(domain))
.when()
.post("/v2/domainnames")
.then()
.statusCode(201);
}
private static org.hamcrest.Matcher<Iterable<? super String>> hasItemEqualTo(String value) {
return org.hamcrest.Matchers.hasItem(equalTo(value));
}
@@ -20,9 +20,9 @@ class ApiMappingIdTest {
@Test
void rootLikeKeysThatWerePersistedSeparatelyKeepSeparateIds() {
String canonical = ApiGatewayController.apiMappingId("(none)");
String slash = ApiGatewayController.apiMappingId("/");
String empty = ApiGatewayController.apiMappingId("");
String canonical = ApiGatewayService.apiMappingId("(none)");
String slash = ApiGatewayService.apiMappingId("/");
String empty = ApiGatewayService.apiMappingId("");
assertNotEquals(canonical, slash);
assertNotEquals(canonical, empty);
@@ -32,17 +32,17 @@ class ApiMappingIdTest {
@Test
void everyIdIsNonEmptyAndStable() {
// A record stored under an empty key must still produce an id a caller can put in a URL.
assertFalse(ApiGatewayController.apiMappingId("").isEmpty());
assertFalse(ApiGatewayController.apiMappingId(null).isEmpty());
assertFalse(ApiGatewayService.apiMappingId("").isEmpty());
assertFalse(ApiGatewayService.apiMappingId(null).isEmpty());
assertEquals(ApiGatewayController.apiMappingId("orders"),
ApiGatewayController.apiMappingId("orders"));
assertEquals(ApiGatewayService.apiMappingId("orders"),
ApiGatewayService.apiMappingId("orders"));
}
@Test
void distinctKeysSharingAJavaHashKeepDistinctIds() {
assertEquals("Aa".hashCode(), "BB".hashCode());
assertNotEquals(ApiGatewayController.apiMappingId("Aa"),
ApiGatewayController.apiMappingId("BB"));
assertNotEquals(ApiGatewayService.apiMappingId("Aa"),
ApiGatewayService.apiMappingId("BB"));
}
}
@@ -52,8 +52,8 @@ class LegacyBasePathMappingIntegrationTest {
void eachRecordKeepsItsOwnIdAndDeletesItself() {
seedLegacyState();
String canonicalId = ApiGatewayController.apiMappingId("(none)");
String legacyId = ApiGatewayController.apiMappingId("");
String canonicalId = ApiGatewayService.apiMappingId("(none)");
String legacyId = ApiGatewayService.apiMappingId("");
assertNotEquals(canonicalId, legacyId);
given()
@@ -86,6 +86,69 @@ class CloudControlServiceTest {
Map.of("VpcId", "vpc-account-a"));
}
/**
* Cloud Control names an AWS::ApiGatewayV2::ApiMapping by the type's primary identifier,
* {@code <ApiMappingId>|<DomainName>}, where CloudFormation's Ref is the bare ApiMappingId.
*/
@Test
void anApiMappingIsIdentifiedByItsIdAndItsDomain() throws Exception {
CfnResourceDispatcher provisioner = mock(CfnResourceDispatcher.class);
StackResource resource = new StackResource();
resource.setPhysicalId("abc123");
resource.setAttributes(Map.of("ApiMappingId", "abc123"));
when(provisioner.provisionStandalone(eq("AWS::ApiGatewayV2::ApiMapping"),
any(), eq("us-east-1"), eq("111111111111"))).thenReturn(resource);
CloudControlService service = new CloudControlService(
mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class), provisioner,
new ObjectMapper());
String identifier = "abc123|api.example.com";
CloudControlService.ProgressEvent pending = service.createResource("us-east-1", "111111111111",
"AWS::ApiGatewayV2::ApiMapping",
"{\"DomainName\":\"api.example.com\",\"ApiId\":\"a1b2c3\",\"Stage\":\"$default\"}");
awaitSuccess(service, "111111111111", pending.requestToken());
assertEquals(identifier, service.requestStatus("111111111111", pending.requestToken()).identifier());
String model = service.getResource("us-east-1", "111111111111",
"AWS::ApiGatewayV2::ApiMapping", identifier).properties();
assertEquals("abc123", new ObjectMapper().readTree(model).path("ApiMappingId").asText());
assertEquals("SUCCESS", service.deleteResource("us-east-1", "111111111111",
"AWS::ApiGatewayV2::ApiMapping", identifier).operationStatus());
verify(provisioner).deleteStandalone("AWS::ApiGatewayV2::ApiMapping", identifier, "us-east-1",
Map.of("ApiMappingId", "abc123"));
assertThrows(AwsException.class, () -> service.getResource("us-east-1", "111111111111",
"AWS::ApiGatewayV2::ApiMapping", identifier));
}
/**
* A create that finished just before a restart is recorded while its request still reads
* IN_PROGRESS; recovery reports it done under the whole identifier, a compound one included.
*/
@Test
void aRecoveredCreateKeepsItsCompoundIdentifier() {
AccountAwareStorageBackend<CloudControlService.PersistedRequest> requests =
AccountAwareStorageBackend.inMemory("000000000000");
AccountAwareStorageBackend<CloudControlService.PersistedCreatedResource> created =
AccountAwareStorageBackend.inMemory("000000000000");
String type = "AWS::ApiGatewayV2::ApiMapping";
String identifier = "abc123|api.example.com";
requests.putForAccount("111111111111", "token-1", new CloudControlService.PersistedRequest(
new CloudControlService.ProgressEvent(type, null, "token-1", "CREATE", "IN_PROGRESS",
null, null, "111111111111"),
"us-east-1", "{\"DomainName\":\"api.example.com\"}", 1L));
created.putForAccount("111111111111", "us-east-1|" + type + "|" + identifier,
new CloudControlService.PersistedCreatedResource("token-1", "111111111111", "us-east-1", type,
identifier, Map.of("ApiMappingId", "abc123"), "{\"ApiMappingId\":\"abc123\"}"));
CloudControlService restarted = new CloudControlService(
mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class),
mock(CfnResourceDispatcher.class), new ObjectMapper(), requests, created);
CloudControlService.ProgressEvent recovered = restarted.requestStatus("111111111111", "token-1");
assertEquals("SUCCESS", recovered.operationStatus());
assertEquals(identifier, recovered.identifier());
}
@Test
void restoresAccountOwnersAndRequestStateFromMetadataStores() throws Exception {
CfnResourceDispatcher provisioner = mock(CfnResourceDispatcher.class);
@@ -0,0 +1,568 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsAction;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Provisions {@code AWS::ApiGatewayV2::DomainName} and {@code AWS::ApiGatewayV2::ApiMapping} through
* CloudFormation, with stubbing of unsupported types turned off so a type nothing provisions fails
* the stack instead of reporting CREATE_COMPLETE. Asserts that {@code Ref} and every
* {@code Fn::GetAtt} attribute are what the v2 API reports, that a request sent to the custom
* domain reaches the integration, and that updates behave as on AWS: the domain's configuration and
* the mapping's key, API and stage change in place with the mapping keeping its id, a new domain
* name replaces what it names with the displaced domain deleted in the cleanup phase, kept under
* {@code UpdateReplacePolicy: Retain} and put back when a later resource fails the update.
*
* <p>Two more stacks are what {@code aws-cdk-lib} 2.272.0 synthesizes, checked in verbatim with the
* app that produced them under {@code cloudformation/apigatewayv2-domain/}: an {@code HttpApi} with a
* {@code defaultDomainMapping}, a keyed mapping and a Route 53 alias, and a REST API on a custom
* domain under a key with several levels, which CDK maps with {@code AWS::ApiGatewayV2::ApiMapping}.
*/
@QuarkusTest
@TestProfile(CloudFormationUnsupportedResourceTypeStrictIntegrationTest.StrictProfile.class)
class ApiGatewayV2DomainCfnIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261002/us-east-1/cloudformation/aws4_request";
private static final String ROUTE53_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261002/us-east-1/route53/aws4_request";
private static final String ZONE = "apigwv2-domain-cfn-it.example.com";
private static final String CDK_DOMAIN = "cdk." + ZONE;
private static final String CDK_REST_DOMAIN = "rest.apigwv2-rest-cfn-it.example.com";
private static final String BACKEND_BODY = "reached the integration";
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* The domain, mapping key, mapped stage, certificate name and tag value are parameters, so one
* template drives the create, the in-place update and the replacement. {@code Break} adds a
* mapping onto a stage that does not exist after everything else, which fails the stack there.
*/
private static final String TEMPLATE = """
{
"Parameters": {
"Domain": {"Type": "String"},
"MappingKey": {"Type": "String"},
"MappingStage": {"Type": "String"},
"CertificateName": {"Type": "String"},
"TagValue": {"Type": "String"},
"BackendUrl": {"Type": "String"},
"Break": {"Type": "String", "Default": "no"}
},
"Conditions": {"Breaks": {"Fn::Equals": [{"Ref": "Break"}, "yes"]}},
"Resources": {
"Cert": {
"Type": "AWS::CertificateManager::Certificate",
"Properties": {"DomainName": "*.apigwv2-domain-cfn-it.example.com", "ValidationMethod": "DNS"}
},
"Api": {
"Type": "AWS::ApiGatewayV2::Api",
"Properties": {"Name": "apigwv2-domain-cfn-it", "ProtocolType": "HTTP"}
},
"Backend": {
"Type": "AWS::ApiGatewayV2::Integration",
"Properties": {
"ApiId": {"Ref": "Api"},
"IntegrationType": "HTTP_PROXY",
"IntegrationUri": {"Ref": "BackendUrl"},
"PayloadFormatVersion": "1.0"
}
},
"HelloRoute": {
"Type": "AWS::ApiGatewayV2::Route",
"Properties": {
"ApiId": {"Ref": "Api"},
"RouteKey": "GET /hello",
"Target": {"Fn::Join": ["/", ["integrations", {"Ref": "Backend"}]]}
}
},
"DefaultStage": {
"Type": "AWS::ApiGatewayV2::Stage",
"Properties": {"ApiId": {"Ref": "Api"}, "StageName": "$default", "AutoDeploy": true}
},
"ProdStage": {
"Type": "AWS::ApiGatewayV2::Stage",
"Properties": {"ApiId": {"Ref": "Api"}, "StageName": "prod", "AutoDeploy": true}
},
"ApiDomain": {
"Type": "AWS::ApiGatewayV2::DomainName",
"Properties": {
"DomainName": {"Ref": "Domain"},
"DomainNameConfigurations": [{
"CertificateArn": {"Ref": "Cert"},
"CertificateName": {"Ref": "CertificateName"},
"EndpointType": "REGIONAL",
"SecurityPolicy": "TLS_1_2"
}],
"Tags": {"stack": {"Ref": "TagValue"}}
}
},
"Mapping": {
"Type": "AWS::ApiGatewayV2::ApiMapping",
"DependsOn": ["DefaultStage", "ProdStage"],
"Properties": {
"DomainName": {"Ref": "ApiDomain"},
"ApiId": {"Ref": "Api"},
"Stage": {"Ref": "MappingStage"},
"ApiMappingKey": {"Ref": "MappingKey"}
}
},
"Breaker": {
"Type": "AWS::ApiGatewayV2::ApiMapping",
"Condition": "Breaks",
"DependsOn": ["Mapping"],
"Properties": {
"DomainName": {"Ref": "ApiDomain"},
"ApiId": {"Ref": "Api"},
"Stage": "no-such-stage",
"ApiMappingKey": "broken"
}
}
},
"Outputs": {
"CertArn": {"Value": {"Ref": "Cert"}},
"ApiId": {"Value": {"Ref": "Api"}},
"DomainRef": {"Value": {"Ref": "ApiDomain"}},
"DomainNameArn": {"Value": {"Fn::GetAtt": ["ApiDomain", "DomainNameArn"]}},
"RegionalDomainName": {"Value": {"Fn::GetAtt": ["ApiDomain", "RegionalDomainName"]}},
"RegionalHostedZoneId": {"Value": {"Fn::GetAtt": ["ApiDomain", "RegionalHostedZoneId"]}},
"MappingRef": {"Value": {"Ref": "Mapping"}},
"MappingId": {"Value": {"Fn::GetAtt": ["Mapping", "ApiMappingId"]}}
}
}
""";
private static HttpServer backend;
private static final AtomicInteger backendHits = new AtomicInteger();
private static String backendUrl;
@BeforeAll
static void startBackend() throws Exception {
RestAssuredJsonUtils.configureAwsContentTypes();
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backend.createContext("/", exchange -> {
backendHits.incrementAndGet();
byte[] body = BACKEND_BODY.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
backend.start();
backendUrl = "http://127.0.0.1:" + backend.getAddress().getPort();
}
@AfterAll
static void stopBackend() {
if (backend != null) {
backend.stop(0);
}
}
@Test
void domainAndMappingExposeRealValuesRouteRequestsUpdateInPlaceReplaceAndDelete() {
String stack = "apigwv2-domain-lifecycle";
String domain = "api.lifecycle." + ZONE;
String renamed = "gateway.lifecycle." + ZONE;
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
String stacks = describeStacks(stack, "CREATE_COMPLETE");
String apiId = outputValue(stacks, "ApiId");
String certificateArn = outputValue(stacks, "CertArn");
assertTrue(certificateArn.startsWith("arn:aws:acm:us-east-1:"), certificateArn);
assertEquals(domain, outputValue(stacks, "DomainRef"));
assertEquals("arn:aws:apigateway:us-east-1::/domainnames/" + domain, outputValue(stacks, "DomainNameArn"));
ValidatableResponse created = getDomain(domain).statusCode(200)
.body("domainNameArn", equalTo(outputValue(stacks, "DomainNameArn")))
.body("domainNameConfigurations[0].certificateArn", equalTo(certificateArn))
.body("domainNameConfigurations[0].certificateName", equalTo("first"))
.body("domainNameConfigurations[0].endpointType", equalTo("REGIONAL"))
.body("domainNameConfigurations[0].securityPolicy", equalTo("TLS_1_2"))
.body("tags.stack", equalTo("created"));
String regionalDomainName = created.extract().path("domainNameConfigurations[0].apiGatewayDomainName");
assertEquals(regionalDomainName, outputValue(stacks, "RegionalDomainName"));
assertEquals(created.extract().<String>path("domainNameConfigurations[0].hostedZoneId"),
outputValue(stacks, "RegionalHostedZoneId"));
String mappingId = outputValue(stacks, "MappingRef");
assertEquals(mappingId, outputValue(stacks, "MappingId"), "Ref and GetAtt ApiMappingId are the same id");
getMappings(domain).statusCode(200).body("items.apiMappingId", hasItem(mappingId));
getMapping(domain, mappingId).statusCode(200)
.body("apiId", equalTo(apiId))
.body("stage", equalTo("$default"))
.body("apiMappingKey", equalTo("v1"));
invokeThroughDomain(domain, "/v1/hello");
invokeThroughDomain(regionalDomainName, "/v1/hello");
// The domain's configuration and tags and the mapping's key and stage all change in place,
// as on AWS: the mapping keeps its id, and the domain the regional name a DNS alias points at.
cloudFormation(stack, "UpdateStack", TEMPLATE, parameters(domain, "v2", "prod", "second", "updated"));
stacks = describeStacks(stack, "UPDATE_COMPLETE");
assertEquals(domain, outputValue(stacks, "DomainRef"));
assertEquals(regionalDomainName, outputValue(stacks, "RegionalDomainName"));
assertEquals(mappingId, outputValue(stacks, "MappingRef"));
assertEquals(mappingId, outputValue(stacks, "MappingId"));
getDomain(domain).statusCode(200)
.body("domainNameConfigurations[0].apiGatewayDomainName", equalTo(regionalDomainName))
.body("domainNameConfigurations[0].certificateArn", equalTo(certificateArn))
.body("domainNameConfigurations[0].certificateName", equalTo("second"))
.body("tags.stack", equalTo("updated"));
getMapping(domain, mappingId).statusCode(200)
.body("apiMappingKey", equalTo("v2"))
.body("stage", equalTo("prod"));
getMappings(domain).statusCode(200).body("items.size()", equalTo(1));
invokeThroughDomain(domain, "/v2/hello");
assertNotRouted(domain, "/v1/hello");
// DomainName is createOnly on both types: the new domain and its mapping are created, and the
// displaced ones are deleted once the update has committed.
cloudFormation(stack, "UpdateStack", TEMPLATE, parameters(renamed, "v2", "prod", "second", "updated"));
stacks = describeStacks(stack, "UPDATE_COMPLETE");
assertEquals(renamed, outputValue(stacks, "DomainRef"));
assertEquals("arn:aws:apigateway:us-east-1::/domainnames/" + renamed, outputValue(stacks, "DomainNameArn"));
assertEquals(certificateArn, outputValue(stacks, "CertArn"), "the wildcard certificate is kept");
String renamedMappingId = outputValue(stacks, "MappingRef");
assertNotEquals(mappingId, renamedMappingId, "a replaced mapping gets an id of its own");
getDomain(domain).statusCode(404);
getDomain(renamed).statusCode(200)
.body("domainNameConfigurations[0].certificateArn", equalTo(certificateArn))
.body("domainNameConfigurations[0].certificateName", equalTo("second"))
.body("tags.stack", equalTo("updated"));
getMapping(renamed, renamedMappingId).statusCode(200)
.body("apiId", equalTo(apiId))
.body("stage", equalTo("prod"))
.body("apiMappingKey", equalTo("v2"));
invokeThroughDomain(renamed, "/v2/hello");
String events = stackEvents(stack);
assertTrue(events.contains("<ResourceStatus>UPDATE_COMPLETE_CLEANUP_IN_PROGRESS</ResourceStatus>"), events);
assertTrue(hasEvent(events, "ApiDomain", domain, "DELETE_COMPLETE"), "the displaced domain is deleted in the cleanup");
assertTrue(hasEvent(events, "Mapping", mappingId, "DELETE_COMPLETE"), "the displaced mapping is deleted in the cleanup");
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
getDomain(renamed).statusCode(404);
given().when().get("/v2/apis/" + apiId).then().statusCode(404);
awsAction("CertificateManager", "DescribeCertificate", "{\"CertificateArn\": \"" + certificateArn + "\"}")
.then().statusCode(404);
}
@Test
void aRenameALaterResourceFailsIsRolledBackToTheOriginalDomainAndMapping() {
String stack = "apigwv2-domain-rename-rollback";
String domain = "api.rename-rollback." + ZONE;
String renamed = "gateway.rename-rollback." + ZONE;
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
String mappingId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "MappingRef");
Map<String, String> breaking = parameters(renamed, "v1", "$default", "first", "created");
breaking.put("Break", "yes");
cloudFormation(stack, "UpdateStack", TEMPLATE, breaking);
String stacks = describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(domain, outputValue(stacks, "DomainRef"));
assertEquals(mappingId, outputValue(stacks, "MappingRef"));
getDomain(renamed).statusCode(404);
getDomain(domain).statusCode(200);
getMapping(domain, mappingId).statusCode(200).body("apiMappingKey", equalTo("v1"));
invokeThroughDomain(domain, "/v1/hello");
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
getDomain(domain).statusCode(404);
}
@Test
void anInPlaceUpdateALaterResourceFailsIsPutBack() {
String stack = "apigwv2-domain-in-place-rollback";
String domain = "api.in-place-rollback." + ZONE;
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
String mappingId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "MappingRef");
Map<String, String> breaking = parameters(domain, "v2", "prod", "second", "updated");
breaking.put("Break", "yes");
cloudFormation(stack, "UpdateStack", TEMPLATE, breaking);
describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
getDomain(domain).statusCode(200)
.body("domainNameConfigurations[0].certificateName", equalTo("first"))
.body("tags.stack", equalTo("created"));
getMapping(domain, mappingId).statusCode(200)
.body("apiMappingKey", equalTo("v1"))
.body("stage", equalTo("$default"));
getMappings(domain).statusCode(200).body("items.size()", equalTo(1));
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
}
@Test
void retainKeepsTheDomainARenameDisplaced() {
String stack = "apigwv2-domain-retain";
String domain = "api.retain." + ZONE;
String renamed = "gateway.retain." + ZONE;
String template = TEMPLATE.replace("\"Type\": \"AWS::ApiGatewayV2::DomainName\",",
"\"Type\": \"AWS::ApiGatewayV2::DomainName\", \"UpdateReplacePolicy\": \"Retain\",");
cloudFormation(stack, "CreateStack", template, parameters(domain, "v1", "$default", "first", "created"));
describeStacks(stack, "CREATE_COMPLETE");
cloudFormation(stack, "UpdateStack", template, parameters(renamed, "v1", "$default", "first", "created"));
describeStacks(stack, "UPDATE_COMPLETE");
getDomain(domain).statusCode(200);
getMappings(domain).statusCode(200).body("items.size()", equalTo(0));
getDomain(renamed).statusCode(200);
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
getDomain(renamed).statusCode(404);
getDomain(domain).statusCode(200);
given().when().delete("/v2/domainnames/" + domain).then().statusCode(204);
}
@Test
void aCreateALaterResourceFailsRemovesTheDomainAndMapping() {
String stack = "apigwv2-domain-create-rollback";
String domain = "api.create-rollback." + ZONE;
Map<String, String> breaking = parameters(domain, "v1", "$default", "first", "created");
breaking.put("Break", "yes");
cloudFormation(stack, "CreateStack", TEMPLATE, breaking);
describeStacks(stack, "ROLLBACK_COMPLETE");
getDomain(domain).statusCode(404);
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
}
@Test
void aMappingDroppedFromTheTemplateIsDeleted() {
String stack = "apigwv2-domain-drop-mapping";
String domain = "api.drop-mapping." + ZONE;
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
describeStacks(stack, "CREATE_COMPLETE");
cloudFormation(stack, "UpdateStack", withoutMapping(), parameters(domain, "v1", "$default", "first", "created"));
describeStacks(stack, "UPDATE_COMPLETE");
getDomain(domain).statusCode(200);
getMappings(domain).statusCode(200).body("items.size()", equalTo(0));
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
}
@Test
void aStackWhoseDomainWasDeletedOutsideItStillDeletes() {
String stack = "apigwv2-domain-gone";
String domain = "api.gone." + ZONE;
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
describeStacks(stack, "CREATE_COMPLETE");
given().when().delete("/v2/domainnames/" + domain).then().statusCode(204);
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
}
@Test
void cdkHttpApiWithADefaultDomainMappingAKeyedMappingAndAnAliasRecord() {
String stack = "apigwv2-domain-cdk-http";
cloudFormation(stack, "CreateStack", template("http-api-domain.template.json"), Map.of("BackendUrl", backendUrl));
String stacks = describeStacks(stack, "CREATE_COMPLETE");
String apiId = outputValue(stacks, "ApiId");
String regionalDomainName = outputValue(stacks, "RegionalDomainName");
getDomain(CDK_DOMAIN).statusCode(200)
.body("domainNameConfigurations[0].apiGatewayDomainName", equalTo(regionalDomainName))
.body("domainNameConfigurations[0].hostedZoneId", equalTo(outputValue(stacks, "RegionalHostedZoneId")));
getMappings(CDK_DOMAIN).statusCode(200)
.body("items.size()", equalTo(2))
.body("items.find { it.apiMappingKey == '' }.stage", equalTo("$default"))
.body("items.find { it.apiMappingKey == '' }.apiId", equalTo(apiId))
.body("items.find { it.apiMappingKey == 'prod' }.stage", equalTo("prod"));
// The alias carries the domain's real regional name and zone, not the literal attribute
// names an unset Fn::GetAtt would leave there.
given().header("Authorization", ROUTE53_AUTH)
.when().get("/2013-04-01/hostedzone/" + outputValue(stacks, "ZoneId") + "/rrset")
.then().statusCode(200)
.body(containsString("<DNSName>" + regionalDomainName))
.body(containsString("<HostedZoneId>" + outputValue(stacks, "RegionalHostedZoneId") + "</HostedZoneId>"));
invokeThroughDomain(CDK_DOMAIN, "/anything");
invokeThroughDomain(CDK_DOMAIN, "/prod/anything");
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
getDomain(CDK_DOMAIN).statusCode(404);
given().when().get("/v2/apis/" + apiId).then().statusCode(404);
}
@Test
void cdkRestApiOnACustomDomainUnderAKeyWithSeveralLevels() {
String stack = "apigwv2-domain-cdk-rest";
cloudFormation(stack, "CreateStack", template("rest-api-multi-level-domain.template.json"),
Map.of("BackendUrl", backendUrl));
String restApiId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "RestApiId");
getMappings(CDK_REST_DOMAIN).statusCode(200)
.body("items.size()", equalTo(1))
.body("items[0].apiId", equalTo(restApiId))
.body("items[0].stage", equalTo("prod"))
.body("items[0].apiMappingKey", equalTo("orders/v1"));
invokeThroughDomain(CDK_REST_DOMAIN, "/orders/v1/items");
cloudFormation(stack, "DeleteStack", null, Map.of());
CfnStackWaits.awaitStackDeleted(stack);
getDomain(CDK_REST_DOMAIN).statusCode(404);
}
private static Map<String, String> parameters(String domain, String mappingKey, String mappingStage,
String certificateName, String tagValue) {
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("Domain", domain);
parameters.put("MappingKey", mappingKey);
parameters.put("MappingStage", mappingStage);
parameters.put("CertificateName", certificateName);
parameters.put("TagValue", tagValue);
parameters.put("BackendUrl", backendUrl);
return parameters;
}
/** The lifecycle template with the mappings and every output naming them taken out. */
private static String withoutMapping() {
try {
ObjectNode template = (ObjectNode) MAPPER.readTree(TEMPLATE);
((ObjectNode) template.get("Resources")).remove("Mapping");
((ObjectNode) template.get("Resources")).remove("Breaker");
((ObjectNode) template.get("Outputs")).remove("MappingRef");
((ObjectNode) template.get("Outputs")).remove("MappingId");
return template.toString();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static String template(String name) {
try (InputStream in = ApiGatewayV2DomainCfnIntegrationTest.class.getResourceAsStream(
"/cloudformation/apigatewayv2-domain/" + name)) {
if (in == null) {
throw new IllegalStateException("Missing test template " + name);
}
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static void cloudFormation(String stack, String action, String templateBody,
Map<String, String> parameters) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (templateBody != null) {
request.formParam("TemplateBody", templateBody);
}
int index = 1;
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
index++;
}
request.when().post("/").then().statusCode(200);
}
/** Waits for the create or update to settle, then hands back the DescribeStacks body. */
private static String describeStacks(String stack, String expectedStatus) {
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, CFN_AUTH);
assertEquals(expectedStatus, state.status(), state.reason());
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.extract().asString();
}
private static String stackEvents(String stack) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.extract().asString();
}
/** Whether one event names this resource, physical id and status together. */
private static boolean hasEvent(String events, String logicalId, String physicalId, String status) {
return Arrays.stream(events.split("<member>"))
.anyMatch(event -> event.contains("<LogicalResourceId>" + logicalId + "</LogicalResourceId>")
&& event.contains("<PhysicalResourceId>" + physicalId + "</PhysicalResourceId>")
&& event.contains("<ResourceStatus>" + status + "</ResourceStatus>"));
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
private static ValidatableResponse getDomain(String domain) {
return given().when().get("/v2/domainnames/" + domain).then();
}
private static ValidatableResponse getMappings(String domain) {
return given().when().get("/v2/domainnames/" + domain + "/apimappings").then();
}
private static ValidatableResponse getMapping(String domain, String apiMappingId) {
return given().when().get("/v2/domainnames/" + domain + "/apimappings/" + apiMappingId).then();
}
/** The custom domain filter routes on the Host header, the way a DNS alias would deliver the request. */
private static void invokeThroughDomain(String host, String path) {
int before = backendHits.get();
given().header("Host", host).when().get(path).then()
.statusCode(200)
.body(equalTo(BACKEND_BODY));
assertEquals(before + 1, backendHits.get(), "the request through " + host + path + " reached the integration");
}
private static void assertNotRouted(String host, String path) {
int before = backendHits.get();
given().header("Host", host).when().get(path);
assertEquals(before, backendHits.get(), "the request through " + host + path + " reached the integration");
}
}
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayRestApiCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2DomainCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApplicationAutoScalingCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingGroupCfnProvisioner;
@@ -358,6 +359,7 @@ final class CfnProvisionerFixture {
discovered.add(new ApiGatewayApiKeyCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayUsagePlanCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayDomainCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayV2DomainCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayGatewayResponseCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayRestApiCfnProvisioner(apiGatewayService, s3Service, objectMapper));
}
@@ -0,0 +1,638 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The API Gateway v2 custom domain provisioner in isolation, over a mocked service. The validation
* is the service's and is tested there; here every case asserts the exact physical id and the exact
* {@code Fn::GetAtt} attribute keys, since an unmapped type still reports CREATE_COMPLETE through
* the dispatcher's stub arm, and how a replacement and a rollback reach the service. The replacement
* lifecycle is {@link ReplacementCleanup}'s own, not a stand-in.
*/
class ApiGatewayV2DomainCfnProvisionerTest {
private static final String DOMAIN_TYPE = "AWS::ApiGatewayV2::DomainName";
private static final String MAPPING_TYPE = "AWS::ApiGatewayV2::ApiMapping";
private static final String REGION = "us-east-1";
private static final String DOMAIN = "api.example.com";
private static final String OLD_DOMAIN = "old.example.com";
private static final String DOMAIN_ARN = "arn:aws:apigateway:us-east-1::/domainnames/api.example.com";
private static final String CERTIFICATE_ARN =
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555";
private static final String RENEWED_CERTIFICATE_ARN =
"arn:aws:acm:us-east-1:000000000000:certificate/99999999-2222-3333-4444-555555555555";
private static final String API_ID = "abc123def4";
private static final String OTHER_API_ID = "zyx987wvu6";
private static final String DOMAIN_ATTR = "__FlociApiMappingDomainName";
private static final String DOMAIN_SNAPSHOT_ATTR = CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR;
private static final String MAPPING_SNAPSHOT_ATTR = CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR;
private static final String V1_MAPPING_ID = ApiGatewayService.apiMappingId("v1");
private static final String MOVED_MAPPING_ID = V1_MAPPING_ID + "-2";
private static final AwsException DOMAIN_NOT_FOUND =
new AwsException("NotFoundException", "Invalid domain name identifier specified", 404);
private static final AwsException MAPPING_NOT_FOUND =
new AwsException("NotFoundException", "Unable to find ApiMapping with ID " + V1_MAPPING_ID, 404);
private final ApiGatewayService apiGateway = mock(ApiGatewayService.class);
private final ApiGatewayV2DomainCfnProvisioner provisioner = new ApiGatewayV2DomainCfnProvisioner(apiGateway);
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx() {
return ctx(null);
}
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
}
private static StackResource resource(String type) {
StackResource r = new StackResource();
r.setLogicalId("Res");
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
private static StackResource resource(String type, String physicalId) {
StackResource r = resource(type);
r.setPhysicalId(physicalId);
return r;
}
/** A domain resource as an earlier provision left it. */
private static StackResource provisionedDomain(String domainName) {
StackResource r = resource(DOMAIN_TYPE, domainName);
r.getAttributes().put("DomainNameArn", "arn:aws:apigateway:us-east-1::/domainnames/" + domainName);
r.getAttributes().put("RegionalDomainName", domainName + ".regional.local");
r.getAttributes().put("RegionalHostedZoneId", "Z2FDTNDATAQYL2");
return r;
}
/** A mapping resource as an earlier provision left it: its id and the domain it was created on. */
private static StackResource provisionedMapping(String apiMappingId, String domainName) {
StackResource r = resource(MAPPING_TYPE, apiMappingId);
r.getAttributes().put("ApiMappingId", apiMappingId);
r.getAttributes().put(DOMAIN_ATTR, domainName);
return r;
}
private static CustomDomain regionalDomain(String name) {
CustomDomain d = new CustomDomain();
d.setDomainName(name);
d.setEndpointConfigurationType("REGIONAL");
d.setRegionalCertificateArn(CERTIFICATE_ARN);
d.setSecurityPolicy("TLS_1_2");
d.setRegionalDomainName(name + ".regional.local");
d.setRegionalHostedZoneId("Z2FDTNDATAQYL2");
d.setTags(new LinkedHashMap<>(Map.of("stack", "my-stack")));
return d;
}
private static StoredMapping storedMapping(String apiMappingId, String storedPath, String apiId, String stage) {
BasePathMapping mapping = new BasePathMapping(storedPath, apiId, stage);
mapping.setApiMappingId(apiMappingId);
return new StoredMapping(storedPath, mapping);
}
private ObjectNode domainProps(String certificateArn, String securityPolicy) {
ObjectNode props = mapper.createObjectNode().put("DomainName", DOMAIN);
props.putArray("DomainNameConfigurations").addObject()
.put("CertificateArn", certificateArn)
.put("EndpointType", "REGIONAL")
.put("SecurityPolicy", securityPolicy);
props.putObject("Tags").put("stack", "my-stack");
return props;
}
private static Map<String, Object> domainRequest(String certificateArn, String securityPolicy) {
Map<String, Object> configuration = new LinkedHashMap<>();
configuration.put("certificateArn", certificateArn);
configuration.put("endpointType", "REGIONAL");
configuration.put("securityPolicy", securityPolicy);
return Map.of("domainName", DOMAIN, "domainNameConfigurations", List.of(configuration),
"tags", Map.of("stack", "my-stack"));
}
private ObjectNode mappingProps(String domainName, String apiMappingKey, String apiId, String stage) {
ObjectNode props = mapper.createObjectNode()
.put("DomainName", domainName)
.put("ApiId", apiId)
.put("Stage", stage);
if (apiMappingKey != null) {
props.put("ApiMappingKey", apiMappingKey);
}
return props;
}
@Test
void servesBothTypes() {
assertEquals(Set.of(DOMAIN_TYPE, MAPPING_TYPE), provisioner.resourceTypes());
}
@Test
void domainSetsItsNameAsPhysicalIdAndTheThreeSchemaAttributes() {
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
StackResource r = resource(DOMAIN_TYPE);
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx());
verify(apiGateway).createV2DomainName(REGION, domainRequest(CERTIFICATE_ARN, "TLS_1_2"));
assertEquals(DOMAIN, r.getPhysicalId());
assertEquals(Map.of(
"DomainNameArn", DOMAIN_ARN,
"RegionalDomainName", "api.example.com.regional.local",
"RegionalHostedZoneId", "Z2FDTNDATAQYL2"), r.getAttributes());
}
@Test
void domainHandsEveryInputToTheServiceToJudge() {
// The service refuses what floci does not emulate, so the template's values must reach it.
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2").put("RoutingMode", "API_MAPPING_ONLY");
((ObjectNode) props.withArray("DomainNameConfigurations").get(0))
.put("IpAddressType", "dualstack")
.put("OwnershipVerificationCertificateArn", RENEWED_CERTIFICATE_ARN);
props.putObject("MutualTlsAuthentication").put("TruststoreUri", "s3://bucket/truststore.pem");
provisioner.provision(resource(DOMAIN_TYPE), props, ctx());
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
verify(apiGateway).createV2DomainName(eq(REGION), request.capture());
assertEquals("API_MAPPING_ONLY", request.getValue().get("routingMode"));
assertEquals(Map.of("truststoreUri", "s3://bucket/truststore.pem"),
request.getValue().get("mutualTlsAuthentication"));
@SuppressWarnings("unchecked")
Map<String, Object> configuration =
((List<Map<String, Object>>) request.getValue().get("domainNameConfigurations")).getFirst();
assertEquals("dualstack", configuration.get("ipAddressType"));
assertEquals(RENEWED_CERTIFICATE_ARN, configuration.get("ownershipVerificationCertificateArn"));
}
@Test
void resourcesWithoutPropertiesAreRejected() {
assertThrows(IllegalArgumentException.class, () -> provisioner.provision(resource(DOMAIN_TYPE), null, ctx()));
assertThrows(IllegalArgumentException.class, () -> provisioner.provision(resource(MAPPING_TYPE), null, ctx()));
verify(apiGateway, never()).createV2DomainName(any(), anyMap());
verify(apiGateway, never()).createApiMapping(any(), any(), any(), any(), any(), any());
}
@Test
void domainUpdateWithUnchangedNameReplacesItsConfigurationInPlace() {
when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(regionalDomain(DOMAIN));
CustomDomain updated = regionalDomain(DOMAIN);
updated.setRegionalCertificateArn(RENEWED_CERTIFICATE_ARN);
when(apiGateway.replaceV2DomainConfiguration(eq(REGION), eq(DOMAIN), anyMap())).thenReturn(updated);
StackResource r = provisionedDomain(DOMAIN);
provisioner.provision(r, domainProps(RENEWED_CERTIFICATE_ARN, "TLS_1_2"), ctx(DOMAIN));
verify(apiGateway).replaceV2DomainConfiguration(REGION, DOMAIN, domainRequest(RENEWED_CERTIFICATE_ARN, "TLS_1_2"));
verify(apiGateway, never()).createV2DomainName(any(), anyMap());
verify(apiGateway, never()).deleteDomainName(any(), any());
assertEquals(DOMAIN, r.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(r));
assertTrue(r.getAttributes().containsKey(DOMAIN_SNAPSHOT_ATTR), "the prior configuration is kept for a rollback");
}
@Test
void domainUpdateDrivesTagsToTheTemplate() {
CustomDomain existing = regionalDomain(DOMAIN);
existing.setTags(new LinkedHashMap<>(Map.of("stack", "my-stack", "owner", "old")));
when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(existing);
when(apiGateway.replaceV2DomainConfiguration(eq(REGION), eq(DOMAIN), anyMap())).thenReturn(existing);
ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2");
((ObjectNode) props.get("Tags")).put("team", "api");
provisioner.provision(provisionedDomain(DOMAIN), props, ctx(DOMAIN));
verify(apiGateway).untagDomainName(REGION, DOMAIN, List.of("owner"));
verify(apiGateway).tagDomainName(REGION, DOMAIN, Map.of("stack", "my-stack", "team", "api"));
}
@Test
void domainUpdateTheServiceRefusesLeavesTheTagsAlone() {
when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(regionalDomain(DOMAIN));
when(apiGateway.replaceV2DomainConfiguration(eq(REGION), eq(DOMAIN), anyMap()))
.thenThrow(new AwsException("BadRequestException", "Mutual TLS authentication is not supported", 400));
ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2");
((ObjectNode) props.get("Tags")).put("team", "api");
assertThrows(AwsException.class, () -> provisioner.provision(provisionedDomain(DOMAIN), props, ctx(DOMAIN)));
verify(apiGateway, never()).tagDomainName(any(), any(), anyMap());
}
@Test
void domainRenameCreatesTheNewDomainAndLeavesTheOldOneToTheCleanup() {
when(apiGateway.getDomainName(REGION, OLD_DOMAIN)).thenReturn(regionalDomain(OLD_DOMAIN));
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
StackResource r = provisionedDomain(OLD_DOMAIN);
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(OLD_DOMAIN));
verify(apiGateway).createV2DomainName(eq(REGION), anyMap());
verify(apiGateway, never()).deleteDomainName(any(), any());
assertEquals(DOMAIN, r.getPhysicalId());
assertEquals("api.example.com.regional.local", r.getAttributes().get("RegionalDomainName"));
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals(OLD_DOMAIN, provisioner.updateCleanupPhysicalId(r));
UpdateCleanupResult cleanup = provisioner.completeUpdate(r);
assertTrue(cleanup.complete());
verify(apiGateway).deleteDomainName(REGION, OLD_DOMAIN);
}
@Test
void domainRenameUnderRetainKeepsTheOldDomain() {
when(apiGateway.getDomainName(REGION, OLD_DOMAIN)).thenReturn(regionalDomain(OLD_DOMAIN));
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
StackResource r = provisionedDomain(OLD_DOMAIN);
r.setUpdateReplacePolicy("Retain");
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(OLD_DOMAIN));
provisioner.completeUpdate(r);
verify(apiGateway, never()).deleteDomainName(any(), any());
}
@Test
void domainRenameRollbackPutsTheOldDomainBackAndDeletesTheNewOne() {
when(apiGateway.getDomainName(REGION, OLD_DOMAIN)).thenReturn(regionalDomain(OLD_DOMAIN));
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
StackResource r = provisionedDomain(OLD_DOMAIN);
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(OLD_DOMAIN));
assertTrue(provisioner.rollbackUpdate(r));
verify(apiGateway).deleteDomainName(REGION, DOMAIN);
verify(apiGateway, never()).deleteDomainName(REGION, OLD_DOMAIN);
assertEquals(OLD_DOMAIN, r.getPhysicalId());
assertEquals("old.example.com.regional.local", r.getAttributes().get("RegionalDomainName"));
assertFalse(provisioner.hasReplacementUpdate(r));
}
@Test
void domainInPlaceRollbackRestoresTheConfigurationAndTagsItHadBefore() {
CustomDomain existing = regionalDomain(DOMAIN);
existing.setRegionalCertificateName("before");
when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(existing);
CustomDomain updated = regionalDomain(DOMAIN);
updated.setTags(new LinkedHashMap<>(Map.of("stack", "my-stack", "team", "api")));
when(apiGateway.replaceV2DomainConfiguration(eq(REGION), eq(DOMAIN), anyMap())).thenReturn(updated);
ObjectNode props = domainProps(RENEWED_CERTIFICATE_ARN, "TLS_1_2");
((ObjectNode) props.get("Tags")).put("team", "api");
StackResource r = provisionedDomain(DOMAIN);
provisioner.provision(r, props, ctx(DOMAIN));
assertTrue(provisioner.rollbackUpdate(r));
Map<String, Object> configuration = new LinkedHashMap<>();
configuration.put("certificateArn", CERTIFICATE_ARN);
configuration.put("certificateName", "before");
configuration.put("endpointType", "REGIONAL");
configuration.put("securityPolicy", "TLS_1_2");
verify(apiGateway).replaceV2DomainConfiguration(REGION, DOMAIN,
Map.of("domainName", DOMAIN, "domainNameConfigurations", List.of(configuration)));
verify(apiGateway).untagDomainName(REGION, DOMAIN, List.of("team"));
assertFalse(r.getAttributes().containsKey(DOMAIN_SNAPSHOT_ATTR));
}
@Test
void domainUpdateWhosePriorDomainIsGoneCreatesItAgain() {
when(apiGateway.getDomainName(REGION, DOMAIN)).thenThrow(DOMAIN_NOT_FOUND);
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
StackResource r = provisionedDomain(DOMAIN);
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(DOMAIN));
verify(apiGateway).createV2DomainName(eq(REGION), anyMap());
assertEquals(DOMAIN, r.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(r), "the same name is the same domain, nothing to clean up");
}
@Test
void domainDeleteToleratesAnAlreadyDeletedDomain() {
doThrow(DOMAIN_NOT_FOUND).when(apiGateway).deleteDomainName(REGION, DOMAIN);
assertDoesNotThrow(() -> provisioner.delete(resource(DOMAIN_TYPE, DOMAIN), REGION));
}
@Test
void domainDeletePropagatesOtherFailures() {
doThrow(new AwsException("BadRequestException", "Domain is in use", 400))
.when(apiGateway).deleteDomainName(REGION, DOMAIN);
assertThrows(AwsException.class, () -> provisioner.delete(resource(DOMAIN_TYPE, DOMAIN), REGION));
}
@Test
void mappingPhysicalIdIsTheIdTheServiceGaveIt() {
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of()))
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
StackResource r = resource(MAPPING_TYPE);
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx());
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
assertEquals(Map.of("ApiMappingId", V1_MAPPING_ID, DOMAIN_ATTR, DOMAIN), r.getAttributes());
}
@Test
void mappingWithoutAKeyIsTheRootMapping() {
String rootId = ApiGatewayService.apiMappingId("(none)");
when(apiGateway.createApiMapping(REGION, DOMAIN, null, API_ID, "$default", Set.of()))
.thenReturn(storedMapping(rootId, "(none)", API_ID, "$default"));
StackResource r = resource(MAPPING_TYPE);
provisioner.provision(r, mappingProps(DOMAIN, null, API_ID, "$default"), ctx());
assertEquals(rootId, r.getPhysicalId());
}
@Test
void mappingRequiresDomainNameApiIdAndStage() {
for (String missing : List.of("DomainName", "ApiId", "Stage")) {
ObjectNode props = mappingProps(DOMAIN, "v1", API_ID, "$default");
props.remove(missing);
assertThrows(IllegalArgumentException.class,
() -> provisioner.provision(resource(MAPPING_TYPE), props, ctx()), missing);
}
verify(apiGateway, never()).createApiMapping(any(), any(), any(), any(), any(), any());
}
@Test
void mappingUpdateOnTheSameDomainIsInPlaceAndKeepsTheIdThroughAKeyChange() {
when(apiGateway.getApiMapping(REGION, DOMAIN, V1_MAPPING_ID))
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
when(apiGateway.updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v2", OTHER_API_ID, "prod"))
.thenReturn(storedMapping(V1_MAPPING_ID, "v2", OTHER_API_ID, "prod"));
StackResource r = provisionedMapping(V1_MAPPING_ID, DOMAIN);
provisioner.provision(r, mappingProps(DOMAIN, "v2", OTHER_API_ID, "prod"), ctx(V1_MAPPING_ID));
verify(apiGateway).updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v2", OTHER_API_ID, "prod");
verify(apiGateway, never()).createApiMapping(any(), any(), any(), any(), any(), any());
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
assertEquals(V1_MAPPING_ID, r.getAttributes().get("ApiMappingId"));
assertFalse(provisioner.hasReplacementUpdate(r));
assertTrue(r.getAttributes().containsKey(MAPPING_SNAPSHOT_ATTR));
}
@Test
void mappingUpdateTheServiceRefusesCreatesNothing() {
when(apiGateway.getApiMapping(REGION, DOMAIN, V1_MAPPING_ID))
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
when(apiGateway.updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v1", API_ID, "nosuchstage"))
.thenThrow(new AwsException("BadRequestException", "Invalid stage identifier specified", 400));
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(
provisionedMapping(V1_MAPPING_ID, DOMAIN), mappingProps(DOMAIN, "v1", API_ID, "nosuchstage"),
ctx(V1_MAPPING_ID)));
assertEquals("BadRequestException", failure.getErrorCode());
verify(apiGateway, never()).createApiMapping(any(), any(), any(), any(), any(), any());
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
}
@Test
void mappingInPlaceRollbackPutsTheKeyApiAndStageBack() {
when(apiGateway.getApiMapping(REGION, DOMAIN, V1_MAPPING_ID))
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
when(apiGateway.updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v2", OTHER_API_ID, "prod"))
.thenReturn(storedMapping(V1_MAPPING_ID, "v2", OTHER_API_ID, "prod"));
StackResource r = provisionedMapping(V1_MAPPING_ID, DOMAIN);
provisioner.provision(r, mappingProps(DOMAIN, "v2", OTHER_API_ID, "prod"), ctx(V1_MAPPING_ID));
assertTrue(provisioner.rollbackUpdate(r));
verify(apiGateway).updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v1", API_ID, "$default");
assertFalse(r.getAttributes().containsKey(MAPPING_SNAPSHOT_ATTR));
}
@Test
void mappingInPlaceRollbackOfTheRootMappingRestoresTheRoot() {
String rootId = ApiGatewayService.apiMappingId("(none)");
when(apiGateway.getApiMapping(REGION, DOMAIN, rootId))
.thenReturn(storedMapping(rootId, "(none)", API_ID, "$default"));
when(apiGateway.updateApiMapping(REGION, DOMAIN, rootId, "v1", API_ID, "$default"))
.thenReturn(storedMapping(rootId, "v1", API_ID, "$default"));
StackResource r = provisionedMapping(rootId, DOMAIN);
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(rootId));
assertTrue(provisioner.rollbackUpdate(r));
verify(apiGateway).updateApiMapping(REGION, DOMAIN, rootId, null, API_ID, "$default");
}
@Test
void mappingMovedToAnotherDomainGetsANewIdAndTheOldOneWaitsForTheCleanup() {
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of(V1_MAPPING_ID)))
.thenReturn(storedMapping(MOVED_MAPPING_ID, "v1", API_ID, "$default"));
StackResource r = provisionedMapping(V1_MAPPING_ID, OLD_DOMAIN);
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(V1_MAPPING_ID));
verify(apiGateway, never()).getApiMapping(any(), any(), any());
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
assertEquals(MOVED_MAPPING_ID, r.getPhysicalId());
assertEquals(DOMAIN, r.getAttributes().get(DOMAIN_ATTR));
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals(V1_MAPPING_ID, provisioner.updateCleanupPhysicalId(r));
assertTrue(provisioner.completeUpdate(r).complete());
verify(apiGateway).deleteApiMapping(REGION, OLD_DOMAIN, V1_MAPPING_ID);
verify(apiGateway, never()).deleteApiMapping(REGION, DOMAIN, MOVED_MAPPING_ID);
assertFalse(provisioner.hasReplacementUpdate(r));
}
@Test
void mappingMoveRollbackPutsTheOldMappingBackAndDeletesTheNewOne() {
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of(V1_MAPPING_ID)))
.thenReturn(storedMapping(MOVED_MAPPING_ID, "v1", API_ID, "$default"));
StackResource r = provisionedMapping(V1_MAPPING_ID, OLD_DOMAIN);
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(V1_MAPPING_ID));
assertTrue(provisioner.rollbackUpdate(r));
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, MOVED_MAPPING_ID);
verify(apiGateway, never()).deleteApiMapping(REGION, OLD_DOMAIN, V1_MAPPING_ID);
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
assertEquals(V1_MAPPING_ID, r.getAttributes().get("ApiMappingId"));
assertEquals(OLD_DOMAIN, r.getAttributes().get(DOMAIN_ATTR));
}
@Test
void mappingMoveRollbackWhoseDeleteFailsStillNamesTheOldDomain() {
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of(V1_MAPPING_ID)))
.thenReturn(storedMapping(MOVED_MAPPING_ID, "v1", API_ID, "$default"));
doThrow(new AwsException("BadRequestException", "Invalid request", 400))
.when(apiGateway).deleteApiMapping(REGION, DOMAIN, MOVED_MAPPING_ID);
StackResource r = provisionedMapping(V1_MAPPING_ID, OLD_DOMAIN);
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(V1_MAPPING_ID));
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
assertEquals(OLD_DOMAIN, r.getAttributes().get(DOMAIN_ATTR));
// The replacement stays owed, and the next cleanup reaches it through the domain it is on.
assertTrue(provisioner.hasReplacementUpdate(r));
doThrow(MAPPING_NOT_FOUND).when(apiGateway).deleteApiMapping(REGION, DOMAIN, MOVED_MAPPING_ID);
assertTrue(provisioner.completeUpdate(r).complete());
verify(apiGateway, never()).deleteApiMapping(REGION, OLD_DOMAIN, MOVED_MAPPING_ID);
}
@Test
void mappingUpdateWhosePriorMappingIsGoneCreatesItAgain() {
when(apiGateway.getApiMapping(REGION, DOMAIN, V1_MAPPING_ID)).thenThrow(MAPPING_NOT_FOUND);
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of()))
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
StackResource r = provisionedMapping(V1_MAPPING_ID, DOMAIN);
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(V1_MAPPING_ID));
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(r));
}
@Test
void mappingUpdateFromAStubbedResourceCreatesTheMappingAndDeletesNothingForTheStub() {
// A stack persisted before this provisioner existed carries the stub arm's id and no domain.
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of()))
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
StackResource r = resource(MAPPING_TYPE, "Mapping-1a2b3c4d");
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx("Mapping-1a2b3c4d"));
verify(apiGateway, never()).getApiMapping(any(), any(), any());
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
assertTrue(provisioner.completeUpdate(r).complete());
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
}
@Test
void mappingRollbackFromAStubbedResourceLeavesNoDomainBehind() {
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of()))
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
StackResource r = resource(MAPPING_TYPE, "Mapping-1a2b3c4d");
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx("Mapping-1a2b3c4d"));
assertTrue(provisioner.rollbackUpdate(r));
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
assertEquals("Mapping-1a2b3c4d", r.getPhysicalId());
assertNull(r.getAttributes().get(DOMAIN_ATTR));
}
@Test
void mappingDeleteAddressesTheRecordedDomain() {
provisioner.delete(provisionedMapping(V1_MAPPING_ID, DOMAIN), REGION);
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
}
@Test
void mappingDeleteToleratesAMappingAlreadyGone() {
doThrow(MAPPING_NOT_FOUND).when(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
assertDoesNotThrow(() -> provisioner.delete(provisionedMapping(V1_MAPPING_ID, DOMAIN), REGION));
}
@Test
void mappingDeleteToleratesAMappingRemovedWithItsDomain() {
doThrow(DOMAIN_NOT_FOUND).when(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
assertDoesNotThrow(() -> provisioner.delete(provisionedMapping(V1_MAPPING_ID, DOMAIN), REGION));
}
@Test
void mappingDeletePropagatesOtherFailures() {
doThrow(new AwsException("BadRequestException", "Invalid request", 400))
.when(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
assertThrows(AwsException.class,
() -> provisioner.delete(provisionedMapping(V1_MAPPING_ID, DOMAIN), REGION));
}
@Test
void mappingDeleteByThePrimaryIdentifierAddressesItsDomain() {
// Cloud Control names a mapping by the schema's primary identifier, <ApiMappingId>|<DomainName>.
provisioner.delete(MAPPING_TYPE, V1_MAPPING_ID + "|" + DOMAIN, REGION);
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
}
@Test
void mappingDeleteByThePrimaryIdentifierWithItsRecordedDomainAddressesTheMapping() {
// Cloud Control keys what it created by the primary identifier, and deletes it with the
// attributes the create recorded, the domain among them.
provisioner.delete(provisionedMapping(V1_MAPPING_ID + "|" + DOMAIN, DOMAIN), REGION);
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
}
@Test
void mappingDeleteByABareIdAnswersNotFound() {
// A bare id names no domain to look in; the stack path treats NotFoundException as already
// deleted, and Cloud Control reports it instead of claiming a delete that did not happen.
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.delete(resource(MAPPING_TYPE, "Mapping-1a2b3c4d"), REGION));
assertEquals("NotFoundException", failure.getErrorCode());
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
}
@Test
void clearUpdateDropsTheSnapshots() {
StackResource r = provisionedMapping(V1_MAPPING_ID, DOMAIN);
r.getAttributes().put(MAPPING_SNAPSHOT_ATTR, "{}");
r.getAttributes().put(DOMAIN_SNAPSHOT_ATTR, "{}");
provisioner.clearUpdate(r);
assertEquals(Map.of("ApiMappingId", V1_MAPPING_ID, DOMAIN_ATTR, DOMAIN), r.getAttributes());
}
}
@@ -0,0 +1,76 @@
// The CDK app that synthesized http-api-domain.template.json and rest-api-multi-level-domain.template.json,
// which ApiGatewayV2DomainCfnIntegrationTest deploys verbatim. To regenerate, in an empty directory:
// npm install aws-cdk-lib@2.272.0 constructs@10 && CDK_OUTDIR=out node cdk-app.js
// then copy out/HttpApiDomain.template.json and out/RestApiMultiLevelDomain.template.json here.
// aws-cdk-lib 2.270.0 synthesizes the same resources.
const cdk = require('aws-cdk-lib');
const apigateway = require('aws-cdk-lib/aws-apigateway');
const apigwv2 = require('aws-cdk-lib/aws-apigatewayv2');
const integrations = require('aws-cdk-lib/aws-apigatewayv2-integrations');
const acm = require('aws-cdk-lib/aws-certificatemanager');
const route53 = require('aws-cdk-lib/aws-route53');
const targets = require('aws-cdk-lib/aws-route53-targets');
const app = new cdk.App();
const synthesizer = () => new cdk.DefaultStackSynthesizer({ generateBootstrapVersionRule: false });
// An HTTP API on a custom domain: the default stage mapped at the root, a second stage mapped
// under a key, and an alias record to the domain.
{
const stack = new cdk.Stack(app, 'HttpApiDomain', { synthesizer: synthesizer() });
const backendUrl = new cdk.CfnParameter(stack, 'BackendUrl', { type: 'String' });
const zoneName = 'apigwv2-domain-cfn-it.example.com';
const domainName = `cdk.${zoneName}`;
const zone = new route53.PublicHostedZone(stack, 'Zone', { zoneName });
const certificate = new acm.Certificate(stack, 'Certificate', {
domainName,
validation: acm.CertificateValidation.fromDns(zone),
});
const domain = new apigwv2.DomainName(stack, 'Domain', { domainName, certificate });
const api = new apigwv2.HttpApi(stack, 'HttpApi', {
defaultIntegration: new integrations.HttpUrlIntegration('Backend', backendUrl.valueAsString),
defaultDomainMapping: { domainName: domain },
});
const prod = api.addStage('Prod', { stageName: 'prod', autoDeploy: true });
new apigwv2.ApiMapping(stack, 'ProdMapping', { api, domainName: domain, stage: prod, apiMappingKey: 'prod' });
new route53.ARecord(stack, 'Alias', {
zone,
recordName: domainName,
target: route53.RecordTarget.fromAlias(
new targets.ApiGatewayv2DomainProperties(domain.regionalDomainName, domain.regionalHostedZoneId)),
});
new cdk.CfnOutput(stack, 'ApiId', { value: api.apiId });
new cdk.CfnOutput(stack, 'ZoneId', { value: zone.hostedZoneId });
new cdk.CfnOutput(stack, 'RegionalDomainName', { value: domain.regionalDomainName });
new cdk.CfnOutput(stack, 'RegionalHostedZoneId', { value: domain.regionalHostedZoneId });
}
// A REST API on a custom domain under a key with several levels, which CDK maps with
// AWS::ApiGatewayV2::ApiMapping because AWS::ApiGateway::BasePathMapping takes one level only.
{
const stack = new cdk.Stack(app, 'RestApiMultiLevelDomain', { synthesizer: synthesizer() });
const backendUrl = new cdk.CfnParameter(stack, 'BackendUrl', { type: 'String' });
const zoneName = 'apigwv2-rest-cfn-it.example.com';
const domainName = `rest.${zoneName}`;
const zone = new route53.PublicHostedZone(stack, 'Zone', { zoneName });
const certificate = new acm.Certificate(stack, 'Certificate', {
domainName,
validation: acm.CertificateValidation.fromDns(zone),
});
const api = new apigateway.RestApi(stack, 'RestApi');
api.root.addResource('items').addMethod('GET', new apigateway.HttpIntegration(backendUrl.valueAsString));
const domain = new apigateway.DomainName(stack, 'Domain', {
domainName,
certificate,
mapping: api,
basePath: 'orders/v1',
});
new route53.ARecord(stack, 'Alias', {
zone,
recordName: domainName,
target: route53.RecordTarget.fromAlias(new targets.ApiGatewayDomain(domain)),
});
new cdk.CfnOutput(stack, 'RestApiId', { value: api.restApiId });
}
app.synth();
@@ -0,0 +1,199 @@
{
"Parameters": {
"BackendUrl": {
"Type": "String"
}
},
"Resources": {
"ZoneA5DE4B68": {
"Type": "AWS::Route53::HostedZone",
"Properties": {
"Name": "apigwv2-domain-cfn-it.example.com."
}
},
"Certificate4E7ABB08": {
"Type": "AWS::CertificateManager::Certificate",
"Properties": {
"DomainName": "cdk.apigwv2-domain-cfn-it.example.com",
"DomainValidationOptions": [
{
"DomainName": "cdk.apigwv2-domain-cfn-it.example.com",
"HostedZoneId": {
"Ref": "ZoneA5DE4B68"
}
}
],
"Tags": [
{
"Key": "Name",
"Value": "HttpApiDomain/Certificate"
}
],
"ValidationMethod": "DNS"
}
},
"Domain66AC69E0": {
"Type": "AWS::ApiGatewayV2::DomainName",
"Properties": {
"DomainName": "cdk.apigwv2-domain-cfn-it.example.com",
"DomainNameConfigurations": [
{
"CertificateArn": {
"Ref": "Certificate4E7ABB08"
},
"EndpointType": "REGIONAL"
}
]
}
},
"HttpApiF5A9A8A7": {
"Type": "AWS::ApiGatewayV2::Api",
"Properties": {
"Name": "HttpApi",
"ProtocolType": "HTTP"
}
},
"HttpApiDefaultRouteBackendAF181430": {
"Type": "AWS::ApiGatewayV2::Integration",
"Properties": {
"ApiId": {
"Ref": "HttpApiF5A9A8A7"
},
"IntegrationMethod": "ANY",
"IntegrationType": "HTTP_PROXY",
"IntegrationUri": {
"Ref": "BackendUrl"
},
"PayloadFormatVersion": "1.0"
}
},
"HttpApiDefaultRoute146696CE": {
"Type": "AWS::ApiGatewayV2::Route",
"Properties": {
"ApiId": {
"Ref": "HttpApiF5A9A8A7"
},
"AuthorizationType": "NONE",
"RouteKey": "$default",
"Target": {
"Fn::Join": [
"",
[
"integrations/",
{
"Ref": "HttpApiDefaultRouteBackendAF181430"
}
]
]
}
}
},
"HttpApiDefaultStage3EEB07D6": {
"Type": "AWS::ApiGatewayV2::Stage",
"Properties": {
"ApiId": {
"Ref": "HttpApiF5A9A8A7"
},
"AutoDeploy": true,
"StageName": "$default"
},
"DependsOn": [
"Domain66AC69E0"
]
},
"HttpApiDefaultStageHttpApiDomainDomainundefined7285D8B3": {
"Type": "AWS::ApiGatewayV2::ApiMapping",
"Properties": {
"ApiId": {
"Ref": "HttpApiF5A9A8A7"
},
"DomainName": {
"Ref": "Domain66AC69E0"
},
"Stage": "$default"
},
"DependsOn": [
"Domain66AC69E0",
"HttpApiDefaultStage3EEB07D6"
]
},
"HttpApiProdFCF6FCB2": {
"Type": "AWS::ApiGatewayV2::Stage",
"Properties": {
"ApiId": {
"Ref": "HttpApiF5A9A8A7"
},
"AutoDeploy": true,
"StageName": "prod"
}
},
"ProdMappingCD2A8E2B": {
"Type": "AWS::ApiGatewayV2::ApiMapping",
"Properties": {
"ApiId": {
"Ref": "HttpApiF5A9A8A7"
},
"ApiMappingKey": "prod",
"DomainName": {
"Ref": "Domain66AC69E0"
},
"Stage": "prod"
},
"DependsOn": [
"HttpApiProdFCF6FCB2"
]
},
"Alias325C5727": {
"Type": "AWS::Route53::RecordSet",
"Properties": {
"AliasTarget": {
"DNSName": {
"Fn::GetAtt": [
"Domain66AC69E0",
"RegionalDomainName"
]
},
"HostedZoneId": {
"Fn::GetAtt": [
"Domain66AC69E0",
"RegionalHostedZoneId"
]
}
},
"HostedZoneId": {
"Ref": "ZoneA5DE4B68"
},
"Name": "cdk.apigwv2-domain-cfn-it.example.com.",
"Type": "A"
}
}
},
"Outputs": {
"ApiId": {
"Value": {
"Ref": "HttpApiF5A9A8A7"
}
},
"ZoneId": {
"Value": {
"Ref": "ZoneA5DE4B68"
}
},
"RegionalDomainName": {
"Value": {
"Fn::GetAtt": [
"Domain66AC69E0",
"RegionalDomainName"
]
}
},
"RegionalHostedZoneId": {
"Value": {
"Fn::GetAtt": [
"Domain66AC69E0",
"RegionalHostedZoneId"
]
}
}
}
}
@@ -0,0 +1,243 @@
{
"Parameters": {
"BackendUrl": {
"Type": "String"
}
},
"Resources": {
"ZoneA5DE4B68": {
"Type": "AWS::Route53::HostedZone",
"Properties": {
"Name": "apigwv2-rest-cfn-it.example.com."
}
},
"Certificate4E7ABB08": {
"Type": "AWS::CertificateManager::Certificate",
"Properties": {
"DomainName": "rest.apigwv2-rest-cfn-it.example.com",
"DomainValidationOptions": [
{
"DomainName": "rest.apigwv2-rest-cfn-it.example.com",
"HostedZoneId": {
"Ref": "ZoneA5DE4B68"
}
}
],
"Tags": [
{
"Key": "Name",
"Value": "RestApiMultiLevelDomain/Certificate"
}
],
"ValidationMethod": "DNS"
}
},
"RestApi0C43BF4B": {
"Type": "AWS::ApiGateway::RestApi",
"Properties": {
"Name": "RestApi"
}
},
"RestApiCloudWatchRoleE3ED6605": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
}
}
],
"Version": "2012-10-17"
},
"ManagedPolicyArns": [
{
"Fn::Join": [
"",
[
"arn:",
{
"Ref": "AWS::Partition"
},
":iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
]
]
}
]
},
"UpdateReplacePolicy": "Retain",
"DeletionPolicy": "Retain"
},
"RestApiAccount7C83CF5A": {
"Type": "AWS::ApiGateway::Account",
"Properties": {
"CloudWatchRoleArn": {
"Fn::GetAtt": [
"RestApiCloudWatchRoleE3ED6605",
"Arn"
]
}
},
"DependsOn": [
"RestApi0C43BF4B"
],
"UpdateReplacePolicy": "Retain",
"DeletionPolicy": "Retain"
},
"RestApiDeployment180EC503bf7e2070a8bd9afd3cc70fd4d322d3c1": {
"Type": "AWS::ApiGateway::Deployment",
"Properties": {
"Description": "Automatically created by the RestApi construct",
"RestApiId": {
"Ref": "RestApi0C43BF4B"
}
},
"DependsOn": [
"RestApiitemsGET2AAECCB8",
"RestApiitems0D5B6650"
],
"Metadata": {
"aws:cdk:do-not-refactor": true
}
},
"RestApiDeploymentStageprod3855DE66": {
"Type": "AWS::ApiGateway::Stage",
"Properties": {
"DeploymentId": {
"Ref": "RestApiDeployment180EC503bf7e2070a8bd9afd3cc70fd4d322d3c1"
},
"RestApiId": {
"Ref": "RestApi0C43BF4B"
},
"StageName": "prod"
},
"DependsOn": [
"RestApiAccount7C83CF5A"
]
},
"RestApiitems0D5B6650": {
"Type": "AWS::ApiGateway::Resource",
"Properties": {
"ParentId": {
"Fn::GetAtt": [
"RestApi0C43BF4B",
"RootResourceId"
]
},
"PathPart": "items",
"RestApiId": {
"Ref": "RestApi0C43BF4B"
}
}
},
"RestApiitemsGET2AAECCB8": {
"Type": "AWS::ApiGateway::Method",
"Properties": {
"AuthorizationType": "NONE",
"HttpMethod": "GET",
"Integration": {
"IntegrationHttpMethod": "GET",
"Type": "HTTP_PROXY",
"Uri": {
"Ref": "BackendUrl"
}
},
"ResourceId": {
"Ref": "RestApiitems0D5B6650"
},
"RestApiId": {
"Ref": "RestApi0C43BF4B"
}
}
},
"Domain66AC69E0": {
"Type": "AWS::ApiGateway::DomainName",
"Properties": {
"DomainName": "rest.apigwv2-rest-cfn-it.example.com",
"EndpointConfiguration": {
"Types": [
"REGIONAL"
]
},
"RegionalCertificateArn": {
"Ref": "Certificate4E7ABB08"
}
}
},
"DomainMapordersv1RestApiMultiLevelDomainRestApiDeploymentStageprodBABADAB2A4BBC31B": {
"Type": "AWS::ApiGatewayV2::ApiMapping",
"Properties": {
"ApiId": {
"Ref": "RestApi0C43BF4B"
},
"ApiMappingKey": "orders/v1",
"DomainName": {
"Ref": "Domain66AC69E0"
},
"Stage": {
"Ref": "RestApiDeploymentStageprod3855DE66"
}
}
},
"Alias325C5727": {
"Type": "AWS::Route53::RecordSet",
"Properties": {
"AliasTarget": {
"DNSName": {
"Fn::GetAtt": [
"Domain66AC69E0",
"RegionalDomainName"
]
},
"HostedZoneId": {
"Fn::GetAtt": [
"Domain66AC69E0",
"RegionalHostedZoneId"
]
}
},
"HostedZoneId": {
"Ref": "ZoneA5DE4B68"
},
"Name": "rest.apigwv2-rest-cfn-it.example.com.",
"Type": "A"
}
}
},
"Outputs": {
"RestApiEndpoint0551178A": {
"Value": {
"Fn::Join": [
"",
[
"https://",
{
"Ref": "RestApi0C43BF4B"
},
".execute-api.",
{
"Ref": "AWS::Region"
},
".",
{
"Ref": "AWS::URLSuffix"
},
"/",
{
"Ref": "RestApiDeploymentStageprod3855DE66"
},
"/"
]
]
}
},
"RestApiId": {
"Value": {
"Ref": "RestApi0C43BF4B"
}
}
}
}
@@ -12,8 +12,10 @@ AWS::ApiGateway::Stage ApiGatewayRestApiCfnProvisioner
AWS::ApiGateway::UsagePlan ApiGatewayUsagePlanCfnProvisioner
AWS::ApiGateway::UsagePlanKey ApiGatewayUsagePlanCfnProvisioner
AWS::ApiGatewayV2::Api ApiGatewayV2CfnProvisioner
AWS::ApiGatewayV2::ApiMapping ApiGatewayV2DomainCfnProvisioner
AWS::ApiGatewayV2::Authorizer ApiGatewayV2CfnProvisioner
AWS::ApiGatewayV2::Deployment ApiGatewayV2CfnProvisioner
AWS::ApiGatewayV2::DomainName ApiGatewayV2DomainCfnProvisioner
AWS::ApiGatewayV2::Integration ApiGatewayV2CfnProvisioner
AWS::ApiGatewayV2::Route ApiGatewayV2CfnProvisioner
AWS::ApiGatewayV2::Stage ApiGatewayV2CfnProvisioner
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
12 AWS::ApiGateway::UsagePlan ApiGatewayUsagePlanCfnProvisioner
13 AWS::ApiGateway::UsagePlanKey ApiGatewayUsagePlanCfnProvisioner
14 AWS::ApiGatewayV2::Api ApiGatewayV2CfnProvisioner
15 AWS::ApiGatewayV2::ApiMapping ApiGatewayV2DomainCfnProvisioner
16 AWS::ApiGatewayV2::Authorizer ApiGatewayV2CfnProvisioner
17 AWS::ApiGatewayV2::Deployment ApiGatewayV2CfnProvisioner
18 AWS::ApiGatewayV2::DomainName ApiGatewayV2DomainCfnProvisioner
19 AWS::ApiGatewayV2::Integration ApiGatewayV2CfnProvisioner
20 AWS::ApiGatewayV2::Route ApiGatewayV2CfnProvisioner
21 AWS::ApiGatewayV2::Stage ApiGatewayV2CfnProvisioner
+1 -1
View File
@@ -102,7 +102,7 @@ type_order:
AWS::AutoScaling: [LaunchConfiguration, AutoScalingGroup, LifecycleHook]
AWS::Route53: [HostedZone, RecordSet]
AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account, DomainName, BasePathMapping, GatewayResponse]
AWS::ApiGatewayV2: [Api, Authorizer, Route, Integration, Stage, Deployment]
AWS::ApiGatewayV2: [Api, Authorizer, Route, Integration, Stage, Deployment, DomainName, ApiMapping]
AWS::AppSync: [GraphQLApi, GraphQLSchema, DataSource, FunctionConfiguration, Resolver, ApiKey]
AWS::CodePipeline: [Pipeline, CustomActionType, Webhook]
AWS::Batch: [ComputeEnvironment, JobQueue, JobDefinition]