fix(cloudformation): expand AWS::Serverless::HttpApi via SAM transform (#2146)

* fix(cloudformation): expand AWS::Serverless::HttpApi via SAM transform

SamTransformProcessor's switch on SAM resource types only handled
AWS::Serverless::Function, AWS::Serverless::SimpleTable, and
AWS::Serverless::Api (REST, v1) — AWS::Serverless::HttpApi fell into the
default branch and was silently dropped from the expanded template, along
with any Auth.Authorizers/DefaultAuthorizer config and any HttpApi-typed
Events on a sibling Function. A stack using AWS::Serverless::HttpApi
reported CREATE_COMPLETE with a synthesized physical id for the resource,
but no AWS::ApiGatewayV2::Api ever existed.

Adds expandServerlessHttpApi, mirroring the existing explicit-API pattern
(expandServerlessApi for REST v1) rather than the implicit-API path
(generateImplicitApi/collectApiRoutes), scoped to the explicit
AWS::Serverless::HttpApi + Function Events ApiId: {Ref: ...} form. For
each explicit HttpApi resource this synthesizes a real
AWS::ApiGatewayV2::Api, a $default auto-deploy Stage, one
AWS::ApiGatewayV2::Authorizer per Auth.Authorizers entry (mapping SAM's
mixed-case JwtConfiguration.issuer/audience onto the PascalCase
Issuer/Audience the raw CFN resource expects), and — for every Function
event bound to that API — an AWS_PROXY Integration, a Route wired to
Auth.DefaultAuthorizer when present, and a Lambda::Permission.

Implicit HttpApi (a Function's HttpApi event with no ApiId, where SAM
auto-creates the API) is intentionally out of scope here, matching how
this file already keeps generateImplicitApi/collectApiRoutes as a separate
concern from expandServerlessApi's explicit-resource handling.

Full JWT-authorizer enforcement additionally requires #1758
(AWS::ApiGatewayV2::Authorizer CloudFormation provisioning) — without it,
the Authorizer resource this transform synthesizes is itself dropped by
the provisioner's default branch, the same way it is for a raw (non-SAM)
template. Verified locally with both fixes applied together; #1758 is a
separate PR since the bugs are independent (raw-CFN provisioning vs. SAM
transform expansion) even though a SAM+JWT-authorizer template needs both.

Fixes #1759.

* fix(cloudformation): honor per-event Auth: {Authorizer: NONE} on HttpApi events

expandServerlessHttpApi applied the HttpApi's Auth.DefaultAuthorizer to every
route uniformly, ignoring SAM's documented per-event override
(Events.<Name>.Properties.Auth.Authorizer: NONE) that lets a specific route
opt out of the default authorizer — e.g. a route whose auth is handled
inside the application itself and needs a missing/invalid token to still
reach the handler rather than being rejected by the gateway.

HttpApiRoute now carries whether its event declared Auth.Authorizer: NONE,
collected in collectHttpApiRoutes alongside the existing path/method
fields, and expandHttpApiRoute skips wiring the default authorizer for
routes that opted out.

Found while validating #1759's fix against a template with this exact
pattern (one route using the default JWT authorizer, a second explicitly
set to Authorizer: NONE) — the original fix would have silently applied
the default authorizer to both.

* fix(cloudformation): forward SAM authorizer IdentitySource for HttpApi JWT authorizers

expandServerlessHttpApi's buildHttpApiAuthorizer hardcoded IdentitySource to
$request.header.Authorization regardless of what the SAM template's
Authorizers.<Name>.IdentitySource declared, silently overriding any
non-default source (e.g. $request.querystring.token) with the header form.

CloudFormationResourceProvisioner.resolveIdentitySource and
ApiGatewayExecuteController already support arbitrary identity sources,
including querystring, for raw (non-SAM) AWS::ApiGatewayV2::Authorizer
resources — this closes the same gap for the SAM transform, accepting either
the documented array form or a scalar string, matching the raw provisioner's
leniency.

Verified by reverting the fix and confirming
createStack_samHttpApiAuthorizerHonorsCustomIdentitySource fails.

* fix(cloudformation): reject SAM JWT authorizer with no IdentitySource

Real sam deploy rejects a JWT authorizer that omits IdentitySource
(_validate_jwt_authorizer in samtranslator/model/apigatewayv2.py) rather
than defaulting it. This transform was silently defaulting to
$request.header.Authorization instead, so a template real SAM refuses
would pass here quietly.

* fix(cloudformation): reject SAM HttpApi authorizer with no JwtConfiguration, honor case-insensitive Issuer/Audience

SAM's _validate_jwt_authorizer checks JwtConfiguration before IdentitySource,
rejecting a template that omits it. buildHttpApiAuthorizer treated it as
optional, silently producing an authorizer that would never validate a token
for real sam deploy. It now rejects in the same order SAM does.

SAM's _get_jwt_configuration also lower-cases every JwtConfiguration key
before reading it, so any casing of issuer/audience is accepted, not just the
two spellings the docs happen to show. Only the lowercase form was read here,
so a template using another casing silently produced an authorizer with an
empty JwtConfiguration instead of an error.
This commit is contained in:
Jay authored and GitHub committed 2026-08-14 22:03:23 -04:00
1 parent 80d1dc732e
commit 58129108bf
2 files changed
+726

No files matched your search

@@ -7051,6 +7051,494 @@ class CloudFormationIntegrationTest {
.body("Configuration.ImageConfigResponse.ImageConfig.WorkingDirectory", equalTo("/var/task"));
}
// ── Issue #1759: SAM AWS::Serverless::HttpApi transform not expanded ──────
@Test
void createStack_samHttpApiExpandsToRealApiRouteAndAuthorizer() {
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Zip",
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({ statusCode: 200, body: 'hello' });",
"Events": {
"HelloEvent": {
"Type": "HttpApi",
"Properties": {
"ApiId": { "Ref": "MyHttpApi" },
"Path": "/hello",
"Method": "get"
}
}
}
}
},
"MyHttpApi": {
"Type": "AWS::Serverless::HttpApi",
"Properties": {
"Auth": {
"Authorizers": {
"MyAuthorizer": {
"IdentitySource": "$request.header.Authorization",
"JwtConfiguration": {
"issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx",
"audience": ["my-client-id"]
}
}
},
"DefaultAuthorizer": "MyAuthorizer"
}
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "MyHttpApi" } }
}
}
""";
String stackName = "cfn-sam-httpapi-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
String createXml = apigwv2DescribeStacks(stackName);
String apiId = apigwOutputValue(createXml, "ApiId");
// The AWS::Serverless::HttpApi transform resource is a real ApiGatewayV2 API,
// not silently dropped by the SAM-type default branch.
given()
.header("X-Amz-Target", "AmazonApiGatewayV2.GetApis")
.contentType(APIGWV2_CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Items.findAll { it.ApiId == '" + apiId + "' }.size()", equalTo(1));
// The Auth.Authorizers entry expanded to a real JWT authorizer.
String authorizerId = getAuthorizers(apiId)
.body("Items.size()", equalTo(1))
.body("Items[0].Name", equalTo("MyAuthorizer"))
.body("Items[0].AuthorizerType", equalTo("JWT"))
.body("Items[0].JwtConfiguration.Issuer",
equalTo("https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx"))
.extract().path("Items[0].AuthorizerId");
// The Function's HttpApi event expanded to a route wired to the DefaultAuthorizer,
// backed by an AWS_PROXY integration targeting the function.
getRoutes(apiId).body("Items.size()", equalTo(1))
.body("Items[0].RouteKey", equalTo("GET /hello"))
.body("Items[0].AuthorizationType", equalTo("JWT"))
.body("Items[0].AuthorizerId", equalTo(authorizerId));
getIntegrations(apiId).body("Items.size()", equalTo(1))
.body("Items[0].IntegrationType", equalTo("AWS_PROXY"));
getStages(apiId).body("Items.size()", equalTo(1))
.body("Items[0].StageName", equalTo("$default"))
.body("Items[0].AutoDeploy", equalTo(true));
}
@Test
void createStack_samHttpApiAuthorizerHonorsCustomIdentitySource() {
// SAM's Authorizers.<Name>.IdentitySource lets a JWT authorizer read the token from
// somewhere other than the default Authorization header — e.g. a query-string token,
// the same case CloudFormationResourceProvisioner/ApiGatewayExecuteController already
// support end-to-end for raw (non-SAM) templates. The SAM transform must forward it
// rather than always emitting the header default.
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Zip",
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({ statusCode: 200, body: 'hello' });",
"Events": {
"HelloEvent": {
"Type": "HttpApi",
"Properties": {
"ApiId": { "Ref": "MyHttpApi" },
"Path": "/hello",
"Method": "get"
}
}
}
}
},
"MyHttpApi": {
"Type": "AWS::Serverless::HttpApi",
"Properties": {
"Auth": {
"Authorizers": {
"MyAuthorizer": {
"IdentitySource": "$request.querystring.token",
"JwtConfiguration": {
"issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx",
"audience": ["my-client-id"]
}
}
},
"DefaultAuthorizer": "MyAuthorizer"
}
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "MyHttpApi" } }
}
}
""";
String stackName = "cfn-sam-httpapi-identitysource-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
String createXml = apigwv2DescribeStacks(stackName);
String apiId = apigwOutputValue(createXml, "ApiId");
// The scalar IdentitySource from the SAM template is forwarded, not overridden with the
// $request.header.Authorization default.
getAuthorizers(apiId)
.body("Items.size()", equalTo(1))
.body("Items[0].IdentitySource", hasItems("$request.querystring.token"));
}
@Test
void createStack_samHttpApiAuthorizerMissingIdentitySourceIsRejected() {
// Real SAM's _validate_jwt_authorizer rejects a JWT authorizer with no IdentitySource
// rather than defaulting it — CreateStack must fail the same way instead of silently
// provisioning an authorizer that would never have deployed for real.
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Zip",
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({ statusCode: 200, body: 'hello' });",
"Events": {
"HelloEvent": {
"Type": "HttpApi",
"Properties": {
"ApiId": { "Ref": "MyHttpApi" },
"Path": "/hello",
"Method": "get"
}
}
}
}
},
"MyHttpApi": {
"Type": "AWS::Serverless::HttpApi",
"Properties": {
"Auth": {
"Authorizers": {
"MyAuthorizer": {
"JwtConfiguration": {
"issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx",
"audience": ["my-client-id"]
}
}
},
"DefaultAuthorizer": "MyAuthorizer"
}
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "MyHttpApi" } }
}
}
""";
String stackName = "cfn-sam-httpapi-missing-identitysource-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_FAILED</StackStatus>"))
.body(containsString("IdentitySource"));
}
@Test
void createStack_samHttpApiAuthorizerMissingJwtConfigurationIsRejected() {
// _validate_jwt_authorizer checks JwtConfiguration before IdentitySource, and real SAM
// rejects a template missing it rather than provisioning an authorizer that would never
// validate a token.
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Zip",
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({ statusCode: 200, body: 'hello' });",
"Events": {
"HelloEvent": {
"Type": "HttpApi",
"Properties": {
"ApiId": { "Ref": "MyHttpApi" },
"Path": "/hello",
"Method": "get"
}
}
}
}
},
"MyHttpApi": {
"Type": "AWS::Serverless::HttpApi",
"Properties": {
"Auth": {
"Authorizers": {
"MyAuthorizer": {
"IdentitySource": "$request.header.Authorization"
}
},
"DefaultAuthorizer": "MyAuthorizer"
}
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "MyHttpApi" } }
}
}
""";
String stackName = "cfn-sam-httpapi-missing-jwtconfiguration-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_FAILED</StackStatus>"))
.body(containsString("JwtConfiguration"));
}
@Test
void createStack_samHttpApiAuthorizerJwtConfigurationKeysAreCaseInsensitive() {
// SAM's _get_jwt_configuration lower-cases every JwtConfiguration key before reading it, so
// any casing is accepted, not just lowercase-OpenAPI or uppercase-CFN. AUDIENCE and Issuer
// (neither the documented lowercase nor the documented uppercase spelling) exercise that a
// true case-insensitive fold is happening rather than a check against two hardcoded spellings.
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Zip",
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({ statusCode: 200, body: 'hello' });",
"Events": {
"HelloEvent": {
"Type": "HttpApi",
"Properties": {
"ApiId": { "Ref": "MyHttpApi" },
"Path": "/hello",
"Method": "get"
}
}
}
}
},
"MyHttpApi": {
"Type": "AWS::Serverless::HttpApi",
"Properties": {
"Auth": {
"Authorizers": {
"MyAuthorizer": {
"IdentitySource": "$request.header.Authorization",
"JwtConfiguration": {
"Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx",
"AUDIENCE": ["my-client-id"]
}
}
},
"DefaultAuthorizer": "MyAuthorizer"
}
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "MyHttpApi" } }
}
}
""";
String stackName = "cfn-sam-httpapi-caseinsensitive-jwtconfig-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
String createXml = apigwv2DescribeStacks(stackName);
String apiId = apigwOutputValue(createXml, "ApiId");
getAuthorizers(apiId)
.body("Items.size()", equalTo(1))
.body("Items[0].JwtConfiguration.Issuer",
equalTo("https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx"))
.body("Items[0].JwtConfiguration.Audience", contains("my-client-id"));
}
@Test
void createStack_samHttpApiPerEventAuthNoneOverridesDefaultAuthorizer() {
// Mirrors a function with two HttpApi events on the same explicit HttpApi: one route picks
// up Auth.DefaultAuthorizer, the other opts out via Auth: {Authorizer: NONE} (SAM's documented
// per-event override) — e.g. a protocol whose auth is handled inside the app itself, which
// needs a missing/invalid token to still reach the handler rather than be rejected by the
// gateway's authorizer.
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Zip",
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({ statusCode: 200, body: 'hello' });",
"Events": {
"PingEvent": {
"Type": "HttpApi",
"Properties": {
"ApiId": { "Ref": "MyHttpApi" },
"Path": "/v1/ping",
"Method": "get"
}
},
"OpenEvent": {
"Type": "HttpApi",
"Properties": {
"ApiId": { "Ref": "MyHttpApi" },
"Path": "/open",
"Method": "any",
"Auth": { "Authorizer": "NONE" }
}
}
}
}
},
"MyHttpApi": {
"Type": "AWS::Serverless::HttpApi",
"Properties": {
"Auth": {
"Authorizers": {
"MyAuthorizer": {
"IdentitySource": "$request.header.Authorization",
"JwtConfiguration": {
"issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx",
"audience": ["my-client-id"]
}
}
},
"DefaultAuthorizer": "MyAuthorizer"
}
}
}
},
"Outputs": {
"ApiId": { "Value": { "Ref": "MyHttpApi" } }
}
}
""";
String stackName = "cfn-sam-httpapi-per-event-auth-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
String apiId = apigwOutputValue(apigwv2DescribeStacks(stackName), "ApiId");
getRoutes(apiId).body("Items.size()", equalTo(2))
.body("Items.findAll { it.RouteKey == 'GET /v1/ping' }.AuthorizationType", hasItem("JWT"))
.body("Items.findAll { it.RouteKey == 'ANY /open' }.AuthorizationType", hasItem("NONE"));
}
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
@Test