fix(cloudformation): provision AWS::ApiGatewayV2::Authorizer and wire Route.AuthorizerId (#1760)

* fix(cloudformation): provision AWS::ApiGatewayV2::Authorizer and wire Route.AuthorizerId

CloudFormationResourceProvisioner had no case for AWS::ApiGatewayV2::Authorizer,
so the resource fell through the default stub branch and never reached
ApiGatewayV2Service — the same failure mode #788/#796 fixed for the v1
AWS::ApiGateway::Authorizer type. Stacks reported CREATE_COMPLETE, but
apigatewayv2 get-authorizers came back empty and routes referencing the
authorizer carried no authorizerId, so a JWT-authorized route silently
served every request unauthenticated.

Adds provisionApiGatewayV2Authorizer, modeled on the neighboring v2
Route/Integration/Stage provisioners, mapping the CFN PascalCase properties
(Name, AuthorizerType, IdentitySource, JwtConfiguration, AuthorizerUri,
AuthorizerPayloadFormatVersion, AuthorizerResultTtlInSeconds,
EnableSimpleResponses) onto the existing ApiGatewayV2Service.createAuthorizer
camelCase request shape. Also fixes provisionApiGatewayV2Route, which built
its request map without reading AuthorizerId at all even though
ApiGatewayV2Service.createRoute/updateRoute already handle it.

Fixes #1758.

* fix(cloudformation): accept scalar IdentitySource on ApiGatewayV2 Authorizer

resolveStringListOrEmpty silently returned an empty list when a template
supplied IdentitySource as a bare scalar string rather than the documented
array form, dropping the identity source instead of persisting it.
ApiGatewayV2Service.createAuthorizer/updateAuthorizer already accept a
scalar string for identitySource (identitySourceRaw instanceof String), so
the CFN provisioner was stricter than the service it calls.

Adds resolveIdentitySource, a local resolver that accepts both a scalar
string and an array. Adds a regression test asserting the scalar form is
persisted, alongside strengthening the existing test to assert
IdentitySource itself (previously unchecked).

Addresses review feedback on #1760.

* fix(cloudformation): populate AuthorizerId attribute, add scoped delete for AWS::ApiGatewayV2::Authorizer

- Fn::GetAtt Authorizer.AuthorizerId now resolves: provisionApiGatewayV2Authorizer
  only set the physical id, never the resource's attributes map, so GetAtt (which
  reads a separate map from Ref) fell back to a literal placeholder string.

- Stack deletion now actually removes the authorizer: the generic type/physicalId
  delete switch had no case for AWS::ApiGatewayV2::Authorizer at all and silently
  no-op'd. Added a scoped case in delete(StackResource, region) following the same
  shape already used for AWS::EKS::Nodegroup (a resource needing extra context
  beyond type+physicalId, stored as an attribute during provisioning).

Both fixes store ApiId as a resource attribute during provisioning, since it's
needed by the new delete path and wasn't previously retained anywhere.

* fix(apigateway): support $request.querystring.* identity sources for JWT authorizers

extractToken only checked HttpHeaders — it had no query-parameter access at all, so
any IdentitySource entry like $request.querystring.token was silently unusable, and
a request using a valid token there always 401'd. Threads UriInfo through
enforceJwtAuthorizer/extractToken and adds a $request.querystring. branch mirroring
the one enforceRequestAuthorizerV2 already has for Lambda REQUEST authorizers.

* chore: retrigger CI

The Build and Test job failed on a single flaky error in
RuntimeApiServerTest.extensionRegister_racedAgainstStop_eventuallyDeliversShutdown
(EOFException on an HTTP/2 read while racing extension registration against
server stop) — 1 of 8325 tests. This branch changes no Lambda code; that test
is from #1773 and lives on main independently. Passes locally on repeat runs.
This commit is contained in:
Jay authored and GitHub committed 2026-08-05 22:23:47 -05:00
1 parent f71903379c
commit 7f51c746cd
4 files changed
+527 -4

No files matched your search

@@ -1212,7 +1212,7 @@ public class ApiGatewayExecuteController {
}
if ("JWT".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
Response authError = enforceJwtAuthorizer(region, apiId, route, headers);
Response authError = enforceJwtAuthorizer(region, apiId, route, headers, uriInfo);
if (authError != null) return authError;
}
@@ -1441,7 +1441,8 @@ public class ApiGatewayExecuteController {
/** Extracts parameter names from a route template; the pattern itself is constant. */
private static final Pattern ROUTE_PARAM_NAMES = Pattern.compile("\\{([a-zA-Z_]+)\\+?\\}");
private Response enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers) {
private Response enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers,
UriInfo uriInfo) {
Authorizer authorizer;
try {
authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, route.getAuthorizerId());
@@ -1451,7 +1452,7 @@ public class ApiGatewayExecuteController {
.type(MediaType.APPLICATION_JSON).build();
}
String token = extractToken(authorizer, headers);
String token = extractToken(authorizer, headers, uriInfo);
if (token == null) {
return Response.status(401)
.entity(jsonMessage("Unauthorized"))
@@ -1763,7 +1764,7 @@ public class ApiGatewayExecuteController {
}
}
private String extractToken(Authorizer authorizer, HttpHeaders headers) {
private String extractToken(Authorizer authorizer, HttpHeaders headers, UriInfo uriInfo) {
List<String> sources = authorizer.getIdentitySource();
if (sources == null || sources.isEmpty()) {
// Default: Authorization header
@@ -1775,6 +1776,10 @@ public class ApiGatewayExecuteController {
String headerName = source.substring("$request.header.".length());
String value = headers.getHeaderString(headerName);
if (value != null) return stripBearer(value);
} else if (source.startsWith("$request.querystring.")) {
String paramName = source.substring("$request.querystring.".length());
String value = uriInfo.getQueryParameters().getFirst(paramName);
if (value != null) return stripBearer(value);
}
}
return null;
@@ -314,6 +314,7 @@ public class CloudFormationResourceProvisioner {
case "AWS::ApiGateway::Deployment" -> provisionApiGatewayDeployment(resource, properties, engine, region);
case "AWS::ApiGateway::Stage" -> provisionApiGatewayStage(resource, properties, engine, region);
case "AWS::ApiGatewayV2::Api" -> provisionApiGatewayV2Api(resource, properties, engine, region, accountId, stackName);
case "AWS::ApiGatewayV2::Authorizer" -> provisionApiGatewayV2Authorizer(resource, properties, engine, region);
case "AWS::ApiGatewayV2::Route" -> provisionApiGatewayV2Route(resource, properties, engine, region);
case "AWS::ApiGatewayV2::Integration" -> provisionApiGatewayV2Integration(resource, properties, engine, region);
case "AWS::ApiGatewayV2::Stage" -> provisionApiGatewayV2Stage(resource, properties, engine, region);
@@ -436,6 +437,21 @@ public class CloudFormationResourceProvisioner {
resource.getAttributes().get("EventBusName"), region);
return;
}
// Authorizer deletion needs the api id (a stored attribute, not the physical id, which is
// the authorizer id) — same shape as the Nodegroup case above. Without this, the generic
// type/physicalId delete path has no case for this type at all and silently no-ops,
// leaving the authorizer behind in AWS after the stack reports deleted.
if ("AWS::ApiGatewayV2::Authorizer".equals(resourceType)) {
String apiId = resource.getAttributes().get("ApiId");
if (apiId != null && !apiId.isBlank()) {
try {
apiGatewayV2Service.deleteAuthorizer(region, apiId, resource.getPhysicalId());
} catch (Exception e) {
LOG.debugv("Error deleting authorizer {0}: {1}", resource.getPhysicalId(), e.getMessage());
}
}
return;
}
// AWS::IAM::Policy is an inline policy; detaching it needs the principals it was attached to,
// which the type/physicalId delete path can't provide (only the delete-stack path has them).
if ("AWS::IAM::Policy".equals(resourceType)) {
@@ -3578,12 +3594,78 @@ public class CloudFormationResourceProvisioner {
return out;
}
/**
* Resolves {@code IdentitySource} accepting either the documented array form or a single
* scalar string — {@code ApiGatewayV2Service.createAuthorizer}/{@code updateAuthorizer}
* already accept both ({@code identitySourceRaw instanceof String}), so the CFN provisioner
* should not be stricter than the service it calls.
*/
private List<String> resolveIdentitySource(JsonNode props, String source, CloudFormationTemplateEngine engine) {
if (props == null || !props.has(source) || props.get(source).isNull()) {
return List.of();
}
JsonNode resolved = engine.resolveNode(props.get(source));
if (resolved == null) {
return List.of();
}
if (resolved.isTextual()) {
return List.of(resolved.asText());
}
if (!resolved.isArray()) {
return List.of();
}
List<String> values = new ArrayList<>();
resolved.forEach(v -> values.add(v.asText()));
return values;
}
private void provisionApiGatewayV2Authorizer(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region) {
String apiId = resolveOptional(props, "ApiId", engine);
Map<String, Object> req = new HashMap<>();
req.put("name", resolveOptional(props, "Name", engine));
req.put("authorizerType", resolveOptional(props, "AuthorizerType", engine));
req.put("identitySource", resolveIdentitySource(props, "IdentitySource", engine));
req.put("authorizerUri", resolveOptional(props, "AuthorizerUri", engine));
req.put("authorizerPayloadFormatVersion", resolveOptional(props, "AuthorizerPayloadFormatVersion", engine));
String ttl = resolveOptional(props, "AuthorizerResultTtlInSeconds", engine);
if (ttl != null) {
req.put("authorizerResultTtlInSeconds", Integer.parseInt(ttl));
}
String simpleResponses = resolveOptional(props, "EnableSimpleResponses", engine);
if (simpleResponses != null) {
req.put("enableSimpleResponses", simpleResponses);
}
JsonNode jwtConfigNode = props != null ? props.get("JwtConfiguration") : null;
if (jwtConfigNode != null && !jwtConfigNode.isNull()) {
Map<String, Object> jwtConfig = new HashMap<>();
jwtConfig.put("audience", resolveStringListOrEmpty(jwtConfigNode, "Audience", engine));
jwtConfig.put("issuer", resolveOptional(jwtConfigNode, "Issuer", engine));
req.put("jwtConfiguration", jwtConfig);
}
Authorizer authorizer;
if (r.getPhysicalId() == null) {
authorizer = apiGatewayV2Service.createAuthorizer(region, apiId, req);
} else {
authorizer = apiGatewayV2Service.updateAuthorizer(region, apiId, r.getPhysicalId(), req);
}
r.setPhysicalId(authorizer.getAuthorizerId());
r.getAttributes().put("AuthorizerId", authorizer.getAuthorizerId());
// ApiId is needed by delete(StackResource, region) to scope deleteAuthorizer — the
// type/physicalId-only delete overload has no apiId to call it with.
r.getAttributes().put("ApiId", apiId);
}
private void provisionApiGatewayV2Route(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region) {
String apiId = resolveOptional(props, "ApiId", engine);
Map<String, Object> req = new HashMap<>();
req.put("routeKey", resolveOptional(props, "RouteKey", engine));
req.put("authorizationType", resolveOrDefault(props, "AuthorizationType", engine, "NONE"));
req.put("authorizerId", resolveOptional(props, "AuthorizerId", engine));
req.put("target", resolveOptional(props, "Target", engine));
Route route;
@@ -0,0 +1,149 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
/**
* Regression test: HTTP API (v2) JWT authorizers support {@code $request.querystring.*}
* identity sources, not just {@code $request.header.*} — a template/API call configuring
* a query-string token source must not 401 a request carrying a valid token there.
*
* <p>Tokens here are unsigned (header.payload.signature-shaped strings whose payload is
* plain base64url JSON) — {@code ApiGatewayExecuteController.parseJwtClaims} doesn't verify
* a signature, matching this emulator's local-dev scope, so no real signing key is needed
* to exercise the extraction and claims-matching logic under test.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class HttpApiJwtAuthorizerQuerystringTest {
private static String httpApiId;
private static String integrationId;
private static String routeId;
private static String authorizerId;
private static final String ISSUER = "https://issuer.example.com";
private static final String AUDIENCE = "my-client-id";
@Test
@Order(1)
void setup() {
httpApiId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"http-v2-jwt-querystring-test","protocolType":"HTTP"}
""")
.when().post("/v2/apis")
.then()
.statusCode(201)
.body("apiId", notNullValue())
.extract().path("apiId");
given()
.contentType(ContentType.JSON)
.body("""
{"stageName":"test"}
""")
.when().post("/v2/apis/" + httpApiId + "/stages")
.then()
.statusCode(201);
integrationId = given()
.contentType(ContentType.JSON)
.body("""
{"integrationType":"HTTP_PROXY","integrationUri":"https://backend.example.com","payloadFormatVersion":"1.0"}
""")
.when().post("/v2/apis/" + httpApiId + "/integrations")
.then()
.statusCode(201)
.extract().path("integrationId");
routeId = given()
.contentType(ContentType.JSON)
.body("""
{"routeKey":"GET /hello","target":"integrations/%s"}
""".formatted(integrationId))
.when().post("/v2/apis/" + httpApiId + "/routes")
.then()
.statusCode(201)
.extract().path("routeId");
authorizerId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"jwt-querystring-auth","authorizerType":"JWT",\
"identitySource":"$request.querystring.token",\
"jwtConfiguration":{"audience":["%s"],"issuer":"%s"}}
""".formatted(AUDIENCE, ISSUER))
.when().post("/v2/apis/" + httpApiId + "/authorizers")
.then().statusCode(201)
.extract().path("authorizerId");
given()
.contentType(ContentType.JSON)
.body("""
{"authorizationType":"JWT","authorizerId":"%s"}
""".formatted(authorizerId))
.when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId)
.then().statusCode(200);
}
@Test
@Order(10)
void requestWithValidTokenInQueryStringIsAuthorized() {
// The integration target isn't a real reachable backend, so a successful proxy
// round-trip isn't asserted here — only that the request got past the authorizer.
// Before the fix, an invalid/missing token (or a source type extractToken can't read)
// 401s before ever reaching the integration; getting a 502 (backend unreachable) rather
// than a 401 proves the querystring token was actually extracted and accepted.
String token = fakeJwt(ISSUER, AUDIENCE);
given()
.when().get("/execute-api/" + httpApiId + "/test/hello?token=" + token)
.then().statusCode(502);
}
@Test
@Order(20)
void requestWithNoTokenAnywhereIsUnauthorized() {
given()
.when().get("/execute-api/" + httpApiId + "/test/hello")
.then().statusCode(401);
}
@Test
@Order(30)
void requestWithValidTokenOnlyInHeaderIsUnauthorizedWhenSourceIsQuerystring() {
// The authorizer's IdentitySource is $request.querystring.token, not a header — a
// token presented via Authorization must not satisfy an identity source it wasn't
// configured for.
String token = fakeJwt(ISSUER, AUDIENCE);
given()
.header("Authorization", "Bearer " + token)
.when().get("/execute-api/" + httpApiId + "/test/hello")
.then().statusCode(401);
}
private static String fakeJwt(String issuer, String audience) {
String header = base64Url("{\"alg\":\"none\"}");
String payload = base64Url(
"{\"iss\":\"" + issuer + "\",\"aud\":\"" + audience + "\",\"exp\":9999999999}");
return header + "." + payload + ".signature";
}
private static String base64Url(String json) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(json.getBytes(StandardCharsets.UTF_8));
}
}
@@ -6504,6 +6504,293 @@ class CloudFormationIntegrationTest {
.statusCode(200);
}
private io.restassured.response.ValidatableResponse getAuthorizers(String apiId) {
return given()
.header("X-Amz-Target", "AmazonApiGatewayV2.GetAuthorizers")
.contentType(APIGWV2_CONTENT_TYPE)
.body("{\"ApiId\": \"" + apiId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
}
// ── Issue #1758: AWS::ApiGatewayV2::Authorizer dropped by CloudFormation ──
@Test
void createStack_apiGatewayV2AuthorizerIsProvisionedAndWiredToRoute() {
String template = """
{
"Resources": {
"HttpApi": {
"Type": "AWS::ApiGatewayV2::Api",
"Properties": { "Name": "cfn-apigwv2-authz-api", "ProtocolType": "HTTP" }
},
"Authorizer": {
"Type": "AWS::ApiGatewayV2::Authorizer",
"Properties": {
"ApiId": { "Ref": "HttpApi" },
"Name": "cfn-jwt-authorizer",
"AuthorizerType": "JWT",
"IdentitySource": ["$request.header.Authorization"],
"JwtConfiguration": {
"Audience": ["my-client-id"],
"Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx"
}
}
},
"Integration": {
"Type": "AWS::ApiGatewayV2::Integration",
"Properties": {
"ApiId": { "Ref": "HttpApi" },
"IntegrationType": "HTTP_PROXY",
"IntegrationUri": "https://example.com",
"PayloadFormatVersion": "1.0"
}
},
"Route": {
"Type": "AWS::ApiGatewayV2::Route",
"Properties": {
"ApiId": { "Ref": "HttpApi" },
"RouteKey": "GET /hello",
"AuthorizationType": "JWT",
"AuthorizerId": { "Ref": "Authorizer" },
"Target": { "Fn::Join": ["/", ["integrations", { "Ref": "Integration" }]] }
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "HttpApi" } },
"AuthorizerId": { "Value": { "Ref": "Authorizer" } },
"RouteId": { "Value": { "Ref": "Route" } }
}
}
""";
String stackName = "cfn-apigwv2-authorizer-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
String createXml = apigwv2DescribeStacks(stackName);
String apiId = apigwOutputValue(createXml, "ApiId");
String authorizerId = apigwOutputValue(createXml, "AuthorizerId");
String routeId = apigwOutputValue(createXml, "RouteId");
// The authorizer is a real resource, not dropped by the default-case stub.
getAuthorizers(apiId).body("Items.size()", equalTo(1))
.body("Items[0].AuthorizerId", equalTo(authorizerId))
.body("Items[0].Name", equalTo("cfn-jwt-authorizer"))
.body("Items[0].AuthorizerType", equalTo("JWT"))
.body("Items[0].IdentitySource", hasItem("$request.header.Authorization"))
.body("Items[0].JwtConfiguration.Issuer",
equalTo("https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx"));
// The route's Ref to the authorizer resolved to a real id and was persisted.
getRoutes(apiId).body("Items.size()", equalTo(1))
.body("Items[0].RouteId", equalTo(routeId))
.body("Items[0].AuthorizerId", equalTo(authorizerId));
}
@Test
void createStack_apiGatewayV2AuthorizerAcceptsScalarIdentitySource() {
// IdentitySource is documented as Array of String, but ApiGatewayV2Service.createAuthorizer
// already accepts a bare scalar string too — the CFN provisioner must not be stricter than
// the service it calls, or a template written with the scalar form silently loses its
// identity source instead of erroring or working.
String template = """
{
"Resources": {
"HttpApi": {
"Type": "AWS::ApiGatewayV2::Api",
"Properties": { "Name": "cfn-apigwv2-authz-scalar-api", "ProtocolType": "HTTP" }
},
"Authorizer": {
"Type": "AWS::ApiGatewayV2::Authorizer",
"Properties": {
"ApiId": { "Ref": "HttpApi" },
"Name": "cfn-jwt-authorizer-scalar",
"AuthorizerType": "JWT",
"IdentitySource": "$request.header.Authorization",
"JwtConfiguration": {
"Audience": ["my-client-id"],
"Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx"
}
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "HttpApi" } }
}
}
""";
String stackName = "cfn-apigwv2-authorizer-scalar-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
String apiId = apigwOutputValue(apigwv2DescribeStacks(stackName), "ApiId");
getAuthorizers(apiId).body("Items.size()", equalTo(1))
.body("Items[0].IdentitySource", hasItem("$request.header.Authorization"));
}
@Test
void createStack_apiGatewayV2RouteResolvesAuthorizerIdViaGetAtt() {
// Ref already resolved AuthorizerId via the physical id (covered above); Fn::GetAtt reads
// a separate attributes map that provisionApiGatewayV2Authorizer must also populate, or
// the route ends up wired to the literal placeholder string "Authorizer.AuthorizerId"
// instead of the real id.
String template = """
{
"Resources": {
"HttpApi": {
"Type": "AWS::ApiGatewayV2::Api",
"Properties": { "Name": "cfn-apigwv2-authz-getatt-api", "ProtocolType": "HTTP" }
},
"Authorizer": {
"Type": "AWS::ApiGatewayV2::Authorizer",
"Properties": {
"ApiId": { "Ref": "HttpApi" },
"Name": "cfn-jwt-authorizer-getatt",
"AuthorizerType": "JWT",
"IdentitySource": ["$request.header.Authorization"],
"JwtConfiguration": {
"Audience": ["my-client-id"],
"Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx"
}
}
},
"Integration": {
"Type": "AWS::ApiGatewayV2::Integration",
"Properties": {
"ApiId": { "Ref": "HttpApi" },
"IntegrationType": "HTTP_PROXY",
"IntegrationUri": "https://example.com",
"PayloadFormatVersion": "1.0"
}
},
"Route": {
"Type": "AWS::ApiGatewayV2::Route",
"Properties": {
"ApiId": { "Ref": "HttpApi" },
"RouteKey": "GET /hello",
"AuthorizationType": "JWT",
"AuthorizerId": { "Fn::GetAtt": ["Authorizer", "AuthorizerId"] },
"Target": { "Fn::Join": ["/", ["integrations", { "Ref": "Integration" }]] }
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "HttpApi" } },
"AuthorizerId": { "Value": { "Ref": "Authorizer" } }
}
}
""";
String stackName = "cfn-apigwv2-authorizer-getatt-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
String createXml = apigwv2DescribeStacks(stackName);
String apiId = apigwOutputValue(createXml, "ApiId");
String authorizerId = apigwOutputValue(createXml, "AuthorizerId");
// The route's GetAtt resolved to the real authorizer id, not the literal placeholder.
getRoutes(apiId).body("Items.size()", equalTo(1))
.body("Items[0].AuthorizerId", equalTo(authorizerId));
}
@Test
void deleteStack_apiGatewayV2AuthorizerOnNonStackOwnedApiIsRemoved() {
// The API is created out-of-band (not by this stack) and referenced by a plain literal
// id, the same shape as a template parameter — deliberately not { "Ref": ... } to an
// AWS::ApiGatewayV2::Api resource in this stack. This is the scenario the scoped delete
// path exists for: AWS::ApiGatewayV2::Api's own delete cascades to its authorizers, which
// would make a stack-owned-API test pass even with no delete case for the authorizer at
// all. Here the API survives stack deletion, so the authorizer's removal can only be
// attributed to the authorizer's own scoped delete case actually running.
String apiId = given()
.header("X-Amz-Target", "AmazonApiGatewayV2.CreateApi")
.contentType(APIGWV2_CONTENT_TYPE)
.body("{\"Name\": \"cfn-apigwv2-authz-delete-external-api\", \"ProtocolType\": \"HTTP\"}")
.when()
.post("/")
.then()
.statusCode(201)
.extract().path("ApiId");
String template = """
{
"Resources": {
"Authorizer": {
"Type": "AWS::ApiGatewayV2::Authorizer",
"Properties": {
"ApiId": "%s",
"Name": "cfn-jwt-authorizer-delete",
"AuthorizerType": "JWT",
"IdentitySource": ["$request.header.Authorization"],
"JwtConfiguration": {
"Audience": ["my-client-id"],
"Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx"
}
}
}
}
}
""".formatted(apiId);
String stackName = "cfn-apigwv2-authorizer-delete-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
getAuthorizers(apiId).body("Items.size()", equalTo(1));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
// The API was never part of the stack, so it (and GetAuthorizers against it) still works
// — the authorizer itself must be gone.
getAuthorizers(apiId).body("Items.size()", equalTo(0));
}
// ── SAM AWS::Serverless::Function PackageType: Image dropped by the transform ──
@Test