feat(apigatewayv2): HTTP_PROXY integration with request parameter mapping (#860)

* feat(apigatewayv2): HTTP_PROXY integration with request parameter mapping

Adds full HTTP_PROXY support to API Gateway v2 dispatch, replacing the
previous Lambda-only assumption. Integrations with IntegrationType=HTTP_PROXY
now forward the inbound request to the configured IntegrationUri,
applying RequestParameters transformations.

Supported RequestParameters action × target combinations:
  overwrite | append | remove  ×  path | header.<name> | querystring.<name>

Supported source value expressions:
  $context.authorizer.claims.<name>     JWT claim from authorizer
  $context.authorizer.<name>            authorizer context value
  $context.requestId                    UUID assigned per request
  $context.identity.sourceIp            client IP
  $request.header.<name>                case-insensitive header lookup
  $request.querystring.<name>           query parameter
  $request.path.<name>                  captured path parameter
  literal strings                       returned unchanged

The IntegrationUri may contain {proxy} or {paramName} placeholders,
substituted with captured path parameters from the matched route.
overwrite:path values may also embed $request.path.X / $context.X
substrings which are resolved in-place.

Implementation:
- New package services.apigatewayv2.proxy with RequestContext (DTO),
  ContextValueResolver (source expression parser), PathTemplateResolver
  (URI template substitution), ProxyRequestBuilder (mutable outgoing
  request), RequestParameterMapper (applies RequestParameters), and
  HttpProxyInvoker (orchestrator using java.net.http.HttpClient).
- ApiGatewayExecuteController.dispatchV2 now branches on
  integration.getIntegrationType() and routes HTTP_PROXY requests to
  HttpProxyInvoker, building a RequestContext from the controller state
  including parsed JWT claims for $context.authorizer.claims.X.
- Integration v2 model gains a requestParameters Map field, persisted
  by ApiGatewayV2Service create/update and serialized by both the
  AWS JSON 1.1 handler and the REST controller.

Bug fixes (encountered during integration testing):
- routeKeyMatchesPath now treats `ANY` as the AWS wildcard method,
  matching any inbound HTTP method (previously did literal string
  comparison and rejected ANY routes for non-ANY requests).
- JWT authorizer audience check now also accepts `client_id` claim,
  which Cognito access tokens use instead of `aud` (only ID tokens
  carry `aud`). AWS API Gateway accepts either; floci now matches.

Tests:
- 11 ContextValueResolver tests covering each source expression form
- 7 PathTemplateResolver tests covering placeholder substitution
- 13 RequestParameterMapper tests covering each action × target
- 7 HttpProxyInvokerTest tests using JDK com.sun.net.httpserver as a
  real backend, verifying method/path/headers/body forwarding,
  RequestParameters application, hop-by-hop header stripping, and
  502 error mapping for backend failures
- 1 round-trip integration test confirming RequestParameters survive
  CreateIntegration → GetIntegration via the AWS JSON 1.1 handler

* perf(apigatewayv2): cache compiled route-template patterns per route key

extractV2PathParams compiled both the routing regex and the
parameter-name extraction regex on every inbound request. Route
keys are stable after creation, so this is wasted work on every
request — visible under load on frequently-hit paths.

Cache the routing regex in a ConcurrentHashMap<String, Pattern>
keyed by the raw template string, and hoist the constant
parameter-name pattern to a static final field.

Adds ApiGatewayExecuteControllerTest with 8 cases covering greedy,
non-greedy, mixed, and edge inputs, plus a hot-loop assertion that
repeated calls against the same route key return stable results
(the cache itself is an internal implementation detail and is not
asserted directly).

* fix(apigatewayv2): accept {name+} greedy placeholder in IntegrationUri

PathTemplateResolver's PLACEHOLDER regex matched {paramName} but not
{paramName+}, so configuring IntegrationUri = "http://backend/{proxy+}"
forwarded the literal string "{proxy+}" to the backend and the call
silently 404'd. The mismatch is surprising because {proxy+} is the
canonical AWS form already accepted by route keys (e.g.
"ANY /wallet/{proxy+}"), so most users mirroring the route shape in
the IntegrationUri hit this.

Extend the placeholder pattern with \+? so {name} and {name+} both
resolve to the same parameter keyed by name. Captured path params
are still stored under the bare name (no + suffix), matching the
existing extractV2PathParams behavior, so no other call sites change.

Picked this over documenting the limitation because the AWS
convention is widely expected and the fix is one character.

Adds 4 tests to PathTemplateResolverTest for {name+}: greedy proxy,
greedy named, mixed greedy + non-greedy, and missing-key fallback.
This commit is contained in:
Ricardo Medina authored and GitHub committed 2026-05-17 00:35:42 -05:00
1 parent 0123844d83
commit dc2efe75e8
18 files changed
+1260 -4

No files matched your search

@@ -0,0 +1,79 @@
package io.github.hectorvent.floci.services.apigateway;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Verifies {@link ApiGatewayExecuteController#extractV2PathParams(String, String)}
* captures path parameters correctly for both greedy ({proxy+}) and non-greedy
* ({proxy}) route templates, and that repeated invocations against the same
* route key reuse the cached compiled Pattern (correctness check; the cache
* itself is an internal implementation detail).
*/
class ApiGatewayExecuteControllerTest {
@Test
void capturesGreedyProxyMultiSegment() {
Map<String, String> p = ApiGatewayExecuteController.extractV2PathParams(
"ANY /wallet/{proxy+}", "/wallet/users/123/orders");
assertEquals("users/123/orders", p.get("proxy"));
}
@Test
void capturesNonGreedyNamedParam() {
Map<String, String> p = ApiGatewayExecuteController.extractV2PathParams(
"GET /users/{id}", "/users/42");
assertEquals("42", p.get("id"));
}
@Test
void capturesMultipleNamedParams() {
Map<String, String> p = ApiGatewayExecuteController.extractV2PathParams(
"GET /users/{user}/orders/{order}", "/users/u-1/orders/o-2");
assertEquals("u-1", p.get("user"));
assertEquals("o-2", p.get("order"));
}
@Test
void capturesMixedGreedyAndNamedParams() {
Map<String, String> p = ApiGatewayExecuteController.extractV2PathParams(
"ANY /users/{user}/files/{path+}", "/users/u-1/files/a/b/c");
assertEquals("u-1", p.get("user"));
assertEquals("a/b/c", p.get("path"));
}
@Test
void noMatchReturnsEmptyMap() {
Map<String, String> p = ApiGatewayExecuteController.extractV2PathParams(
"GET /users/{id}", "/orders/42");
assertTrue(p.isEmpty());
}
@Test
void nullRouteKeyReturnsEmptyMap() {
assertTrue(ApiGatewayExecuteController.extractV2PathParams(null, "/x").isEmpty());
}
@Test
void malformedRouteKeyReturnsEmptyMap() {
// No method/path split — caller passed garbage.
assertTrue(ApiGatewayExecuteController.extractV2PathParams("garbage", "/x").isEmpty());
}
@Test
void repeatedCallsAgainstSameRouteAreStable() {
// Second hit reuses the cached compiled Pattern; output must be
// identical for the same inputs. Run hot to give the cache a chance
// to be exercised across multiple invocations.
String routeKey = "ANY /payments/{proxy+}";
for (int i = 0; i < 100; i++) {
Map<String, String> p = ApiGatewayExecuteController.extractV2PathParams(
routeKey, "/payments/spei/" + i);
assertEquals("spei/" + i, p.get("proxy"));
}
}
}
@@ -216,4 +216,69 @@ class ApiGatewayV2JsonHandlerTest {
given().when().delete("/v2/apis/" + apiId + "/stages/prod").then().statusCode(204);
given().when().delete("/v2/apis/" + apiId).then().statusCode(204);
}
@Test
@Order(20)
void json11CreateIntegrationWithRequestParametersRoundTrips() throws Exception {
// Create a fresh API for this test (the cleanup test removed the previous one)
String localApiId = given()
.contentType(AMZ_JSON)
.header("X-Amz-Target", TARGET_PREFIX + "CreateApi")
.header("Authorization", AUTH_HEADER)
.body("""
{"Name":"rp-test","ProtocolType":"HTTP"}
""")
.when().post("/")
.then().statusCode(201).extract().path("ApiId");
// Create HTTP_PROXY integration with RequestParameters
String createBody = given()
.contentType(AMZ_JSON)
.header("X-Amz-Target", TARGET_PREFIX + "CreateIntegration")
.header("Authorization", AUTH_HEADER)
.body("""
{
"ApiId": "%s",
"IntegrationType": "HTTP_PROXY",
"IntegrationUri": "http://example.com/{proxy}",
"PayloadFormatVersion": "1.0",
"RequestParameters": {
"overwrite:path": "/public/$request.path.proxy",
"overwrite:header.Host": "wallet.internal",
"append:header.x-user-id": "$context.authorizer.claims.userId"
}
}
""".formatted(localApiId))
.when().post("/")
.then().statusCode(201).extract().asString();
com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
com.fasterxml.jackson.databind.JsonNode created = mapper.readTree(createBody);
String localIntegrationId = created.get("IntegrationId").asText();
org.junit.jupiter.api.Assertions.assertEquals("HTTP_PROXY", created.get("IntegrationType").asText());
com.fasterxml.jackson.databind.JsonNode createdRP = created.get("RequestParameters");
org.junit.jupiter.api.Assertions.assertNotNull(createdRP, "CreateIntegration response should include RequestParameters");
org.junit.jupiter.api.Assertions.assertEquals("/public/$request.path.proxy", createdRP.get("overwrite:path").asText());
org.junit.jupiter.api.Assertions.assertEquals("wallet.internal", createdRP.get("overwrite:header.Host").asText());
org.junit.jupiter.api.Assertions.assertEquals("$context.authorizer.claims.userId", createdRP.get("append:header.x-user-id").asText());
// Get the integration and assert RequestParameters survived persistence
String getBody = given()
.contentType(AMZ_JSON)
.header("X-Amz-Target", TARGET_PREFIX + "GetIntegration")
.header("Authorization", AUTH_HEADER)
.body("""
{"ApiId":"%s","IntegrationId":"%s"}
""".formatted(localApiId, localIntegrationId))
.when().post("/")
.then().statusCode(200).extract().asString();
com.fasterxml.jackson.databind.JsonNode getRP = mapper.readTree(getBody).get("RequestParameters");
org.junit.jupiter.api.Assertions.assertNotNull(getRP, "GetIntegration response should include RequestParameters");
org.junit.jupiter.api.Assertions.assertEquals("/public/$request.path.proxy", getRP.get("overwrite:path").asText());
org.junit.jupiter.api.Assertions.assertEquals("$context.authorizer.claims.userId", getRP.get("append:header.x-user-id").asText());
// Cleanup
given().when().delete("/v2/apis/" + localApiId).then().statusCode(204);
}
}
@@ -0,0 +1,103 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Verifies {@link ContextValueResolver} resolves the documented HTTP API v2
* source value expressions: $context.*, $request.*, and literal pass-through.
*/
class ContextValueResolverTest {
private RequestContext ctx(Map<String, Object> claims, Map<String, Object> authContext,
Map<String, String> headers, Map<String, String> query,
Map<String, String> pathParams) {
return new RequestContext("api1", "$default", "GET", "/foo", "foo", "ANY /foo",
"req-1", "1.2.3.4", headers, query, pathParams, null, claims, authContext);
}
@Test
void literalValuePassesThrough() {
var r = new ContextValueResolver();
assertEquals("wallet.internal",
r.resolve("wallet.internal", ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
}
@Test
void contextAuthorizerClaimsResolves() {
var r = new ContextValueResolver();
var c = ctx(Map.of("userId", "u-123", "email", "a@b.com"),
Map.of(), Map.of(), Map.of(), Map.of());
assertEquals("u-123", r.resolve("$context.authorizer.claims.userId", c));
assertEquals("a@b.com", r.resolve("$context.authorizer.claims.email", c));
}
@Test
void contextAuthorizerClaimsMissingReturnsNull() {
var r = new ContextValueResolver();
assertNull(r.resolve("$context.authorizer.claims.missing",
ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
}
@Test
void contextAuthorizerArbitraryKeyResolves() {
var r = new ContextValueResolver();
var c = ctx(Map.of(), Map.of("principalId", "p-1"), Map.of(), Map.of(), Map.of());
assertEquals("p-1", r.resolve("$context.authorizer.principalId", c));
}
@Test
void contextRequestIdResolves() {
var r = new ContextValueResolver();
assertEquals("req-1",
r.resolve("$context.requestId", ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
}
@Test
void contextSourceIpResolves() {
var r = new ContextValueResolver();
assertEquals("1.2.3.4",
r.resolve("$context.identity.sourceIp", ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
}
@Test
void requestHeaderResolvesCaseInsensitive() {
var r = new ContextValueResolver();
var c = ctx(Map.of(), Map.of(), Map.of("X-Forwarded-For", "5.6.7.8"), Map.of(), Map.of());
assertEquals("5.6.7.8", r.resolve("$request.header.X-Forwarded-For", c));
assertEquals("5.6.7.8", r.resolve("$request.header.x-forwarded-for", c));
}
@Test
void requestQuerystringResolves() {
var r = new ContextValueResolver();
var c = ctx(Map.of(), Map.of(), Map.of(), Map.of("page", "2"), Map.of());
assertEquals("2", r.resolve("$request.querystring.page", c));
}
@Test
void requestPathResolves() {
var r = new ContextValueResolver();
var c = ctx(Map.of(), Map.of(), Map.of(), Map.of(),
Map.of("proxy", "users/123", "id", "42"));
assertEquals("users/123", r.resolve("$request.path.proxy", c));
assertEquals("42", r.resolve("$request.path.id", c));
}
@Test
void unknownExpressionReturnsNull() {
var r = new ContextValueResolver();
assertNull(r.resolve("$context.unknown",
ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
}
@Test
void nullExpressionReturnsNull() {
var r = new ContextValueResolver();
assertNull(r.resolve(null, ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
}
}
@@ -0,0 +1,217 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Verifies {@link HttpProxyInvoker} forwards method, path, headers, and body
* to a real backend HTTP server, applies RequestParameters transformations,
* and propagates the response back as a ProxyResult.
*/
class HttpProxyInvokerTest {
private HttpServer backend;
private int backendPort;
private final AtomicReference<RecordedRequest> received = new AtomicReference<>();
private record RecordedRequest(String method, String path, String query, Headers headers, byte[] body) {}
@BeforeEach
void setUp() throws IOException {
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backend.createContext("/", exchange -> {
byte[] reqBody = exchange.getRequestBody().readAllBytes();
received.set(new RecordedRequest(
exchange.getRequestMethod(),
exchange.getRequestURI().getPath(),
exchange.getRequestURI().getQuery(),
exchange.getRequestHeaders(),
reqBody));
byte[] resp = "{\"ok\":true}".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.getResponseHeaders().add("X-Backend", "true");
exchange.sendResponseHeaders(200, resp.length);
exchange.getResponseBody().write(resp);
exchange.close();
});
backend.start();
backendPort = backend.getAddress().getPort();
}
@AfterEach
void tearDown() {
backend.stop(0);
}
private Integration httpProxyIntegration(String uri, Map<String, String> requestParameters) {
Integration i = new Integration();
i.setIntegrationType("HTTP_PROXY");
i.setIntegrationUri(uri);
i.setIntegrationMethod("ANY");
i.setRequestParameters(requestParameters);
return i;
}
private RequestContext ctxFor(String method, String path, String proxy, Map<String, String> headers,
Map<String, String> query, byte[] body, Map<String, Object> claims) {
return new RequestContext("api1", "$default", method, path, proxy, "ANY /wallet/{proxy+}",
"req-test", "127.0.0.1", headers, query,
proxy == null ? Map.of() : Map.of("proxy", proxy),
body, claims, Map.of());
}
@Test
void forwardsMethodPathAndBody() {
Integration integration = httpProxyIntegration(
"http://127.0.0.1:" + backendPort + "/public/{proxy}",
null);
RequestContext ctx = ctxFor("POST", "/wallet/balance", "balance",
Map.of("Content-Type", "application/json"),
Map.of(),
"{\"a\":1}".getBytes(StandardCharsets.UTF_8),
Map.of());
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
assertEquals(200, result.statusCode());
RecordedRequest r = received.get();
assertNotNull(r, "backend should have received the request");
assertEquals("POST", r.method());
assertEquals("/public/balance", r.path());
assertEquals("{\"a\":1}", new String(r.body(), StandardCharsets.UTF_8));
}
@Test
void appliesRequestParametersHeaderInjection() {
Integration integration = httpProxyIntegration(
"http://127.0.0.1:" + backendPort + "/public/{proxy}",
Map.of("append:header.x-user-id", "$context.authorizer.claims.userId"));
RequestContext ctx = ctxFor("GET", "/wallet/balance", "balance",
Map.of(), Map.of(), null,
Map.of("userId", "u-42"));
new HttpProxyInvoker().invoke(integration, ctx);
assertEquals("u-42", received.get().headers().getFirst("X-User-Id"));
}
@Test
void overwritePathReplacesBackendPath() {
Integration integration = httpProxyIntegration(
"http://127.0.0.1:" + backendPort + "/wrong",
Map.of("overwrite:path", "/public/$request.path.proxy"));
RequestContext ctx = ctxFor("GET", "/wallet/balance", "balance",
Map.of(), Map.of(), null, Map.of());
new HttpProxyInvoker().invoke(integration, ctx);
assertEquals("/public/balance", received.get().path());
}
@Test
void hopByHopHeadersAreNotForwarded() {
Integration integration = httpProxyIntegration(
"http://127.0.0.1:" + backendPort + "/foo",
null);
Map<String, String> headers = new LinkedHashMap<>();
headers.put("Connection", "close");
headers.put("Transfer-Encoding", "chunked");
headers.put("X-Custom", "kept");
RequestContext ctx = ctxFor("GET", "/wallet/foo", "foo",
headers, Map.of(), null, Map.of());
new HttpProxyInvoker().invoke(integration, ctx);
Headers received = this.received.get().headers();
// We sent "Connection: close" inbound. The JDK HttpClient may set its own
// Connection header (e.g. "Upgrade, HTTP2-Settings" for HTTP/2 negotiation),
// but our inbound "close" must NOT pass through.
String conn = received.getFirst("Connection");
if (conn != null) {
assertFalse(conn.toLowerCase().contains("close"),
"inbound Connection: close must not be forwarded; got: " + conn);
}
// Also, Transfer-Encoding from inbound must not be forwarded
assertNull(received.getFirst("Transfer-encoding"),
"Transfer-Encoding should be stripped (hop-by-hop)");
assertEquals("kept", received.getFirst("X-Custom"));
}
@Test
void responseStatusAndBodyPropagated() {
backend.removeContext("/");
backend.createContext("/", exchange -> {
byte[] resp = "{\"err\":\"not found\"}".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(404, resp.length);
exchange.getResponseBody().write(resp);
exchange.close();
});
Integration integration = httpProxyIntegration(
"http://127.0.0.1:" + backendPort + "/foo", null);
RequestContext ctx = ctxFor("GET", "/wallet/foo", "foo",
Map.of(), Map.of(), null, Map.of());
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
assertEquals(404, result.statusCode());
assertEquals("{\"err\":\"not found\"}", new String(result.body(), StandardCharsets.UTF_8));
}
@Test
void backendUnreachableReturns502() {
// Stop the backend to simulate connection refused
backend.stop(0);
Integration integration = httpProxyIntegration(
"http://127.0.0.1:" + backendPort + "/foo", null);
RequestContext ctx = ctxFor("GET", "/wallet/foo", "foo",
Map.of(), Map.of(), null, Map.of());
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
assertEquals(502, result.statusCode());
assertTrue(new String(result.body(), StandardCharsets.UTF_8).contains("Bad Gateway"));
// Restart backend so @AfterEach doesn't NPE
try { backend.start(); } catch (IllegalStateException ignored) {}
}
@Test
void queryParamsForwardedAndAppendable() {
Integration integration = httpProxyIntegration(
"http://127.0.0.1:" + backendPort + "/foo",
Map.of("append:querystring.user", "$context.authorizer.claims.userId"));
RequestContext ctx = ctxFor("GET", "/wallet/foo", "foo",
Map.of(),
Map.of("page", "2"),
null,
Map.of("userId", "u-42"));
new HttpProxyInvoker().invoke(integration, ctx);
String q = received.get().query();
assertNotNull(q);
assertTrue(q.contains("page=2"));
assertTrue(q.contains("user=u-42"));
}
}
@@ -0,0 +1,81 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Verifies {@link PathTemplateResolver} substitutes {paramName} placeholders
* in IntegrationUri templates against the captured path parameters of the
* matched route.
*/
class PathTemplateResolverTest {
@Test
void substitutesProxyPlaceholder() {
assertEquals("http://x/users/123",
PathTemplateResolver.resolve("http://x/{proxy}", Map.of("proxy", "users/123")));
}
@Test
void substitutesNamedPlaceholder() {
assertEquals("/v1/orders/42",
PathTemplateResolver.resolve("/v1/orders/{id}", Map.of("id", "42")));
}
@Test
void substitutesMultiplePlaceholders() {
assertEquals("/users/u-1/orders/42",
PathTemplateResolver.resolve("/users/{user}/orders/{id}",
Map.of("user", "u-1", "id", "42")));
}
@Test
void missingPlaceholderBecomesEmpty() {
assertEquals("/x/", PathTemplateResolver.resolve("/x/{missing}", Map.of()));
}
@Test
void noPlaceholdersPassThrough() {
assertEquals("/static", PathTemplateResolver.resolve("/static", Map.of()));
}
@Test
void nullTemplateReturnsNull() {
assertNull(PathTemplateResolver.resolve(null, Map.of()));
}
@Test
void nullPathParamsTreatedAsEmpty() {
assertEquals("/x/", PathTemplateResolver.resolve("/x/{anything}", null));
}
@Test
void substitutesGreedyProxyPlaceholder() {
// AWS-style {proxy+} (greedy) in IntegrationUri resolves against the same
// "proxy" key extracted from a "ANY /wallet/{proxy+}" route key.
assertEquals("http://x/users/123",
PathTemplateResolver.resolve("http://x/{proxy+}", Map.of("proxy", "users/123")));
}
@Test
void substitutesGreedyNamedPlaceholder() {
assertEquals("/v1/path/a/b/c",
PathTemplateResolver.resolve("/v1/path/{tail+}", Map.of("tail", "a/b/c")));
}
@Test
void mixesGreedyAndNonGreedyPlaceholders() {
assertEquals("/users/u-1/files/a/b",
PathTemplateResolver.resolve("/users/{user}/files/{path+}",
Map.of("user", "u-1", "path", "a/b")));
}
@Test
void missingGreedyPlaceholderBecomesEmpty() {
assertEquals("/x/", PathTemplateResolver.resolve("/x/{missing+}", Map.of()));
}
}
@@ -0,0 +1,131 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Verifies {@link RequestParameterMapper} applies the documented
* action × target combinations (overwrite|append|remove × path|header|querystring)
* with source values resolved through {@link ContextValueResolver}.
*/
class RequestParameterMapperTest {
private RequestParameterMapper mapper;
private RequestContext ctx;
private ProxyRequestBuilder builder;
@BeforeEach
void setUp() {
mapper = new RequestParameterMapper(new ContextValueResolver());
ctx = new RequestContext("api1", "$default", "GET", "/wallet/balance", "balance",
"ANY /wallet/{proxy+}", "req-1", "1.2.3.4",
Map.of("Original-Header", "kept"),
Map.of("page", "2"),
Map.of("proxy", "balance"),
null,
Map.of("userId", "u-42", "email", "a@b.com"),
Map.of());
builder = new ProxyRequestBuilder("http://backend.local/foo", "GET");
}
@Test
void overwriteHeaderWithLiteralValue() {
mapper.apply(Map.of("overwrite:header.Host", "wallet.internal"), builder, ctx);
assertEquals("wallet.internal", builder.headers().get("Host").get(0));
}
@Test
void appendHeaderResolvesContextClaim() {
mapper.apply(Map.of("append:header.x-user-id", "$context.authorizer.claims.userId"), builder, ctx);
assertEquals("u-42", builder.headers().get("x-user-id").get(0));
}
@Test
void appendHeaderToExistingHeaderAccumulates() {
builder.overwriteHeader("x-trace", "first");
mapper.apply(Map.of("append:header.x-trace", "second"), builder, ctx);
assertEquals(2, builder.headers().get("x-trace").size());
assertTrue(builder.headers().get("x-trace").contains("first"));
assertTrue(builder.headers().get("x-trace").contains("second"));
}
@Test
void removeHeaderDropsHeaderEvenWhenSourceIsLiteral() {
builder.overwriteHeader("Authorization", "Bearer xxx");
mapper.apply(Map.of("remove:header.Authorization", ""), builder, ctx);
assertFalse(builder.headers().containsKey("Authorization"));
}
@Test
void overwritePathReplacesPathPreservingHostAndScheme() {
// Source contains $request.path.proxy that must be substituted
mapper.apply(Map.of("overwrite:path", "/public/$request.path.proxy"), builder, ctx);
assertEquals("http://backend.local/public/balance", builder.url());
}
@Test
void overwritePathWithLiteral() {
mapper.apply(Map.of("overwrite:path", "/literal/path"), builder, ctx);
assertEquals("http://backend.local/literal/path", builder.url());
}
@Test
void overwriteQuerystringSetsParam() {
mapper.apply(Map.of("overwrite:querystring.tier", "gold"), builder, ctx);
assertEquals("gold", builder.queryParams().get("tier").get(0));
}
@Test
void appendQuerystringResolvesContextValue() {
mapper.apply(Map.of("append:querystring.user", "$context.authorizer.claims.userId"), builder, ctx);
assertEquals("u-42", builder.queryParams().get("user").get(0));
}
@Test
void removeQuerystringDropsParam() {
builder.overwriteQuery("debug", "true");
mapper.apply(Map.of("remove:querystring.debug", ""), builder, ctx);
assertFalse(builder.queryParams().containsKey("debug"));
}
@Test
void unresolvedSourceSkipsHeader() {
// append:header.X with $context.authorizer.claims.missing should NOT add the header
mapper.apply(Map.of("append:header.x-missing", "$context.authorizer.claims.missing"),
builder, ctx);
assertFalse(builder.headers().containsKey("x-missing"));
}
@Test
void multipleParametersAppliedInOrder() {
var params = new java.util.LinkedHashMap<String, String>();
params.put("overwrite:header.Host", "wallet.internal");
params.put("append:header.x-user-id", "$context.authorizer.claims.userId");
params.put("overwrite:path", "/public/$request.path.proxy");
mapper.apply(params, builder, ctx);
assertEquals("wallet.internal", builder.headers().get("Host").get(0));
assertEquals("u-42", builder.headers().get("x-user-id").get(0));
assertEquals("http://backend.local/public/balance", builder.url());
}
@Test
void emptyParamsIsNoOp() {
mapper.apply(Map.of(), builder, ctx);
mapper.apply(null, builder, ctx);
assertEquals("http://backend.local/foo", builder.url());
assertTrue(builder.headers().isEmpty());
}
@Test
void malformedKeyIsSkipped() {
// No colon in key — should be skipped silently
mapper.apply(Map.of("not-a-valid-key", "value"), builder, ctx);
assertEquals("http://backend.local/foo", builder.url());
}
}