mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
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:
1 parent
0123844d83
commit
dc2efe75e8
18 files changed
+1260
-4
No files matched your search
@@ -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());
|
||||
}
|
||||
|
||||
+124
-3
@@ -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;
|
||||
|
||||
+4
@@ -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());
|
||||
}
|
||||
|
||||
+11
-1
@@ -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;
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
+63
@@ -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;
|
||||
}
|
||||
}
|
||||
+144
@@ -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));
|
||||
}
|
||||
}
|
||||
+40
@@ -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();
|
||||
}
|
||||
}
|
||||
+61
@@ -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; }
|
||||
}
|
||||
@@ -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) {}
|
||||
+24
@@ -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) {
|
||||
}
|
||||
+95
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user