Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigatewayv2): CloudFormation AuthorizationScopes pass-through and scope-ingestion hardening (follow-up to #2011) (#2431)
mitsukado-shinagawad0a96d87b1a9
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.javaindex bfe7d515b4..91f9780bfe 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java@@ -361,9 +361,7 @@ public class ApiGatewayV2Service {route.setRouteKey((String) request.get("routeKey"));route.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));route.setAuthorizerId((String) request.get("authorizerId"));- @SuppressWarnings("unchecked")- List<String> authorizationScopes = (List<String>) request.get("authorizationScopes");- route.setAuthorizationScopes(authorizationScopes);+ route.setAuthorizationScopes(toStringList(request.get("authorizationScopes")));route.setTarget((String) request.get("target"));route.setRouteResponseSelectionExpression((String) request.get("routeResponseSelectionExpression"));@@ -400,9 +398,7 @@ public class ApiGatewayV2Service {route.setAuthorizerId((String) request.get("authorizerId"));}if (request.containsKey("authorizationScopes") && request.get("authorizationScopes") != null) {- @SuppressWarnings("unchecked")- List<String> authorizationScopes = (List<String>) request.get("authorizationScopes");- route.setAuthorizationScopes(authorizationScopes);+ route.setAuthorizationScopes(toStringList(request.get("authorizationScopes")));}if (request.containsKey("target") && request.get("target") != null) {route.setTarget((String) request.get("target"));@@ -415,6 +411,25 @@ public class ApiGatewayV2Service {return route;}+ // JSON bodies can carry non-string elements (numbers, booleans); downstream code+ // (response serialization, scope enforcement) assumes String elements, so normalize+ // at ingestion instead of unchecked-casting. A present-but-non-array value must be+ // rejected, not treated as absent — silently returning null would create the route+ // without scope enforcement (or clear it on update).+ private static List<String> toStringList(Object value) {+ if (value == null) {+ return null;+ }+ if (!(value instanceof List<?> list)) {+ throw new AwsException("BadRequestException",+ "authorizationScopes must be a list of strings", 400);+ }+ return list.stream()+ .filter(java.util.Objects::nonNull)+ .map(String::valueOf)+ .toList();+ }+/*** Finds the best matching route for the given HTTP method and path.* Priority: exact match > path-template match > $default.diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex aa8bf0a664..0e379aaf79 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -5305,6 +5305,9 @@ public class CloudFormationResourceProvisioner {req.put("routeKey", resolveOptional(props, "RouteKey", engine));req.put("authorizationType", resolveOrDefault(props, "AuthorizationType", engine, "NONE"));req.put("authorizerId", resolveOptional(props, "AuthorizerId", engine));+ // Always present (empty when the property is absent) so an UpdateStack that removes+ // AuthorizationScopes from the template clears the route's scopes instead of keeping them.+ req.put("authorizationScopes", resolveStringListOrEmpty(props, "AuthorizationScopes", engine));req.put("target", resolveOptional(props, "Target", engine));Route route;diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/RouteAuthorizationScopesJson11Test.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/RouteAuthorizationScopesJson11Test.javanew file mode 100644index 0000000000..f97cc62d37--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/RouteAuthorizationScopesJson11Test.java@@ -0,0 +1,106 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasKey;+import static org.hamcrest.Matchers.not;++/**+ * Round-trip coverage for {@code AuthorizationScopes} on Route resources over the+ * JSON 1.1 surface (X-Amz-Target AmazonApiGatewayV2.*). The REST surface is covered+ * by {@link RouteAuthorizerIdResponseTest}; this guards the {@code toRouteNode}+ * rendering in {@code ApiGatewayV2JsonHandler}, which is a separate code path.+ */+@QuarkusTest+class RouteAuthorizationScopesJson11Test {++ private static final String AMZ_JSON = "application/x-amz-json-1.1";+ private static final String TARGET_PREFIX = "AmazonApiGatewayV2.";+ private static final String AUTH_HEADER =+ "AWS4-HMAC-SHA256 Credential=test/20260820/us-east-1/apigatewayv2/aws4_request";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void authorizationScopesRoundTripOverJson11() {+ String apiId = given()+ .contentType(AMZ_JSON)+ .header("X-Amz-Target", TARGET_PREFIX + "CreateApi")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"Name":"scopes-json11-api","ProtocolType":"HTTP"}+ """)+ .when().post("/")+ .then().statusCode(201)+ .extract().path("ApiId");++ String routeId = given()+ .contentType(AMZ_JSON)+ .header("X-Amz-Target", TARGET_PREFIX + "CreateRoute")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"ApiId":"%s","RouteKey":"GET /scoped","AuthorizationType":"JWT","AuthorizationScopes":["orders/read","orders/write"]}+ """.formatted(apiId))+ .when().post("/")+ .then().statusCode(201)+ .body("AuthorizationScopes", contains("orders/read", "orders/write"))+ .extract().path("RouteId");++ given()+ .contentType(AMZ_JSON)+ .header("X-Amz-Target", TARGET_PREFIX + "GetRoute")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"ApiId":"%s","RouteId":"%s"}+ """.formatted(apiId, routeId))+ .when().post("/")+ .then().statusCode(200)+ .body("AuthorizationScopes", contains("orders/read", "orders/write"));++ given()+ .contentType(AMZ_JSON)+ .header("X-Amz-Target", TARGET_PREFIX + "UpdateRoute")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"ApiId":"%s","RouteId":"%s","AuthorizationScopes":["orders/admin"]}+ """.formatted(apiId, routeId))+ .when().post("/")+ .then().statusCode(200)+ .body("AuthorizationScopes", contains("orders/admin"));+ }++ @Test+ void routeWithoutScopesOmitsAuthorizationScopesKey() {+ String apiId = given()+ .contentType(AMZ_JSON)+ .header("X-Amz-Target", TARGET_PREFIX + "CreateApi")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"Name":"noscopes-json11-api","ProtocolType":"HTTP"}+ """)+ .when().post("/")+ .then().statusCode(201)+ .extract().path("ApiId");++ given()+ .contentType(AMZ_JSON)+ .header("X-Amz-Target", TARGET_PREFIX + "CreateRoute")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"ApiId":"%s","RouteKey":"GET /open","AuthorizationType":"NONE"}+ """.formatted(apiId))+ .when().post("/")+ .then().statusCode(201)+ .body("RouteKey", equalTo("GET /open"))+ .body("$", not(hasKey("AuthorizationScopes")));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/RouteAuthorizerIdResponseTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/RouteAuthorizerIdResponseTest.javaindex 300a943b50..01defb77dc 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/RouteAuthorizerIdResponseTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/RouteAuthorizerIdResponseTest.java@@ -125,6 +125,87 @@ class RouteAuthorizerIdResponseTest {.body("authorizationScopes", equalTo(java.util.List.of("orders/admin")));}+ @Test+ void authorizationScopesNonStringElementsNormalizedToStrings() {+ // Route scopes arrive as a JSON array; a non-string element (legal JSON, invalid input)+ // used to survive the unchecked List<String> cast and blow up with ClassCastException+ // when the response was serialized. They are now normalized to strings at ingestion.+ String apiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"authz-route-scope-norm","protocolType":"HTTP"}+ """)+ .when().post("/v2/apis")+ .then().statusCode(201)+ .extract().path("apiId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {+ "routeKey":"GET /norm",+ "authorizationType":"JWT",+ "authorizationScopes":["orders/read", 42]+ }+ """)+ .when().post("/v2/apis/" + apiId + "/routes")+ .then().statusCode(201)+ .body("authorizationScopes", equalTo(java.util.List.of("orders/read", "42")));+ }++ @Test+ void nonArrayAuthorizationScopesRejectedWithoutClearingEnforcement() {+ // A present-but-non-array value must 400, not be treated as absent: silently+ // mapping it to null would create the route without scope enforcement, or+ // clear the scopes of an existing route on update.+ String apiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"authz-route-scope-badreq","protocolType":"HTTP"}+ """)+ .when().post("/v2/apis")+ .then().statusCode(201)+ .extract().path("apiId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {+ "routeKey":"GET /bad",+ "authorizationType":"JWT",+ "authorizationScopes":"orders/read"+ }+ """)+ .when().post("/v2/apis/" + apiId + "/routes")+ .then().statusCode(400);++ String routeId = given()+ .contentType(ContentType.JSON)+ .body("""+ {+ "routeKey":"GET /guarded",+ "authorizationType":"JWT",+ "authorizationScopes":["orders/read"]+ }+ """)+ .when().post("/v2/apis/" + apiId + "/routes")+ .then().statusCode(201)+ .extract().path("routeId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"authorizationScopes":"orders/write"}+ """)+ .when().patch("/v2/apis/" + apiId + "/routes/" + routeId)+ .then().statusCode(400);++ given()+ .when().get("/v2/apis/" + apiId + "/routes/" + routeId)+ .then().statusCode(200)+ .body("authorizationScopes", equalTo(java.util.List.of("orders/read")));+ }+@Testvoid authorizerIdReturnedAfterUpdate() {String apiId = given()diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.javaindex 8c5e8c83f9..f3804e23c0 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java@@ -6991,6 +6991,88 @@ class CloudFormationIntegrationTest {.body("Items[0].AuthorizerId", equalTo(authorizerId));}+ // ── PR #2011 follow-up: AWS::ApiGatewayV2::Route AuthorizationScopes pass-through ──++ @Test+ void apiGatewayV2RouteAuthorizationScopesProvisionedAndClearedOnUpdate() {+ // %s slot holds the AuthorizationScopes property line ("" to omit it entirely).+ String template = """+ {+ "Resources": {+ "HttpApi": {+ "Type": "AWS::ApiGatewayV2::Api",+ "Properties": { "Name": "cfn-apigwv2-scopes-api", "ProtocolType": "HTTP" }+ },+ "Authorizer": {+ "Type": "AWS::ApiGatewayV2::Authorizer",+ "Properties": {+ "ApiId": { "Ref": "HttpApi" },+ "Name": "cfn-jwt-scopes-authorizer",+ "AuthorizerType": "JWT",+ "IdentitySource": ["$request.header.Authorization"],+ "JwtConfiguration": {+ "Audience": ["my-client-id"],+ "Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx"+ }+ }+ },+ "Route": {+ "Type": "AWS::ApiGatewayV2::Route",+ "Properties": {+ "ApiId": { "Ref": "HttpApi" },+ "RouteKey": "GET /scoped",+ "AuthorizationType": "JWT",+ "AuthorizerId": { "Ref": "Authorizer" },+ %s+ "Target": "integrations/none"+ }+ }+ },+ "Outputs": {+ "ApiId": { "Value": { "Ref": "HttpApi" } },+ "RouteId": { "Value": { "Ref": "Route" } }+ }+ }+ """;++ String stackName = "cfn-apigwv2-route-scopes-stack";++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template.formatted(+ "\"AuthorizationScopes\": [\"orders/read\", \"orders/write\"],"))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ String createXml = apigwv2DescribeStacks(stackName);+ String apiId = apigwOutputValue(createXml, "ApiId");+ String routeId = apigwOutputValue(createXml, "RouteId");++ getRoutes(apiId).body("Items.size()", equalTo(1))+ .body("Items[0].RouteId", equalTo(routeId))+ .body("Items[0].AuthorizationScopes", contains("orders/read", "orders/write"));++ // Removing the property from the template clears the scopes in place.+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "UpdateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template.formatted(""))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ apigwv2DescribeStacks(stackName);+ getRoutes(apiId).body("Items.size()", equalTo(1))+ .body("Items[0].RouteId", equalTo(routeId))+ .body("Items[0].AuthorizationScopes", nullValue());+ }+@Testvoid createStack_apiGatewayV2AuthorizerAcceptsScalarIdentitySource() {// IdentitySource is documented as Array of String, but ApiGatewayV2Service.createAuthorizer