Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(apigateway): route REST execute-api virtual hosts (#4553)

vamsiakaf3d387140b8
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index 4ae578040c..3e661c84d0 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -267,7 +267,11 @@ These management-plane operations have no handler in v1. Calls will return `404`
- Client Certificates (5 operations)
- `GetExport` / `ImportDocumentationParts`
-The execute plane (actual proxied HTTP traffic via `/restapis/{id}/{stage}/_user_request_/…`) is implemented separately and is not counted as management-plane operations. It supports these integration types; others return an error:
+The execute plane (actual proxied HTTP traffic via `/restapis/{id}/{stage}/_user_request_/…`)
+is implemented separately and is not counted as management-plane operations. A deployed REST
+API is also available at `http://{apiId}.execute-api.localhost.floci.io:4566/{stage}/{path}`
+and `/execute-api/{apiId}/{stage}/{path}`. All three forms use the same method authorization
+and mappings. It supports these integration types; others return an error:
| Type | Support |
| --- | --- |
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.java
index 16f88d7631..eb9a11d166 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
@@ -1636,7 +1636,8 @@ public class ApiGatewayController {
v1Request.put("restApiId", apiId);
v1Request.put("stage", stage);
v1Request.put("basePath", basePath);
- BasePathMapping mapping = service.createBasePathMapping(region, domainName, v1Request);
+ BasePathMapping mapping = service.createBasePathMapping(region, domainName, v1Request,
+ v2Service.getApi(region, apiId).getProtocolType());
return Response.status(201).entity(toApiMappingNode(basePath, mapping).toString())
.type(MediaType.APPLICATION_JSON).build();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java
index b51355ee0a..ed2304ab01 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -36,12 +37,15 @@ public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter {
private static final String REGIONAL_SUFFIX = ".regional.local";
private final ApiGatewayService apiGatewayService;
+ private final ApiGatewayV2Service apiGatewayV2Service;
private final ApiGatewayExecuteRouteContext routeContext;
@Inject
public ApiGatewayCustomDomainFilter(ApiGatewayService apiGatewayService,
+ ApiGatewayV2Service apiGatewayV2Service,
ApiGatewayExecuteRouteContext routeContext) {
this.apiGatewayService = apiGatewayService;
+ this.apiGatewayV2Service = apiGatewayV2Service;
this.routeContext = routeContext;
}
@@ -107,6 +111,14 @@ public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter {
LOG.debugv("Custom domain routing: {0}{1} -> {2}", host, path, newUri.getPath());
// AWS_IAM dispatch rebuilds the caller's canonical request, which covers the path they
// signed: the custom-domain path, not the /execute-api/... form this rewrite produces.
+ // Older persisted mappings have no type. Prefer REST if that API exists; otherwise
+ // retain v2 routing when a v2 API owns the id.
+ if ("REST".equals(mapping.getApiType())
+ || (mapping.getApiType() == null
+ && (apiGatewayService.hasRestApi(restApiId)
+ || apiGatewayV2Service.findApiOwner(restApiId).isEmpty()))) {
+ routeContext.routeToRestApi();
+ }
routeContext.recordSignedRequestPath(path);
requestContext.setRequestUri(newUri);
}
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.java
index c7e6bb486c..4df1b9c296 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
@@ -162,6 +162,12 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
return;
}
} catch (AwsException e) {
+ // The v2 owner lookup is account-independent. When it found no owner, let the
+ // REST execute controller resolve the API after account context is established.
+ if (owner.isEmpty()) {
+ routeToRestApi(requestContext, originalUri, originalPath, apiId);
+ return;
+ }
LOG.debugv(e, "Execute API host did not resolve to a routable API: apiId={0}, region={1}",
apiId, region);
return;
@@ -195,6 +201,18 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
requestContext.setRequestUri(newUri);
}
+ private void routeToRestApi(ContainerRequestContext requestContext, URI originalUri,
+ String originalPath, String apiId) {
+ String path = originalPath == null || originalPath.isEmpty() ? "/" : originalPath;
+ URI newUri = UriBuilder.fromUri(originalUri)
+ .replacePath("/execute-api/" + apiId + path)
+ .buildFromEncoded();
+ LOG.debugv("REST execute-api host routing: {0} -> {1}", originalPath, newUri.getRawPath());
+ routeContext.routeToRestApi();
+ routeContext.recordSignedRequestPath(originalPath);
+ requestContext.setRequestUri(newUri);
+ }
+
private boolean stageExists(String region, String apiId, String stageName) {
try {
apiGatewayLookup.requireStage(region, apiId, stageName);
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.java
index 651c923a44..bc798b67fe 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
@@ -168,6 +168,13 @@ public class ApiGatewayExecuteController {
private static final String CONNECTIONS_PREFIX = "@connections/";
+ private boolean isWebSocketConnectionRequest(String apiId, String proxy) {
+ if (proxy == null || !proxy.startsWith(CONNECTIONS_PREFIX) || routeContext.isRestApiRoute()) {
+ return false;
+ }
+ return apiGatewayV2Service.hasWebSocketApi(apiId);
+ }
+
private String decodeConnectionId(String rawConnectionId) {
return URLDecoder.decode(rawConnectionId, StandardCharsets.UTF_8);
}
@@ -230,7 +237,7 @@ public class ApiGatewayExecuteController {
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
- if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
+ if (isWebSocketConnectionRequest(apiId, proxy)) {
String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
return handleGetConnectionInfo(connectionId);
}
@@ -245,7 +252,7 @@ public class ApiGatewayExecuteController {
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy,
byte[] body) {
- if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
+ if (isWebSocketConnectionRequest(apiId, proxy)) {
String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
return handlePostToConnection(connectionId, body);
}
@@ -270,7 +277,7 @@ public class ApiGatewayExecuteController {
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
- if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
+ if (isWebSocketConnectionRequest(apiId, proxy)) {
String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
return handleDeleteConnection(connectionId);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java
index e433b59c1c..9950f21855 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java
@@ -11,6 +11,7 @@ import jakarta.ws.rs.core.UriInfo;
public class ApiGatewayExecuteRouteContext {
private String httpApiRegion;
+ private boolean restApiRoute;
private String signedRequestPath;
void routeToHttpApi(String region) {
@@ -21,6 +22,14 @@ public class ApiGatewayExecuteRouteContext {
return httpApiRegion;
}
+ void routeToRestApi() {
+ this.restApiRoute = true;
+ }
+
+ boolean isRestApiRoute() {
+ return restApiRoute;
+ }
+
/**
* Records the raw path as the client sent it, before a pre-matching filter rewrote the request
* URI onto the internal {@code /execute-api/...} form. SigV4 covers the path the caller signed,
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.java
index 343dfc582e..4c04fd155a 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
@@ -332,6 +332,11 @@ public class ApiGatewayService {
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404));
}
+ public boolean hasRestApi(String apiId) {
+ return apiStore.keys().stream().anyMatch(key -> key.endsWith("::" + apiId));
+ }
+
+
public String resolveRestApiRegion(String preferredRegion, String apiId) {
if (apiStore.get(apiKey(preferredRegion, apiId)).isPresent()) {
return preferredRegion;
@@ -2122,11 +2127,17 @@ public class ApiGatewayService {
}
public BasePathMapping createBasePathMapping(String region, String domainName, Map<String, Object> request) {
+ return createBasePathMapping(region, domainName, request, "REST");
+ }
+
+ BasePathMapping createBasePathMapping(String region, String domainName,
+ Map<String, Object> request, String apiType) {
String basePath = canonicalBasePath((String) request.get("basePath"));
String apiId = (String) request.get("restApiId");
String stage = (String) request.get("stage");
BasePathMapping mapping = new BasePathMapping(basePath, apiId, stage);
+ mapping.setApiType(apiType);
synchronized (domainNameLock) {
getDomainName(region, domainName);
String key = mappingKey(region, domainName, basePath);
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/BasePathMapping.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/BasePathMapping.java
index 0846c2e076..17b88719ad 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/BasePathMapping.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/BasePathMapping.java
@@ -9,6 +9,7 @@ public class BasePathMapping {
private String basePath;
private String restApiId;
private String stage;
+ private String apiType;
public BasePathMapping() {
this.basePath = "(none)";
@@ -28,4 +29,7 @@ public class BasePathMapping {
public String getStage() { return stage; }
public void setStage(String stage) { this.stage = stage; }
+
+ public String getApiType() { return apiType; }
+ public void setApiType(String apiType) { this.apiType = apiType; }
}
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.java
index 273d54b5b0..9500e39ec4 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
@@ -193,6 +193,12 @@ public class ApiGatewayV2Service {
.map(entry -> new ApiOwner(entry.accountId(), regionFromApiKey(entry.key())));
}
+ /** Connection management only needs to know whether any owner uses this ID for WebSocket. */
+ public boolean hasWebSocketApi(String apiId) {
+ return apiStore.scanAllAccountEntries(key -> key.endsWith("::" + apiId)).stream()
+ .anyMatch(entry -> "WEBSOCKET".equals(entry.value().getProtocolType()));
+ }
+
private static String regionFromApiKey(String key) {
int delimiter = key.indexOf("::");
if (delimiter <= 0) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilterTest.java
index a16225b0fb..bb6593cfa0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilterTest.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
@@ -29,7 +30,8 @@ class ApiGatewayCustomDomainFilterTest {
URI.create("http://" + DOMAIN + ".regional.local:4566/v1/iam?tenant=alpha"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
- new ApiGatewayCustomDomainFilter(service, routeContext).filter(request.context());
+ new ApiGatewayCustomDomainFilter(service, mock(ApiGatewayV2Service.class), routeContext)
+ .filter(request.context());
assertEquals("/execute-api/" + API_ID + "/prod/iam", request.routedUri().getRawPath());
assertEquals("tenant=alpha", request.routedUri().getRawQuery());
@@ -43,7 +45,8 @@ class ApiGatewayCustomDomainFilterTest {
DOMAIN, URI.create("http://" + DOMAIN + "/orders/42"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
- new ApiGatewayCustomDomainFilter(service, routeContext).filter(request.context());
+ new ApiGatewayCustomDomainFilter(service, mock(ApiGatewayV2Service.class), routeContext)
+ .filter(request.context());
assertEquals("/execute-api/" + API_ID + "/prod/orders/42", request.routedUri().getRawPath());
assertEquals("/orders/42", routeContext.signedRequestPath());
@@ -56,7 +59,8 @@ class ApiGatewayCustomDomainFilterTest {
"localhost:4566", URI.create("http://localhost:4566/v1/iam"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
- new ApiGatewayCustomDomainFilter(service, routeContext).filter(request.context());
+ new ApiGatewayCustomDomainFilter(service, mock(ApiGatewayV2Service.class), routeContext)
+ .filter(request.context());
assertNull(request.routedUri());
assertNull(routeContext.signedRequestPath());
@@ -72,7 +76,8 @@ class ApiGatewayCustomDomainFilterTest {
DOMAIN, URI.create("http://" + DOMAIN + "/unmapped"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
- new ApiGatewayCustomDomainFilter(service, routeContext).filter(request.context());
+ new ApiGatewayCustomDomainFilter(service, mock(ApiGatewayV2Service.class), routeContext)
+ .filter(request.context());
assertNull(request.routedUri());
assertNull(routeContext.signedRequestPath());
@@ -83,6 +88,7 @@ class ApiGatewayCustomDomainFilterTest {
CustomDomain domain = new CustomDomain();
domain.setDomainName(DOMAIN);
BasePathMapping mapping = new BasePathMapping(basePath, API_ID, stage);
+ mapping.setApiType("REST");
when(service.findDomainByRegionalHostname(DOMAIN + ".regional.local")).thenReturn(domain);
when(service.findDomainByName(DOMAIN)).thenReturn(domain);
when(service.resolveBasePathMapping(anyString(), anyString())).thenReturn(mapping);
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java
index f1cd317104..7ab540b0a8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java
@@ -85,6 +85,24 @@ class ApiGatewayExecuteApiHostFilterTest {
assertEquals("/execute-api/abc123/dev/", request.routedUri().getRawPath());
}
+ @Test
+ void routesRestHostWhenNoV2ApiOwnsTheIdentifier() {
+ FakeApiGatewayLookup lookup = new FakeApiGatewayLookup();
+ RecordingRequest request = new RecordingRequest(
+ "abc123.execute-api.localhost.floci.io",
+ URI.create("http://abc123.execute-api.localhost.floci.io/dev/deep/path?value=a%2Fb"));
+ ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
+
+ new ApiGatewayExecuteApiHostFilter(
+ lookup, new RegionResolver(REGION, "000000000000"), routeContext)
+ .filter(request.context());
+
+ assertEquals("/execute-api/abc123/dev/deep/path", request.routedUri().getRawPath());
+ assertEquals("value=a%2Fb", request.routedUri().getRawQuery());
+ assertNull(routeContext.httpApiRegion());
+ assertEquals("/dev/deep/path", routeContext.signedRequestPath());
+ }
+
@Test
void resolvesUnsignedApiOutsideDefaultRegion() {
FakeApiGatewayLookup lookup = new FakeApiGatewayLookup();
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRestExecuteApiHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRestExecuteApiHostIntegrationTest.java
new file mode 100644
index 0000000000..f198ba7508
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRestExecuteApiHostIntegrationTest.java
@@ -0,0 +1,306 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.RequestScopes;
+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
+import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
+import io.github.hectorvent.floci.testing.ConfiguredHostnameProfile;
+import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.http.ContentType;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+@QuarkusTest
+@TestProfile(ConfiguredHostnameProfile.class)
+class ApiGatewayRestExecuteApiHostIntegrationTest {
+
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ @Inject
+ ApiGatewayV2Service v2Service;
+
+ @Test
+ void routesRestApiVirtualHostToDeployedMethods() {
+ String apiId = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec())
+ .when().post("/restapis")
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201);
+
+ given()
+ .when().get("/execute-api/" + apiId + "/test/ping")
+ .then().statusCode(200)
+ .body("route", equalTo("ping"));
+
+ given()
+ .header("Host", apiId + ".execute-api.localhost.floci.io:4566")
+ .when().get("/test/ping")
+ .then().statusCode(200)
+ .body("route", equalTo("ping"));
+
+ given()
+ .header("Host", apiId + ".execute-api.localhost.floci.io:4566")
+ .when().get("/test/deep/path")
+ .then().statusCode(200)
+ .body("route", equalTo("nested"));
+
+ given()
+ .header("Host", apiId + ".execute-api.localhost.floci.io:4566")
+ .when().get("/test/@connections/demo")
+ .then().statusCode(200)
+ .body("route", equalTo("rest-connection"));
+
+ given()
+ .when().get("/execute-api/" + apiId + "/test/@connections/demo")
+ .then().statusCode(200)
+ .body("route", equalTo("rest-connection"));
+
+ given()
+ .when().get("/restapis/" + apiId + "/test/_user_request_/ping")
+ .then().statusCode(200)
+ .body("route", equalTo("ping"));
+ }
+
+ @Test
+ void signedRestHostRequestUsesOriginalPath() throws Exception {
+ String apiId = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec())
+ .when().post("/restapis")
+ .then().statusCode(201)
+ .extract().path("id");
+ String methodPath = "/restapis/" + apiId + "/resources/" + resourceId(apiId, "/ping")
+ + "/methods/GET";
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/authorizationType\","
+ + "\"value\":\"AWS_IAM\"}]}")
+ .when().patch(methodPath)
+ .then().statusCode(200)
+ .body("authorizationType", equalTo("AWS_IAM"));
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"signed\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201);
+
+ String host = apiId + ".execute-api.localhost.floci.io:4566";
+ String path = "/signed/ping";
+ given()
+ .header("Host", host)
+ .when().get(path)
+ .then().statusCode(403);
+
+ Map<String, String> signedHeaders = ExecuteApiRequestSigner.signedHeaders(
+ "GET", path, Map.of(), host, null, "test", "test", "us-east-1", Instant.now());
+ given()
+ .header("Host", host)
+ .headers(signedHeaders)
+ .when().get(path)
+ .then().statusCode(200)
+ .body("route", equalTo("ping"));
+ }
+
+ @Test
+ void websocketConnectionManagementStillUsesWebSocketApi() {
+ String apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"connection-routing\",\"protocolType\":\"WEBSOCKET\","
+ + "\"routeSelectionExpression\":\"$request.body.action\"}")
+ .when().post("/v2/apis")
+ .then().statusCode(201)
+ .extract().path("apiId");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\"}")
+ .when().post("/v2/apis/" + apiId + "/stages")
+ .then().statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"rest-id-collision\",\"tags\":{\"floci:override-id\":\"" + apiId + "\"}}")
+ .when().post("/restapis")
+ .then().statusCode(201)
+ .body("id", equalTo(apiId));
+
+ given()
+ .when().get("/execute-api/" + apiId + "/test/@connections/missing")
+ .then().statusCode(410);
+
+ given()
+ .header("Host", apiId + ".execute-api.localhost.floci.io:4566")
+ .when().get("/test/@connections/missing")
+ .then().statusCode(410);
+ }
+
+ @Test
+ void restCustomDomainWinsOverWebSocketIdCollision() {
+ String apiId = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec())
+ .when().post("/restapis")
+ .then().statusCode(201)
+ .extract().path("id");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"websocket-id-collision\",\"protocolType\":\"WEBSOCKET\","
+ + "\"routeSelectionExpression\":\"$request.body.action\","
+ + "\"tags\":{\"floci:override-id\":\"" + apiId + "\"}}")
+ .when().post("/v2/apis")
+ .then().statusCode(201)
+ .body("apiId", equalTo(apiId));
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"domainName\":\"collision.example.com\","
+ + "\"certificateArn\":\"arn:aws:acm:us-east-1:000000000000:certificate/demo\"}")
+ .when().post("/domainnames")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"basePath\":\"(none)\",\"restApiId\":\"" + apiId + "\",\"stage\":\"test\"}")
+ .when().post("/domainnames/collision.example.com/basepathmappings")
+ .then().statusCode(201);
+
+ given()
+ .header("Host", "collision.example.com.regional.local")
+ .when().get("/@connections/demo")
+ .then().statusCode(200)
+ .body("route", equalTo("rest-connection"));
+
+ given()
+ .when().get("/execute-api/" + apiId + "/test/@connections/missing")
+ .then().statusCode(410);
+ }
+
+ @Test
+ void websocketApiMappingKeepsConnectionManagementWithRestIdCollision() {
+ String apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"websocket-domain\",\"protocolType\":\"WEBSOCKET\","
+ + "\"routeSelectionExpression\":\"$request.body.action\"}")
+ .when().post("/v2/apis")
+ .then().statusCode(201)
+ .extract().path("apiId");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\"}")
+ .when().post("/v2/apis/" + apiId + "/stages")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"domainName\":\"websocket.example.com\","
+ + "\"domainNameConfigurations\":[{\"endpointType\":\"REGIONAL\"}]}")
+ .when().post("/v2/domainnames")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"apiId\":\"" + apiId + "\",\"stage\":\"test\"}")
+ .when().post("/v2/domainnames/websocket.example.com/apimappings")
+ .then().statusCode(201);
+
+ given()
+ .header("Host", "websocket.example.com.regional.local")
+ .when().get("/@connections/missing")
+ .then().statusCode(410);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"rest-id-collision\",\"tags\":{\"floci:override-id\":\"" + apiId + "\"}}")
+ .when().post("/restapis")
+ .then().statusCode(201)
+ .body("id", equalTo(apiId));
+ given()
+ .header("Host", "websocket.example.com.regional.local")
+ .when().get("/@connections/missing")
+ .then().statusCode(410);
+ }
+
+ @Test
+ void directWebSocketConnectionRoutingFindsNonDefaultAndDuplicateOwners() {
+ String authorization = "AWS4-HMAC-SHA256 Credential=000000000001/20260929/us-east-1/apigateway/aws4_request, "
+ + "SignedHeaders=host, Signature=abc";
+ String apiId = given()
+ .header("Authorization", authorization)
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"other-account-websocket\",\"protocolType\":\"WEBSOCKET\","
+ + "\"routeSelectionExpression\":\"$request.body.action\"}")
+ .when().post("/v2/apis")
+ .then().statusCode(201)
+ .extract().path("apiId");
+ given()
+ .when().get("/execute-api/" + apiId + "/test/@connections/missing")
+ .then().statusCode(410);
+
+ Api firstAccountApi = RequestScopes.callAs("000000000001",
+ () -> v2Service.getApi("us-east-1", apiId));
+ RequestScopes.runAs("000000000002", () -> v2Service.putApi("us-east-1", firstAccountApi));
+ try {
+ given()
+ .when().get("/execute-api/" + apiId + "/test/@connections/missing")
+ .then().statusCode(410);
+ } finally {
+ RequestScopes.runAs("000000000002", () -> v2Service.deleteApi("us-east-1", apiId));
+ RequestScopes.runAs("000000000001", () -> v2Service.deleteApi("us-east-1", apiId));
+ }
+ }
+
+ private static String resourceId(String apiId, String path) throws Exception {
+ String resources = given()
+ .when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200)
+ .extract().asString();
+ for (JsonNode resource : JSON.readTree(resources).path("item")) {
+ if (path.equals(resource.path("path").asText())) {
+ return resource.path("id").asText();
+ }
+ }
+ throw new AssertionError("Imported resource was not found: " + path);
+ }
+
+ private static String spec() {
+ ObjectNode root = JSON.createObjectNode();
+ root.put("openapi", "3.0.1");
+ root.putObject("info").put("title", "REST virtual host").put("version", "1.0");
+ ObjectNode paths = root.putObject("paths");
+ addMockMethod(paths, "/ping", "ping");
+ addMockMethod(paths, "/deep/path", "nested");
+ addMockMethod(paths, "/@connections/demo", "rest-connection");
+ return root.toString();
+ }
+
+ private static void addMockMethod(ObjectNode paths, String path, String route) {
+ ObjectNode operation = paths.putObject(path).putObject("get");
+ operation.putObject("responses").putObject("200").put("description", "ok");
+ ObjectNode integration = operation.putObject("x-amazon-apigateway-integration");
+ integration.put("type", "mock");
+ integration.putObject("requestTemplates").put("application/json", "{\"statusCode\":200}");
+ integration.putObject("responses").putObject("default")
+ .put("statusCode", "200")
+ .putObject("responseTemplates").put("application/json", "{\"route\":\"" + route + "\"}");
+ }
+}