Light, fluffy, and always free - The AWS Local Emulator alternative
feat(apigatewayv2): HTTP_PROXY integration with request parameter mapping (#860)
Ricardo Medinadc2efe75e890
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.javaindex ac3bb9172d..e3fc15fe8f 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@@ -1586,6 +1586,10 @@ public class ApiGatewayController {ObjectNode responseTemplates = node.putObject("responseTemplates");i.getResponseTemplates().forEach(responseTemplates::put);}+ if (i.getRequestParameters() != null) {+ ObjectNode requestParameters = node.putObject("requestParameters");+ i.getRequestParameters().forEach(requestParameters::put);+ }if (i.getTemplateSelectionExpression() != null) {node.put("templateSelectionExpression", i.getTemplateSelectionExpression());}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 4d74521948..8396cf6055 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@@ -35,6 +35,8 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.UUID;+import java.util.concurrent.ConcurrentHashMap;+import java.util.regex.Matcher;import java.util.regex.Pattern;/**@@ -981,6 +983,13 @@ public class ApiGatewayExecuteController {.type(MediaType.APPLICATION_JSON).build();}+ String integrationType = integration.getIntegrationType();+ if (integrationType == null || integrationType.isEmpty()) integrationType = "AWS_PROXY";++ if ("HTTP_PROXY".equalsIgnoreCase(integrationType)) {+ return dispatchHttpProxyV2(integration, route, httpMethod, path, headers, uriInfo, body, apiId, stageName);+ }+String functionName = functionNameFromUri(integration.getIntegrationUri());if (functionName == null) {return Response.status(500)@@ -1008,6 +1017,112 @@ public class ApiGatewayExecuteController {}}+ private final io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker httpProxyInvoker =+ new io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker();++ private Response dispatchHttpProxyV2(io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration,+ Route route, String httpMethod, String path,+ HttpHeaders headers, UriInfo uriInfo, byte[] body,+ String apiId, String stageName) {+ Map<String, String> requestHeaders = new java.util.LinkedHashMap<>();+ for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {+ requestHeaders.put(e.getKey(), String.join(",", e.getValue()));+ }+ Map<String, String> queryParams = new java.util.LinkedHashMap<>();+ for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {+ queryParams.put(e.getKey(), String.join(",", e.getValue()));+ }+ Map<String, String> pathParams = extractV2PathParams(route.getRouteKey(), path);++ Map<String, Object> claims = Map.of();+ if ("JWT".equalsIgnoreCase(route.getAuthorizationType())) {+ String token = extractBearerToken(headers);+ if (token != null) {+ Map<String, Object> parsed = parseAllJwtClaims(token);+ if (parsed != null) claims = parsed;+ }+ }++ String sourceIp = requestHeaders.getOrDefault("X-Forwarded-For", "127.0.0.1");+ io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx =+ new io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext(+ apiId, stageName, httpMethod, path,+ pathParams.getOrDefault("proxy", ""), route.getRouteKey(),+ UUID.randomUUID().toString(), sourceIp,+ requestHeaders, queryParams, pathParams, body,+ claims, Map.of());++ LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}",+ httpMethod, apiId, stageName, path, integration.getIntegrationUri());++ io.github.hectorvent.floci.services.apigatewayv2.proxy.ProxyResult result =+ httpProxyInvoker.invoke(integration, ctx);++ Response.ResponseBuilder rb = Response.status(result.statusCode());+ if (result.body() != null) rb.entity(result.body());+ if (result.headers() != null) {+ for (Map.Entry<String, String> e : result.headers().entrySet()) {+ rb.header(e.getKey(), e.getValue());+ }+ }+ return rb.build();+ }++ private static String extractBearerToken(HttpHeaders headers) {+ String auth = headers.getHeaderString("Authorization");+ if (auth == null) return null;+ if (auth.startsWith("Bearer ")) return auth.substring("Bearer ".length()).trim();+ return null;+ }++ /** Extracts ALL JWT claims as a Map<String,Object> for use as $context.authorizer.claims.X source values. */+ private Map<String, Object> parseAllJwtClaims(String token) {+ try {+ String[] parts = token.split("\\.");+ if (parts.length < 2) return null;+ byte[] payloadBytes = Base64.getUrlDecoder().decode(padBase64(parts[1]));+ String payload = new String(payloadBytes, StandardCharsets.UTF_8);+ JsonNode root = objectMapper.readTree(payload);+ return objectMapper.convertValue(root, MAP_TYPE);+ } catch (Exception e) {+ LOG.debugv("JWT full-claims parse error: {0}", e.getMessage());+ return null;+ }+ }++ /**+ * Captures path parameters from a route key like {@code "ANY /wallet/{proxy+}"} matched+ * against an actual path. Compiled regexes are cached per route key so the regex is+ * built once and reused on every subsequent request to that route.+ */+ static Map<String, String> extractV2PathParams(String routeKey, String actualPath) {+ if (routeKey == null) return Map.of();+ String[] parts = routeKey.split("\\s+", 2);+ if (parts.length != 2) return Map.of();+ String template = parts[1];++ Pattern p = ROUTE_TEMPLATE_PATTERNS.computeIfAbsent(template, t -> {+ String regex = t.replaceAll("\\{([a-zA-Z_]+)\\+\\}", "(?<$1>.+)")+ .replaceAll("\\{([a-zA-Z_]+)\\}", "(?<$1>[^/]+)");+ return Pattern.compile("^" + regex + "$");+ });+ Matcher m = p.matcher(actualPath);+ if (!m.matches()) return Map.of();++ Map<String, String> result = new java.util.LinkedHashMap<>();+ Matcher names = ROUTE_PARAM_NAMES.matcher(template);+ while (names.find()) {+ try { result.put(names.group(1), m.group(names.group(1))); } catch (Exception ignored) {}+ }+ return result;+ }++ /** Cache of compiled route-template patterns keyed by the raw template (e.g. {@code "/wallet/{proxy+}"}). */+ private static final ConcurrentHashMap<String, Pattern> ROUTE_TEMPLATE_PATTERNS = new ConcurrentHashMap<>();++ /** Extracts parameter names from a route template; the pattern itself is constant. */+ private static final Pattern ROUTE_PARAM_NAMES = Pattern.compile("\\{([a-zA-Z_]+)\\+?\\}");+private Response enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers) {Authorizer authorizer;try {@@ -1048,7 +1163,10 @@ public class ApiGatewayExecuteController {List<String> audiences = authorizer.getJwtConfiguration().audience();if (audiences != null && !audiences.isEmpty()) {- boolean audMatch = audiences.stream().anyMatch(a -> a.equals(claims.aud));+ // Cognito access tokens omit `aud` and use `client_id` instead.+ // Match either to support both ID tokens and access tokens.+ boolean audMatch = audiences.stream().anyMatch(a ->+ a.equals(claims.aud) || a.equals(claims.clientId));if (!audMatch) {return Response.status(401).entity(jsonMessage("Unauthorized"))@@ -1083,7 +1201,7 @@ public class ApiGatewayExecuteController {return value;}- private record JwtClaims(String iss, String aud, long exp) {}+ private record JwtClaims(String iss, String aud, String clientId, long exp) {}private JwtClaims parseJwtClaims(String token) {try {@@ -1094,8 +1212,11 @@ public class ApiGatewayExecuteController {JsonNode claims = objectMapper.readTree(payload);String iss = claims.path("iss").asText(null);String aud = claims.path("aud").asText(null);+ // Cognito access tokens omit `aud` and use `client_id` instead. AWS HTTP API+ // JWT authorizers accept either when matching the configured audience list.+ String clientId = claims.path("client_id").asText(null);long exp = claims.path("exp").asLong(0);- return new JwtClaims(iss, aud, exp);+ return new JwtClaims(iss, aud, clientId, exp);} catch (Exception e) {LOG.debugv("JWT parse error: {0}", e.getMessage());return null;diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.javaindex 58145350a8..8b176ef1ea 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java@@ -569,6 +569,10 @@ public class ApiGatewayV2JsonHandler {ObjectNode responseTemplates = node.putObject("ResponseTemplates");i.getResponseTemplates().forEach(responseTemplates::put);}+ if (i.getRequestParameters() != null) {+ ObjectNode requestParameters = node.putObject("RequestParameters");+ i.getRequestParameters().forEach(requestParameters::put);+ }if (i.getTemplateSelectionExpression() != null) {node.put("TemplateSelectionExpression", i.getTemplateSelectionExpression());}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 b2621576b4..bd5098c94d 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@@ -338,7 +338,8 @@ public class ApiGatewayV2Service {if (space < 0) return false;String method = routeKey.substring(0, space);String pattern = routeKey.substring(space + 1);- if (!method.equalsIgnoreCase(httpMethod)) return false;+ // ANY is the AWS wildcard method — matches any inbound HTTP method.+ if (!"ANY".equalsIgnoreCase(method) && !method.equalsIgnoreCase(httpMethod)) return false;// Build regex from path template: {proxy+} -> .+, {param} -> [^/]+// Quote literal segments to avoid regex injection from path patterns@@ -379,6 +380,10 @@ public class ApiGatewayV2Service {Map<String, String> responseTemplates = (Map<String, String>) request.get("responseTemplates");integration.setResponseTemplates(responseTemplates);+ @SuppressWarnings("unchecked")+ Map<String, String> requestParameters = (Map<String, String>) request.get("requestParameters");+ integration.setRequestParameters(requestParameters);+integrationStore.put(integrationKey(region, apiId, integration.getIntegrationId()), integration);return integration;}@@ -430,6 +435,11 @@ public class ApiGatewayV2Service {Map<String, String> responseTemplates = (Map<String, String>) request.get("responseTemplates");integration.setResponseTemplates(responseTemplates);}+ if (request.containsKey("requestParameters") && request.get("requestParameters") != null) {+ @SuppressWarnings("unchecked")+ Map<String, String> requestParameters = (Map<String, String>) request.get("requestParameters");+ integration.setRequestParameters(requestParameters);+ }integrationStore.put(integrationKey(region, apiId, integrationId), integration);return integration;diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.javaindex accaf1e1be..7c5a7447ed 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java@@ -17,6 +17,7 @@ public class Integration {private Map<String, String> requestTemplates;private Map<String, String> responseTemplates;private String templateSelectionExpression;+ private Map<String, String> requestParameters;public Integration() {}@@ -46,4 +47,7 @@ public class Integration {public String getTemplateSelectionExpression() { return templateSelectionExpression; }public void setTemplateSelectionExpression(String templateSelectionExpression) { this.templateSelectionExpression = templateSelectionExpression; }++ public Map<String, String> getRequestParameters() { return requestParameters; }+ public void setRequestParameters(Map<String, String> requestParameters) { this.requestParameters = requestParameters; }}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ContextValueResolver.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ContextValueResolver.javanew file mode 100644index 0000000000..7da8e20444--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ContextValueResolver.java@@ -0,0 +1,63 @@+package io.github.hectorvent.floci.services.apigatewayv2.proxy;++import java.util.Map;++/**+ * Resolves source value expressions used by HTTP API v2 RequestParameters.+ * Returns the literal string for non-{@code $} prefixed values, looks up+ * the appropriate field on {@link RequestContext} for $-prefixed expressions,+ * and returns {@code null} for missing or unknown references.+ *+ * <p>Supported expressions:+ * <ul>+ * <li>{@code $context.authorizer.claims.<name>} — JWT claim from authorizer</li>+ * <li>{@code $context.authorizer.<name>} — authorizer context value</li>+ * <li>{@code $context.requestId} — UUID assigned per request</li>+ * <li>{@code $context.identity.sourceIp} — client IP</li>+ * <li>{@code $request.header.<name>} — case-insensitive header lookup</li>+ * <li>{@code $request.querystring.<name>} — query parameter</li>+ * <li>{@code $request.path.<name>} — captured path parameter</li>+ * <li>literal strings — returned unchanged</li>+ * </ul>+ */+public class ContextValueResolver {++ public String resolve(String expression, RequestContext ctx) {+ if (expression == null) return null;+ if (!expression.startsWith("$")) return expression;++ if (expression.startsWith("$context.authorizer.claims.")) {+ String claim = expression.substring("$context.authorizer.claims.".length());+ Object v = ctx.authorizerClaims() == null ? null : ctx.authorizerClaims().get(claim);+ return v == null ? null : v.toString();+ }+ if (expression.startsWith("$context.authorizer.")) {+ String key = expression.substring("$context.authorizer.".length());+ Object v = ctx.authorizerContext() == null ? null : ctx.authorizerContext().get(key);+ return v == null ? null : v.toString();+ }+ if (expression.equals("$context.requestId")) return ctx.requestId();+ if (expression.equals("$context.identity.sourceIp")) return ctx.sourceIp();+ if (expression.startsWith("$request.header.")) {+ String name = expression.substring("$request.header.".length());+ return getCaseInsensitive(ctx.requestHeaders(), name);+ }+ if (expression.startsWith("$request.querystring.")) {+ String name = expression.substring("$request.querystring.".length());+ return ctx.queryParams() == null ? null : ctx.queryParams().get(name);+ }+ if (expression.startsWith("$request.path.")) {+ String name = expression.substring("$request.path.".length());+ return ctx.pathParams() == null ? null : ctx.pathParams().get(name);+ }+ return null;+ }++ private static String getCaseInsensitive(Map<String, String> headers, String name) {+ if (headers == null) return null;+ for (Map.Entry<String, String> e : headers.entrySet()) {+ if (e.getKey().equalsIgnoreCase(name)) return e.getValue();+ }+ return null;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.javanew file mode 100644index 0000000000..4061f364d0--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java@@ -0,0 +1,144 @@+package io.github.hectorvent.floci.services.apigatewayv2.proxy;++import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;+import org.jboss.logging.Logger;++import java.net.URI;+import java.net.URLEncoder;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.nio.charset.StandardCharsets;+import java.time.Duration;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.StringJoiner;++/**+ * Invokes an HTTP_PROXY integration: builds the target URL from the integration's+ * IntegrationUri (with {placeholder} substitution from path params), seeds an+ * outgoing request with the inbound headers + query, applies RequestParameters+ * transformations, and forwards the call to the backend via java.net.http.HttpClient.+ *+ * <p>Hop-by-hop headers (per RFC 7230 §6.1) are stripped from both the outgoing+ * request and the response. Java's HttpClient also restricts certain headers+ * (Host, Content-Length, etc.) — those are skipped silently.+ *+ * <p>If the backend is unreachable or times out, returns a 502 Bad Gateway+ * ProxyResult so the controller can relay a clean error to the original client.+ */+public class HttpProxyInvoker {+ private static final Logger LOG = Logger.getLogger(HttpProxyInvoker.class);++ /** RFC 7230 hop-by-hop headers that must not be forwarded across proxies. */+ private static final Set<String> HOP_BY_HOP = Set.of(+ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization",+ "te", "trailers", "transfer-encoding", "upgrade", "content-length", "host");++ /** Headers java.net.http.HttpClient refuses to set via Builder.header(). */+ private static final Set<String> RESTRICTED = Set.of(+ "connection", "content-length", "expect", "host", "upgrade");++ private final HttpClient client = HttpClient.newBuilder()+ .connectTimeout(Duration.ofSeconds(10))+ .followRedirects(HttpClient.Redirect.NEVER)+ .build();++ private final RequestParameterMapper mapper = new RequestParameterMapper(new ContextValueResolver());++ public ProxyResult invoke(Integration integration, RequestContext ctx) {+ // 1. Resolve target URL from IntegrationUri template + captured path params+ String resolvedUrl = PathTemplateResolver.resolve(integration.getIntegrationUri(), ctx.pathParams());++ // 2. Determine HTTP method (integration.method=ANY/null means use the inbound method)+ String method = integration.getIntegrationMethod();+ if (method == null || method.isEmpty() || method.equalsIgnoreCase("ANY")) {+ method = ctx.httpMethod();+ }++ // 3. Build mutable request, seed with inbound headers/query (excluding hop-by-hop)+ ProxyRequestBuilder builder = new ProxyRequestBuilder(resolvedUrl, method);+ if (ctx.requestHeaders() != null) {+ for (Map.Entry<String, String> e : ctx.requestHeaders().entrySet()) {+ if (!HOP_BY_HOP.contains(e.getKey().toLowerCase())) {+ builder.overwriteHeader(e.getKey(), e.getValue());+ }+ }+ }+ if (ctx.queryParams() != null) {+ for (Map.Entry<String, String> e : ctx.queryParams().entrySet()) {+ builder.overwriteQuery(e.getKey(), e.getValue());+ }+ }+ builder.setBody(ctx.body());++ // 4. Apply RequestParameters+ mapper.apply(integration.getRequestParameters(), builder, ctx);++ // 5. Build java.net.http.HttpRequest+ HttpRequest.Builder hrb;+ try {+ hrb = HttpRequest.newBuilder()+ .uri(URI.create(buildFinalUrl(builder)))+ .timeout(Duration.ofSeconds(30));+ } catch (IllegalArgumentException e) {+ LOG.warnv("HTTP_PROXY: invalid target URL: {0}", e.getMessage());+ return errorResult("Bad Gateway: invalid target URL: " + e.getMessage());+ }++ switch (method.toUpperCase()) {+ case "GET" -> hrb.GET();+ case "DELETE" -> hrb.DELETE();+ case "HEAD" -> hrb.method("HEAD", HttpRequest.BodyPublishers.noBody());+ case "OPTIONS" -> hrb.method("OPTIONS", HttpRequest.BodyPublishers.noBody());+ default -> hrb.method(method.toUpperCase(),+ builder.body() != null+ ? HttpRequest.BodyPublishers.ofByteArray(builder.body())+ : HttpRequest.BodyPublishers.noBody());+ }++ for (Map.Entry<String, List<String>> e : builder.headers().entrySet()) {+ if (RESTRICTED.contains(e.getKey().toLowerCase())) continue;+ for (String v : e.getValue()) {+ hrb.header(e.getKey(), v);+ }+ }++ try {+ HttpResponse<byte[]> resp = client.send(hrb.build(), HttpResponse.BodyHandlers.ofByteArray());+ Map<String, String> respHeaders = new LinkedHashMap<>();+ for (Map.Entry<String, List<String>> e : resp.headers().map().entrySet()) {+ if (HOP_BY_HOP.contains(e.getKey().toLowerCase())) continue;+ respHeaders.put(e.getKey(), String.join(",", e.getValue()));+ }+ return new ProxyResult(resp.statusCode(), respHeaders, resp.body());+ } catch (Exception e) {+ LOG.warnv("HTTP_PROXY backend call failed: {0}", e.getMessage());+ return errorResult("Bad Gateway: " + e.getMessage());+ }+ }++ private static String buildFinalUrl(ProxyRequestBuilder builder) {+ if (builder.queryParams().isEmpty()) return builder.url();+ URI parsed = URI.create(builder.url());+ StringJoiner sj = new StringJoiner("&");+ if (parsed.getRawQuery() != null) sj.add(parsed.getRawQuery());+ for (Map.Entry<String, List<String>> e : builder.queryParams().entrySet()) {+ for (String v : e.getValue()) {+ sj.add(URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "=" ++ URLEncoder.encode(v, StandardCharsets.UTF_8));+ }+ }+ String base = builder.url().split("\\?")[0];+ return base + "?" + sj;+ }++ private static ProxyResult errorResult(String message) {+ String body = "{\"message\":\"" + message.replace("\"", "\\\"") + "\"}";+ return new ProxyResult(502,+ Map.of("Content-Type", "application/json"),+ body.getBytes(StandardCharsets.UTF_8));+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolver.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolver.javanew file mode 100644index 0000000000..57719c4d7b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolver.java@@ -0,0 +1,40 @@+package io.github.hectorvent.floci.services.apigatewayv2.proxy;++import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++/**+ * Substitutes {paramName} and {paramName+} placeholders in URI templates+ * against a map of captured path parameters. Used by HttpProxyInvoker to+ * resolve the target URL from an integration's IntegrationUri (e.g.+ * {@code http://backend/{proxy}} or {@code http://backend/{proxy+}}) and by+ * RequestParameterMapper to apply overwrite:path values.+ *+ * <p>Both {@code {name}} and {@code {name+}} resolve to the same parameter+ * keyed by {@code name} — the trailing {@code +} is AWS's "greedy" marker+ * used in route keys (e.g. {@code "ANY /wallet/{proxy+}"}) to capture+ * multi-segment suffixes, and it's accepted in IntegrationUri templates+ * too so the URI can mirror the route shape verbatim.+ *+ * <p>Missing parameters are replaced with the empty string, mirroring AWS+ * API Gateway's behavior for unresolved placeholders.+ */+public final class PathTemplateResolver {+ private static final Pattern PLACEHOLDER = Pattern.compile("\\{([a-zA-Z_][a-zA-Z0-9_]*)\\+?\\}");++ private PathTemplateResolver() {}++ public static String resolve(String template, Map<String, String> pathParams) {+ if (template == null) return null;+ Matcher m = PLACEHOLDER.matcher(template);+ StringBuilder out = new StringBuilder();+ while (m.find()) {+ String key = m.group(1);+ String value = pathParams == null ? "" : pathParams.getOrDefault(key, "");+ m.appendReplacement(out, Matcher.quoteReplacement(value));+ }+ m.appendTail(out);+ return out.toString();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ProxyRequestBuilder.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ProxyRequestBuilder.javanew file mode 100644index 0000000000..d0d11238dc--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ProxyRequestBuilder.java@@ -0,0 +1,61 @@+package io.github.hectorvent.floci.services.apigatewayv2.proxy;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * Mutable builder for an outgoing proxied HTTP request. Single source of+ * truth between the initial integration template + inbound request data and+ * the final {@link java.net.http.HttpRequest} sent to the backend.+ *+ * <p>Headers and query params are stored as multimaps to support+ * {@code append:header.X} and {@code append:querystring.X} actions.+ */+public class ProxyRequestBuilder {+ private String url;+ private String method;+ private final Map<String, List<String>> headers = new LinkedHashMap<>();+ private final Map<String, List<String>> queryParams = new LinkedHashMap<>();+ private byte[] body;++ public ProxyRequestBuilder(String url, String method) {+ this.url = url;+ this.method = method;+ }++ public void setUrl(String url) { this.url = url; }+ public void setMethod(String method) { this.method = method; }+ public void setBody(byte[] body) { this.body = body; }++ public void overwriteHeader(String name, String value) {+ if (value == null) { headers.remove(name); return; }+ List<String> list = new ArrayList<>();+ list.add(value);+ headers.put(name, list);+ }+ public void appendHeader(String name, String value) {+ if (value == null) return;+ headers.computeIfAbsent(name, k -> new ArrayList<>()).add(value);+ }+ public void removeHeader(String name) { headers.remove(name); }++ public void overwriteQuery(String name, String value) {+ if (value == null) { queryParams.remove(name); return; }+ List<String> list = new ArrayList<>();+ list.add(value);+ queryParams.put(name, list);+ }+ public void appendQuery(String name, String value) {+ if (value == null) return;+ queryParams.computeIfAbsent(name, k -> new ArrayList<>()).add(value);+ }+ public void removeQuery(String name) { queryParams.remove(name); }++ public String url() { return url; }+ public String method() { return method; }+ public Map<String, List<String>> headers() { return headers; }+ public Map<String, List<String>> queryParams() { return queryParams; }+ public byte[] body() { return body; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ProxyResult.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ProxyResult.javanew file mode 100644index 0000000000..351f8d58d4--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ProxyResult.java@@ -0,0 +1,10 @@+package io.github.hectorvent.floci.services.apigatewayv2.proxy;++import java.util.Map;++/**+ * Result of an HTTP_PROXY integration invocation. Carries the backend's+ * response status, headers (combined when multi-valued), and body bytes+ * back to the API Gateway dispatcher for relay to the original caller.+ */+public record ProxyResult(int statusCode, Map<String, String> headers, byte[] body) {}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContext.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContext.javanew file mode 100644index 0000000000..6da827e2bd--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContext.java@@ -0,0 +1,24 @@+package io.github.hectorvent.floci.services.apigatewayv2.proxy;++import java.util.Map;++/**+ * Bundles the inbound request data and authorizer-derived context that an+ * HTTP_PROXY integration may reference via $context.* / $request.* expressions.+ */+public record RequestContext(+ String apiId,+ String stageName,+ String httpMethod,+ String path,+ String proxy,+ String routeKey,+ String requestId,+ String sourceIp,+ Map<String, String> requestHeaders,+ Map<String, String> queryParams,+ Map<String, String> pathParams,+ byte[] body,+ Map<String, Object> authorizerClaims,+ Map<String, Object> authorizerContext) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapper.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapper.javanew file mode 100644index 0000000000..c3ea56b1b8--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapper.java@@ -0,0 +1,95 @@+package io.github.hectorvent.floci.services.apigatewayv2.proxy;++import java.net.URI;+import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++/**+ * Applies HTTP API v2 RequestParameters to an outgoing {@link ProxyRequestBuilder}.+ *+ * <p>Each entry in the requestParameters map has the form+ * {@code (action):(target).(name) -> sourceValue}, where:+ * <ul>+ * <li>{@code action} ∈ {overwrite, append, remove}</li>+ * <li>{@code target} ∈ {path, header, querystring}</li>+ * <li>{@code name} is the header or querystring parameter name (omitted for path)</li>+ * <li>{@code sourceValue} is a literal or expression resolved by {@link ContextValueResolver}</li>+ * </ul>+ *+ * <p>For {@code overwrite:path}, the source value may contain embedded+ * {@code $request.path.X} / {@code $context.X} substrings which are resolved in-place.+ *+ * <p>When a source resolves to {@code null} (missing claim, missing header, etc.),+ * overwrite/append actions are silently skipped to match AWS behavior. {@code remove}+ * is unconditional.+ */+public class RequestParameterMapper {+ private static final Pattern EMBEDDED_VAR =+ Pattern.compile("\\$[a-zA-Z]+(\\.[a-zA-Z][a-zA-Z0-9_-]*)+");++ private final ContextValueResolver resolver;++ public RequestParameterMapper(ContextValueResolver resolver) {+ this.resolver = resolver;+ }++ public void apply(Map<String, String> requestParameters, ProxyRequestBuilder builder, RequestContext ctx) {+ if (requestParameters == null || requestParameters.isEmpty()) return;+ for (Map.Entry<String, String> entry : requestParameters.entrySet()) {+ String key = entry.getKey();+ String source = entry.getValue();++ int colonIdx = key.indexOf(':');+ if (colonIdx < 0) continue;+ String action = key.substring(0, colonIdx);+ String fullTarget = key.substring(colonIdx + 1);++ String resolvedValue;+ if (action.equals("remove")) {+ resolvedValue = null;+ } else if (fullTarget.equals("path")) {+ // path source may contain embedded variables that must be substituted in-place+ resolvedValue = substituteEmbeddedVars(source, ctx);+ } else {+ resolvedValue = resolver.resolve(source, ctx);+ }++ if (fullTarget.equals("path")) {+ if (action.equals("overwrite") && resolvedValue != null) {+ URI current = URI.create(builder.url());+ String newUrl = current.getScheme() + "://" + current.getRawAuthority() + resolvedValue;+ if (current.getRawQuery() != null) newUrl += "?" + current.getRawQuery();+ builder.setUrl(newUrl);+ }+ } else if (fullTarget.startsWith("header.")) {+ String headerName = fullTarget.substring("header.".length());+ switch (action) {+ case "overwrite" -> { if (resolvedValue != null) builder.overwriteHeader(headerName, resolvedValue); }+ case "append" -> { if (resolvedValue != null) builder.appendHeader(headerName, resolvedValue); }+ case "remove" -> builder.removeHeader(headerName);+ }+ } else if (fullTarget.startsWith("querystring.")) {+ String paramName = fullTarget.substring("querystring.".length());+ switch (action) {+ case "overwrite" -> { if (resolvedValue != null) builder.overwriteQuery(paramName, resolvedValue); }+ case "append" -> { if (resolvedValue != null) builder.appendQuery(paramName, resolvedValue); }+ case "remove" -> builder.removeQuery(paramName);+ }+ }+ }+ }++ private String substituteEmbeddedVars(String template, RequestContext ctx) {+ if (template == null) return null;+ if (!template.contains("$")) return template;+ Matcher m = EMBEDDED_VAR.matcher(template);+ StringBuilder out = new StringBuilder();+ while (m.find()) {+ String resolved = resolver.resolve(m.group(), ctx);+ m.appendReplacement(out, Matcher.quoteReplacement(resolved == null ? "" : resolved));+ }+ m.appendTail(out);+ return out.toString();+ }+}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.javanew file mode 100644index 0000000000..56bbd0cabc--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java@@ -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"));+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandlerTest.javaindex 8b469e8557..c5e918f350 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandlerTest.java@@ -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);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ContextValueResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ContextValueResolverTest.javanew file mode 100644index 0000000000..27eff7a17c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/ContextValueResolverTest.java@@ -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", "[email protected]"),+ Map.of(), Map.of(), Map.of(), Map.of());+ assertEquals("u-123", r.resolve("$context.authorizer.claims.userId", c));+ assertEquals("[email protected]", 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())));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.javanew file mode 100644index 0000000000..f38bbcbdfb--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java@@ -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"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolverTest.javanew file mode 100644index 0000000000..9d89d132ae--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolverTest.java@@ -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()));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapperTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapperTest.javanew file mode 100644index 0000000000..e539ef7348--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapperTest.java@@ -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", "[email protected]"),+ 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());+ }+}