fix(cloudformation): relocate SAM schemes without auth defaults (#6656)

* fix(cloudformation): relocate SAM schemes without auth defaults

Follow the separate postprocessing request in upstream #6638. Relocate declared OpenAPI security schemes independently of Auth defaults, preserving Swagger and operation requirements.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>

* fix(sam): centralize OpenAPI security scheme relocation

Keep the defaults helper responsible only for generating AWS_IAM and api_key definitions. Relocate the security scheme map exclusively in the shared final OpenAPI phase, including documents without Auth defaults.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>

---------

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-26 13:49:34 -04:00
1 parent b89b6da1a4
commit 07597598b6
4 files changed
+134 -7

No files matched your search

+4 -1
View File
@@ -785,7 +785,10 @@ nested `Fn::If` around an operation is left as written, without the defaults, as
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 requirements unchanged. For inline OpenAPI 3 documents, non-empty
`securityDefinitions` replace `components.securitySchemes` and are removed even when
`Auth` is absent, empty, or selects no default. Empty or absent definitions do not replace
existing schemes. Swagger documents retain their definitions. 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
@@ -29,6 +29,27 @@ final class SamRestApiAuth {
}
void apply(JsonNode auth, JsonNode body) {
applyDefaults(auth, body);
relocateOpenApiSchemes(body);
}
private void relocateOpenApiSchemes(JsonNode body) {
if (!(body instanceof ObjectNode document) || document.hasNonNull("swagger")) {
return;
}
JsonNode version = document.path("openapi");
JsonNode definitions = document.path("securityDefinitions");
if (version.isTextual() && OPENAPI_3.matcher(version.asText()).matches()
&& SamTransformProcessor.isTruthy(definitions)) {
if (!SamTransformProcessor.isTruthy(document.path("components"))) {
document.set("components", mapper.createObjectNode());
}
object(document, "components").set("securitySchemes", definitions);
document.remove("securityDefinitions");
}
}
private void applyDefaults(JsonNode auth, JsonNode body) {
if (auth.isMissingNode() || auth.isNull()) {
return;
}
@@ -57,7 +78,7 @@ final class SamRestApiAuth {
}
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.
// leaves operation security as written after checking what SAM checks for any Auth.
requireSamDocument(document);
return;
}
@@ -108,12 +129,11 @@ final class SamRestApiAuth {
}
}
if (!swagger) {
replaceOpenApiSchemes(document, iam, keyRequired);
addOpenApiDefaultSchemes(document, iam, keyRequired);
}
}
private void replaceOpenApiSchemes(ObjectNode document, boolean iam, boolean keyRequired) {
// SAM replaces the whole OpenAPI map with its generated Swagger definitions.
private void addOpenApiDefaultSchemes(ObjectNode document, boolean iam, boolean keyRequired) {
ObjectNode definitions = object(document, "securityDefinitions");
if (iam) {
addScheme(definitions, "AWS_IAM", true);
@@ -121,8 +141,6 @@ final class SamRestApiAuth {
if (keyRequired) {
addScheme(definitions, "api_key", false);
}
object(document, "components").set("securitySchemes", definitions);
document.remove("securityDefinitions");
}
private void applyDefaults(ObjectNode operation, ObjectNode definitions, boolean iam, boolean keyRequired) {
@@ -97,6 +97,38 @@ class SamRestApiAuthIntegrationTest {
});
}
@ParameterizedTest
@ValueSource(strings = {"missing", "{}", "{\"ApiKeyRequired\":false}"})
void importedApiUsesRelocatedSchemesWithoutDefaults(String auth) throws Exception {
ObjectNode template = template(false);
ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
if ("missing".equals(auth)) {
properties.remove("Auth");
} else {
properties.set("Auth", mapper.readTree(auth));
}
ObjectNode body = (ObjectNode) properties.get("DefinitionBody");
body.set("components", mapper.readTree("{\"securitySchemes\":{}}"));
body.set("securityDefinitions", mapper.readTree("""
{"declaredKey":{"type":"apiKey","name":"x-api-key","in":"header"}}
"""));
((ObjectNode) body.at("/paths/~1items/post")).set("security",
mapper.readTree("[{\"declaredKey\":[]}]"));
try (ApiGatewayClient client = ApiGatewayClient.builder().endpointOverride(endpoint)
.region(Region.US_EAST_1).httpClientBuilder(UrlConnectionHttpClient.builder())
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.build()) {
withDeployedApi(template, "sam-relocated-key-", apiId -> {
String resourceId = client.getResources(request -> request.restApiId(apiId)).items().stream()
.filter(resource -> "/items".equals(resource.path())).findFirst().orElseThrow().id();
GetMethodResponse method = client.getMethod(request -> request.restApiId(apiId)
.resourceId(resourceId).httpMethod("POST"));
assertEquals("NONE", method.authorizationType());
assertEquals(true, method.apiKeyRequired());
});
}
}
@Test
void undeclaredInlineApiKeyDoesNotSurviveSamOpenApiPostProcessing() throws Exception {
ObjectNode template = template(false);
@@ -43,6 +43,80 @@ class SamRestApiAuthTest {
assertEquals("x-api-key", schemes.path("api_key").path("name").asText());
}
@ParameterizedTest
@ValueSource(strings = {"missing", "null", "{}", "{\"ApiKeyRequired\":false}"})
void relocatesDeclaredSchemesWithoutAuthDefaults(String auth) throws Exception {
ObjectNode template = template(false);
ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
if ("missing".equals(auth)) {
properties.remove("Auth");
} else {
properties.set("Auth", mapper.readTree(auth));
}
ObjectNode body = (ObjectNode) properties.get("DefinitionBody");
body.set("components", mapper.readTree("""
{"schemas":{"Example":{"type":"string"}},"securitySchemes":{"old":{"type":"apiKey"}}}
"""));
JsonNode definitions = existingSchemes();
body.set("securityDefinitions", definitions.deepCopy());
body.set("security", mapper.readTree("[{\"existingKey\":[]}]"));
JsonNode original = template.deepCopy();
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
assertFalse(expanded.has("securityDefinitions"));
assertEquals(definitions, expanded.at("/components/securitySchemes"));
assertEquals(body.at("/components/schemas"), expanded.at("/components/schemas"));
assertEquals(body.get("security"), expanded.get("security"));
assertEquals(body.get("paths"), expanded.get("paths"));
assertEquals(original, template);
}
@ParameterizedTest
@ValueSource(strings = {"3.0.1", "3.1.0", "3.0"})
void relocatesSchemesIntoAbsentOrNullComponents(String version) throws Exception {
ObjectNode template = template(false);
ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
properties.remove("Auth");
ObjectNode body = (ObjectNode) properties.get("DefinitionBody");
body.put("openapi", version);
for (boolean nullComponents : new boolean[] {false, true}) {
if (nullComponents) {
body.putNull("components");
} else {
body.remove("components");
}
body.set("securityDefinitions", existingSchemes());
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
assertEquals(existingSchemes(), expanded.at("/components/securitySchemes"));
assertFalse(expanded.has("securityDefinitions"));
}
}
@ParameterizedTest
@ValueSource(strings = {"swagger", "both", "invalidVersion", "nullVersion", "emptyDefinitions",
"nullDefinitions", "missingDefinitions", "intrinsic"})
void leavesDocumentsOutsideRelocationScopeUnchanged(String shape) throws Exception {
ObjectNode template = template(false);
ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");
properties.remove("Auth");
ObjectNode body = (ObjectNode) properties.get("DefinitionBody");
body.set("securityDefinitions", existingSchemes());
switch (shape) {
case "swagger" -> {
body.remove("openapi");
body.put("swagger", "2.0");
}
case "both" -> body.put("swagger", "2.0");
case "invalidVersion" -> body.put("openapi", "3.invalid");
case "nullVersion" -> body.putNull("openapi");
case "emptyDefinitions" -> body.set("securityDefinitions", mapper.createObjectNode());
case "nullDefinitions" -> body.putNull("securityDefinitions");
case "missingDefinitions" -> body.remove("securityDefinitions");
default -> properties.set("DefinitionBody", mapper.readTree("{\"Ref\":\"Document\"}"));
}
JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");
assertEquals(properties.get("DefinitionBody"), expanded);
}
@Test
void leavesOperationsAndRootSecurityAsWrittenWhenNoDefaultApplies() throws Exception {
ObjectNode template = template(false);