Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Jay58129108bf4f
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java
index 524ffcb4ea..90e72c47c9 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
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.AwsException;
import org.jboss.logging.Logger;
import java.util.ArrayList;
@@ -73,6 +74,11 @@ class SamTransformProcessor {
// Collect implicit-API routes from function Api events before the functions are expanded.
List<ApiRoute> apiRoutes = collectApiRoutes(samLogicalIds, resources);
+ // Collect explicit HttpApi routes (Function Events of Type HttpApi bound to an
+ // AWS::Serverless::HttpApi via ApiId: {Ref: <logicalId>}) before either side is expanded,
+ // so expansion order between the Function and the HttpApi resource doesn't matter.
+ List<HttpApiRoute> httpApiRoutes = collectHttpApiRoutes(samLogicalIds, resources);
+
for (String logicalId : samLogicalIds) {
JsonNode resDef = resources.get(logicalId);
String type = resDef.path("Type").asText();
@@ -85,6 +91,9 @@ class SamTransformProcessor {
expandServerlessSimpleTable(logicalId, mergeGlobals(globals, "SimpleTable", properties), expandedResources);
case "AWS::Serverless::Api" ->
expandServerlessApi(logicalId, mergeGlobals(globals, "Api", properties), expandedResources);
+ case "AWS::Serverless::HttpApi" ->
+ expandServerlessHttpApi(logicalId, mergeGlobals(globals, "HttpApi", properties),
+ httpApiRoutes, expandedResources);
default -> LOG.debugv("Unsupported SAM resource type: {0} ({1})", type, logicalId);
}
}
@@ -139,6 +148,232 @@ class SamTransformProcessor {
return routes;
}
+ /**
+ * @param noAuthorizer true when this event declares {@code Auth: {Authorizer: NONE}},
+ * overriding the API's {@code DefaultAuthorizer} for this route specifically
+ * (SAM's documented per-event opt-out of the default authorizer).
+ */
+ private record HttpApiRoute(String functionLogicalId, String apiLogicalId, String path, String httpMethod,
+ boolean noAuthorizer) {}
+
+ /**
+ * Collects HttpApi-typed Function events bound to an explicit {@code AWS::Serverless::HttpApi}
+ * via {@code ApiId: {Ref: <logicalId>}}. Events with no {@code ApiId} (SAM's implicit HttpApi,
+ * auto-created rather than declared as its own resource) are intentionally not handled here —
+ * that is a separate expansion path, mirroring how {@link #collectApiRoutes} and
+ * {@link #generateImplicitApi} are already split out from {@link #expandServerlessApi}'s
+ * explicit-REST-API handling.
+ */
+ private List<HttpApiRoute> collectHttpApiRoutes(List<String> samLogicalIds, JsonNode resources) {
+ List<HttpApiRoute> routes = new ArrayList<>();
+ for (String logicalId : samLogicalIds) {
+ JsonNode resDef = resources.get(logicalId);
+ if (!"AWS::Serverless::Function".equals(resDef.path("Type").asText())) {
+ continue;
+ }
+ JsonNode events = resDef.path("Properties").path("Events");
+ if (!events.isObject()) {
+ continue;
+ }
+ Iterator<Map.Entry<String, JsonNode>> it = events.fields();
+ while (it.hasNext()) {
+ JsonNode ev = it.next().getValue();
+ if (!"HttpApi".equals(ev.path("Type").asText())) {
+ continue;
+ }
+ JsonNode p = ev.path("Properties");
+ String apiLogicalId = p.path("ApiId").path("Ref").asText(null);
+ if (apiLogicalId == null) {
+ continue; // no explicit ApiId (implicit HttpApi) — not handled by this path
+ }
+ JsonNode pathNode = p.path("Path");
+ if (!pathNode.isTextual()) {
+ continue; // needs a literal path; skip intrinsics (Ref/Fn::Sub)
+ }
+ JsonNode methodNode = p.path("Method");
+ String method = methodNode.isTextual() ? methodNode.asText() : "ANY";
+ boolean noAuthorizer = "NONE".equals(p.path("Auth").path("Authorizer").asText(null));
+ routes.add(new HttpApiRoute(logicalId, apiLogicalId, pathNode.asText(), method, noAuthorizer));
+ }
+ }
+ return routes;
+ }
+
+ private void expandServerlessHttpApi(String logicalId, JsonNode properties,
+ List<HttpApiRoute> allRoutes, ObjectNode resources) {
+ resources.remove(logicalId);
+
+ ObjectNode apiDef = objectMapper.createObjectNode();
+ apiDef.put("Type", "AWS::ApiGatewayV2::Api");
+ ObjectNode apiProps = objectMapper.createObjectNode();
+ JsonNode name = properties.path("Name");
+ apiProps.set("Name", !name.isMissingNode() ? name.deepCopy() : objectMapper.getNodeFactory().textNode(logicalId));
+ apiProps.put("ProtocolType", "HTTP");
+ copyIfPresent(properties, "Description", apiProps);
+ apiDef.set("Properties", apiProps);
+ resources.set(logicalId, apiDef);
+
+ // Auth.Authorizers -> one AWS::ApiGatewayV2::Authorizer per entry, keyed by SAM authorizer
+ // name so routes referencing Auth.DefaultAuthorizer (the only form handled here — per-route
+ // Auth overrides are not expanded) can resolve the logical id to Ref.
+ Map<String, String> authorizerLogicalIdsByName = new java.util.LinkedHashMap<>();
+ JsonNode auth = properties.path("Auth");
+ JsonNode authorizers = auth.path("Authorizers");
+ if (authorizers.isObject()) {
+ Iterator<Map.Entry<String, JsonNode>> it = authorizers.fields();
+ while (it.hasNext()) {
+ Map.Entry<String, JsonNode> entry = it.next();
+ String authorizerName = entry.getKey();
+ String authorizerLogicalId = uniqueId(logicalId + sanitize(authorizerName) + "Authorizer", resources);
+ resources.set(authorizerLogicalId, buildHttpApiAuthorizer(logicalId, authorizerName, entry.getValue()));
+ authorizerLogicalIdsByName.put(authorizerName, authorizerLogicalId);
+ }
+ }
+ String defaultAuthorizerName = auth.path("DefaultAuthorizer").asText(null);
+ String defaultAuthorizerLogicalId = defaultAuthorizerName != null
+ ? authorizerLogicalIdsByName.get(defaultAuthorizerName) : null;
+
+ String stageLogicalId = uniqueId(logicalId + "ApiDefaultStage", resources);
+ ObjectNode stageDef = objectMapper.createObjectNode();
+ stageDef.put("Type", "AWS::ApiGatewayV2::Stage");
+ ObjectNode stageProps = objectMapper.createObjectNode();
+ stageProps.set("ApiId", ref(logicalId));
+ stageProps.put("StageName", "$default");
+ stageProps.put("AutoDeploy", true);
+ stageDef.set("Properties", stageProps);
+ resources.set(stageLogicalId, stageDef);
+
+ for (HttpApiRoute route : allRoutes) {
+ if (!logicalId.equals(route.apiLogicalId())) {
+ continue;
+ }
+ expandHttpApiRoute(logicalId, route, defaultAuthorizerLogicalId, resources);
+ }
+ }
+
+ private ObjectNode buildHttpApiAuthorizer(String apiLogicalId, String authorizerName, JsonNode samAuthorizer) {
+ ObjectNode authDef = objectMapper.createObjectNode();
+ authDef.put("Type", "AWS::ApiGatewayV2::Authorizer");
+ ObjectNode authProps = objectMapper.createObjectNode();
+ authProps.set("ApiId", ref(apiLogicalId));
+ authProps.put("Name", authorizerName);
+ authProps.put("AuthorizerType", "JWT");
+
+ JsonNode jwtConfig = samAuthorizer.path("JwtConfiguration");
+ if (!jwtConfig.isObject()) {
+ throw new AwsException("ValidationError",
+ "OAuth2 Authorizer must define 'JwtConfiguration'; authorizer " + authorizerName, 400);
+ }
+
+ authProps.set("IdentitySource", resolveIdentitySource(authorizerName, samAuthorizer));
+
+ ObjectNode jwtProps = objectMapper.createObjectNode();
+ JsonNode issuer = fieldIgnoreCase(jwtConfig, "issuer");
+ if (!issuer.isMissingNode()) {
+ jwtProps.set("Issuer", issuer.deepCopy());
+ }
+ JsonNode audience = fieldIgnoreCase(jwtConfig, "audience");
+ if (audience.isArray()) {
+ jwtProps.set("Audience", audience.deepCopy());
+ }
+ authProps.set("JwtConfiguration", jwtProps);
+
+ authDef.set("Properties", authProps);
+ return authDef;
+ }
+
+ /**
+ * SAM's {@code _get_jwt_configuration} lower-cases every key of the {@code JwtConfiguration}
+ * map before reading it ({@code {k.lower(): v for k, v in props.items()}} in
+ * samtranslator/model/apigatewayv2.py), so any casing of {@code issuer}/{@code audience} is
+ * accepted, not just the two spellings the docs happen to show.
+ */
+ private JsonNode fieldIgnoreCase(JsonNode node, String fieldName) {
+ Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
+ while (fields.hasNext()) {
+ Map.Entry<String, JsonNode> field = fields.next();
+ if (field.getKey().equalsIgnoreCase(fieldName)) {
+ return field.getValue();
+ }
+ }
+ return objectMapper.missingNode();
+ }
+
+ /**
+ * Resolves the SAM authorizer's {@code IdentitySource}, accepting either the documented array
+ * form or a single scalar string — mirroring
+ * {@code CloudFormationResourceProvisioner.resolveIdentitySource}, since the raw
+ * {@code AWS::ApiGatewayV2::Authorizer} resource this expands to accepts both. SAM itself
+ * rejects a JWT authorizer with no {@code IdentitySource} ({@code _validate_jwt_authorizer} in
+ * samtranslator/model/apigatewayv2.py), so an absent or empty value is a template error here
+ * too.
+ */
+ private ArrayNode resolveIdentitySource(String authorizerName, JsonNode samAuthorizer) {
+ ArrayNode identitySource = objectMapper.createArrayNode();
+ JsonNode raw = samAuthorizer.path("IdentitySource");
+ if (raw.isTextual()) {
+ identitySource.add(raw.asText());
+ } else if (raw.isArray() && !raw.isEmpty()) {
+ raw.forEach(v -> identitySource.add(v.asText()));
+ } else {
+ throw new AwsException("ValidationError",
+ "OAuth2 Authorizer must define 'IdentitySource'; authorizer " + authorizerName, 400);
+ }
+ return identitySource;
+ }
+
+ private void expandHttpApiRoute(String apiLogicalId, HttpApiRoute route,
+ String defaultAuthorizerLogicalId, ObjectNode resources) {
+ String integrationLogicalId = uniqueId(
+ apiLogicalId + "Integration" + sanitize(route.functionLogicalId()), resources);
+ ObjectNode integDef = objectMapper.createObjectNode();
+ integDef.put("Type", "AWS::ApiGatewayV2::Integration");
+ ObjectNode integProps = objectMapper.createObjectNode();
+ integProps.set("ApiId", ref(apiLogicalId));
+ integProps.put("IntegrationType", "AWS_PROXY");
+ integProps.set("IntegrationUri", lambdaInvokeUri(route.functionLogicalId()));
+ integProps.put("PayloadFormatVersion", "2.0");
+ integDef.set("Properties", integProps);
+ resources.set(integrationLogicalId, integDef);
+
+ String routeKey = route.httpMethod().toUpperCase() + " " + route.path();
+ String routeLogicalId = uniqueId(
+ apiLogicalId + "Route" + sanitize(route.functionLogicalId()) + sanitize(route.path()), resources);
+ ObjectNode routeDef = objectMapper.createObjectNode();
+ routeDef.put("Type", "AWS::ApiGatewayV2::Route");
+ ObjectNode routeProps = objectMapper.createObjectNode();
+ routeProps.set("ApiId", ref(apiLogicalId));
+ routeProps.put("RouteKey", routeKey);
+ if (defaultAuthorizerLogicalId != null && !route.noAuthorizer()) {
+ routeProps.put("AuthorizationType", "JWT");
+ routeProps.set("AuthorizerId", ref(defaultAuthorizerLogicalId));
+ } else {
+ routeProps.put("AuthorizationType", "NONE");
+ }
+ ObjectNode join = objectMapper.createObjectNode();
+ ArrayNode joinArgs = objectMapper.createArrayNode();
+ joinArgs.add("/");
+ ArrayNode joinValues = objectMapper.createArrayNode();
+ joinValues.add("integrations");
+ joinValues.add(ref(integrationLogicalId));
+ joinArgs.add(joinValues);
+ join.set("Fn::Join", joinArgs);
+ routeProps.set("Target", join);
+ routeDef.set("Properties", routeProps);
+ resources.set(routeLogicalId, routeDef);
+
+ String permissionLogicalId = uniqueId(
+ route.functionLogicalId() + "HttpApiPermission" + sanitize(apiLogicalId), resources);
+ ObjectNode perm = objectMapper.createObjectNode();
+ perm.put("Type", "AWS::Lambda::Permission");
+ ObjectNode permProps = objectMapper.createObjectNode();
+ permProps.set("FunctionName", ref(route.functionLogicalId()));
+ permProps.put("Action", "lambda:InvokeFunction");
+ permProps.put("Principal", "apigateway.amazonaws.com");
+ perm.set("Properties", permProps);
+ resources.set(permissionLogicalId, perm);
+ }
+
private void generateImplicitApi(List<ApiRoute> routes, JsonNode globals, ObjectNode resources) {
// Collision-safe: reuse "ServerlessRestApi" when free, otherwise a suffixed id, so an existing
// resource with that logical id is never silently overwritten.
@@ -570,6 +805,9 @@ class SamTransformProcessor {
case "Api" ->
LOG.debugv("SAM Api event for {0}.{1} — handled by Api resource",
functionLogicalId, eventName);
+ case "HttpApi" ->
+ LOG.debugv("SAM HttpApi event for {0}.{1} — handled by HttpApi resource",
+ functionLogicalId, eventName);
default ->
LOG.debugv("SAM event type {0} for {1}.{2} not expanded",
eventType, functionLogicalId, eventName);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index d62fa4a299..74d1da0649 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -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