Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(cloudformation): scope SAM REST auth defaults to each operation (#6358)

Jackson Price2705818ff1a2
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SamRestApiRootSecurityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SamRestApiRootSecurityTest.java
new file mode 100644
index 0000000000..78ae5953be
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SamRestApiRootSecurityTest.java
@@ -0,0 +1,121 @@
+package com.floci.test;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
+import software.amazon.awssdk.services.apigateway.model.GetMethodResponse;
+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
+import software.amazon.awssdk.services.cloudformation.model.Capability;
+import software.amazon.awssdk.services.cloudformation.model.TemplateStage;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * A SAM REST API whose OpenAPI root security names its own SigV4 scheme, with
+ * {@code Auth.DefaultAuthorizer: AWS_IAM}. SAM adds the default to each operation's own security
+ * and leaves the root security as written, so the operation carries one IAM requirement rather
+ * than two, which the importer would refuse.
+ */
+@DisplayName("SAM REST API root security")
+class SamRestApiRootSecurityTest {
+
+ private static final Duration DEPLOY_TIMEOUT =
+ TestFixtures.isRealAws() ? Duration.ofMinutes(10) : Duration.ofSeconds(30);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static CloudFormationClient cfn;
+ private static ApiGatewayClient apiGateway;
+
+ private final List<String> stacks = new ArrayList<>();
+
+ @BeforeAll
+ static void setup() {
+ cfn = TestFixtures.cloudFormationClient();
+ apiGateway = TestFixtures.apiGatewayClient();
+ }
+
+ @AfterAll
+ static void closeClients() {
+ cfn.close();
+ apiGateway.close();
+ }
+
+ @AfterEach
+ void deleteStacks() {
+ // DeleteStack answers for a stack that is gone too, so a failure here is a real one.
+ stacks.forEach(stack -> cfn.deleteStack(request -> request.stackName(stack)));
+ }
+
+ @ParameterizedTest(name = "swagger={0}")
+ @ValueSource(booleans = {false, true})
+ @DisplayName("the IAM default is the operation's only requirement and root security is kept")
+ void iamDefaultIsTheOperationsOnlyRequirement(boolean swagger) throws Exception {
+ String stack = TestFixtures.uniqueName("compat-sam-root-security");
+ stacks.add(stack);
+ cfn.createStack(request -> request.stackName(stack).templateBody(template(swagger))
+ .capabilities(Capability.CAPABILITY_AUTO_EXPAND));
+ assertThat(TestFixtures.awaitStackTerminal(cfn, stack, DEPLOY_TIMEOUT)).isEqualTo("CREATE_COMPLETE");
+
+ JsonNode body = MAPPER.readTree(cfn.getTemplate(request -> request.stackName(stack)
+ .templateStage(TemplateStage.PROCESSED)).templateBody()).at("/Resources/Api/Properties/Body");
+ assertThat(body.get("security")).isEqualTo(MAPPER.readTree("[{\"sigv4\":[]}]"));
+ assertThat(body.at("/paths/~1items/get/security")).isEqualTo(MAPPER.readTree("[{\"AWS_IAM\":[]}]"));
+
+ String apiId = cfn.describeStackResource(request -> request.stackName(stack).logicalResourceId("Api"))
+ .stackResourceDetail().physicalResourceId();
+ String resourceId = apiGateway.getResources(request -> request.restApiId(apiId)).items().stream()
+ .filter(resource -> "/items".equals(resource.path()))
+ .findFirst().orElseThrow().id();
+ GetMethodResponse method = apiGateway.getMethod(request -> request.restApiId(apiId)
+ .resourceId(resourceId).httpMethod("GET"));
+ assertThat(method.authorizationType()).isEqualTo("AWS_IAM");
+ assertThat(method.apiKeyRequired()).isFalse();
+ }
+
+ private static String template(boolean swagger) {
+ String version = swagger ? "\"swagger\": \"2.0\"" : "\"openapi\": \"3.0.1\"";
+ String sigv4 = """
+ {"sigv4": {"type": "apiKey", "name": "Authorization", "in": "header",
+ "x-amazon-apigateway-authtype": "awsSigv4"}}""";
+ String schemes = swagger ? "\"securityDefinitions\": " + sigv4
+ : "\"components\": {\"securitySchemes\": " + sigv4 + "}";
+ return """
+ {
+ "Transform": "AWS::Serverless-2016-10-31",
+ "Resources": {
+ "Api": {
+ "Type": "AWS::Serverless::Api",
+ "Properties": {
+ "StageName": "test",
+ "Auth": {"DefaultAuthorizer": "AWS_IAM"},
+ "DefinitionBody": {
+ %s,
+ "info": {"title": "SAM root security", "version": "1"},
+ %s,
+ "security": [{"sigv4": []}],
+ "paths": {"/items": {"get": {
+ "responses": {"200": {"description": "ok"}},
+ "x-amazon-apigateway-integration": {
+ "type": "mock",
+ "requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
+ "responses": {"default": {"statusCode": "200"}}
+ }
+ }}}
+ }
+ }
+ }
+ }
+ }
+ """.formatted(version, schemes);
+ }
+}
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 7f57a8ce3b..3dacff3737 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -765,12 +765,26 @@ always lists both stages, matching AWS.
adds the corresponding security schemes and operation requirements. API Gateway imports
these as `authorizationType: AWS_IAM` and `apiKeyRequired: true`: invocation requires both
a valid SigV4 signature and an enabled API key associated with the invoked stage when both
-controls are selected. Existing inline requirements and their scheme definitions are
+controls are selected. Existing operation requirements and their scheme definitions are
preserved. Defaults are selected by the SAM names `AWS_IAM` and `api_key`; an existing
scheme with another name does not suppress either default.
-
-Other `Auth` properties, custom default authorizers, external definitions, unresolved or
-malformed security requirements, and method override markers are rejected. Existing
+As in SAM, the defaults are added to each operation's own `security`, inside each branch of
+an `Fn::If` written around a path or an operation, skipping an `AWS::NoValue` branch. A
+nested `Fn::If` around an operation is left as written, without the defaults, as SAM leaves
+it.
+Root-level `security` stays in the document as written and is not copied into operations,
+and an `Auth` that selects no default, such as `ApiKeyRequired: false` alone, leaves the
+document unchanged. floci's REST importer still applies root-level `security` to an
+operation that has none of its own, which API Gateway does not. As in SAM, any non-empty
+`Auth`, even one that selects no default, needs a Swagger or OpenAPI 3 `DefinitionBody`
+whose `paths` entries, and the branches of an `Fn::If` around one, are objects, so a body or
+a `paths` map written as an `Fn::If` is rejected.
+
+Other `Auth` properties, custom default authorizers and external definitions are rejected.
+When a default applies, so are unresolved or malformed security requirements, method
+override markers, a nested `Fn::If` around a path item, a body or security
+scheme map written as an intrinsic function, an `AWS_IAM` or `api_key` scheme that contains
+one, and a body that declares both `swagger` and `openapi`. Existing
custom schemes remain subject to API Gateway's importer and invocation support; preserving
them does not implement another authentication protocol. The importer rejects multiple
authorizer or IAM requirements, including a defined custom authorizer alongside the
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuth.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuth.java
index c0fda92f45..858ed65e58 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuth.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuth.java
@@ -6,9 +6,12 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
+import java.util.ArrayList;
import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Pattern;
/** Translates the supported explicit REST API authentication controls into inline OpenAPI. */
final class SamRestApiAuth {
@@ -17,6 +20,7 @@ final class SamRestApiAuth {
"get", "put", "post", "delete", "options", "head", "patch", "trace",
"x-amazon-apigateway-any-method");
private static final Set<String> SUPPORTED = Set.of("DefaultAuthorizer", "ApiKeyRequired");
+ private static final Pattern OPENAPI_3 = Pattern.compile("3(\\.\\d)(\\.\\d)?");
private final ObjectMapper mapper;
@@ -51,14 +55,26 @@ final class SamRestApiAuth {
if (!(body instanceof ObjectNode document) || !body.path("paths").isObject()) {
throw invalid("Auth requires an inline DefinitionBody with a paths object.");
}
- ObjectNode definitions;
- if ("2.0".equals(body.path("swagger").asText())) {
- definitions = object(document, "securityDefinitions");
- } else if (body.path("openapi").asText().startsWith("3.0.")) {
- definitions = object(object(document, "components"), "securitySchemes");
- } else {
+ if (!iam && !keyRequired) {
+ // Like SAM, an Auth that selects no default, such as ApiKeyRequired: false alone,
+ // leaves the document as written once it has checked what SAM checks for any Auth.
+ requireSamDocument(document);
+ return;
+ }
+ // The template engine keeps only an intrinsic function's result, and the importer reads a
+ // document naming both versions as OpenAPI 3: either way the defaults would be lost.
+ if (CloudFormationTemplateEngine.callsIntrinsic(document)) {
+ throw invalid("Auth requires a DefinitionBody written inline, not as an intrinsic function.");
+ }
+ if (document.has("swagger") && document.has("openapi")) {
+ throw invalid("Auth requires a DefinitionBody that declares swagger or openapi, not both.");
+ }
+ boolean swagger = "2.0".equals(body.path("swagger").asText());
+ if (!swagger && !body.path("openapi").asText().startsWith("3.0.")) {
throw invalid("Auth currently supports Swagger 2.0 and OpenAPI 3.0 only.");
}
+ ObjectNode definitions = swagger ? object(document, "securityDefinitions")
+ : object(object(document, "components"), "securitySchemes");
if (iam) {
addScheme(definitions, "AWS_IAM", true);
}
@@ -67,33 +83,107 @@ final class SamRestApiAuth {
}
Iterator<Map.Entry<String, JsonNode>> paths = document.path("paths").fields();
while (paths.hasNext()) {
- JsonNode path = paths.next().getValue();
- if (!path.isObject() || path.has("$ref")) {
- throw invalid("Auth requires inline path objects.");
- }
- Iterator<Map.Entry<String, JsonNode>> methods = path.fields();
- while (methods.hasNext()) {
- Map.Entry<String, JsonNode> method = methods.next();
- if (!METHODS.contains(method.getKey())) {
- continue;
- }
- if (!(method.getValue() instanceof ObjectNode operation)) {
- throw invalid("Auth requires inline operation objects.");
+ for (JsonNode path : branches(paths.next().getValue())) {
+ if (!path.isObject() || path.has("$ref")) {
+ throw invalid("Auth requires inline path objects.");
}
- JsonNode existing = operation.has("security")
- ? operation.get("security") : document.path("security");
- ArrayNode security = security(existing, definitions);
- if (iam && !hasScheme(security, "AWS_IAM")) {
- security.add(mapper.createObjectNode().set("AWS_IAM", mapper.createArrayNode()));
+ Iterator<Map.Entry<String, JsonNode>> methods = path.fields();
+ while (methods.hasNext()) {
+ Map.Entry<String, JsonNode> method = methods.next();
+ if (!METHODS.contains(method.getKey())) {
+ continue;
+ }
+ for (JsonNode branch : conditionalContents(method.getValue())) {
+ // SAM reads one level of Fn::If around an operation and skips a branch without
+ // an integration, so a nested Fn::If there is left as written, without defaults.
+ if (branch.has("Fn::If")) {
+ continue;
+ }
+ if (!(branch instanceof ObjectNode operation)) {
+ throw invalid("Auth requires inline operation objects.");
+ }
+ applyDefaults(operation, definitions, iam, keyRequired);
+ }
}
- if (keyRequired && !hasScheme(security, "api_key")) {
- security.add(mapper.createObjectNode().set("api_key", mapper.createArrayNode()));
+ }
+ }
+ }
+
+ private void applyDefaults(ObjectNode operation, ObjectNode definitions, boolean iam, boolean keyRequired) {
+ // SAM starts from the operation's own security, never the document's root security.
+ ArrayNode security = security(operation.path("security"), definitions);
+ if (iam && !hasScheme(security, "AWS_IAM")) {
+ security.add(mapper.createObjectNode().set("AWS_IAM", mapper.createArrayNode()));
+ }
+ if (keyRequired && !hasScheme(security, "api_key")) {
+ security.add(mapper.createObjectNode().set("api_key", mapper.createArrayNode()));
+ }
+ operation.set("security", security);
+ }
+
+ /**
+ * The checks SAM makes for any non-empty Auth before it applies a default: SwaggerEditor.is_valid
+ * wants a truthy swagger or an openapi of 3.x, and the SwaggerEditor constructor wants every
+ * paths entry, and each branch of an {@code Fn::If} around one, to be an object.
+ */
+ private void requireSamDocument(ObjectNode document) {
+ JsonNode openapi = document.path("openapi");
+ if (!SamTransformProcessor.isTruthy(document.path("swagger"))
+ && !(SamTransformProcessor.isTruthy(openapi) && OPENAPI_3.matcher(openapi.asText()).matches())) {
+ throw invalid("Auth requires a Swagger or OpenAPI 3 DefinitionBody.");
+ }
+ Iterator<JsonNode> paths = document.path("paths").elements();
+ while (paths.hasNext()) {
+ for (JsonNode path : conditionalContents(paths.next())) {
+ if (!path.isObject()) {
+ throw invalid("Auth requires inline path objects.");
}
- operation.set("security", security);
}
}
}
+ /**
+ * The values a path item may take when a default is added to its operations: as
+ * {@link #conditionalContents}, refusing a nested {@code Fn::If}, as SAM does once it reads the
+ * methods of the inner one. The template engine keeps only the chosen branch, so a default must
+ * be written inside each branch, not beside the {@code Fn::If}.
+ */
+ private List<JsonNode> branches(JsonNode node) {
+ List<JsonNode> branches = conditionalContents(node);
+ for (JsonNode branch : branches) {
+ if (branch.has("Fn::If")) {
+ throw invalid("Auth does not support a nested Fn::If in paths.");
+ }
+ }
+ return branches;
+ }
+
+ /**
+ * SAM's get_conditional_contents: both branches of an {@code Fn::If} other than
+ * {@code AWS::NoValue}, or the node itself.
+ */
+ private List<JsonNode> conditionalContents(JsonNode node) {
+ if (!node.has("Fn::If")) {
+ return List.of(node);
+ }
+ JsonNode arguments = node.get("Fn::If");
+ if (!arguments.isArray()) {
+ throw invalid("Fn::If must be a list.");
+ }
+ List<JsonNode> branches = new ArrayList<>();
+ for (int i = 1; i < arguments.size(); i++) {
+ JsonNode branch = arguments.get(i);
+ if (!isNoValue(branch)) {
+ branches.add(branch);
+ }
+ }
+ return branches;
+ }
+
+ private static boolean isNoValue(JsonNode node) {
+ return node.isObject() && node.size() == 1 && "AWS::NoValue".equals(node.path("Ref").asText());
+ }
+
private ArrayNode security(JsonNode value, ObjectNode definitions) {
if (value.isMissingNode()) {
return mapper.createArrayNode();
@@ -148,7 +238,8 @@ final class SamRestApiAuth {
}
private boolean isScheme(JsonNode scheme, boolean iam) {
- return "apiKey".equals(scheme.path("type").asText())
+ return !CloudFormationTemplateEngine.callsIntrinsic(scheme)
+ && "apiKey".equals(scheme.path("type").asText())
&& "header".equals(scheme.path("in").asText())
&& (iam ? "Authorization" : "x-api-key").equalsIgnoreCase(scheme.path("name").asText())
&& !scheme.has("x-amazon-apigateway-authorizer")
@@ -163,6 +254,12 @@ final class SamRestApiAuth {
if (!(parent.get(name) instanceof ObjectNode result)) {
throw invalid(name + " must be an object.");
}
+ // The template engine keeps only an intrinsic function's result, so a generated scheme
+ // written beside one would be dropped and the operations would name a scheme the importer
+ // ignores.
+ if (CloudFormationTemplateEngine.callsIntrinsic(result)) {
+ throw invalid(name + " must be written inline, not as an intrinsic function.");
+ }
return result;
}
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 bafdaf56fe..7e2db2cadc 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
@@ -1545,7 +1545,7 @@ class SamTransformProcessor {
}
/** Python truthiness, which SAM applies to an optional property before reading it. */
- private static boolean isTruthy(JsonNode node) {
+ static boolean isTruthy(JsonNode node) {
if (node.isMissingNode() || node.isNull()) {
return false;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthIntegrationTest.java
index 01b1323c91..e4120dcf71 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthIntegrationTest.java
@@ -3,12 +3,16 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
+import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.Map;
@@ -17,6 +21,7 @@ import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** Exercises transformed auth through the REST importer and the real execute-api HTTP verifier. */
@@ -53,16 +58,16 @@ class SamRestApiAuthIntegrationTest {
}
@ParameterizedTest
- @CsvSource({"false,false", "false,true", "true,false", "true,true"})
- void importedSamApiRequiresBothValidSignatureAndEnabledStageKey(boolean swagger, boolean existingScheme)
+ @CsvSource({"false,none", "false,custom-authentication", "false,awsSigv4",
+ "true,none", "true,custom-authentication", "true,awsSigv4"})
+ void importedSamApiRequiresBothValidSignatureAndEnabledStageKey(boolean swagger, String rootAuthType)
throws Exception {
ObjectNode template = template(swagger);
- if (existingScheme) {
+ if (!"none".equals(rootAuthType)) {
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
- ObjectNode schemes = mapper.createObjectNode().set("existing", mapper.readTree("""
- {"type":"apiKey","name":"Authorization","in":"header",
- "x-amazon-apigateway-authtype":"custom-authentication"}
- """));
+ ObjectNode schemes = mapper.createObjectNode().set("existing", mapper.createObjectNode()
+ .put("type", "apiKey").put("name", "Authorization").put("in", "header")
+ .put("x-amazon-apigateway-authtype", rootAuthType));
if (swagger) {
body.set("securityDefinitions", schemes);
} else {
@@ -160,6 +165,137 @@ class SamRestApiAuthIntegrationTest {
}
}
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void samIamDefaultReachesAnOperationInsideFnIf(boolean pathLevel) throws Exception {
+ ObjectNode template = template(false);
+ template.set("Conditions", mapper.readTree("{\"Enabled\":{\"Fn::Equals\":[\"on\",\"on\"]}}"));
+ ((ObjectNode) template.at("/Resources/Api/Properties/Auth")).remove("ApiKeyRequired");
+ ObjectNode paths = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody/paths");
+ ObjectNode items = (ObjectNode) paths.get("/items");
+ ObjectNode conditional = mapper.createObjectNode();
+ conditional.putArray("Fn::If").add("Enabled").add(pathLevel ? items : items.get("post"))
+ .add(mapper.createObjectNode().put("Ref", "AWS::NoValue"));
+ if (pathLevel) {
+ paths.set("/items", conditional);
+ } else {
+ items.set("post", conditional);
+ }
+ withDeployedApi(template, "sam-conditional-auth-", apiId -> {
+ String resourceId = given().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item.find { it.path == '/items' }.id");
+ given().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
+ .then().statusCode(200)
+ .body("authorizationType", equalTo("AWS_IAM"))
+ .body("apiKeyRequired", equalTo(false));
+ String path = "/execute-api/" + apiId + "/test/items";
+ given().post(path).then().statusCode(403);
+ given().headers(signed(path)).post(path).then().statusCode(200).body("accepted", equalTo(true));
+ });
+ }
+
+ @Test
+ void nestedFnIfAroundAnOperationDeploysAndThePlainBranchGetsTheSamDefault() throws Exception {
+ ObjectNode template = template(false);
+ template.set("Conditions", mapper.readTree("""
+ {"Outer":{"Fn::Equals":["on","off"]},"Inner":{"Fn::Equals":["on","on"]}}
+ """));
+ ((ObjectNode) template.at("/Resources/Api/Properties/Auth")).remove("ApiKeyRequired");
+ ObjectNode items = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody/paths/~1items");
+ JsonNode post = items.get("post").deepCopy();
+ ObjectNode nested = mapper.createObjectNode();
+ nested.putArray("Fn::If").add("Inner").add(post.deepCopy())
+ .add(mapper.createObjectNode().put("Ref", "AWS::NoValue"));
+ ObjectNode outer = mapper.createObjectNode();
+ outer.putArray("Fn::If").add("Outer").add(nested).add(post);
+ items.set("post", outer);
+ withDeployedApi(template, "sam-nested-condition-auth-", apiId -> {
+ String resourceId = given().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item.find { it.path == '/items' }.id");
+ given().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
+ .then().statusCode(200).body("authorizationType", equalTo("AWS_IAM"));
+ String path = "/execute-api/" + apiId + "/test/items";
+ given().post(path).then().statusCode(403);
+ given().headers(signed(path)).post(path).then().statusCode(200).body("accepted", equalTo(true));
+ });
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void falseFnIfLeavesNoRouteWhileOtherRoutesGetTheSamDefault(boolean pathLevel) throws Exception {
+ ObjectNode template = template(false);
+ template.set("Conditions", mapper.readTree("{\"Disabled\":{\"Fn::Equals\":[\"on\",\"off\"]}}"));
+ ((ObjectNode) template.at("/Resources/Api/Properties/Auth")).remove("ApiKeyRequired");
+ ObjectNode paths = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody/paths");
+ ObjectNode items = (ObjectNode) paths.get("/items");
+ JsonNode post = items.get("post").deepCopy();
+ ObjectNode conditional = mapper.createObjectNode();
+ conditional.putArray("Fn::If").add("Disabled").add(pathLevel ? items.deepCopy() : post.deepCopy())
+ .add(mapper.createObjectNode().put("Ref", "AWS::NoValue"));
+ if (pathLevel) {
+ paths.set("/items", conditional);
+ paths.set("/other", mapper.createObjectNode().set("post", post));
+ } else {
+ items.set("post", conditional);
+ items.set("put", post);
+ }
+ withDeployedApi(template, "sam-false-condition-auth-", apiId -> {
+ String resources = "/restapis/" + apiId + "/resources";
+ String liveId = given().get(resources).then().statusCode(200)
+ .extract().path("item.find { it.path == '" + (pathLevel ? "/other" : "/items") + "' }.id");
+ if (pathLevel) {
+ given().get(resources).then().body("item.find { it.path == '/items' }", equalTo(null));
+ } else {
+ given().get(resources + "/" + liveId + "/methods/POST").then().statusCode(404);
+ }
+ given().get(resources + "/" + liveId + "/methods/" + (pathLevel ? "POST" : "PUT"))
+ .then().statusCode(200).body("authorizationType", equalTo("AWS_IAM"));
+ });
+ }
+
+ /**
+ * Deploys the template as a stack with an {@code ApiId} output, hands that API id to the
+ * assertions once the stack is {@code CREATE_COMPLETE}, and deletes the stack afterwards.
+ */
+ private void withDeployedApi(ObjectNode template, String stackPrefix, ApiAssertions assertions) throws Exception {
+ template.set("Outputs", mapper.readTree("{\"ApiId\":{\"Value\":{\"Ref\":\"Api\"}}}"));
+ String stack = stackPrefix + UUID.randomUUID();
+ given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack").formParam("StackName", stack)
+ .formParam("TemplateBody", template.toString())
+ .formParam("Capabilities.member.1", "CAPABILITY_AUTO_EXPAND")
+ .when().post("/").then().statusCode(200);
+ try {
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);
+ assertEquals("CREATE_COMPLETE", state.status(), () -> failureReason(stack, state));
+ String outputs = given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks").formParam("StackName", stack)
+ .when().post("/").then().statusCode(200).extract().asString();
+ assertions.accept(XmlParser.extractPairs(outputs, "Outputs", "OutputKey", "OutputValue").get("ApiId"));
+ } finally {
+ given().contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack").formParam("StackName", stack)
+ .when().post("/").then().statusCode(200);
+ CfnStackWaits.awaitStackDeleted(stack);
+ }
+ }
+
+ /**
+ * Why the stack did not reach CREATE_COMPLETE: a transform failure has only the stack's own
+ * reason, and a resource failure (ROLLBACK_COMPLETE) also has the failed resource's.
+ */
+ private static String failureReason(String stack, CfnStackWaits.StackState state) {
+ if (!"ROLLBACK_COMPLETE".equals(state.status())) {
+ return state.reason();
+ }
+ return state.reason() + " " + CfnStackWaits.failedResourceReason(stack);
+ }
+
+ @FunctionalInterface
+ private interface ApiAssertions {
+ void accept(String apiId) throws Exception;
+ }
+
private ObjectNode customAuthorizer() throws Exception {
return (ObjectNode) mapper.readTree("""
{"type":"apiKey","name":"Authorization","in":"header",
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthTest.java
index e8e0c66fae..d7c7cb973d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthTest.java
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
@@ -43,21 +44,35 @@ class SamRestApiAuthTest {
}
@Test
- void preservesInheritedIamAndAnExistingApiKeyWhenDefaultIsFalse() throws Exception {
+ void leavesOperationsAndRootSecurityAsWrittenWhenNoDefaultApplies() throws Exception {
ObjectNode template = template(false);
ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
properties.set("Auth", mapper.readTree("{\"ApiKeyRequired\":false}"));
ObjectNode body = (ObjectNode) properties.get("DefinitionBody");
- body.set("components", mapper.readTree("""
- {"securitySchemes": {
- "existingSigV4": {"type":"apiKey","name":"Authorization","in":"header",
- "x-amazon-apigateway-authtype":"awsSigv4"},
- "existingKey": {"type":"apiKey","name":"x-api-key","in":"header"}
- }}
- """));
+ setSchemes(body, false, existingSchemes());
+ body.set("security", mapper.readTree("[{\"existingSigV4\":[]},{\"existingKey\":[]}]"));
+ JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
+ assertEquals(body.get("security"), expanded.get("security"));
+ for (String method : new String[] {"get", "x-amazon-apigateway-any-method"}) {
+ assertFalse(expanded.path("paths").path("/items").path(method).has("security"), method);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void rootSecurityIsNotMergedIntoTheSamDefaults(boolean swagger) throws Exception {
+ ObjectNode template = template(swagger);
+ ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
+ setSchemes(body, swagger, existingSchemes());
body.set("security", mapper.readTree("[{\"existingSigV4\":[]},{\"existingKey\":[]}]"));
+ JsonNode original = template.deepCopy();
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
- assertEquals(body.get("security"), expanded.at("/paths/~1items/get/security"));
+ assertEquals(original, template);
+ assertEquals(body.get("security"), expanded.get("security"));
+ for (String method : new String[] {"get", "x-amazon-apigateway-any-method"}) {
+ assertEquals(mapper.readTree("[{\"AWS_IAM\":[]},{\"api_key\":[]}]"),
+ expanded.path("paths").path("/items").path(method).path("security"), method);
+ }
}
@ParameterizedTest
@@ -80,7 +95,8 @@ class SamRestApiAuthTest {
void preservesExistingCustomSecurityAndAddsTheNamedDefault() throws Exception {
ObjectNode template = template(false);
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
- body.set("security", mapper.readTree("[{\"custom\":[\"read\"]}]"));
+ ((ObjectNode) body.at("/paths/~1items/get")).set("security",
+ mapper.readTree("[{\"custom\":[\"read\"]}]"));
body.set("components", mapper.readTree("""
{"securitySchemes":{"custom":{"type":"apiKey","name":"Authorization","in":"header",
"x-amazon-apigateway-authorizer":{"type":"request","authorizerUri":"unused"}}}}
@@ -104,7 +120,8 @@ class SamRestApiAuthTest {
.put("x-amazon-apigateway-authtype", authType);
body.set("components", mapper.createObjectNode().set("securitySchemes",
mapper.createObjectNode().set("existing", scheme)));
- body.set("security", mapper.readTree("[{\"existing\":[]}]"));
+ ((ObjectNode) body.at("/paths/~1items/get")).set("security",
+ mapper.readTree("[{\"existing\":[]}]"));
JsonNode original = template.deepCopy();
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
assertEquals(original, template);
@@ -121,7 +138,7 @@ class SamRestApiAuthTest {
body.set("components", mapper.readTree("""
{"securitySchemes":{"existing":{"type":"oauth2","flows":{}}}}
"""));
- body.set("security", mapper.readTree(security));
+ ((ObjectNode) body.at("/paths/~1items/get")).set("security", mapper.readTree(security));
JsonNode original = template.deepCopy();
assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
assertEquals(original, template);
@@ -143,6 +160,174 @@ class SamRestApiAuthTest {
assertThrows(AwsException.class, () -> processor.expandSamTemplate(conflicting));
}
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void addsTheDefaultsInsideEachFnIfBranch(boolean swagger) throws Exception {
+ ObjectNode template = template(swagger);
+ ObjectNode paths = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody/paths");
+ ObjectNode items = (ObjectNode) paths.get("/items");
+ JsonNode get = items.get("get");
+ items.set("get", conditional(get, mapper.readTree("{\"Ref\":\"AWS::NoValue\"}")));
+ items.set("put", conditional(get, items.get("x-amazon-apigateway-any-method")));
+ paths.set("/conditional", conditional(mapper.createObjectNode().set("post", get),
+ mapper.readTree("{\"Ref\":\"AWS::NoValue\"}")));
+ JsonNode original = template.deepCopy();
+ JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body/paths");
+ assertEquals(original, template);
+ JsonNode defaults = mapper.readTree("[{\"AWS_IAM\":[]},{\"api_key\":[]}]");
+ for (String branch : new String[] {
+ "/~1items/get/Fn::If/1", "/~1items/put/Fn::If/1", "/~1items/put/Fn::If/2",
+ "/~1conditional/Fn::If/1/post"}) {
+ assertEquals(defaults, expanded.at(branch + "/security"), branch);
+ }
+ assertFalse(expanded.at("/~1items/get").has("security"));
+ assertFalse(expanded.at("/~1items/put").has("security"));
+ assertEquals(mapper.readTree("{\"Ref\":\"AWS::NoValue\"}"), expanded.at("/~1items/get/Fn::If/2"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "{\"Fn::If\":[\"Enabled\",{\"Fn::If\":[\"Other\",{\"get\":{}},{}]},{}]}",
+ "{\"get\":{\"Fn::If\":\"Enabled\"}}", "{\"get\":{\"Fn::If\":[\"Enabled\",\"get\",{}]}}"
+ })
+ void refusesFnIfShapesItCannotReachInside(String pathItem) throws Exception {
+ ObjectNode template = template(false);
+ ((ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody/paths"))
+ .set("/conditional", mapper.readTree(pathItem));
+ JsonNode original = template.deepCopy();
+ AwsException failure = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
+ assertEquals("ValidationError", failure.getErrorCode());
+ assertEquals(original, template);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void leavesANestedFnIfAroundAnOperationAsWrittenAsSamDoes(boolean swagger) throws Exception {
+ ObjectNode template = template(swagger);
+ ObjectNode items = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody/paths/~1items");
+ JsonNode get = items.get("get");
+ JsonNode nested = conditional(get, mapper.readTree("{\"Ref\":\"AWS::NoValue\"}"));
+ items.set("get", conditional(nested, get));
+ JsonNode branches = processor.expandSamTemplate(template)
+ .at("/Resources/Api/Properties/Body/paths/~1items/get/Fn::If");
+ assertEquals(nested, branches.get(1));
+ assertEquals(mapper.readTree("[{\"AWS_IAM\":[]},{\"api_key\":[]}]"), branches.at("/2/security"));
+ }
+
+ @Test
+ void changesNothingWhenNoDefaultIsSelected() throws Exception {
+ ObjectNode template = template(false);
+ ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
+ properties.set("Auth", mapper.readTree("{\"ApiKeyRequired\":false}"));
+ ((ObjectNode) properties.get("DefinitionBody")).put("openapi", "3.1.0");
+ ObjectNode paths = (ObjectNode) properties.at("/DefinitionBody/paths");
+ JsonNode get = paths.at("/~1items/get");
+ paths.set("/nested", mapper.createObjectNode().set("get",
+ conditional(conditional(get, mapper.readTree("{\"Ref\":\"AWS::NoValue\"}")), get)));
+ ((ObjectNode) paths.at("/~1items/get")).set("security", mapper.readTree("[{\"undefined\":[]}]"));
+ paths.set("/nestedPath", conditional(conditional(mapper.createObjectNode().set("get", get),
+ mapper.readTree("{\"Ref\":\"AWS::NoValue\"}")), mapper.readTree("{\"Ref\":\"AWS::NoValue\"}")));
+ paths.set("/referenced", mapper.readTree("{\"$ref\":\"#/components/pathItems/shared\"}"));
+ JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
+ assertEquals(properties.get("DefinitionBody"), expanded);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"noVersion", "pathsIf", "textPath", "textFnIf"})
+ void refusesWithoutADefaultWhatSamRefusesForAnyAuth(String shape) throws Exception {
+ ObjectNode template = template(false);
+ ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
+ properties.set("Auth", mapper.readTree("{\"ApiKeyRequired\":false}"));
+ ObjectNode body = (ObjectNode) properties.get("DefinitionBody");
+ switch (shape) {
+ case "noVersion" -> body.remove("openapi");
+ case "pathsIf" -> body.set("paths", conditional(body.get("paths"), body.get("paths")));
+ case "textPath" -> ((ObjectNode) body.get("paths")).put("/text", "not a path item");
+ default -> ((ObjectNode) body.get("paths")).set("/text", mapper.readTree("{\"Fn::If\":\"Enabled\"}"));
+ }
+ JsonNode original = template.deepCopy();
+ AwsException failure = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
+ assertEquals("ValidationError", failure.getErrorCode());
+ assertEquals(original, template);
+ }
+
+ @ParameterizedTest
+ @CsvSource(delimiter = '|', value = {
+ "false|components|{\"Fn::If\":[\"Enabled\",{\"securitySchemes\":{}},{\"Ref\":\"AWS::NoValue\"}]}",
+ "false|components|{\"securitySchemes\":{\"Fn::If\":[\"Enabled\",{},{}]}}",
+ "true|securityDefinitions|{\"Fn::If\":[\"Enabled\",{},{}]}"
+ })
+ void refusesSchemeMapsWrittenAsIntrinsics(boolean swagger, String member, String value) throws Exception {
+ ObjectNode template = template(swagger);
+ ((ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody")).set(member, mapper.readTree(value));
+ JsonNode original = template.deepCopy();
+ AwsException failure = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
+ assertEquals("ValidationError", failure.getErrorCode());
+ assertEquals(original, template);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"bothVersions", "bodyIf", "iamSchemeIf", "keySchemeIf"})
+ void refusesBodiesWhoseDefaultsWouldNotReachTheImporter(String shape) throws Exception {
+ ObjectNode template = template(false);
+ ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
+ JsonNode arguments = mapper.readTree("[\"Enabled\",{},{}]");
+ switch (shape) {
+ case "bothVersions" -> body.put("swagger", "2.0");
+ case "bodyIf" -> body.set("Fn::If", arguments);
+ default -> {
+ boolean iam = "iamSchemeIf".equals(shape);
+ ObjectNode scheme = mapper.createObjectNode().put("type", "apiKey").put("in", "header")
+ .put("name", iam ? "Authorization" : "x-api-key");
+ if (iam) {
+ scheme.put("x-amazon-apigateway-authtype", "awsSigv4");
+ }
+ scheme.set("Fn::If", arguments);
+ setSchemes(body, false, mapper.createObjectNode().set(iam ? "AWS_IAM" : "api_key", scheme));
+ }
+ }
+ JsonNode original = template.deepCopy();
+ AwsException failure = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
+ assertEquals("ValidationError", failure.getErrorCode());
+ assertEquals(original, template);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"{\"ApiKeyRequired\":false}", "{\"DefaultAuthorizer\":\"AWS_IAM\"}"})
+ void refusesADefinitionBodyWrittenAsFnIfAsSamDoes(String auth) throws Exception {
+ ObjectNode template = template(false);
+ ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
+ properties.set("Auth", mapper.readTree(auth));
+ JsonNode body = properties.get("DefinitionBody");
+ properties.set("DefinitionBody", conditional(body, body));
+ JsonNode original = template.deepCopy();
+ AwsException failure = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
+ assertEquals("ValidationError", failure.getErrorCode());
+ assertEquals(original, template);
+ }
+
+ private ObjectNode conditional(JsonNode whenTrue, JsonNode whenFalse) {
+ ObjectNode conditional = mapper.createObjectNode();
+ conditional.putArray("Fn::If").add("Enabled").add(whenTrue.deepCopy()).add(whenFalse.deepCopy());
+ return conditional;
+ }
+
+ private ObjectNode existingSchemes() throws Exception {
+ return (ObjectNode) mapper.readTree("""
+ {"existingSigV4":{"type":"apiKey","name":"Authorization","in":"header",
+ "x-amazon-apigateway-authtype":"awsSigv4"},
+ "existingKey":{"type":"apiKey","name":"x-api-key","in":"header"}}
+ """);
+ }
+
+ private void setSchemes(ObjectNode body, boolean swagger, ObjectNode schemes) {
+ if (swagger) {
+ body.set("securityDefinitions", schemes);
+ } else {
+ body.set("components", mapper.createObjectNode().set("securitySchemes", schemes));
+ }
+ }
+
private ObjectNode template(boolean swagger) throws Exception {
ObjectNode template = (ObjectNode) mapper.readTree("""
{