Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigatewayv2): route requests to API-owning account (#2377)
Saatvik Aryaba9ce8424223
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.javaindex 732225d4e7..003fcb7413 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigateway;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.RequestContext;import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;import jakarta.annotation.Priority;import jakarta.enterprise.context.ApplicationScoped;@@ -18,6 +19,7 @@ import org.jboss.logging.Logger;import java.net.URI;import java.util.Locale;+import java.util.Optional;import java.util.regex.Matcher;import java.util.regex.Pattern;@@ -37,13 +39,20 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {private final RegionResolver regionResolver;private final ApiGatewayExecuteRouteContext routeContext;private final String baseHostname;+ private final RequestContext requestContext;@Injectpublic ApiGatewayExecuteApiHostFilter(ApiGatewayV2Service apiGatewayV2Service,RegionResolver regionResolver,ApiGatewayExecuteRouteContext routeContext,- EmulatorConfig config) {+ EmulatorConfig config,+ RequestContext requestContext) {this(new ApiGatewayLookup() {+ @Override+ public Optional<ApiGatewayV2Service.ApiOwner> findApiOwner(String apiId) {+ return apiGatewayV2Service.findApiOwner(apiId);+ }+@Overridepublic String resolveApiRegion(String preferredRegion, String apiId) {return apiGatewayV2Service.resolveApiRegion(preferredRegion, apiId);@@ -63,24 +72,31 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {public void requireStage(String region, String apiId, String stageName) {apiGatewayV2Service.getStage(region, apiId, stageName);}- }, regionResolver, routeContext, config.hostname().orElse("localhost"));+ }, regionResolver, routeContext, config.hostname().orElse("localhost"), requestContext);}ApiGatewayExecuteApiHostFilter(ApiGatewayLookup apiGatewayLookup, RegionResolver regionResolver) {- this(apiGatewayLookup, regionResolver, new ApiGatewayExecuteRouteContext(), "localhost");+ this(apiGatewayLookup, regionResolver, new ApiGatewayExecuteRouteContext(), "localhost", null);}ApiGatewayExecuteApiHostFilter(ApiGatewayLookup apiGatewayLookup, RegionResolver regionResolver,ApiGatewayExecuteRouteContext routeContext) {- this(apiGatewayLookup, regionResolver, routeContext, "localhost");+ this(apiGatewayLookup, regionResolver, routeContext, "localhost", null);}ApiGatewayExecuteApiHostFilter(ApiGatewayLookup apiGatewayLookup, RegionResolver regionResolver,ApiGatewayExecuteRouteContext routeContext, String baseHostname) {+ this(apiGatewayLookup, regionResolver, routeContext, baseHostname, null);+ }++ ApiGatewayExecuteApiHostFilter(ApiGatewayLookup apiGatewayLookup, RegionResolver regionResolver,+ ApiGatewayExecuteRouteContext routeContext, String baseHostname,+ RequestContext requestContext) {this.apiGatewayLookup = apiGatewayLookup;this.regionResolver = regionResolver;this.routeContext = routeContext;this.baseHostname = baseHostname;+ this.requestContext = requestContext;}@Override@@ -94,15 +110,26 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {if (apiId == null) {return;}- // Region: the host label when it is a real AWS region (…execute-api.{region}.…), else the- // SigV4 credential scope. The cross-region apiId scan (resolveApiRegion) is the final- // fallback so an API created outside the default region still resolves — including on the- // regionless built-in suffixes, which carry no region label (issue #1871).- String hostRegion = regionResolver.resolveRegionFromHost(host);- String preferredRegion = hostRegion != null- ? hostRegion- : regionResolver.resolveRegionFromAuth(requestContext.getHeaderString("Authorization"));- String region = apiGatewayLookup.resolveApiRegion(preferredRegion, apiId);+ Optional<ApiGatewayV2Service.ApiOwner> owner = apiGatewayLookup.findApiOwner(apiId);+ String region;+ if (owner.isPresent()) {+ ApiGatewayV2Service.ApiOwner apiOwner = owner.get();+ if (this.requestContext != null) {+ this.requestContext.setAccountId(apiOwner.accountId());+ this.requestContext.setRegion(apiOwner.region());+ }+ region = apiOwner.region();+ } else {+ // Region: the host label when it is a real AWS region (…execute-api.{region}.…), else+ // the SigV4 credential scope. The cross-region apiId scan (resolveApiRegion) is the+ // final fallback so an API created outside the default region still resolves —+ // including on regionless built-in suffixes (issue #1871).+ String hostRegion = regionResolver.resolveRegionFromHost(host);+ String preferredRegion = hostRegion != null+ ? hostRegion+ : regionResolver.resolveRegionFromAuth(requestContext.getHeaderString("Authorization"));+ region = apiGatewayLookup.resolveApiRegion(preferredRegion, apiId);+ }URI originalUri = requestContext.getUriInfo().getRequestUri();String originalPath = originalUri.getRawPath();@@ -175,6 +202,10 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {}interface ApiGatewayLookup {+ default Optional<ApiGatewayV2Service.ApiOwner> findApiOwner(String apiId) {+ return Optional.empty();+ }+String resolveApiRegion(String preferredRegion, String apiId);String protocolType(String region, String apiId);diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.javaindex 47313268f9..a667d6b229 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsErrorResponse;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.RequestContext;import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;import io.github.hectorvent.floci.services.apigateway.model.ApiKey;import io.github.hectorvent.floci.services.apigateway.model.Integration;@@ -94,6 +95,7 @@ public class ApiGatewayExecuteController {private final SqsQueryHandler sqsQueryHandler;private final ApiGatewayExecuteRouteContext routeContext;private final JwtSignatureVerifier jwtSignatureVerifier;+ private final RequestContext requestContext;@Injectpublic ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,@@ -104,7 +106,8 @@ public class ApiGatewayExecuteController {ElbV2Service elbV2Service,SqsQueryHandler sqsQueryHandler,ApiGatewayExecuteRouteContext routeContext,- JwtSignatureVerifier jwtSignatureVerifier) {+ JwtSignatureVerifier jwtSignatureVerifier,+ RequestContext requestContext) {this.apiGatewayService = apiGatewayService;this.apiGatewayV2Service = apiGatewayV2Service;this.lambdaService = lambdaService;@@ -117,6 +120,7 @@ public class ApiGatewayExecuteController {this.sqsQueryHandler = sqsQueryHandler;this.routeContext = routeContext;this.jwtSignatureVerifier = jwtSignatureVerifier;+ this.requestContext = requestContext;}/** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */@@ -256,6 +260,11 @@ public class ApiGatewayExecuteController {String region = regionResolver.resolveRegion(headers);String httpApiRegion = routeContext.httpApiRegion();if (httpApiRegion != null) {+ Optional<ApiGatewayV2Service.ApiOwner> owner = apiGatewayV2Service.findApiOwner(apiId);+ if (owner.isPresent()) {+ applyApiOwnerContext(owner.get());+ httpApiRegion = owner.get().region();+ }return dispatchV2(httpMethod, apiId, stageName, proxy, headers, uriInfo, body, httpApiRegion);}@@ -272,6 +281,12 @@ public class ApiGatewayExecuteController {try {apiGatewayService.getRestApi(region, apiId);} catch (AwsException restApiError) {+ Optional<ApiGatewayV2Service.ApiOwner> owner = apiGatewayV2Service.findApiOwner(apiId);+ if (owner.isPresent()) {+ applyApiOwnerContext(owner.get());+ return dispatchV2(httpMethod, apiId, stageName, proxy, headers, uriInfo, body, owner.get().region());+ }+String v2Region = apiGatewayV2Service.resolveApiRegion(preferredRegion, apiId);try {apiGatewayV2Service.getApi(v2Region, apiId);@@ -358,6 +373,11 @@ public class ApiGatewayExecuteController {};}+ private void applyApiOwnerContext(ApiGatewayV2Service.ApiOwner owner) {+ requestContext.setAccountId(owner.accountId());+ requestContext.setRegion(owner.region());+ }+// ──────────────────────────── AWS_PROXY ────────────────────────────private Response invokeProxy(String region, String apiId, String httpMethod, String path, String proxy,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 a69d7a5668..4255cf59d0 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@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.ReservedTags;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import com.fasterxml.jackson.core.type.TypeReference;@@ -15,6 +16,7 @@ import org.jboss.logging.Logger;import java.util.List;import java.util.Map;+import java.util.Optional;import java.util.UUID;import java.util.regex.Pattern;@@ -23,7 +25,7 @@ public class ApiGatewayV2Service {private static final Logger LOG = Logger.getLogger(ApiGatewayV2Service.class);- private final StorageBackend<String, Api> apiStore;+ private final AccountAwareStorageBackend<Api> apiStore;private final StorageBackend<String, Route> routeStore;private final StorageBackend<String, Integration> integrationStore;private final StorageBackend<String, Authorizer> authorizerStore;@@ -35,6 +37,8 @@ public class ApiGatewayV2Service {private final StorageBackend<String, VpcLink> vpcLinkStore;private final RegionResolver regionResolver;+ public record ApiOwner(String accountId, String region) {}+@Injectpublic ApiGatewayV2Service(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {this.apiStore = storageFactory.create("apigatewayv2", "apigatewayv2-apis.json",@@ -86,7 +90,7 @@ public class ApiGatewayV2Service {Map<String, String> tags = (Map<String, String>) request.get("tags");String overrideId = ReservedTags.extractOverrideApiId(tags);String apiId = overrideId != null ? overrideId : shortId(10);- if (apiStore.get(apiKey(region, apiId)).isPresent()) {+ if (findApiOwner(apiId).isPresent()) {throw new AwsException("ConflictException","API with id '" + apiId + "' already exists", 409);}@@ -144,6 +148,27 @@ public class ApiGatewayV2Service {.orElse(preferredRegion);}+ /** Resolves the account and region that own an API ID for data-plane requests. */+ public Optional<ApiOwner> findApiOwner(String apiId) {+ List<AccountAwareStorageBackend.AccountEntry<Api>> matches = apiStore+ .scanAllAccountEntries(key -> key.endsWith("::" + apiId));+ if (matches.size() > 1) {+ throw new AwsException("ConflictException",+ "API id '" + apiId + "' is ambiguous across accounts", 409);+ }+ return matches.stream()+ .findFirst()+ .map(entry -> new ApiOwner(entry.accountId(), regionFromApiKey(entry.key())));+ }++ private static String regionFromApiKey(String key) {+ int delimiter = key.indexOf("::");+ if (delimiter <= 0) {+ throw new IllegalStateException("Invalid API storage key: " + key);+ }+ return key.substring(0, delimiter);+ }+public List<Api> getApis(String region) {String prefix = region + "::";return apiStore.scan(k -> k.startsWith(prefix));diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.javaindex 74803e6668..ab8feb2ab6 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java@@ -35,7 +35,7 @@ class ApiGatewayExecuteControllerTest {return new ApiGatewayExecuteController(null, null, null,regionResolver, objectMapper, null,- null, null, null, null, new ApiGatewayExecuteRouteContext(), null);+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);}@Test@@ -235,7 +235,7 @@ class ApiGatewayExecuteControllerTest {ApiGatewayExecuteController controller = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, null,regionResolver, new ObjectMapper(), null,- null, null, null, null, new ApiGatewayExecuteRouteContext(), null);+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);Response response = controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);@@ -265,7 +265,7 @@ class ApiGatewayExecuteControllerTest {ApiGatewayExecuteController controller = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, null,regionResolver, new ObjectMapper(), null,- null, null, null, null, new ApiGatewayExecuteRouteContext(), null);+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);@@ -299,7 +299,7 @@ class ApiGatewayExecuteControllerTest {ApiGatewayExecuteController controller = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, null,regionResolver, new ObjectMapper(), null,- null, null, null, null, new ApiGatewayExecuteRouteContext(), null);+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);controller.dispatch("GET", "restapi1", "prod", "hello", headers, null, null);diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.javaindex 1bdd5cca2c..89168dbbf2 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java@@ -36,7 +36,7 @@ class ApiGatewayProxyMatchTest {ctrl = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, lambdaService,new RegionResolver("us-east-1", "000000000000"),new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null,- new ApiGatewayExecuteRouteContext(), null);+ new ApiGatewayExecuteRouteContext(), null, null);}private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.javaindex 6cdcb3ac19..52469ac4f7 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java@@ -50,7 +50,7 @@ class BuildV2ProxyEventBodyEncodingTest {controller = new ApiGatewayExecuteController(null, null, null,regionResolver, objectMapper, null,- null, null, null, null, new ApiGatewayExecuteRouteContext(), null+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.javaindex 46c6691baa..9717c515b9 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java@@ -45,7 +45,7 @@ class BuildV2ProxyEventJwtClaimsTest {controller = new ApiGatewayExecuteController(null, null, null,regionResolver, new ObjectMapper(), null,- null, null, null, null, new ApiGatewayExecuteRouteContext(), null+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.javaindex 46edab3deb..2c87f3b60f 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java@@ -41,7 +41,7 @@ class BuildV2ProxyEventPathParametersTest {controller = new ApiGatewayExecuteController(null, null, null,regionResolver, new ObjectMapper(), null,- null, null, null, null, new ApiGatewayExecuteRouteContext(), null+ null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2UnsignedAccountRoutingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2UnsignedAccountRoutingTest.javanew file mode 100644index 0000000000..0a5f8ad8c6--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2UnsignedAccountRoutingTest.java@@ -0,0 +1,117 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.notNullValue;++@QuarkusTest+class ApiGatewayV2UnsignedAccountRoutingTest {++ private static final String ACCOUNT_A = "123456789012";+ private static final String ACCOUNT_B = "210987654321";++ @Test+ void signedAndUnsignedRequestsResolveTheAccountFromApiId() {+ String apiA = createApiGraph(ACCOUNT_A, "account-a-function");+ String apiB = createApiGraph(ACCOUNT_B, "account-b-function");++ given()+ .header("Authorization", authorization(ACCOUNT_B, "execute-api"))+ .when().get("/execute-api/" + apiA + "/$default/health")+ .then()+ .statusCode(404)+ .body(containsString("Function not found: account-a-function"));++ given()+ .header("Host", apiB + ".execute-api.localhost.floci.io")+ .when().get("/health")+ .then()+ .statusCode(404)+ .body(containsString("Function not found: account-b-function"));+ }++ @Test+ void rejectsDuplicateApiIdsAcrossAccounts() {+ String apiId = "shared-account-api";+ createApiWithId(ACCOUNT_A, apiId, 201);+ createApiWithId(ACCOUNT_B, apiId, 409);+ }++ private String createApiGraph(String accountId, String functionName) {+ String authorization = authorization(accountId, "apigatewayv2");+ String apiId = given()+ .contentType(ContentType.JSON)+ .header("Authorization", authorization)+ .body("""+ {"name":"shared-local-api","protocolType":"HTTP"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ String integrationId = given()+ .contentType(ContentType.JSON)+ .header("Authorization", authorization)+ .body("""+ {+ "integrationType":"AWS_PROXY",+ "integrationUri":"arn:aws:lambda:us-east-1:%s:function:%s",+ "payloadFormatVersion":"2.0"+ }+ """.formatted(accountId, functionName))+ .when().post("/v2/apis/" + apiId + "/integrations")+ .then()+ .statusCode(201)+ .body("integrationId", notNullValue())+ .extract().path("integrationId");++ given()+ .contentType(ContentType.JSON)+ .header("Authorization", authorization)+ .body("""+ {"routeKey":"GET /health","target":"integrations/%s"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + apiId + "/routes")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .header("Authorization", authorization)+ .body("""+ {"stageName":"$default","autoDeploy":true}+ """)+ .when().post("/v2/apis/" + apiId + "/stages")+ .then()+ .statusCode(201);++ return apiId;+ }++ private String authorization(String accountId, String service) {+ return "AWS4-HMAC-SHA256 Credential=" + accountId+ + "/20260803/us-east-1/" + service + "/aws4_request";+ }++ private void createApiWithId(String accountId, String apiId, int expectedStatus) {+ given()+ .contentType(ContentType.JSON)+ .header("Authorization", authorization(accountId, "apigatewayv2"))+ .body("""+ {+ "name":"account-owned-api",+ "protocolType":"HTTP",+ "tags":{"floci:override-id":"%s"}+ }+ """.formatted(apiId))+ .when().post("/v2/apis")+ .then()+ .statusCode(expectedStatus);+ }+}