mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): preserve SAM implicit API auth (#3501)
This commit is contained in:
1 parent
99bc6c977d
commit
8963c665eb
3 files changed
+538
-4
No files matched your search
+163
-4
@@ -148,7 +148,7 @@ class SamTransformProcessor {
|
||||
return template.path("Globals");
|
||||
}
|
||||
|
||||
private record ApiRoute(String functionLogicalId, String path, String httpMethod) {}
|
||||
private record ApiRoute(String functionLogicalId, String path, String httpMethod, String authorizerName) {}
|
||||
|
||||
private List<ApiRoute> collectApiRoutes(List<String> samLogicalIds, JsonNode resources) {
|
||||
List<ApiRoute> routes = new ArrayList<>();
|
||||
@@ -178,7 +178,8 @@ class SamTransformProcessor {
|
||||
}
|
||||
JsonNode methodNode = p.path("Method");
|
||||
String method = methodNode.isTextual() ? methodNode.asText() : "ANY";
|
||||
routes.add(new ApiRoute(logicalId, pathNode.asText(), method));
|
||||
String authorizerName = p.path("Auth").path("Authorizer").asText(null);
|
||||
routes.add(new ApiRoute(logicalId, pathNode.asText(), method, authorizerName));
|
||||
}
|
||||
}
|
||||
return routes;
|
||||
@@ -546,6 +547,143 @@ class SamTransformProcessor {
|
||||
resources.set(permissionLogicalId, perm);
|
||||
}
|
||||
|
||||
private Map<String, String> expandImplicitRestApiAuthorizers(String apiId, JsonNode auth,
|
||||
ObjectNode resources) {
|
||||
Map<String, String> logicalIds = new java.util.LinkedHashMap<>();
|
||||
JsonNode authorizers = auth.path("Authorizers");
|
||||
if (authorizers.isTextual()) {
|
||||
if (!"AWS_IAM".equals(authorizers.asText())) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM Api Auth.Authorizers must be AWS_IAM or an authorizer map.", 400);
|
||||
}
|
||||
return logicalIds;
|
||||
}
|
||||
if (!authorizers.isObject()) {
|
||||
return logicalIds;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> it = authorizers.fields();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = it.next();
|
||||
String name = entry.getKey();
|
||||
JsonNode config = entry.getValue();
|
||||
String payloadType = config.path("FunctionPayloadType").asText("TOKEN");
|
||||
if (!"REQUEST".equals(payloadType)) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM implicit REST API authorizer " + name + " uses unsupported FunctionPayloadType "
|
||||
+ payloadType + "; Floci currently supports REQUEST authorizers only.", 400);
|
||||
}
|
||||
JsonNode functionArn = config.get("FunctionArn");
|
||||
if (functionArn == null || functionArn.isNull() || functionArn.isMissingNode()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM REQUEST authorizer " + name + " must define FunctionArn.", 400);
|
||||
}
|
||||
JsonNode identity = config.path("Identity");
|
||||
if (!identity.isObject()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM REQUEST authorizer " + name + " must define Identity.", 400);
|
||||
}
|
||||
if (config.has("FunctionInvokeRole") && !config.path("FunctionInvokeRole").isNull()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM REQUEST authorizer " + name + " uses FunctionInvokeRole, which Floci does not "
|
||||
+ "model yet; refusing to drop authorizer credentials silently.", 400);
|
||||
}
|
||||
|
||||
String logicalId = uniqueId(apiId + sanitize(name) + "Authorizer", resources);
|
||||
ObjectNode def = objectMapper.createObjectNode();
|
||||
def.put("Type", "AWS::ApiGateway::Authorizer");
|
||||
ObjectNode props = objectMapper.createObjectNode();
|
||||
props.set("RestApiId", ref(apiId));
|
||||
props.put("Name", name);
|
||||
props.put("Type", "REQUEST");
|
||||
props.set("AuthorizerUri", authorizerInvokeUri(functionArn));
|
||||
|
||||
String identitySource = requestAuthorizerIdentitySource(identity);
|
||||
if (identitySource != null) {
|
||||
props.put("IdentitySource", identitySource);
|
||||
}
|
||||
JsonNode reauthorizeEvery = identity.path("ReauthorizeEvery");
|
||||
if (!reauthorizeEvery.isMissingNode() && !reauthorizeEvery.isNull()) {
|
||||
if (!reauthorizeEvery.isIntegralNumber()
|
||||
|| reauthorizeEvery.asInt() < 0 || reauthorizeEvery.asInt() > 3600) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM REQUEST authorizer " + name
|
||||
+ " Identity.ReauthorizeEvery must be an integer from 0 to 3600.", 400);
|
||||
}
|
||||
props.set("AuthorizerResultTtlInSeconds", reauthorizeEvery.deepCopy());
|
||||
}
|
||||
def.set("Properties", props);
|
||||
resources.set(logicalId, def);
|
||||
logicalIds.put(name, logicalId);
|
||||
|
||||
if (!config.path("DisableFunctionDefaultPermissions").asBoolean(false)) {
|
||||
ObjectNode permission = objectMapper.createObjectNode();
|
||||
permission.put("Type", "AWS::Lambda::Permission");
|
||||
ObjectNode permissionProps = objectMapper.createObjectNode();
|
||||
permissionProps.set("FunctionName", functionArn.deepCopy());
|
||||
permissionProps.put("Action", "lambda:InvokeFunction");
|
||||
permissionProps.put("Principal", "apigateway.amazonaws.com");
|
||||
permission.set("Properties", permissionProps);
|
||||
resources.set(uniqueId(logicalId + "Permission", resources), permission);
|
||||
}
|
||||
}
|
||||
return logicalIds;
|
||||
}
|
||||
|
||||
private String requestAuthorizerIdentitySource(JsonNode identity) {
|
||||
if (!identity.isObject()) {
|
||||
return null;
|
||||
}
|
||||
List<String> sources = new ArrayList<>();
|
||||
appendIdentitySources(identity.path("Headers"), "method.request.header.", sources);
|
||||
appendIdentitySources(identity.path("QueryStrings"), "method.request.querystring.", sources);
|
||||
appendIdentitySources(identity.path("StageVariables"), "stageVariables.", sources);
|
||||
appendIdentitySources(identity.path("Context"), "context.", sources);
|
||||
return sources.isEmpty() ? null : String.join(",", sources);
|
||||
}
|
||||
|
||||
private void appendIdentitySources(JsonNode values, String prefix, List<String> target) {
|
||||
if (!values.isArray()) {
|
||||
return;
|
||||
}
|
||||
for (JsonNode value : values) {
|
||||
if (value.isTextual() && !value.asText().isBlank()) {
|
||||
target.add(prefix + value.asText());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode authorizerInvokeUri(JsonNode functionArn) {
|
||||
ObjectNode sub = objectMapper.createObjectNode();
|
||||
ArrayNode args = objectMapper.createArrayNode();
|
||||
args.add("arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${AuthorizerArn}/invocations");
|
||||
ObjectNode vars = objectMapper.createObjectNode();
|
||||
vars.set("AuthorizerArn", functionArn.deepCopy());
|
||||
args.add(vars);
|
||||
sub.set("Fn::Sub", args);
|
||||
return sub;
|
||||
}
|
||||
|
||||
private void applyImplicitRestApiAuthorization(ObjectNode methodProperties, String requestedAuthorizer,
|
||||
String defaultAuthorizer,
|
||||
Map<String, String> authorizerLogicalIds) {
|
||||
String effective = requestedAuthorizer != null ? requestedAuthorizer : defaultAuthorizer;
|
||||
if (effective == null || "NONE".equals(effective)) {
|
||||
methodProperties.put("AuthorizationType", "NONE");
|
||||
return;
|
||||
}
|
||||
if ("AWS_IAM".equals(effective)) {
|
||||
methodProperties.put("AuthorizationType", "AWS_IAM");
|
||||
return;
|
||||
}
|
||||
String logicalId = authorizerLogicalIds.get(effective);
|
||||
if (logicalId == null) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM Api authorizer '" + effective + "' is not defined in Auth.Authorizers.", 400);
|
||||
}
|
||||
methodProperties.put("AuthorizationType", "CUSTOM");
|
||||
methodProperties.set("AuthorizerId", ref(logicalId));
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -563,6 +701,20 @@ class SamTransformProcessor {
|
||||
api.set("Properties", apiProps);
|
||||
resources.set(apiId, api);
|
||||
|
||||
JsonNode auth = globals.path("Api").path("Auth");
|
||||
Map<String, String> authorizerLogicalIds = expandImplicitRestApiAuthorizers(apiId, auth, resources);
|
||||
String defaultAuthorizer = auth.path("DefaultAuthorizer").asText(null);
|
||||
if (defaultAuthorizer == null && auth.path("Authorizers").isTextual()
|
||||
&& "AWS_IAM".equals(auth.path("Authorizers").asText())) {
|
||||
defaultAuthorizer = "AWS_IAM";
|
||||
}
|
||||
if (defaultAuthorizer != null && !"AWS_IAM".equals(defaultAuthorizer)
|
||||
&& !"NONE".equals(defaultAuthorizer)
|
||||
&& !authorizerLogicalIds.containsKey(defaultAuthorizer)) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM Api authorizer '" + defaultAuthorizer + "' is not defined in Auth.Authorizers.", 400);
|
||||
}
|
||||
|
||||
Map<String, String> pathToResource = new java.util.LinkedHashMap<>();
|
||||
List<String> methodIds = new ArrayList<>();
|
||||
java.util.Set<String> permissionFns = new java.util.LinkedHashSet<>();
|
||||
@@ -575,14 +727,15 @@ class SamTransformProcessor {
|
||||
}
|
||||
String resourceId = ensureResourcePath(apiId, r.path(), pathToResource, resources);
|
||||
|
||||
String methodLogicalId = uniqueId(apiId + "Method" + sanitize(r.path()) + capitalize(method.toLowerCase()), resources);
|
||||
String methodLogicalId = uniqueId(
|
||||
apiId + "Method" + sanitize(r.path()) + capitalize(method.toLowerCase()), resources);
|
||||
ObjectNode m = objectMapper.createObjectNode();
|
||||
m.put("Type", "AWS::ApiGateway::Method");
|
||||
ObjectNode mp = objectMapper.createObjectNode();
|
||||
mp.set("RestApiId", ref(apiId));
|
||||
mp.set("ResourceId", resourceId == null ? getAtt(apiId, "RootResourceId") : ref(resourceId));
|
||||
mp.put("HttpMethod", method);
|
||||
mp.put("AuthorizationType", "NONE");
|
||||
applyImplicitRestApiAuthorization(mp, r.authorizerName(), defaultAuthorizer, authorizerLogicalIds);
|
||||
ObjectNode integ = objectMapper.createObjectNode();
|
||||
integ.put("Type", "AWS_PROXY");
|
||||
integ.put("IntegrationHttpMethod", "POST");
|
||||
@@ -1068,6 +1221,12 @@ class SamTransformProcessor {
|
||||
}
|
||||
|
||||
private void expandServerlessApi(String logicalId, JsonNode properties, ObjectNode resources) {
|
||||
JsonNode auth = properties.path("Auth");
|
||||
if (auth.isObject() && !auth.isEmpty()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"SAM AWS::Serverless::Api Auth is not supported for explicit REST APIs yet; "
|
||||
+ "Floci refuses to drop the authorization configuration silently.", 400);
|
||||
}
|
||||
resources.remove(logicalId);
|
||||
|
||||
ObjectNode apiDef = objectMapper.createObjectNode();
|
||||
|
||||
+99
@@ -470,6 +470,105 @@ class SamTransformIntegrationTest {
|
||||
assertThat(resourcesXml, not(containsString("AWS::Serverless::Api")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void samImplicitApi_globalRequestAuthorizerCreatesAndWiresApiGatewayAuthorizer() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "sam-api-auth-" + suffix;
|
||||
String apiName = "sam-api-auth-" + suffix;
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String template = """
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: AWS::Serverless-2016-10-31
|
||||
Globals:
|
||||
Api:
|
||||
Name: %s
|
||||
Auth:
|
||||
DefaultAuthorizer: MyAuth
|
||||
Authorizers:
|
||||
MyAuth:
|
||||
FunctionPayloadType: REQUEST
|
||||
FunctionArn: !GetAtt AuthFn.Arn
|
||||
Identity:
|
||||
Headers: [Authorization]
|
||||
ReauthorizeEvery: 0
|
||||
Resources:
|
||||
ApiFn:
|
||||
Type: AWS::Serverless::Function
|
||||
Properties:
|
||||
Handler: index.handler
|
||||
Runtime: nodejs22.x
|
||||
InlineCode: "exports.handler = async () => ({statusCode:200, body:'ok'});"
|
||||
Events:
|
||||
Get:
|
||||
Type: Api
|
||||
Properties:
|
||||
Path: /secret
|
||||
Method: get
|
||||
AuthFn:
|
||||
Type: AWS::Serverless::Function
|
||||
Properties:
|
||||
Handler: index.handler
|
||||
Runtime: nodejs22.x
|
||||
InlineCode: >-
|
||||
exports.handler = async () => ({principalId:'p',
|
||||
policyDocument:{Version:'2012-10-17', Statement:[]}});
|
||||
""".formatted(apiName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
waitForStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
String apiId = given()
|
||||
.when()
|
||||
.get("/restapis")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.find { it.name == '" + apiName + "' }.name", equalTo(apiName))
|
||||
.extract()
|
||||
.path("item.find { it.name == '" + apiName + "' }.id");
|
||||
|
||||
String authorizerId = given()
|
||||
.when()
|
||||
.get("/restapis/" + apiId + "/authorizers")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.size()", equalTo(1))
|
||||
.body("item[0].name", equalTo("MyAuth"))
|
||||
.body("item[0].type", equalTo("REQUEST"))
|
||||
.body("item[0].identitySource", equalTo("method.request.header.Authorization"))
|
||||
.body("item[0].authorizerResultTtlInSeconds", equalTo(0))
|
||||
.extract()
|
||||
.path("item[0].id");
|
||||
|
||||
String resourceId = given()
|
||||
.when()
|
||||
.get("/restapis/" + apiId + "/resources")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.path", hasItem("/secret"))
|
||||
.extract()
|
||||
.path("item.find { it.path == '/secret' }.id");
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("authorizationType", equalTo("CUSTOM"))
|
||||
.body("authorizerId", equalTo(authorizerId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void samApi_definitionBodyCreatesApiGatewayMethods() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
|
||||
+276
@@ -854,6 +854,282 @@ class SamTransformProcessorTest {
|
||||
assertTrue(hasPermission, "expected a Lambda permission for apigateway.amazonaws.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_implicitApiGlobalRequestAuthorizerWiresMethods() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Globals": {
|
||||
"Api": {
|
||||
"Auth": {
|
||||
"DefaultAuthorizer": "MyAuth",
|
||||
"Authorizers": {
|
||||
"MyAuth": {
|
||||
"FunctionPayloadType": "REQUEST",
|
||||
"FunctionArn": {"Fn::GetAtt": ["AuthFn", "Arn"]},
|
||||
"Identity": {
|
||||
"Headers": ["Authorization", "X-Tenant"],
|
||||
"QueryStrings": ["token"],
|
||||
"ReauthorizeEvery": 60
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Resources": {
|
||||
"ApiFn": {
|
||||
"Type": "AWS::Serverless::Function",
|
||||
"Properties": {
|
||||
"Handler": "index.handler",
|
||||
"Runtime": "nodejs20.x",
|
||||
"InlineCode": "code",
|
||||
"Events": {
|
||||
"Get": {"Type": "Api", "Properties": {"Path": "/secret", "Method": "GET"}}
|
||||
}
|
||||
}
|
||||
},
|
||||
"AuthFn": {
|
||||
"Type": "AWS::Serverless::Function",
|
||||
"Properties": {
|
||||
"Handler": "index.handler",
|
||||
"Runtime": "nodejs20.x",
|
||||
"InlineCode": "code"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
JsonNode resources = processor.expandSamTemplate(template).path("Resources");
|
||||
|
||||
JsonNode authorizer = resources.fields().next().getValue();
|
||||
for (Iterator<Map.Entry<String, JsonNode>> it = resources.fields(); it.hasNext();) {
|
||||
JsonNode candidate = it.next().getValue();
|
||||
if ("AWS::ApiGateway::Authorizer".equals(candidate.path("Type").asText())) {
|
||||
authorizer = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertEquals("REQUEST", authorizer.path("Properties").path("Type").asText());
|
||||
assertEquals("MyAuth", authorizer.path("Properties").path("Name").asText());
|
||||
assertEquals("method.request.header.Authorization,method.request.header.X-Tenant,"
|
||||
+ "method.request.querystring.token",
|
||||
authorizer.path("Properties").path("IdentitySource").asText());
|
||||
assertEquals(60, authorizer.path("Properties").path("AuthorizerResultTtlInSeconds").asInt());
|
||||
|
||||
boolean customMethod = false;
|
||||
boolean authPermission = false;
|
||||
for (Iterator<Map.Entry<String, JsonNode>> it = resources.fields(); it.hasNext();) {
|
||||
JsonNode candidate = it.next().getValue();
|
||||
if ("AWS::ApiGateway::Method".equals(candidate.path("Type").asText())
|
||||
&& "CUSTOM".equals(candidate.path("Properties").path("AuthorizationType").asText())
|
||||
&& candidate.path("Properties").path("AuthorizerId").path("Ref").isTextual()) {
|
||||
customMethod = true;
|
||||
}
|
||||
if ("AWS::Lambda::Permission".equals(candidate.path("Type").asText())
|
||||
&& "AuthFn".equals(candidate.path("Properties").path("FunctionName")
|
||||
.path("Fn::GetAtt").path(0).asText())) {
|
||||
authPermission = true;
|
||||
}
|
||||
}
|
||||
assertTrue(customMethod, "expected the implicit method to reference the generated authorizer");
|
||||
assertTrue(authPermission, "expected SAM to grant API Gateway permission to invoke the authorizer");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_implicitApiEventCanOptOutOfGlobalAuthorizer() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Globals": {"Api": {"Auth": {
|
||||
"DefaultAuthorizer": "AWS_IAM"
|
||||
}}},
|
||||
"Resources": {
|
||||
"Fn": {
|
||||
"Type": "AWS::Serverless::Function",
|
||||
"Properties": {
|
||||
"Handler": "index.handler", "Runtime": "nodejs20.x", "InlineCode": "code",
|
||||
"Events": {
|
||||
"Private": {"Type": "Api", "Properties": {"Path": "/private", "Method": "GET"}},
|
||||
"Public": {"Type": "Api", "Properties": {"Path": "/public", "Method": "GET",
|
||||
"Auth": {"Authorizer": "NONE"}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
JsonNode resources = processor.expandSamTemplate(template).path("Resources");
|
||||
int iam = 0;
|
||||
int none = 0;
|
||||
for (Iterator<Map.Entry<String, JsonNode>> it = resources.fields(); it.hasNext();) {
|
||||
JsonNode candidate = it.next().getValue();
|
||||
if (!"AWS::ApiGateway::Method".equals(candidate.path("Type").asText())) {
|
||||
continue;
|
||||
}
|
||||
String authorizationType = candidate.path("Properties").path("AuthorizationType").asText();
|
||||
if ("AWS_IAM".equals(authorizationType)) iam++;
|
||||
if ("NONE".equals(authorizationType)) none++;
|
||||
}
|
||||
assertEquals(1, iam);
|
||||
assertEquals(1, none);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_implicitApiSupportsAwsIamAuthorizersShorthand() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Globals": {"Api": {"Auth": {"Authorizers": "AWS_IAM"}}},
|
||||
"Resources": {
|
||||
"Fn": {
|
||||
"Type": "AWS::Serverless::Function",
|
||||
"Properties": {
|
||||
"Handler": "index.handler", "Runtime": "nodejs20.x", "InlineCode": "code",
|
||||
"Events": {"Get": {"Type": "Api", "Properties": {"Path": "/x", "Method": "GET"}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
JsonNode resources = processor.expandSamTemplate(template).path("Resources");
|
||||
boolean found = false;
|
||||
for (Iterator<Map.Entry<String, JsonNode>> it = resources.fields(); it.hasNext();) {
|
||||
JsonNode candidate = it.next().getValue();
|
||||
if ("AWS::ApiGateway::Method".equals(candidate.path("Type").asText())) {
|
||||
assertEquals("AWS_IAM", candidate.path("Properties").path("AuthorizationType").asText());
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
assertTrue(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_requestAuthorizerRequiresIdentity() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Globals": {"Api": {"Auth": {
|
||||
"DefaultAuthorizer": "MyAuth",
|
||||
"Authorizers": {"MyAuth": {
|
||||
"FunctionPayloadType": "REQUEST",
|
||||
"FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:auth"
|
||||
}}
|
||||
}}},
|
||||
"Resources": {
|
||||
"Fn": {"Type": "AWS::Serverless::Function", "Properties": {
|
||||
"Handler": "index.handler", "Runtime": "nodejs20.x", "InlineCode": "code",
|
||||
"Events": {"Get": {"Type": "Api", "Properties": {"Path": "/x", "Method": "GET"}}}
|
||||
}}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
|
||||
assertTrue(error.getMessage().contains("Identity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_requestAuthorizerRejectsUnsupportedInvokeRole() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Globals": {"Api": {"Auth": {
|
||||
"DefaultAuthorizer": "MyAuth",
|
||||
"Authorizers": {"MyAuth": {
|
||||
"FunctionPayloadType": "REQUEST",
|
||||
"FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:auth",
|
||||
"FunctionInvokeRole": "arn:aws:iam::000000000000:role/auth-invoke",
|
||||
"Identity": {"Headers": ["Authorization"]}
|
||||
}}
|
||||
}}},
|
||||
"Resources": {
|
||||
"Fn": {"Type": "AWS::Serverless::Function", "Properties": {
|
||||
"Handler": "index.handler", "Runtime": "nodejs20.x", "InlineCode": "code",
|
||||
"Events": {"Get": {"Type": "Api", "Properties": {"Path": "/x", "Method": "GET"}}}
|
||||
}}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
|
||||
assertTrue(error.getMessage().contains("FunctionInvokeRole"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_requestAuthorizerRejectsOutOfRangeTtl() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Globals": {"Api": {"Auth": {
|
||||
"DefaultAuthorizer": "MyAuth",
|
||||
"Authorizers": {"MyAuth": {
|
||||
"FunctionPayloadType": "REQUEST",
|
||||
"FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:auth",
|
||||
"Identity": {"Headers": ["Authorization"], "ReauthorizeEvery": 3601}
|
||||
}}
|
||||
}}},
|
||||
"Resources": {
|
||||
"Fn": {"Type": "AWS::Serverless::Function", "Properties": {
|
||||
"Handler": "index.handler", "Runtime": "nodejs20.x", "InlineCode": "code",
|
||||
"Events": {"Get": {"Type": "Api", "Properties": {"Path": "/x", "Method": "GET"}}}
|
||||
}}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
|
||||
assertTrue(error.getMessage().contains("ReauthorizeEvery"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_implicitApiRejectsUnknownDefaultAuthorizer() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Globals": {"Api": {"Auth": {"DefaultAuthorizer": "Missing"}}},
|
||||
"Resources": {
|
||||
"Fn": {
|
||||
"Type": "AWS::Serverless::Function",
|
||||
"Properties": {
|
||||
"Handler": "index.handler", "Runtime": "nodejs20.x", "InlineCode": "code",
|
||||
"Events": {"Get": {"Type": "Api", "Properties": {"Path": "/x", "Method": "GET"}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("Missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_explicitServerlessApiAuthFailsInsteadOfBeingDropped() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{
|
||||
"Transform": "AWS::Serverless-2016-10-31",
|
||||
"Resources": {
|
||||
"Api": {
|
||||
"Type": "AWS::Serverless::Api",
|
||||
"Properties": {
|
||||
"StageName": "Prod",
|
||||
"Auth": {"DefaultAuthorizer": "AWS_IAM"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("Auth"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expandSamTemplate_dedupesDuplicateApiRoutes() throws Exception {
|
||||
// Two events resolving to the same (path, method) must collapse to a single API Gateway Method.
|
||||
|
||||
Reference in new issue
Block a user