fix(cloudformation): drop undeclared OpenAPI authorizer schemes (#6632)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-26 08:06:31 -04:00
1 parent 7453011c43
commit f32db4fe49
4 files changed
+103 -11

No files matched your search

+8 -6
View File
@@ -772,9 +772,11 @@ 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 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.
controls are selected. Existing operation requirements are preserved. When a default applies
to OpenAPI 3, inline custom authorizer schemes are removed unless they also appear in the
SAM `securityDefinitions` map. This matches SAM's removal of undeclared OpenAPI authorizers
before import. Swagger 2 keeps its custom schemes. 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
@@ -792,9 +794,9 @@ When a default applies, so are unresolved or malformed security requirements, me
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
custom schemes retained by the transform 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.
@@ -107,6 +107,22 @@ final class SamRestApiAuth {
}
}
}
if (!swagger) {
removeUndeclaredCustomSchemes(document, definitions);
}
}
private void removeUndeclaredCustomSchemes(ObjectNode document, ObjectNode definitions) {
// SAM builds securityDefinitions first, then replaces OpenAPI securitySchemes with it.
// Inline OpenAPI authorizers absent from that generated map do not reach the importer.
Iterator<Map.Entry<String, JsonNode>> schemes = definitions.fields();
while (schemes.hasNext()) {
Map.Entry<String, JsonNode> scheme = schemes.next();
if (scheme.getValue().has("x-amazon-apigateway-authorizer")
&& !document.path("securityDefinitions").has(scheme.getKey())) {
schemes.remove();
}
}
}
private void applyDefaults(ObjectNode operation, ObjectNode definitions, boolean iam, boolean keyRequired) {
@@ -31,7 +31,7 @@ class SamRestApiAuthIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@ParameterizedTest
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
@CsvSource({"false,true", "true,false", "true,true"})
void conflictingAuthorizersCannotSilentlyReplaceTheSamIamDefault(boolean swagger, boolean repeated)
throws Exception {
ObjectNode template = template(swagger);
@@ -57,6 +57,34 @@ class SamRestApiAuthIntegrationTest {
.body("item.find { it.name == '" + title + "' }", equalTo(null));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void undeclaredOpenApiCustomAuthorizerDoesNotConflictWithIam(boolean conditional) throws Exception {
ObjectNode template = template(false);
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
body.set("components", mapper.createObjectNode().set("securitySchemes",
mapper.createObjectNode().set("custom", customAuthorizer())));
ObjectNode operation = (ObjectNode) body.at("/paths/~1items/post");
operation.set("security", mapper.readTree("[{\"custom\":[\"read\"]}]"));
if (conditional) {
template.set("Conditions", mapper.readTree("{\"Enabled\":{\"Fn::Equals\":[\"on\",\"on\"]}}"));
ObjectNode choice = mapper.createObjectNode();
choice.putArray("Fn::If").add("Enabled").add(operation)
.add(mapper.createObjectNode().put("Ref", "AWS::NoValue"));
((ObjectNode) body.at("/paths/~1items")).set("post", choice);
}
withDeployedApi(template, "sam-pruned-authorizer-", 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(true));
given().get("/restapis/" + apiId + "/authorizers").then().statusCode(200)
.body("item.size()", equalTo(0));
});
}
@ParameterizedTest
@CsvSource({"false,none", "false,custom-authentication", "false,awsSigv4",
"true,none", "true,custom-authentication", "true,awsSigv4"})
@@ -77,7 +77,8 @@ class SamRestApiAuthTest {
@ParameterizedTest
@ValueSource(strings = {
"{\"Authorizers\":{}}", "{\"ResourcePolicy\":{}}", "{\"UsagePlan\":{}}",
"{\"Authorizers\":{}}", "{\"Authorizers\":{\"custom\":{\"FunctionArn\":\"example\"}}}",
"{\"ResourcePolicy\":{}}", "{\"UsagePlan\":{}}",
"{\"InvokeRole\":\"CALLER_CREDENTIALS\"}", "{\"AddDefaultAuthorizerToCorsPreflight\":false}",
"{\"DefaultAuthorizer\":\"CUSTOM\"}", "{\"DefaultAuthorizer\":null}",
"{\"ApiKeyRequired\":\"true\"}", "\"AWS_IAM\""
@@ -92,7 +93,7 @@ class SamRestApiAuthTest {
}
@Test
void preservesExistingCustomSecurityAndAddsTheNamedDefault() throws Exception {
void dropsUndeclaredOpenApiCustomSchemeAndAddsTheNamedDefault() throws Exception {
ObjectNode template = template(false);
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
((ObjectNode) body.at("/paths/~1items/get")).set("security",
@@ -104,12 +105,57 @@ class SamRestApiAuthTest {
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"));
assertTrue(expanded.at("/components/securitySchemes/custom").isMissingNode());
assertEquals(mapper.readTree("[{\"custom\":[\"read\"]},{\"AWS_IAM\":[]},{\"api_key\":[]}]"),
expanded.at("/paths/~1items/get/security"));
}
@ParameterizedTest
@CsvSource({"false,iam,false", "false,key,false", "false,none,true",
"true,iam,true", "true,key,true", "true,none,true"})
void customSchemePruningDependsOnDocumentAndSelectedDefault(boolean swagger, String defaults,
boolean retained) throws Exception {
ObjectNode template = template(swagger);
ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
properties.set("Auth", mapper.readTree(switch (defaults) {
case "iam" -> "{\"DefaultAuthorizer\":\"AWS_IAM\"}";
case "key" -> "{\"ApiKeyRequired\":true}";
default -> "{\"ApiKeyRequired\":false}";
}));
ObjectNode body = (ObjectNode) properties.get("DefinitionBody");
JsonNode custom = mapper.readTree("""
{"type":"apiKey","name":"Authorization","in":"header",
"x-amazon-apigateway-authorizer":{"type":"request","authorizerUri":"unused"}}
""");
setSchemes(body, swagger, mapper.createObjectNode().set("custom", custom));
JsonNode security = mapper.readTree("[{\"custom\":[\"read\"]},{}]");
body.set("security", security.deepCopy());
((ObjectNode) body.at("/paths/~1items/get")).set("security", security.deepCopy());
JsonNode original = template.deepCopy();
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
JsonNode schemes = swagger ? expanded.path("securityDefinitions")
: expanded.at("/components/securitySchemes");
assertEquals(retained, schemes.has("custom"));
assertEquals(security, expanded.path("security"));
assertEquals(security.get(0), expanded.at("/paths/~1items/get/security/0"));
assertEquals(security.get(1), expanded.at("/paths/~1items/get/security/1"));
assertEquals(original, template);
}
@Test
void keepsCustomSchemeAlsoDeclaredInSamSecurityDefinitions() throws Exception {
ObjectNode template = template(false);
ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");
JsonNode definitions = mapper.readTree("""
{"custom":{"type":"apiKey","name":"Authorization","in":"header",
"x-amazon-apigateway-authorizer":{"type":"request","authorizerUri":"unused"}}}
""");
setSchemes(body, false, definitions.deepCopy());
body.set("securityDefinitions", definitions.deepCopy());
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
assertEquals(definitions.get("custom"), expanded.at("/components/securitySchemes/custom"));
}
@ParameterizedTest
@ValueSource(strings = {"custom-authentication", "awsSigv4"})
void existingSchemeMetadataDoesNotSuppressTheNamedIamDefault(String authType) throws Exception {