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

* fix(cloudformation): leave root security out of SAM REST auth defaults

AWS::Serverless::Api Auth (DefaultAuthorizer: AWS_IAM, ApiKeyRequired)
gave each operation without security of its own a copy of the
document's root security before adding the defaults. SAM reads only
the operation's own security and leaves the root security as written,
and API Gateway does not apply root-level security. As a result:

- a root requirement naming a SigV4 scheme or an authorizer, beside
  the generated AWS_IAM default, failed the import with "Only one
  Authorizer or IAM authorization is allowed per operation", where SAM
  gives the operation the one AWS_IAM requirement;
- other root requirements, such as an API key scheme, were copied into
  every operation and enforced, where AWS does not enforce them.

The defaults now start from the operation's own security. An Auth
that selects no default, such as ApiKeyRequired: false alone, now
leaves the body as written, as SAM does; it used to copy the root
security into every operation.

The docs also say that floci's REST importer still applies root-level
security to an operation that has none of its own, which API Gateway
does not.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): add SAM REST auth defaults inside Fn::If branches

An Fn::If written around a path item or an operation in the
DefinitionBody of an AWS::Serverless::Api kept the Auth defaults from
reaching the operation. A conditional path item was skipped, because
its only key is not a method, and a conditional operation got the
default beside the Fn::If, which the template engine drops when it
keeps the chosen branch. Either way the method was imported with
authorizationType NONE and answered unsigned calls, where SAM adds the
default inside each branch.

The defaults are now added inside each branch, skipping an
AWS::NoValue one, as SAM's get_conditional_contents does. When a
default applies, a nested Fn::If, or one whose value is not a list, is
refused with a ValidationError instead of being left without the
defaults.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): refuse SAM REST bodies that would lose the defaults

Some DefinitionBody shapes lost the generated AWS_IAM and api_key
schemes or requirements on their way to the REST importer, which then
imported the methods with authorizationType NONE:

- a securityDefinitions, components or securitySchemes map written as
  an intrinsic function such as Fn::If. The generated schemes were
  written beside the function, and the template engine keeps only its
  result;
- a body with an Fn::If key beside its own keys, which the engine
  replaces with the chosen branch;
- an existing AWS_IAM or api_key scheme with the expected fields and
  an Fn::If key, which the engine replaces with a branch that need not
  be that scheme;
- a body declaring both swagger: "2.0" and an openapi version. The
  transform wrote the schemes into securityDefinitions, which the
  importer, reading the body as OpenAPI 3, ignores.

When a default applies, these are now refused with a ValidationError,
as a path item written as a $ref already is.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): cover SAM REST root security through the SDK

The SDK suite creates a stack whose AWS::Serverless::Api root security
names its own SigV4 scheme, with DefaultAuthorizer: AWS_IAM, in Swagger
2.0 and OpenAPI 3.0. It checks that the stack deploys, that the
processed template keeps the root security and gives the operation the
one AWS_IAM requirement, and that the method is imported as AWS_IAM
without an API key.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): pin false Fn::If routes and conditional bodies

An Fn::If around a path item or an operation whose condition is false
resolves to AWS::NoValue. The transform adds no default to that
branch, and the REST importer creates no resource or method for it, so
the API has no such route, as on AWS, while the other routes keep the
AWS_IAM default.

A DefinitionBody written as an Fn::If is refused for any non-empty
Auth, ApiKeyRequired: false included. SAM refuses it too: for every
non-empty Auth, _add_auth checks SwaggerEditor.is_valid, which needs a
literal paths object. The docs now say so.

Neither behavior changes here; the tests keep both in place.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(cloudformation): say a SAM REST Auth needs a paths object

The sentence added in the previous commit said any non-empty Auth
needs a literal paths object. The transform, like SAM, accepts any
object there, a paths map written as Fn::If included when no default
is selected. What it refuses is a DefinitionBody without one, such as
a body written as Fn::If.

The previous commit's message also said a false Fn::If around an
operation leaves no route. That holds for get, post and the other HTTP
methods. For x-amazon-apigateway-any-method the REST importer fails
the stack instead, with "expected an Operation object", on main too
and without Auth.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): check no-default SAM REST bodies as SAM does

An Auth that selects no default, such as ApiKeyRequired: false alone,
returned once the DefinitionBody had a paths object. SAM checks more
for any non-empty Auth before it applies a default:
SwaggerEditor.is_valid wants a truthy swagger or an openapi version
3.x, and the SwaggerEditor constructor wants every paths entry, and
each branch of an Fn::If around one, to be an object. floci therefore
accepted a body without a version, a paths map written as Fn::If, or
a path item that is not an object, all of which SAM refuses. The
previous commit's message said SAM accepts such a paths map; it does
not.

These are now refused with a ValidationError when no default is
selected too. Nothing else is checked in that case, as in SAM: an
OpenAPI 3.1 body, a $ref path item, a nested Fn::If or a malformed
security requirement is left as written. SamTransformProcessor's
isTruthy helper, which already models SAM's truthiness, becomes
package-private so the check can share it.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): leave nested Fn::If operations as SAM does

With a default selected, an Fn::If around an operation whose branch
was itself an Fn::If failed the transform with "Auth does not support
a nested Fn::If in paths". SAM does not fail there. Its
iter_on_all_methods_for_path reads one level of Fn::If around an
operation and skips a method definition without an
x-amazon-apigateway-integration. It therefore leaves the nested
branch as written, adds the defaults only to the plain one, and the
template deploys on AWS.

Such a branch is now left as written, without the defaults, and the
plain branches still get them. A nested Fn::If around a path item is
still refused: SAM fails there too, once it reads the methods of the
inner Fn::If.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): share the SAM REST stack deploy in one helper

Three SamRestApiAuthIntegrationTest cases each created the stack,
waited for it, read its ApiId output and deleted it in a finally
block. withDeployedApi now does that once: it adds the ApiId output,
deploys the template, hands the API id to the assertions once the
stack is CREATE_COMPLETE, and deletes the stack in its finally. The
assertions are unchanged; a failed deploy now reports the stack's own
status reason in all three cases.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): keep the failed resource's reason in deploy failures

withDeployedApi reported only the stack's status reason when a stack
did not reach CREATE_COMPLETE. For a resource failure that is the
generic "The following resource(s) failed to create", where two of
its callers used to report the failed resource's own reason, such as
the importer's refusal. The helper now appends that reason when the
stack rolled back, and keeps the stack's reason alone for a transform
failure, which has no failed resource. Only failure messages change.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
Jackson PriceandPriamo Germosen authored and GitHub committed 2026-10-24 20:15:07 -04:00
1 parent eb99ea6655
commit 2705818ff1
6 files changed
+604 -51

No files matched your search

@@ -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);
}
}
+17 -3
View File
@@ -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.
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, external definitions, unresolved or
malformed security requirements, and method override markers are rejected. Existing
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
@@ -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;
for (JsonNode path : branches(paths.next().getValue())) {
if (!path.isObject() || path.has("$ref")) {
throw invalid("Auth requires inline path objects.");
}
if (!(method.getValue() instanceof ObjectNode operation)) {
throw invalid("Auth requires inline operation 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;
}
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);
}
}
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()));
}
if (keyRequired && !hasScheme(security, "api_key")) {
security.add(mapper.createObjectNode().set("api_key", mapper.createArrayNode()));
}
operation.set("security", security);
}
}
}
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.");
}
}
}
}
/**
* 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;
}
@@ -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;
}
@@ -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",
@@ -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.at("/paths/~1items/get/security"));
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(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("""
{