fix(apigateway): import authorizers and security requirements from OpenAPI (#1798)

This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-04 22:20:26 -05:00
1 parent 7e4e3e8c50
commit 91e06ebebf
4 files changed
+831 -4

No files matched your search

@@ -1,10 +1,15 @@
package io.github.hectorvent.floci.services.apigateway;
import java.util.stream.Stream;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -1362,6 +1367,556 @@ class ApiGatewayOpenApiImportTest {
given().delete("/restapis/" + apiId);
}
// ──────────────────────────── Security scheme / authorizer import ────────────────────────────
@Test
@Order(90)
void importRestApi_lambdaAuthorizerFromSecurityScheme() throws Exception {
String spec = """
{
"openapi": "3.0.1",
"info": {"title": "SecuredAPI", "version": "1.0"},
"components": {
"securitySchemes": {
"MyLambdaAuth": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authtype": "custom",
"x-amazon-apigateway-authorizer": {
"type": "token",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:authz/invocations",
"authorizerResultTtlInSeconds": 300
}
}
}
},
"paths": {
"/secure": {
"get": {
"security": [{"MyLambdaAuth": []}],
"x-amazon-apigateway-integration": {
"type": "MOCK",
"requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
"responses": {"default": {"statusCode": "200"}}
}
}
}
}
}
""";
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();
// The security scheme became an Authorizer (previously dropped on import).
String authId = given()
.when().get("/restapis/" + apiId + "/authorizers")
.then().statusCode(200)
.body("item", hasSize(1))
.body("item[0].type", equalTo("TOKEN"))
.body("item[0].authorizerUri", containsString("function:authz"))
.body("item[0].identitySource", equalTo("method.request.header.Authorization"))
.extract().body().jsonPath().getString("item[0].id");
// The GET /secure method is wired to that authorizer (CUSTOM) — not silently left NONE/open.
String resourceId = given()
.when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200)
.extract().body().jsonPath().getString("item.find { it.path == '/secure' }.id");
given()
.when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then().statusCode(200)
.body("authorizationType", equalTo("CUSTOM"))
.body("authorizerId", equalTo(authId));
given().delete("/restapis/" + apiId);
}
@Test
@Order(92)
void importRestApi_cognitoProviderArnsAndTokenDefault() throws Exception {
String spec = """
{
"openapi": "3.0.1",
"info": {"title": "MixedAuthAPI", "version": "1.0"},
"components": {
"securitySchemes": {
"CognitoAuth": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authtype": "cognito_user_pools",
"x-amazon-apigateway-authorizer": {
"type": "cognito_user_pools",
"providerARNs": ["arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_ABC123"]
}
},
"BearerAuth": {
"type": "http", "scheme": "bearer",
"x-amazon-apigateway-authtype": "custom",
"x-amazon-apigateway-authorizer": {
"type": "token",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:bearerAuthz/invocations"
}
}
}
},
"paths": {
"/cog": {
"get": {
"security": [{"CognitoAuth": []}],
"x-amazon-apigateway-integration": {
"type": "MOCK",
"requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
"responses": {"default": {"statusCode": "200"}}
}
}
},
"/tok": {
"get": {
"security": [{"BearerAuth": []}],
"x-amazon-apigateway-integration": {
"type": "MOCK",
"requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
"responses": {"default": {"statusCode": "200"}}
}
}
}
}
}
""";
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()
.when().get("/restapis/" + apiId + "/authorizers")
.then().statusCode(200)
.body("item", hasSize(2))
// Cognito authorizer keeps its user-pool ARNs (previously dropped on import).
.body("item.find { it.name == 'CognitoAuth' }.type", equalTo("COGNITO_USER_POOLS"))
.body("item.find { it.name == 'CognitoAuth' }.providerARNs[0]",
containsString("userpool/us-east-1_ABC123"))
// A TOKEN authorizer whose scheme has no derivable header defaults identitySource
// to the Authorization header, as AWS does (rather than leaving it null).
.body("item.find { it.name == 'BearerAuth' }.type", equalTo("TOKEN"))
.body("item.find { it.name == 'BearerAuth' }.identitySource",
equalTo("method.request.header.Authorization"));
given().delete("/restapis/" + apiId);
}
@Test
@Order(93)
void importRestApi_firstDeclaredAuthorizerWins() throws Exception {
String spec = """
{
"openapi": "3.0.1",
"info": {"title": "MultiAuthAPI", "version": "1.0"},
"components": {
"securitySchemes": {
"AuthA": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authtype": "custom",
"x-amazon-apigateway-authorizer": {
"type": "token",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:authA/invocations"
}
},
"AuthB": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authtype": "custom",
"x-amazon-apigateway-authorizer": {
"type": "token",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:authB/invocations"
}
}
}
},
"paths": {
"/multi": {
"get": {
"security": [{"AuthA": [], "AuthB": []}],
"x-amazon-apigateway-integration": {
"type": "MOCK",
"requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
"responses": {"default": {"statusCode": "200"}}
}
}
}
}
}
""";
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();
// 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
@Order(94)
void putRestApi_overwriteReplacesAuthorizersWithoutLeavingStaleEntries() throws Exception {
String spec = """
{
"openapi": "3.0.1",
"info": {"title": "OverwriteAuthAPI", "version": "1.0"},
"components": {
"securitySchemes": {
"LambdaAuth": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authtype": "custom",
"x-amazon-apigateway-authorizer": {
"type": "token",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:overwriteAuthz/invocations"
}
}
}
},
"paths": {
"/secure": {
"get": {
"security": [{"LambdaAuth": []}],
"x-amazon-apigateway-integration": {"type": "MOCK"}
}
}
}
}
""";
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", "overwrite").body(spec)
.when().put("/restapis/" + apiId)
.then().statusCode(200);
String authorizerId = given()
.when().get("/restapis/" + apiId + "/authorizers")
.then().statusCode(200)
.body("item", hasSize(1))
.extract().body().jsonPath().getString("item[0].id");
String resourceId = given()
.when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200)
.extract().body().jsonPath().getString("item.find { it.path == '/secure' }.id");
given()
.when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then().statusCode(200)
.body("authorizationType", equalTo("CUSTOM"))
.body("authorizerId", equalTo(authorizerId));
given().delete("/restapis/" + apiId);
}
@Test
@Order(95)
void importRestApi_requestAuthorizerWithoutIdentitySourceRejectsDefaultCaching() {
String title = "InvalidCachedRequestAuthorizer";
String spec = requestAuthorizerSpec(title, "", "/invalid");
given()
.contentType(ContentType.JSON).queryParam("mode", "import").body(spec)
.when().post("/restapis")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", allOf(
containsString("RequestAuth"),
containsString("identitySource"),
containsString("caching")));
given()
.when().get("/restapis")
.then().statusCode(200)
.body("item.name", not(hasItem(title)));
}
@Test
@Order(96)
void importRestApi_requestAuthorizerWithoutIdentitySourceAllowsZeroTtl() throws Exception {
String spec = requestAuthorizerSpec(
"UncachedRequestAuthorizer", ", \"authorizerResultTtlInSeconds\": 0", "/uncached");
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();
try {
given()
.when().get("/restapis/" + apiId + "/authorizers")
.then().statusCode(200)
.body("item", hasSize(1))
.body("item[0].type", equalTo("REQUEST"))
.body("item[0].authorizerResultTtlInSeconds", equalTo(0))
.body("item[0].identitySource", nullValue());
} finally {
given().delete("/restapis/" + apiId);
}
}
@Test
@Order(97)
void putRestApi_invalidCachedRequestAuthorizerDoesNotReplaceExistingApi() throws Exception {
String originalSpec = """
{
"openapi": "3.0.1",
"info": {"title": "PreservedAuthorizerAPI", "version": "1.0"},
"components": {
"securitySchemes": {
"HeaderAuth": {
"type": "apiKey", "name": "X-Auth", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "request",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:headerAuth/invocations",
"identitySource": "method.request.header.X-Auth"
}
}
}
},
"paths": {"/kept": {"get": {"security": [{"HeaderAuth": []}]}}}
}
""";
String apiId = mapper.readTree(given()
.contentType(ContentType.JSON).queryParam("mode", "import").body(originalSpec)
.when().post("/restapis")
.then().statusCode(201)
.extract().body().asString()).get("id").asText();
try {
String invalidSpec = requestAuthorizerSpec("MustNotReplaceAPI", "", "/replacement");
given()
.contentType(ContentType.JSON).queryParam("mode", "overwrite").body(invalidSpec)
.when().put("/restapis/" + apiId)
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
given()
.when().get("/restapis/" + apiId)
.then().statusCode(200)
.body("name", equalTo("PreservedAuthorizerAPI"));
given()
.when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200)
.body("item.path", hasItem("/kept"))
.body("item.path", not(hasItem("/replacement")));
given()
.when().get("/restapis/" + apiId + "/authorizers")
.then().statusCode(200)
.body("item", hasSize(1))
.body("item[0].name", equalTo("HeaderAuth"))
.body("item[0].identitySource", equalTo("method.request.header.X-Auth"))
.body("item[0].authorizerResultTtlInSeconds", equalTo(300));
} finally {
given().delete("/restapis/" + apiId);
}
}
@ParameterizedTest(name = "{0}")
@MethodSource("malformedImportedAuthorizerExtensions")
@Order(98)
void putRestApi_malformedAuthorizerExtensionDoesNotReplaceExistingApi(
String caseName,
String expectedProperty,
String expectedType,
String authorizationTypeJson,
String authorizerDefinitionJson) throws Exception {
String originalSpec = requestAuthorizerSpec(
"PreservedAuthTypeAPI",
", \"authorizerResultTtlInSeconds\": 0",
"/kept");
String apiId = mapper.readTree(given()
.contentType(ContentType.JSON).queryParam("mode", "import").body(originalSpec)
.when().post("/restapis").then().statusCode(201)
.extract().body().asString()).get("id").asText();
try {
given()
.contentType(ContentType.JSON).queryParam("mode", "overwrite")
.body(malformedImportedAuthorizerSpec(authorizationTypeJson, authorizerDefinitionJson))
.when().put("/restapis/" + apiId)
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", allOf(
containsString(expectedProperty),
containsString("BrokenAuth"),
containsString("must be " + expectedType)));
given()
.when().get("/restapis/" + apiId)
.then().statusCode(200)
.body("name", equalTo("PreservedAuthTypeAPI"));
String resourceId = given()
.when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200)
.body("item.path", hasItem("/kept"))
.body("item.path", not(hasItem("/replacement")))
.extract().body().jsonPath().getString("item.find { it.path == '/kept' }.id");
String authorizerId = given()
.when().get("/restapis/" + apiId + "/authorizers")
.then().statusCode(200)
.body("item", hasSize(1))
.body("item[0].name", equalTo("RequestAuth"))
.body("item[0].type", equalTo("REQUEST"))
.body("item[0].authorizerResultTtlInSeconds", equalTo(0))
.extract().body().jsonPath().getString("item[0].id");
given()
.when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then().statusCode(200)
.body("authorizationType", equalTo("CUSTOM"))
.body("authorizerId", equalTo(authorizerId));
} finally {
given().delete("/restapis/" + apiId);
}
}
private static Stream<Arguments> malformedImportedAuthorizerExtensions() {
String customAuthType = "\"custom\"";
String authorizerUri = "\"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ "arn:aws:lambda:us-east-1:000000000000:function:brokenAuth/invocations\"";
String validAuthorizer = """
{"type":"token","authorizerUri":%s}
""".formatted(authorizerUri);
return Stream.of(
Arguments.of(
"non-string x-amazon-apigateway-authtype",
"x-amazon-apigateway-authtype",
"a string",
"{\"unexpected\":\"custom\"}",
validAuthorizer),
Arguments.of(
"non-object x-amazon-apigateway-authorizer",
"x-amazon-apigateway-authorizer",
"an object",
customAuthType,
"[\"invalid\"]"),
Arguments.of(
"non-string authorizer type",
"x-amazon-apigateway-authorizer.type",
"a string",
customAuthType,
"""
{"type":{"unexpected":"token"},"authorizerUri":%s}
""".formatted(authorizerUri)),
Arguments.of(
"missing authorizer type",
"x-amazon-apigateway-authorizer.type",
"one of token, request, or cognito_user_pools",
customAuthType,
"""
{"authorizerUri":%s}
""".formatted(authorizerUri)),
Arguments.of(
"unsupported authorizer type",
"x-amazon-apigateway-authorizer.type",
"one of token, request, or cognito_user_pools",
customAuthType,
"""
{"type":"jwt","authorizerUri":%s}
""".formatted(authorizerUri)),
Arguments.of(
"non-string authorizerUri",
"x-amazon-apigateway-authorizer.authorizerUri",
"a string",
customAuthType,
"""
{"type":"token","authorizerUri":{"unexpected":"uri"}}
"""),
Arguments.of(
"non-string identitySource",
"x-amazon-apigateway-authorizer.identitySource",
"a string",
customAuthType,
"""
{
"type":"request",
"authorizerUri":%s,
"identitySource":{"unexpected":"source"},
"authorizerResultTtlInSeconds":0
}
""".formatted(authorizerUri)),
Arguments.of(
"non-array providerARNs",
"x-amazon-apigateway-authorizer.providerARNs",
"an array of strings",
customAuthType,
"""
{"type":"cognito_user_pools","providerARNs":{"unexpected":"arn"}}
"""),
Arguments.of(
"non-string providerARNs member",
"x-amazon-apigateway-authorizer.providerARNs",
"an array of strings",
customAuthType,
"""
{"type":"cognito_user_pools","providerARNs":[{"unexpected":"arn"}]}
"""));
}
private static String malformedImportedAuthorizerSpec(
String authorizationTypeJson, String authorizerDefinitionJson) {
return """
{
"openapi": "3.0.1",
"info": {"title": "MustNotReplaceAuthTypeAPI", "version": "1.0"},
"components": {
"securitySchemes": {
"BrokenAuth": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authtype": %s,
"x-amazon-apigateway-authorizer": %s
}
}
},
"paths": {"/replacement": {"get": {"security": [{"BrokenAuth": []}]}}}
}
""".formatted(authorizationTypeJson, authorizerDefinitionJson);
}
private static String requestAuthorizerSpec(String title, String ttlProperty, String path) {
return """
{
"openapi": "3.0.1",
"info": {"title": "%s", "version": "1.0"},
"components": {
"securitySchemes": {
"RequestAuth": {
"type": "apiKey", "name": "Authorization", "in": "header",
"x-amazon-apigateway-authorizer": {
"type": "request",
"authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:requestAuth/invocations"%s
}
}
}
},
"paths": {"%s": {"get": {"security": [{"RequestAuth": []}]}}}
}
""".formatted(title, ttlProperty, path);
}
// ──────────────────────────── Cleanup ────────────────────────────
@Test