Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigateway): import authorizers and security requirements from OpenAPI (#1798)
Alex Banna91e06ebebf57
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.javaindex 077d010d8e..ecf10fbd71 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java@@ -1653,6 +1653,10 @@ public class ApiGatewayController {if (a.getAuthorizerUri() != null) node.put("authorizerUri", a.getAuthorizerUri());if (a.getIdentitySource() != null) node.put("identitySource", a.getIdentitySource());node.put("authorizerResultTtlInSeconds", Integer.parseInt(a.getAuthorizerResultTtlInSeconds()));+ if (a.getProviderARNs() != null && !a.getProviderARNs().isEmpty()) {+ ArrayNode arns = node.putArray("providerARNs");+ a.getProviderARNs().forEach(arns::add);+ }return node;}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.javaindex 5864e90a65..4599e8ea98 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java@@ -37,6 +37,8 @@ import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;import io.swagger.v3.oas.models.OpenAPI;import io.swagger.v3.oas.models.PathItem;+import io.swagger.v3.oas.models.security.SecurityRequirement;+import io.swagger.v3.oas.models.security.SecurityScheme;import io.swagger.v3.parser.core.models.SwaggerParseResult;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;@@ -633,6 +635,16 @@ public class ApiGatewayService {authorizer.setAuthorizerUri((String) request.get("authorizerUri"));authorizer.setIdentitySource((String) request.get("identitySource"));authorizer.setAuthorizerResultTtlInSeconds(String.valueOf(request.getOrDefault("authorizerResultTtlInSeconds", "300")));+ // COGNITO_USER_POOLS authorizers carry the pool ARNs; keep them so get-authorizer reflects them.+ if (request.get("providerARNs") instanceof List<?> arns) {+ List<String> providerArns = new ArrayList<>();+ for (Object arn : arns) {+ if (arn != null) {+ providerArns.add(arn.toString());+ }+ }+ authorizer.setProviderARNs(providerArns);+ }authorizerStore.put(authorizerKey(region, apiId, authorizer.getId()), authorizer);LOG.infov("Created authorizer {0} for API {1}", authorizer.getId(), apiId);@@ -1100,10 +1112,11 @@ public class ApiGatewayService {resourceStore.put(resourceKey(region, apiId, root.getId()), root);}- // Clear existing models and validators+ // Clear existing models, validators, and authorizers before rebuilding them from the spec.String prefix = region + "::" + apiId + "::";modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);+ authorizerStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(authorizerStore::delete);// Update API metadata from specif (openAPI.getInfo() != null) {@@ -1123,7 +1136,187 @@ public class ApiGatewayService {String errors = result.getMessages() != null ? String.join(", ", result.getMessages()) : "unknown error";throw new AwsException("BadRequestException", "Failed to parse OpenAPI spec: " + errors, 400);}- return result.getOpenAPI();+ OpenAPI openAPI = result.getOpenAPI();+ validateImportedAuthorizers(openAPI);+ return openAPI;+ }++ private void validateImportedAuthorizers(OpenAPI openAPI) {+ if (openAPI.getComponents() == null || openAPI.getComponents().getSecuritySchemes() == null) {+ return;+ }+ for (var entry : openAPI.getComponents().getSecuritySchemes().entrySet()) {+ String schemeName = entry.getKey();+ SecurityScheme scheme = entry.getValue();+ importedAuthorizationType(scheme, schemeName);+ Map<String, Object> authDef = importedAuthorizerDefinition(scheme, schemeName);+ if (authDef == null) {+ continue;+ }+ String type = importedAuthorizerType(authDef, schemeName);+ importedAuthorizerUri(authDef, schemeName);+ importedProviderArns(authDef, schemeName);+ int ttl = importedAuthorizerTtl(authDef, schemeName);+ String identitySource = resolveImportedIdentitySource(scheme, authDef, type, schemeName);+ if ("request".equalsIgnoreCase(type) && ttl > 0 && identitySource == null) {+ throw new AwsException(+ "BadRequestException",+ "REQUEST authorizer " + schemeName+ + " must specify identitySource when authorizer caching is enabled.",+ 400);+ }+ }+ }++ @SuppressWarnings("unchecked")+ private Map<String, Object> importedAuthorizerDefinition(SecurityScheme scheme, String schemeName) {+ if (scheme == null || scheme.getExtensions() == null) {+ return null;+ }+ Object definition = scheme.getExtensions().get("x-amazon-apigateway-authorizer");+ if (definition == null) {+ return null;+ }+ if (definition instanceof Map<?, ?>) {+ return (Map<String, Object>) definition;+ }+ throw invalidImportedAuthorizerProperty(+ "x-amazon-apigateway-authorizer", schemeName, "an object");+ }++ private String importedAuthorizerType(Map<String, Object> authDef, String schemeName) {+ String type = importedAuthorizerString(authDef, "type", schemeName);+ if (type != null) {+ String normalizedType = type.toLowerCase(java.util.Locale.ROOT);+ if ("token".equals(normalizedType)+ || "request".equals(normalizedType)+ || "cognito_user_pools".equals(normalizedType)) {+ return normalizedType;+ }+ }+ throw invalidImportedAuthorizerProperty(+ "x-amazon-apigateway-authorizer.type",+ schemeName,+ "one of token, request, or cognito_user_pools");+ }++ private String importedAuthorizerUri(Map<String, Object> authDef, String schemeName) {+ return importedAuthorizerString(authDef, "authorizerUri", schemeName);+ }++ private String importedAuthorizerString(+ Map<String, Object> authDef, String propertyName, String schemeName) {+ Object value = authDef.get(propertyName);+ if (value == null) {+ return null;+ }+ if (value instanceof String stringValue) {+ return stringValue;+ }+ throw invalidImportedAuthorizerProperty(+ "x-amazon-apigateway-authorizer." + propertyName, schemeName, "a string");+ }++ private List<String> importedProviderArns(Map<String, Object> authDef, String schemeName) {+ Object value = authDef.get("providerARNs");+ if (value == null) {+ return null;+ }+ if (!(value instanceof List<?> rawArns)) {+ throw invalidImportedAuthorizerProperty(+ "x-amazon-apigateway-authorizer.providerARNs",+ schemeName,+ "an array of strings");+ }+ List<String> providerArns = new ArrayList<>();+ for (Object rawArn : rawArns) {+ if (!(rawArn instanceof String arn)) {+ throw invalidImportedAuthorizerProperty(+ "x-amazon-apigateway-authorizer.providerARNs",+ schemeName,+ "an array of strings");+ }+ providerArns.add(arn);+ }+ return providerArns;+ }++ private AwsException invalidImportedAuthorizerProperty(+ String propertyName, String schemeName, String expectedType) {+ return new AwsException(+ "BadRequestException",+ propertyName + " for security scheme " + schemeName + " must be " + expectedType + ".",+ 400);+ }++ private String importedAuthorizationType(SecurityScheme scheme, String schemeName) {+ if (scheme == null || scheme.getExtensions() == null) {+ return null;+ }+ Object value = scheme.getExtensions().get("x-amazon-apigateway-authtype");+ if (value == null) {+ return null;+ }+ if (value instanceof String authorizationType) {+ return authorizationType;+ }+ throw new AwsException(+ "BadRequestException",+ "x-amazon-apigateway-authtype for security scheme " + schemeName + " must be a string.",+ 400);+ }++ private String resolveImportedIdentitySource(+ SecurityScheme scheme,+ Map<String, Object> authDef,+ String authorizerType,+ String schemeName) {+ String configured = importedAuthorizerString(authDef, "identitySource", schemeName);+ String identitySource = configured != null ? configured.trim() : null;+ if (identitySource != null && identitySource.isEmpty()) {+ identitySource = null;+ }+ boolean derivesIdentityFromScheme = authorizerType == null+ || "token".equalsIgnoreCase(authorizerType)+ || "cognito_user_pools".equalsIgnoreCase(authorizerType);+ if (identitySource == null && derivesIdentityFromScheme+ && scheme.getName() != null && scheme.getIn() != null+ && "header".equalsIgnoreCase(scheme.getIn().toString())) {+ identitySource = "method.request.header." + scheme.getName();+ }+ if (identitySource == null+ && (authorizerType == null || "token".equalsIgnoreCase(authorizerType))) {+ identitySource = "method.request.header.Authorization";+ }+ return identitySource;+ }++ private int importedAuthorizerTtl(Map<String, Object> authDef, String schemeName) {+ Object configured = authDef.get("authorizerResultTtlInSeconds");+ if (configured == null) {+ return 300;+ }+ String value = configured.toString();+ if (!value.matches("\\d+")) {+ throw invalidImportedAuthorizerTtl(schemeName);+ }+ try {+ int ttl = Integer.parseInt(value);+ if (ttl > 3600) {+ throw invalidImportedAuthorizerTtl(schemeName);+ }+ return ttl;+ } catch (NumberFormatException e) {+ throw invalidImportedAuthorizerTtl(schemeName);+ }+ }++ private AwsException invalidImportedAuthorizerTtl(String schemeName) {+ return new AwsException(+ "BadRequestException",+ "authorizerResultTtlInSeconds for authorizer " + schemeName+ + " must be an integer between 0 and 3600.",+ 400);}@SuppressWarnings("unchecked")@@ -1174,6 +1367,50 @@ public class ApiGatewayService {}}+ // Import security schemes: create an Authorizer for each x-amazon-apigateway-authorizer scheme+ // and record how each scheme name maps to a method authorizationType, so per-operation/root+ // `security` requirements can be applied to methods below. Without this, imported APIs with a+ // Lambda authorizer land as authorizationType=NONE and are silently open at runtime.+ Map<String, String> schemeToAuthorizerId = new HashMap<>();+ Map<String, String> schemeToAuthType = new HashMap<>();+ if (openAPI.getComponents() != null && openAPI.getComponents().getSecuritySchemes() != null) {+ for (var schemeEntry : openAPI.getComponents().getSecuritySchemes().entrySet()) {+ String schemeName = schemeEntry.getKey();+ SecurityScheme scheme = schemeEntry.getValue();+ String authtype = importedAuthorizationType(scheme, schemeName);+ Map<String, Object> authDef = importedAuthorizerDefinition(scheme, schemeName);+ if (authDef != null) {+ String t = importedAuthorizerType(authDef, schemeName); // token | request | cognito_user_pools+ Map<String, Object> req = new HashMap<>();+ req.put("name", schemeName);+ req.put("authorizerUri", importedAuthorizerUri(authDef, schemeName));+ req.put("authorizerResultTtlInSeconds", importedAuthorizerTtl(authDef, schemeName));+ String identitySource = resolveImportedIdentitySource(scheme, authDef, t, schemeName);+ if (identitySource != null) {+ req.put("identitySource", identitySource);+ }+ if ("cognito_user_pools".equalsIgnoreCase(t)) {+ req.put("type", "COGNITO_USER_POOLS");+ // Cognito user-pool authorizers carry the pool ARNs in the authorizer extension.+ List<String> providerArns = importedProviderArns(authDef, schemeName);+ if (providerArns != null) {+ req.put("providerARNs", providerArns);+ }+ schemeToAuthType.put(schemeName, "COGNITO_USER_POOLS");+ } else {+ req.put("type", t == null ? "TOKEN" : t.toUpperCase());+ schemeToAuthType.put(schemeName, "CUSTOM");+ }+ Authorizer created = createAuthorizer(region, apiId, req);+ schemeToAuthorizerId.put(schemeName, created.getId());+ } else if ("awsSigv4".equalsIgnoreCase(authtype)) {+ schemeToAuthType.put(schemeName, "AWS_IAM");+ } else {+ schemeToAuthType.put(schemeName, "NONE"); // plain apiKey scheme+ }+ }+ }+if (openAPI.getPaths() == null) return;// Find the root resource@@ -1203,7 +1440,32 @@ public class ApiGatewayService {// Create the methodMap<String, Object> methodRequest = new HashMap<>();- methodRequest.put("authorizationType", "NONE");+ // Apply the operation's (or the API root's) security requirement, resolving the scheme+ // to a method authorizationType (CUSTOM/AWS_IAM/COGNITO_USER_POOLS) + authorizerId.+ List<SecurityRequirement> secReqs = operation.getSecurity() != null+ ? operation.getSecurity() : openAPI.getSecurity();+ String authType = "NONE";+ String authorizerId = null;+ if (secReqs != null) {+ // AWS resolves the OR-list of security requirements to the first declared+ // authorizer scheme (a method has exactly one authorizer), so stop at 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;+ }+ authType = mapped;+ authorizerId = schemeToAuthorizerId.get(schemeName);+ break resolveAuth;+ }+ }+ }+ methodRequest.put("authorizationType", authType);+ if (authorizerId != null) {+ methodRequest.put("authorizerId", authorizerId);+ }// Link request models from operation requestBodyif (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Authorizer.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Authorizer.javaindex bd6e6466da..85ba04773a 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Authorizer.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Authorizer.java@@ -3,15 +3,18 @@ package io.github.hectorvent.floci.services.apigateway.model;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import io.quarkus.runtime.annotations.RegisterForReflection;+import java.util.List;+@RegisterForReflection@JsonIgnoreProperties(ignoreUnknown = true)public class Authorizer {private String id;private String name;- private String type; // TOKEN, REQUEST+ private String type; // TOKEN, REQUEST, COGNITO_USER_POOLSprivate String authorizerUri;private String identitySource;private String authorizerResultTtlInSeconds;+ private List<String> providerARNs; // COGNITO_USER_POOLSpublic Authorizer() {}@@ -32,4 +35,7 @@ public class Authorizer {public String getAuthorizerResultTtlInSeconds() { return authorizerResultTtlInSeconds; }public void setAuthorizerResultTtlInSeconds(String ttl) { this.authorizerResultTtlInSeconds = ttl; }++ public List<String> getProviderARNs() { return providerARNs; }+ public void setProviderARNs(List<String> providerARNs) { this.providerARNs = providerARNs; }}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiImportTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiImportTest.javaindex 0d1df24385..52d499e678 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiImportTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiImportTest.java@@ -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