mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(cloudformation): enforce SAM REST authorization defaults (#6021)
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
e520166170
commit
0517a7a936
9 files changed
+601
-39
No files matched your search
@@ -149,6 +149,12 @@ likewise created, or updated, as disabled.
|
||||
|
||||
#### `generateDistinctId`
|
||||
|
||||
REST OpenAPI imports recognize a required `apiKey` security scheme in the `x-api-key` header
|
||||
as `apiKeyRequired`. The imported method uses the same enabled-key and usage-plan stage checks
|
||||
as an explicitly created method. An `awsSigv4` Authorization scheme remains a separate
|
||||
`AWS_IAM` requirement and is not treated as an API key. An operation's explicit `security: []`
|
||||
removes inherited requirements on overwrite.
|
||||
|
||||
API key identifiers are generated independently from their secret values when `generateDistinctId`
|
||||
is absent, matching current AWS behavior, or explicitly set to `true`. The deprecated explicit
|
||||
`generateDistinctId=false` behavior is retained for compatibility and uses the key value as its
|
||||
|
||||
@@ -719,6 +719,29 @@ macro co-declared beside SAM is absent from `Processed` as well.
|
||||
Real AWS's answer for these shapes is unmeasured, co-declared with SAM or not. `StagesAvailable`
|
||||
always lists both stages, matching AWS.
|
||||
|
||||
## Explicit SAM REST API authentication
|
||||
|
||||
`AWS::Serverless::Api.Auth` supports `DefaultAuthorizer: AWS_IAM` and the boolean
|
||||
`ApiKeyRequired` with an inline Swagger 2.0 or OpenAPI 3.0 `DefinitionBody`. The transform
|
||||
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
|
||||
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
|
||||
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
|
||||
generated IAM default, with `BadRequestException`. API-key requirements can accompany
|
||||
one authorizer or IAM requirement. The transform
|
||||
preserves integration credentials, Lambda permissions and inline resource policies.
|
||||
Preserving a policy does not enforce it: API Gateway's documented IAM identity-policy and
|
||||
resource-policy evaluation limitation still applies. This support does not establish
|
||||
`execute-api:Invoke` authorization-policy fidelity.
|
||||
|
||||
## Conditions
|
||||
|
||||
Template `Conditions` are evaluated before provisioning. A resource whose `Condition` evaluates to
|
||||
|
||||
@@ -4296,27 +4296,28 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
List<SecurityRequirement> secReqs = operation.getSecurity() != null
|
||||
? operation.getSecurity() : openAPI.getSecurity();
|
||||
boolean apiKeyRequired = secReqs != null && !secReqs.isEmpty()
|
||||
&& secReqs.stream().allMatch(requirement -> requirement.keySet().stream()
|
||||
&& secReqs.stream().anyMatch(requirement -> requirement.keySet().stream()
|
||||
.anyMatch(apiKeySchemes::contains));
|
||||
String authType = "NONE";
|
||||
String authorizerId = null;
|
||||
List<String> authorizationScopes = List.of();
|
||||
if (secReqs != null) {
|
||||
// An API Gateway method can reference only one authorizer, so preserve the first match.
|
||||
resolveAuth:
|
||||
for (SecurityRequirement secReq : secReqs) {
|
||||
for (String schemeName : secReq.keySet()) {
|
||||
String mapped = schemeToAuthType.get(schemeName);
|
||||
if (mapped == null || "NONE".equals(mapped)) {
|
||||
continue;
|
||||
}
|
||||
if (!"NONE".equals(authType)) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Only one Authorizer or IAM authorization is allowed per operation", 400);
|
||||
}
|
||||
authType = mapped;
|
||||
authorizerId = schemeToAuthorizerId.get(schemeName);
|
||||
List<String> requestedScopes = secReq.get(schemeName);
|
||||
if (requestedScopes != null) {
|
||||
authorizationScopes = requestedScopes;
|
||||
}
|
||||
break resolveAuth;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
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.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/** Translates the supported explicit REST API authentication controls into inline OpenAPI. */
|
||||
final class SamRestApiAuth {
|
||||
|
||||
private static final Set<String> METHODS = Set.of(
|
||||
"get", "put", "post", "delete", "options", "head", "patch", "trace",
|
||||
"x-amazon-apigateway-any-method");
|
||||
private static final Set<String> SUPPORTED = Set.of("DefaultAuthorizer", "ApiKeyRequired");
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
SamRestApiAuth(ObjectMapper mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
void apply(JsonNode auth, JsonNode body) {
|
||||
if (auth.isMissingNode() || auth.isNull()) {
|
||||
return;
|
||||
}
|
||||
if (!auth.isObject()) {
|
||||
throw invalid("Auth must be an object.");
|
||||
}
|
||||
if (auth.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
auth.fieldNames().forEachRemaining(name -> {
|
||||
if (!SUPPORTED.contains(name)) {
|
||||
throw invalid("Unsupported Auth property: " + name + ".");
|
||||
}
|
||||
});
|
||||
boolean iam = auth.has("DefaultAuthorizer");
|
||||
if (iam && (!auth.path("DefaultAuthorizer").isTextual()
|
||||
|| !"AWS_IAM".equals(auth.path("DefaultAuthorizer").asText()))) {
|
||||
throw invalid("DefaultAuthorizer currently supports AWS_IAM only.");
|
||||
}
|
||||
if (auth.has("ApiKeyRequired") && !auth.path("ApiKeyRequired").isBoolean()) {
|
||||
throw invalid("ApiKeyRequired must be a boolean.");
|
||||
}
|
||||
boolean keyRequired = auth.path("ApiKeyRequired").asBoolean(false);
|
||||
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 {
|
||||
throw invalid("Auth currently supports Swagger 2.0 and OpenAPI 3.0 only.");
|
||||
}
|
||||
if (iam) {
|
||||
addScheme(definitions, "AWS_IAM", true);
|
||||
}
|
||||
if (keyRequired) {
|
||||
addScheme(definitions, "api_key", false);
|
||||
}
|
||||
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.");
|
||||
}
|
||||
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 ArrayNode security(JsonNode value, ObjectNode definitions) {
|
||||
if (value.isMissingNode()) {
|
||||
return mapper.createArrayNode();
|
||||
}
|
||||
if (!value.isArray()) {
|
||||
throw invalid("Operation security must be an array.");
|
||||
}
|
||||
for (JsonNode requirement : value) {
|
||||
if (!requirement.isObject()) {
|
||||
throw invalid("Security requirements must be objects.");
|
||||
}
|
||||
requirement.fields().forEachRemaining(entry -> {
|
||||
JsonNode scopes = entry.getValue();
|
||||
JsonNode scheme = definitions.path(entry.getKey());
|
||||
if (!scopes.isArray() || !scheme.isObject()) {
|
||||
throw invalid("Security requirements must reference defined schemes with an array of scopes.");
|
||||
}
|
||||
for (JsonNode scope : scopes) {
|
||||
if (!scope.isTextual()) {
|
||||
throw invalid("Security requirement scopes must be strings.");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return value.deepCopy();
|
||||
}
|
||||
|
||||
private boolean hasScheme(ArrayNode security, String name) {
|
||||
for (JsonNode requirement : security) {
|
||||
if (requirement.has(name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void addScheme(ObjectNode definitions, String name, boolean iam) {
|
||||
if (definitions.has(name)) {
|
||||
if (!isScheme(definitions.get(name), iam)) {
|
||||
throw invalid("Auth conflicts with an existing security scheme.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
ObjectNode scheme = mapper.createObjectNode();
|
||||
scheme.put("type", "apiKey");
|
||||
scheme.put("name", iam ? "Authorization" : "x-api-key");
|
||||
scheme.put("in", "header");
|
||||
if (iam) {
|
||||
scheme.put("x-amazon-apigateway-authtype", "awsSigv4");
|
||||
}
|
||||
definitions.set(name, scheme);
|
||||
}
|
||||
|
||||
private boolean isScheme(JsonNode scheme, boolean iam) {
|
||||
return "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")
|
||||
&& (iam ? "awsSigv4".equalsIgnoreCase(scheme.path("x-amazon-apigateway-authtype").asText())
|
||||
: !scheme.has("x-amazon-apigateway-authtype"));
|
||||
}
|
||||
|
||||
private ObjectNode object(ObjectNode parent, String name) {
|
||||
if (!parent.has(name)) {
|
||||
parent.set(name, mapper.createObjectNode());
|
||||
}
|
||||
if (!(parent.get(name) instanceof ObjectNode result)) {
|
||||
throw invalid(name + " must be an object.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private AwsException invalid(String reason) {
|
||||
return new AwsException("ValidationError", "SAM AWS::Serverless::Api " + reason, 400);
|
||||
}
|
||||
}
|
||||
+1
-6
@@ -1813,12 +1813,6 @@ 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();
|
||||
@@ -1841,6 +1835,7 @@ class SamTransformProcessor {
|
||||
// no Body and no BodyS3Location for that case. The paths are empty either way, so the
|
||||
// runtime outcome (no method reachable) is the same, even though the stored Body differs.
|
||||
applyDefinitionSource(logicalId, properties, apiProps);
|
||||
new SamRestApiAuth(objectMapper).apply(properties.path("Auth"), apiProps.path("Body"));
|
||||
|
||||
apiDef.set("Properties", apiProps);
|
||||
resources.set(logicalId, apiDef);
|
||||
|
||||
+6
-24
@@ -1713,7 +1713,7 @@ class ApiGatewayOpenApiImportTest {
|
||||
|
||||
@Test
|
||||
@Order(93)
|
||||
void importRestApi_firstDeclaredAuthorizerWins() throws Exception {
|
||||
void importRestApi_rejectsMultipleAuthorizers() {
|
||||
String spec = """
|
||||
{
|
||||
"openapi": "3.0.1",
|
||||
@@ -1752,30 +1752,12 @@ class ApiGatewayOpenApiImportTest {
|
||||
}
|
||||
}
|
||||
""";
|
||||
String apiId = mapper.readTree(given()
|
||||
.contentType(ContentType.JSON).queryParam("mode", "import").body(spec)
|
||||
.when().post("/restapis").then().statusCode(201)
|
||||
.extract().body().asString()).get("id").asText();
|
||||
given().contentType(ContentType.JSON).queryParam("mode", "import").body(spec)
|
||||
.post("/restapis").then().statusCode(400)
|
||||
.body("message", containsString("Only one Authorizer or IAM authorization"));
|
||||
given().get("/restapis").then().statusCode(200)
|
||||
.body("item.find { it.name == 'MultiAuthAPI' }", nullValue());
|
||||
|
||||
// The first declared scheme (AuthA) binds the method — not the last (AuthB).
|
||||
String authAId = given()
|
||||
.when().get("/restapis/" + apiId + "/authorizers")
|
||||
.then().statusCode(200)
|
||||
.body("item", hasSize(2))
|
||||
.extract().body().jsonPath().getString("item.find { it.name == 'AuthA' }.id");
|
||||
|
||||
String resourceId = given()
|
||||
.when().get("/restapis/" + apiId + "/resources")
|
||||
.then().statusCode(200)
|
||||
.extract().body().jsonPath().getString("item.find { it.path == '/multi' }.id");
|
||||
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
|
||||
.then().statusCode(200)
|
||||
.body("authorizationType", equalTo("CUSTOM"))
|
||||
.body("authorizerId", equalTo(authAId));
|
||||
|
||||
given().delete("/restapis/" + apiId);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-5
@@ -539,7 +539,7 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptySecurityAlternativeKeepsImportedMethodPublic() throws Exception {
|
||||
void emptySecurityAlternativeDoesNotRemoveApiKeyRequirement() throws Exception {
|
||||
String optionalOperationSecurity = API_KEY_SPEC.replace(
|
||||
"\"security\": [{\"client_key\": []}]",
|
||||
"\"security\": [{\"client_key\": []}, {}]");
|
||||
@@ -552,9 +552,9 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
|
||||
JsonNode method = getJson(methodPath(apiId));
|
||||
deploy(apiId, "optional-security");
|
||||
assertAll(
|
||||
() -> assertFalse(method.path("apiKeyRequired").asBoolean()),
|
||||
() -> assertTrue(method.path("apiKeyRequired").asBoolean()),
|
||||
() -> assertEquals("NONE", method.path("authorizationType").asText()),
|
||||
() -> assertEquals(200, invokeWithoutApiKey(apiId, "optional-security")));
|
||||
() -> assertEquals(403, invokeWithoutApiKey(apiId, "optional-security")));
|
||||
} finally {
|
||||
given().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
@@ -576,7 +576,7 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiKeyAndAuthorizerAlternativesDoNotRequireAnApiKeyAndKeepAuthorizer() throws Exception {
|
||||
void apiKeyAndAuthorizerAlternativesKeepBothRequirements() throws Exception {
|
||||
String apiKeyAndAuthorizerSpec = """
|
||||
{
|
||||
"openapi": "3.0.1",
|
||||
@@ -602,7 +602,7 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {
|
||||
JsonNode method = getJson(methodPath(apiId));
|
||||
deploy(apiId, "mixed-security");
|
||||
assertAll(
|
||||
() -> assertFalse(method.path("apiKeyRequired").asBoolean()),
|
||||
() -> assertTrue(method.path("apiKeyRequired").asBoolean()),
|
||||
() -> assertEquals("CUSTOM", method.path("authorizationType").asText()),
|
||||
() -> assertTrue(method.hasNonNull("authorizerId")),
|
||||
() -> assertEquals(403, invoke(apiId, "mixed-security")),
|
||||
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
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.testutil.ExecuteApiRequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
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.assertNotNull;
|
||||
|
||||
/** Exercises transformed auth through the REST importer and the real execute-api HTTP verifier. */
|
||||
@QuarkusTest
|
||||
class SamRestApiAuthIntegrationTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
|
||||
void conflictingAuthorizersCannotSilentlyReplaceTheSamIamDefault(boolean swagger, boolean repeated)
|
||||
throws Exception {
|
||||
ObjectNode template = template(swagger);
|
||||
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
|
||||
ObjectNode scheme = customAuthorizer();
|
||||
ObjectNode schemes = mapper.createObjectNode().set("custom", scheme);
|
||||
if (swagger) {
|
||||
body.set("securityDefinitions", schemes);
|
||||
} else {
|
||||
body.set("components", mapper.createObjectNode().set("securitySchemes", schemes));
|
||||
}
|
||||
((ObjectNode) body.at("/paths/~1items/post")).set("security",
|
||||
mapper.readTree(repeated ? "[{\"AWS_IAM\":[]},{\"AWS_IAM\":[]}]" : "[{\"custom\":[]}]"));
|
||||
String title = "conflicting-sam-" + UUID.randomUUID();
|
||||
((ObjectNode) body.get("info")).put("title", title);
|
||||
JsonNode document = new SamTransformProcessor(mapper).expandSamTemplate(template)
|
||||
.at("/Resources/Api/Properties/Body");
|
||||
|
||||
given().contentType(ContentType.JSON).queryParam("mode", "import")
|
||||
.body(document.toString()).post("/restapis").then().statusCode(400)
|
||||
.body("message", containsString("Only one Authorizer or IAM authorization"));
|
||||
given().get("/restapis").then().statusCode(200)
|
||||
.body("item.find { it.name == '" + title + "' }", equalTo(null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
|
||||
void importedSamApiRequiresBothValidSignatureAndEnabledStageKey(boolean swagger, boolean existingScheme)
|
||||
throws Exception {
|
||||
ObjectNode template = template(swagger);
|
||||
if (existingScheme) {
|
||||
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"}
|
||||
"""));
|
||||
if (swagger) {
|
||||
body.set("securityDefinitions", schemes);
|
||||
} else {
|
||||
body.set("components", mapper.createObjectNode().set("securitySchemes", schemes));
|
||||
}
|
||||
body.set("security", mapper.readTree("[{\"existing\":[]}]"));
|
||||
}
|
||||
JsonNode document = new SamTransformProcessor(mapper).expandSamTemplate(template)
|
||||
.at("/Resources/Api/Properties/Body");
|
||||
String apiId = null;
|
||||
String keyId = null;
|
||||
String planId = null;
|
||||
try {
|
||||
apiId = given().contentType(ContentType.JSON).queryParam("mode", "import")
|
||||
.body(document.toString()).post("/restapis")
|
||||
.then().statusCode(201).extract().path("id");
|
||||
String resourceId = given().get("/restapis/" + apiId + "/resources")
|
||||
.then().statusCode(200).extract().path("item.find { it.path == '/items' }.id");
|
||||
assertNotNull(resourceId);
|
||||
given().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
|
||||
.then().statusCode(200)
|
||||
.body("authorizationType", equalTo("AWS_IAM"))
|
||||
.body("apiKeyRequired", equalTo(true));
|
||||
for (String stage : new String[] {"test", "unlinked"}) {
|
||||
given().contentType(ContentType.JSON).body(Map.of("stageName", stage))
|
||||
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
|
||||
}
|
||||
String suffix = UUID.randomUUID().toString();
|
||||
keyId = given().contentType(ContentType.JSON)
|
||||
.body(Map.of("name", "sam-key-" + suffix, "enabled", true))
|
||||
.post("/apikeys").then().statusCode(201).extract().path("id");
|
||||
String keyValue = given().queryParam("includeValue", true).get("/apikeys/" + keyId)
|
||||
.then().statusCode(200).extract().path("value");
|
||||
planId = given().contentType(ContentType.JSON)
|
||||
.body(Map.of("name", "sam-plan-" + suffix,
|
||||
"apiStages", new Object[] {Map.of("apiId", apiId, "stage", "test")}))
|
||||
.post("/usageplans").then().statusCode(201).extract().path("id");
|
||||
given().contentType(ContentType.JSON).body(Map.of("keyId", keyId, "keyType", "API_KEY"))
|
||||
.post("/usageplans/" + planId + "/keys").then().statusCode(201);
|
||||
|
||||
String path = "/execute-api/" + apiId + "/test/items";
|
||||
Map<String, String> signed = signed(path);
|
||||
given().header("x-api-key", keyValue).post(path).then().statusCode(403);
|
||||
given().headers(signed).post(path).then().statusCode(403);
|
||||
given().headers(signed).header("x-api-key", "unknown-key").post(path)
|
||||
.then().statusCode(403);
|
||||
given().headers(signed).header("x-api-key", keyValue).body("tampered").post(path)
|
||||
.then().statusCode(403);
|
||||
given().headers(signed).header("x-api-key", keyValue).post(path)
|
||||
.then().statusCode(200).body("accepted", equalTo(true));
|
||||
|
||||
ObjectNode conflicting = document.deepCopy();
|
||||
ObjectNode schemes = (ObjectNode) (swagger ? conflicting.path("securityDefinitions")
|
||||
: conflicting.at("/components/securitySchemes"));
|
||||
schemes.set("custom", customAuthorizer());
|
||||
((ObjectNode) conflicting.at("/paths/~1items/post")).set("security",
|
||||
mapper.readTree("[{\"custom\":[]},{\"AWS_IAM\":[]},{\"api_key\":[]}]"));
|
||||
given().contentType(ContentType.JSON).queryParam("mode", "overwrite")
|
||||
.body(conflicting.toString()).put("/restapis/" + apiId).then().statusCode(400)
|
||||
.body("message", containsString("Only one Authorizer or IAM authorization"));
|
||||
given().headers(signed).header("x-api-key", keyValue).post(path)
|
||||
.then().statusCode(200).body("accepted", equalTo(true));
|
||||
|
||||
String unlinked = "/execute-api/" + apiId + "/unlinked/items";
|
||||
given().headers(signed(unlinked)).header("x-api-key", keyValue).post(unlinked)
|
||||
.then().statusCode(403);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"patchOperations":[{"op":"replace","path":"/enabled","value":"false"}]}
|
||||
""")
|
||||
.patch("/apikeys/" + keyId).then().statusCode(200);
|
||||
given().headers(signed(path)).header("x-api-key", keyValue).post(path)
|
||||
.then().statusCode(403);
|
||||
|
||||
ObjectNode operation = (ObjectNode) document.at("/paths/~1items/post");
|
||||
operation.set("security", mapper.createArrayNode());
|
||||
given().contentType(ContentType.JSON).queryParam("mode", "overwrite")
|
||||
.body(document.toString()).put("/restapis/" + apiId).then().statusCode(200);
|
||||
String newResourceId = given().get("/restapis/" + apiId + "/resources")
|
||||
.then().statusCode(200).extract().path("item.find { it.path == '/items' }.id");
|
||||
given().get("/restapis/" + apiId + "/resources/" + newResourceId + "/methods/POST")
|
||||
.then().statusCode(200)
|
||||
.body("authorizationType", equalTo("NONE"))
|
||||
.body("apiKeyRequired", equalTo(false));
|
||||
} finally {
|
||||
if (planId != null) {
|
||||
given().delete("/usageplans/" + planId).then().statusCode(202);
|
||||
}
|
||||
if (keyId != null) {
|
||||
given().delete("/apikeys/" + keyId).then().statusCode(202);
|
||||
}
|
||||
if (apiId != null) {
|
||||
given().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode customAuthorizer() throws Exception {
|
||||
return (ObjectNode) mapper.readTree("""
|
||||
{"type":"apiKey","name":"Authorization","in":"header",
|
||||
"x-amazon-apigateway-authtype":"custom",
|
||||
"x-amazon-apigateway-authorizer":{"type":"request",
|
||||
"identitySource":"method.request.header.Authorization",
|
||||
"authorizerUri":"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:custom/invocations"}}
|
||||
""");
|
||||
}
|
||||
|
||||
private Map<String, String> signed(String path) throws Exception {
|
||||
return ExecuteApiRequestSigner.signedHeaders("POST", path, Map.of(),
|
||||
"localhost:" + RestAssured.port, null, "test", "test", "us-east-1", Instant.now());
|
||||
}
|
||||
|
||||
private ObjectNode template(boolean swagger) throws Exception {
|
||||
ObjectNode template = (ObjectNode) mapper.readTree("""
|
||||
{"Transform":"AWS::Serverless-2016-10-31","Resources":{
|
||||
"Api":{"Type":"AWS::Serverless::Api","Properties":{
|
||||
"StageName":"test","Auth":{"DefaultAuthorizer":"AWS_IAM","ApiKeyRequired":true},
|
||||
"DefinitionBody":{"openapi":"3.0.1","info":{"title":"SAM auth","version":"1"},
|
||||
"paths":{"/items":{"post":{
|
||||
"responses":{"200":{"description":"Accepted"}},
|
||||
"x-amazon-apigateway-integration":{"type":"mock",
|
||||
"requestTemplates":{"application/json":"{\\"statusCode\\":200}"},
|
||||
"responses":{"default":{"statusCode":"200","responseTemplates":{
|
||||
"application/json":"{\\"accepted\\":true}"}}}}
|
||||
}}}
|
||||
}
|
||||
}}
|
||||
}}
|
||||
""");
|
||||
if (swagger) {
|
||||
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
|
||||
body.remove("openapi");
|
||||
body.put("swagger", "2.0");
|
||||
}
|
||||
return template;
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
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.AwsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SamRestApiAuthTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final SamTransformProcessor processor = new SamTransformProcessor(mapper);
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void translatesIamAndApiKeyWithoutChangingIntegrationPolicyOrSource(boolean swagger) throws Exception {
|
||||
ObjectNode template = template(swagger);
|
||||
JsonNode original = template.deepCopy();
|
||||
JsonNode inputBody = template.at("/Resources/Api/Properties/DefinitionBody");
|
||||
JsonNode result = processor.expandSamTemplate(template);
|
||||
JsonNode body = result.at("/Resources/Api/Properties/Body");
|
||||
|
||||
assertEquals("AWS::ApiGateway::RestApi", result.at("/Resources/Api/Type").asText());
|
||||
assertEquals(inputBody.at("/paths/~1items/get/x-amazon-apigateway-integration"),
|
||||
body.at("/paths/~1items/get/x-amazon-apigateway-integration"));
|
||||
assertEquals(inputBody.get("x-amazon-apigateway-policy"), body.get("x-amazon-apigateway-policy"));
|
||||
assertEquals(original, template);
|
||||
assertEquals(original.at("/Resources/Permission"), result.at("/Resources/Permission"));
|
||||
for (String method : new String[] {"get", "x-amazon-apigateway-any-method"}) {
|
||||
JsonNode security = body.path("paths").path("/items").path(method).path("security");
|
||||
assertEquals(2, security.size());
|
||||
assertTrue(security.toString().contains("AWS_IAM"));
|
||||
assertTrue(security.toString().contains("api_key"));
|
||||
}
|
||||
JsonNode schemes = swagger ? body.path("securityDefinitions")
|
||||
: body.path("components").path("securitySchemes");
|
||||
assertEquals("awsSigv4", schemes.path("AWS_IAM").path("x-amazon-apigateway-authtype").asText());
|
||||
assertEquals("x-api-key", schemes.path("api_key").path("name").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesInheritedIamAndAnExistingApiKeyWhenDefaultIsFalse() 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"}
|
||||
}}
|
||||
"""));
|
||||
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"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{\"Authorizers\":{}}", "{\"ResourcePolicy\":{}}", "{\"UsagePlan\":{}}",
|
||||
"{\"InvokeRole\":\"CALLER_CREDENTIALS\"}", "{\"AddDefaultAuthorizerToCorsPreflight\":false}",
|
||||
"{\"DefaultAuthorizer\":\"CUSTOM\"}", "{\"DefaultAuthorizer\":null}",
|
||||
"{\"ApiKeyRequired\":\"true\"}", "\"AWS_IAM\""
|
||||
})
|
||||
void refusesUnsupportedAuthInsteadOfRemovingIt(String auth) throws Exception {
|
||||
ObjectNode template = template(false);
|
||||
((ObjectNode) template.at("/Resources/Api/Properties")).set("Auth", mapper.readTree(auth));
|
||||
JsonNode original = template.deepCopy();
|
||||
AwsException failure = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertEquals(original, template);
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesExistingCustomSecurityAndAddsTheNamedDefault() throws Exception {
|
||||
ObjectNode template = template(false);
|
||||
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
|
||||
body.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"}}}}
|
||||
"""));
|
||||
JsonNode original = template.deepCopy();
|
||||
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
|
||||
assertEquals(original, template);
|
||||
assertEquals(body.at("/components/securitySchemes/custom"),
|
||||
expanded.at("/components/securitySchemes/custom"));
|
||||
assertEquals(mapper.readTree("[{\"custom\":[\"read\"]},{\"AWS_IAM\":[]},{\"api_key\":[]}]"),
|
||||
expanded.at("/paths/~1items/get/security"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"custom-authentication", "awsSigv4"})
|
||||
void existingSchemeMetadataDoesNotSuppressTheNamedIamDefault(String authType) throws Exception {
|
||||
ObjectNode template = template(false);
|
||||
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
|
||||
ObjectNode scheme = mapper.createObjectNode()
|
||||
.put("type", "apiKey").put("name", "Authorization").put("in", "header")
|
||||
.put("x-amazon-apigateway-authtype", authType);
|
||||
body.set("components", mapper.createObjectNode().set("securitySchemes",
|
||||
mapper.createObjectNode().set("existing", scheme)));
|
||||
body.set("security", mapper.readTree("[{\"existing\":[]}]"));
|
||||
JsonNode original = template.deepCopy();
|
||||
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
|
||||
assertEquals(original, template);
|
||||
assertEquals(scheme, expanded.at("/components/securitySchemes/existing"));
|
||||
assertEquals(mapper.readTree("[{\"existing\":[]},{\"AWS_IAM\":[]},{\"api_key\":[]}]"),
|
||||
expanded.at("/paths/~1items/get/security"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"[{\"missing\":[]}]", "[{\"existing\":\"scope\"}]", "[{\"existing\":[42]}]"})
|
||||
void refusesUndefinedSchemesAndMalformedScopes(String security) throws Exception {
|
||||
ObjectNode template = template(false);
|
||||
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
|
||||
body.set("components", mapper.readTree("""
|
||||
{"securitySchemes":{"existing":{"type":"oauth2","flows":{}}}}
|
||||
"""));
|
||||
body.set("security", mapper.readTree(security));
|
||||
JsonNode original = template.deepCopy();
|
||||
assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
|
||||
assertEquals(original, template);
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesExternalDefinitionAndConflictingGeneratedScheme() throws Exception {
|
||||
ObjectNode external = template(false);
|
||||
ObjectNode properties = (ObjectNode) external.at("/Resources/Api/Properties");
|
||||
properties.remove("DefinitionBody");
|
||||
properties.put("DefinitionUri", "s3://example/spec.json");
|
||||
assertThrows(AwsException.class, () -> processor.expandSamTemplate(external));
|
||||
|
||||
ObjectNode conflicting = template(false);
|
||||
ObjectNode body = (ObjectNode) conflicting.at("/Resources/Api/Properties/DefinitionBody");
|
||||
body.set("components", mapper.readTree("""
|
||||
{"securitySchemes":{"AWS_IAM":{"type":"apiKey","name":"x-api-key","in":"header"}}}
|
||||
"""));
|
||||
assertThrows(AwsException.class, () -> processor.expandSamTemplate(conflicting));
|
||||
}
|
||||
|
||||
private ObjectNode template(boolean swagger) throws Exception {
|
||||
ObjectNode template = (ObjectNode) mapper.readTree("""
|
||||
{
|
||||
"Transform":"AWS::Serverless-2016-10-31",
|
||||
"Resources":{
|
||||
"Api":{"Type":"AWS::Serverless::Api","Properties":{
|
||||
"StageName":"test","Auth":{"DefaultAuthorizer":"AWS_IAM","ApiKeyRequired":true},
|
||||
"DefinitionBody":{
|
||||
"openapi":"3.0.1","info":{"title":"example","version":"1"},
|
||||
"x-amazon-apigateway-policy":{"Version":"2012-10-17","Statement":[]},
|
||||
"paths":{"/items":{
|
||||
"parameters":[],
|
||||
"get":{"x-amazon-apigateway-integration":{
|
||||
"type":"aws_proxy","httpMethod":"POST",
|
||||
"uri":{"Fn::Sub":"arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Function.Arn}:live/invocations"},
|
||||
"credentials":{"Fn::GetAtt":["ExecutionRole","Arn"]}
|
||||
}},
|
||||
"x-amazon-apigateway-any-method":{"x-amazon-apigateway-integration":{"type":"mock"}}
|
||||
}}
|
||||
}
|
||||
}},
|
||||
"Permission":{"Type":"AWS::Lambda::Permission","Properties":{
|
||||
"Action":"lambda:InvokeFunction","FunctionName":{"Ref":"Function"},
|
||||
"Principal":"apigateway.amazonaws.com","SourceArn":{"Fn::Sub":"arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:${Api}/*"}
|
||||
}}
|
||||
}
|
||||
}
|
||||
""");
|
||||
if (swagger) {
|
||||
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
|
||||
body.remove("openapi");
|
||||
body.put("swagger", "2.0");
|
||||
}
|
||||
return template;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user