mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(apigateway): share REST request context and complete mappings (#5035)
* fix(apigateway): share REST request context and complete parameter mappings * fix(apigateway): resolve wildcard request body mappings * fix(apigateway): distinguish scalar and multi-value mapping sources
This commit is contained in:
1 parent
971dc01f34
commit
3f591f853d
8 files changed
+610
-151
No files matched your search
+223
-145
@@ -1,5 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.jayway.jsonpath.Configuration;
|
||||
import com.jayway.jsonpath.InvalidPathException;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
|
||||
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
|
||||
import com.networknt.schema.ValidationMessage;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsEndpoints;
|
||||
@@ -47,12 +52,12 @@ import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.*;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -106,6 +111,7 @@ public class ApiGatewayExecuteController {
|
||||
private final LambdaService lambdaService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final Configuration jsonPathConfiguration;
|
||||
private final VtlTemplateEngine vtlEngine;
|
||||
private final AwsServiceRouter serviceRouter;
|
||||
private final WebSocketConnectionManager webSocketConnectionManager;
|
||||
@@ -136,6 +142,10 @@ public class ApiGatewayExecuteController {
|
||||
this.lambdaService = lambdaService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.jsonPathConfiguration = Configuration.builder()
|
||||
.jsonProvider(new JacksonJsonNodeJsonProvider(objectMapper))
|
||||
.mappingProvider(new JacksonMappingProvider(objectMapper))
|
||||
.build();
|
||||
this.vtlEngine = vtlEngine;
|
||||
this.serviceRouter = serviceRouter;
|
||||
this.webSocketConnectionManager = webSocketConnectionManager;
|
||||
@@ -162,10 +172,16 @@ public class ApiGatewayExecuteController {
|
||||
*/
|
||||
private record GatewayResponseScope(String region, String apiId, String stageName, Stage stage,
|
||||
String httpMethod, String path, ApiGatewayResource resource,
|
||||
HttpHeaders headers, UriInfo uriInfo, byte[] body) {
|
||||
HttpHeaders headers, UriInfo uriInfo, byte[] body, ResolvedApiKey apiKey,
|
||||
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) {
|
||||
GatewayResponseScope withResource(ApiGatewayResource matched) {
|
||||
return new GatewayResponseScope(region, apiId, stageName, stage, httpMethod, path, matched,
|
||||
headers, uriInfo, body);
|
||||
headers, uriInfo, body, apiKey, iamIdentity);
|
||||
}
|
||||
|
||||
GatewayResponseScope withIdentity(ResolvedApiKey key, ExecuteApiSigV4Authorizer.CallerIdentity identity) {
|
||||
return new GatewayResponseScope(region, apiId, stageName, stage, httpMethod, path, resource,
|
||||
headers, uriInfo, body, key, identity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,12 +366,14 @@ public class ApiGatewayExecuteController {
|
||||
apiGatewayV2Service.getApi(v2Region, apiId);
|
||||
return dispatchV2(httpMethod, apiId, stageName, proxy, headers, uriInfo, body, v2Region);
|
||||
} catch (AwsException ignored) {
|
||||
routeContext.routeToRestApi();
|
||||
return Response.status(restApiError.getHttpStatus())
|
||||
.entity(jsonMessage(restApiError.getMessage()))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
}
|
||||
|
||||
routeContext.routeToRestApi();
|
||||
Stage stage;
|
||||
try {
|
||||
stage = apiGatewayService.getStage(region, apiId, stageName);
|
||||
@@ -367,7 +385,7 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
String path = "/" + (proxy == null ? "" : proxy);
|
||||
GatewayResponseScope scope = new GatewayResponseScope(region, apiId, stageName, stage, httpMethod, path,
|
||||
null, headers, uriInfo, body);
|
||||
null, headers, uriInfo, body, null, null);
|
||||
|
||||
// Find matching resource and method
|
||||
List<ApiGatewayResource> resources = apiGatewayService.getResources(region, apiId);
|
||||
@@ -421,6 +439,7 @@ public class ApiGatewayExecuteController {
|
||||
iamIdentity = iamResult.identity();
|
||||
}
|
||||
|
||||
scope = scope.withIdentity(resolvedApiKey, iamIdentity);
|
||||
AuthorizerResult authorizerResult = invokeAuthorizer(scope, region, apiId, stageName, httpMethod, path, matched.getPath(), matched.getId(), stage, method, headers, uriInfo, resolvedApiKey);
|
||||
if (authorizerResult.errorResponse() != null) return authorizerResult.errorResponse();
|
||||
|
||||
@@ -509,7 +528,7 @@ public class ApiGatewayExecuteController {
|
||||
"Cannot resolve function from URI: " + integration.getUri());
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String requestId = routeContext.requestId(headers);
|
||||
String eventJson = buildProxyEvent(region, apiId, httpMethod, path, resource.getPath(),
|
||||
resource.getId(), stageName, stage, headers, uriInfo, body, requestId,
|
||||
authorizerResult.principalId(), authorizerResult.context(), resolvedApiKey, iamIdentity);
|
||||
@@ -556,7 +575,7 @@ public class ApiGatewayExecuteController {
|
||||
"No integration URI configured");
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String requestId = routeContext.requestId(headers);
|
||||
Map<String, Object> mappingContext = httpRequestMappingContext(scope, requestId, authorizerResult);
|
||||
|
||||
// Two views of the same inbound data. The multi-value maps are what gets forwarded: a
|
||||
@@ -580,44 +599,13 @@ public class ApiGatewayExecuteController {
|
||||
pathMap.putAll(extractPathParams(resource.getPath(), path));
|
||||
pathMap.putAll(greedyPathParam(resource.getPath(), path));
|
||||
|
||||
// Mapping sources always read the original request, independent of destination order.
|
||||
Map<String, String> outHeaders = new LinkedHashMap<>(headerMap);
|
||||
Map<String, String> outQuery = new LinkedHashMap<>(queryMap);
|
||||
Map<String, String> outPath = new LinkedHashMap<>(pathMap);
|
||||
|
||||
// REST integration.request.* mappings are applied here rather
|
||||
// than by the v2 RequestParameterMapper: that mapper reads the unrelated v2 syntax
|
||||
// ("append:header.x" → "$request.header.y") and would silently ignore these REST mappings.
|
||||
Map<String, String> requestParameters = integration.getRequestParameters();
|
||||
if (requestParameters != null) {
|
||||
for (Map.Entry<String, String> param : requestParameters.entrySet()) {
|
||||
String dest = param.getKey();
|
||||
String source = param.getValue();
|
||||
String resolved = resolveRequestParameter(source, queryMap, pathMap, headerMap, mappingContext);
|
||||
boolean isContextHeader = dest.startsWith("integration.request.header.")
|
||||
&& source != null && source.startsWith("context.");
|
||||
if (resolved == null && !isContextHeader) {
|
||||
continue;
|
||||
}
|
||||
// An explicit mapping overwrites, so it replaces any repeated inbound values too.
|
||||
if (dest.startsWith("integration.request.header.")) {
|
||||
String name = dest.substring("integration.request.header.".length());
|
||||
// A missing context value must not fall back to a client-supplied trusted header.
|
||||
outHeaders.keySet().removeIf(existing -> existing.equalsIgnoreCase(name));
|
||||
multiValueHeaders.keySet().removeIf(existing -> existing.equalsIgnoreCase(name));
|
||||
if (resolved != null) {
|
||||
outHeaders.put(name, resolved);
|
||||
multiValueHeaders.put(name, List.of(resolved));
|
||||
}
|
||||
} else if (dest.startsWith("integration.request.querystring.")) {
|
||||
String name = dest.substring("integration.request.querystring.".length());
|
||||
outQuery.put(name, resolved);
|
||||
multiValueQuery.put(name, List.of(resolved));
|
||||
} else if (dest.startsWith("integration.request.path.")) {
|
||||
outPath.put(dest.substring("integration.request.path.".length()), resolved);
|
||||
}
|
||||
}
|
||||
}
|
||||
HttpRequestParameters mapped = mapHttpRequestParameters(scope, integration, mappingContext,
|
||||
pathMap, multiValueHeaders, multiValueQuery);
|
||||
Map<String, String> outHeaders = joinedParameterValues(mapped.headers());
|
||||
Map<String, String> outQuery = joinedParameterValues(mapped.query());
|
||||
Map<String, String> outPath = mapped.path();
|
||||
multiValueHeaders = mapped.headers();
|
||||
multiValueQuery = mapped.query();
|
||||
|
||||
// HttpProxyInvoker speaks the v2 integration model. The REST parameter mapping above is
|
||||
// already folded into the header/query/path maps, so this adapter deliberately carries no
|
||||
@@ -633,7 +621,7 @@ public class ApiGatewayExecuteController {
|
||||
apiId, stageName, httpMethod, path,
|
||||
outPath.getOrDefault("proxy", ""), resource.getPath(),
|
||||
requestId,
|
||||
headerMap.getOrDefault("X-Forwarded-For", "127.0.0.1"),
|
||||
routeContext.sourceIp(),
|
||||
outHeaders, outQuery, outPath, body,
|
||||
Map.of(), Map.of(),
|
||||
multiValueHeaders, multiValueQuery);
|
||||
@@ -868,7 +856,7 @@ public class ApiGatewayExecuteController {
|
||||
"No integration URI configured");
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String requestId = routeContext.requestId(headers);
|
||||
Map<String, Object> mappingContext = httpRequestMappingContext(scope, requestId, authorizerResult);
|
||||
boolean binaryRequest = isBinaryMediaType(region, apiId,
|
||||
headers.getHeaderString(HttpHeaders.CONTENT_TYPE));
|
||||
@@ -894,31 +882,16 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
|
||||
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext);
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), scope.stage().getVariables(),
|
||||
vtlAuthorizerContext, httpRequestMappingContext(scope, requestId, authorizerResult));
|
||||
|
||||
// Only explicitly mapped parameters reach the backend — the defining difference from
|
||||
// HTTP_PROXY, which seeds the outgoing request with every inbound header and query param.
|
||||
Map<String, String> outHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
Map<String, String> outQuery = new LinkedHashMap<>();
|
||||
Map<String, String> outPath = new LinkedHashMap<>(pathMap);
|
||||
Map<String, String> requestParameters = integration.getRequestParameters();
|
||||
if (requestParameters != null) {
|
||||
for (Map.Entry<String, String> param : requestParameters.entrySet()) {
|
||||
String dest = param.getKey();
|
||||
String resolved = resolveRequestParameter(param.getValue(), queryMap, pathMap, headerMap, mappingContext);
|
||||
if (resolved == null) {
|
||||
continue;
|
||||
}
|
||||
if (dest.startsWith("integration.request.header.")) {
|
||||
outHeaders.put(dest.substring("integration.request.header.".length()), resolved);
|
||||
} else if (dest.startsWith("integration.request.querystring.")) {
|
||||
outQuery.put(dest.substring("integration.request.querystring.".length()), resolved);
|
||||
} else if (dest.startsWith("integration.request.path.")) {
|
||||
outPath.put(dest.substring("integration.request.path.".length()), resolved);
|
||||
}
|
||||
}
|
||||
}
|
||||
HttpRequestParameters mapped = mapHttpRequestParameters(scope, integration, mappingContext,
|
||||
pathMap, Map.of(), Map.of());
|
||||
Map<String, String> outHeaders = joinedParameterValues(mapped.headers());
|
||||
Map<String, String> outQuery = joinedParameterValues(mapped.query());
|
||||
Map<String, String> outPath = mapped.path();
|
||||
|
||||
RequestTemplateResult requestTemplateResult =
|
||||
applyRequestTemplates(scope, integration, incomingContentType, bodyStr, vtlCtx);
|
||||
@@ -927,9 +900,10 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
// The payload is the rendered template, so the backend is told the media type that template
|
||||
// was keyed under — unless a requestParameters mapping already set one explicitly.
|
||||
outHeaders.putIfAbsent("Content-Type",
|
||||
requestTemplateResult.contentType() != null
|
||||
? requestTemplateResult.contentType() : MediaType.APPLICATION_JSON);
|
||||
String outgoingContentType = requestTemplateResult.contentType() != null
|
||||
? requestTemplateResult.contentType() : MediaType.APPLICATION_JSON;
|
||||
outHeaders.putIfAbsent("Content-Type", outgoingContentType);
|
||||
mapped.headers().putIfAbsent("Content-Type", List.of(outgoingContentType));
|
||||
|
||||
// Reuses the HTTP_PROXY transport (hop-by-hop stripping, chunked decoding, 502-on-failure).
|
||||
// The non-proxy semantics live in what this hands it: a mapped header/query set and a
|
||||
@@ -946,9 +920,9 @@ public class ApiGatewayExecuteController {
|
||||
new io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext(
|
||||
apiId, stageName, httpMethod, path,
|
||||
outPath.getOrDefault("proxy", ""), resource.getPath(),
|
||||
requestId, headerMap.getOrDefault("X-Forwarded-For", "127.0.0.1"),
|
||||
requestId, routeContext.sourceIp(),
|
||||
outHeaders, outQuery, outPath, payload,
|
||||
Map.of(), Map.of());
|
||||
Map.of(), Map.of(), mapped.headers(), mapped.query());
|
||||
|
||||
LOG.debugv("execute-api: {0} {1}/{2}{3} → HTTP {4}", httpMethod, apiId, stageName, path, uri);
|
||||
|
||||
@@ -969,8 +943,8 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
|
||||
responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext);
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), scope.stage().getVariables(),
|
||||
vtlAuthorizerContext, httpRequestMappingContext(scope, requestId, authorizerResult));
|
||||
|
||||
// responseHeaders is already case-insensitive, so a plain lookup suffices.
|
||||
String defaultContentType =
|
||||
@@ -1270,8 +1244,14 @@ public class ApiGatewayExecuteController {
|
||||
ctx.put("path", preservedPath);
|
||||
ctx.put("httpMethod", httpMethod);
|
||||
ctx.put("stage", stageName);
|
||||
ctx.put("requestId", UUID.randomUUID().toString());
|
||||
ctx.put("requestTimeEpoch", System.currentTimeMillis());
|
||||
ctx.put("requestId", routeContext.requestId(headers));
|
||||
ctx.put("requestTimeEpoch", routeContext.requestTime().toEpochMilli());
|
||||
ctx.put("requestTime", GATEWAY_REQUEST_TIME.format(routeContext.requestTime().atZone(ZoneOffset.UTC)));
|
||||
ctx.put("extendedRequestId", routeContext.extendedRequestId());
|
||||
String domain = restDomainName(apiId, region, headers);
|
||||
ctx.put("domainName", domain);
|
||||
ctx.put("domainPrefix", domain != null ? domain.split("\\.")[0] : null);
|
||||
ctx.put("protocol", "HTTP/1.1");
|
||||
|
||||
// identity.apiKey / identity.apiKeyId: resolve from usage plans linked to this (apiId, stage)
|
||||
ObjectNode identity = ctx.putObject("identity");
|
||||
@@ -1389,18 +1369,16 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
String arnRegion = region != null ? region : regionResolver.getDefaultRegion();
|
||||
String domainName = AwsEndpoints.executeApiHost(apiId, arnRegion);
|
||||
long nowMillis = System.currentTimeMillis();
|
||||
String requestTime = DateTimeFormatter
|
||||
.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
|
||||
.format(ZonedDateTime.now(ZoneOffset.UTC));
|
||||
String domainName = restDomainName(apiId, arnRegion, headers);
|
||||
long nowMillis = routeContext.requestTime().toEpochMilli();
|
||||
String requestTime = GATEWAY_REQUEST_TIME.format(routeContext.requestTime().atZone(ZoneOffset.UTC));
|
||||
|
||||
ObjectNode ctx = event.putObject("requestContext");
|
||||
ctx.put("accountId", regionResolver.getAccountId());
|
||||
ctx.put("apiId", apiId);
|
||||
ctx.put("domainName", domainName);
|
||||
ctx.put("domainPrefix", apiId);
|
||||
ctx.put("extendedRequestId", requestId);
|
||||
ctx.put("domainPrefix", domainName.split("\\.")[0]);
|
||||
ctx.put("extendedRequestId", routeContext.extendedRequestId());
|
||||
ctx.put("httpMethod", httpMethod);
|
||||
ctx.put("path", requestPath);
|
||||
ctx.put("protocol", "HTTP/1.1");
|
||||
@@ -1680,7 +1658,7 @@ public class ApiGatewayExecuteController {
|
||||
"Cannot parse AWS integration URI: " + integration.getUri());
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String requestId = routeContext.requestId(headers);
|
||||
String bodyStr = body != null && body.length > 0 ? new String(body) : null;
|
||||
|
||||
// Build VTL context
|
||||
@@ -1703,8 +1681,8 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
|
||||
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext);
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), scope.stage().getVariables(),
|
||||
vtlAuthorizerContext, httpRequestMappingContext(scope, requestId, authorizerResult));
|
||||
|
||||
// AWS selects the request template by the *incoming* request Content-Type. Capture it
|
||||
// before parameter mapping runs, since an integration.request.header.Content-Type
|
||||
@@ -1717,7 +1695,9 @@ public class ApiGatewayExecuteController {
|
||||
for (Map.Entry<String, String> param : integrationReqParams.entrySet()) {
|
||||
String dest = param.getKey(); // integration.request.header.X-Foo or integration.request.querystring.bar
|
||||
String source = param.getValue(); // method.request.querystring.q or method.request.header.Auth or method.request.path.id
|
||||
String resolvedValue = resolveRequestParameter(source, queryMap, pathMap, headerMap, Map.of());
|
||||
List<String> resolvedValues = resolveRequestParameter(source, scope,
|
||||
gatewayRequestPathParams(scope), httpRequestMappingContext(scope, requestId, authorizerResult));
|
||||
String resolvedValue = resolvedValues != null ? String.join(",", resolvedValues) : null;
|
||||
if (resolvedValue != null) {
|
||||
if (dest.startsWith("integration.request.header.")) {
|
||||
headerMap.put(dest.substring("integration.request.header.".length()), resolvedValue);
|
||||
@@ -1856,8 +1836,8 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
|
||||
responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext);
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), scope.stage().getVariables(),
|
||||
vtlAuthorizerContext, httpRequestMappingContext(scope, requestId, authorizerResult));
|
||||
|
||||
int fallbackStatus = errorType != null ? 500 : (serviceStatus >= 400 ? serviceStatus : 200);
|
||||
return mapIntegrationResponse(integration, errorMatchString, responseBodyStr, fallbackStatus,
|
||||
@@ -2080,68 +2060,188 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
private Map<String, Object> httpRequestMappingContext(GatewayResponseScope scope, String requestId,
|
||||
AuthorizerResult authorizerResult) {
|
||||
Map<String, Object> context = restRequestContext(scope, requestId);
|
||||
context.put("authorizer", vtlAuthorizerContext(authorizerResult.principalId(), authorizerResult.context()));
|
||||
return context;
|
||||
}
|
||||
|
||||
private Map<String, Object> restRequestContext(GatewayResponseScope scope, String requestId) {
|
||||
String region = scope.region() != null ? scope.region() : regionResolver.getDefaultRegion();
|
||||
String domain = restDomainName(scope.apiId(), region, scope.headers());
|
||||
Map<String, Object> context = new LinkedHashMap<>();
|
||||
context.put("accountId", regionResolver.getAccountId());
|
||||
context.put("apiId", scope.apiId());
|
||||
context.put("deploymentId", scope.stage().getDeploymentId());
|
||||
context.put("deploymentId", scope.stage() != null ? scope.stage().getDeploymentId() : null);
|
||||
context.put("domainName", domain);
|
||||
context.put("domainPrefix", domain != null ? domain.split("\\.")[0] : null);
|
||||
context.put("extendedRequestId", routeContext.extendedRequestId());
|
||||
context.put("httpMethod", scope.httpMethod());
|
||||
context.put("path", "/" + scope.stageName() + scope.path());
|
||||
context.put("protocol", "HTTP/1.1");
|
||||
context.put("requestId", requestId);
|
||||
context.put("resourceId", scope.resource().getId());
|
||||
context.put("resourcePath", scope.resource().getPath());
|
||||
context.put("requestTime", GATEWAY_REQUEST_TIME.format(routeContext.requestTime().atZone(ZoneOffset.UTC)));
|
||||
context.put("requestTimeEpoch", routeContext.requestTime().toEpochMilli());
|
||||
context.put("resourceId", scope.resource() != null ? scope.resource().getId() : "");
|
||||
context.put("resourcePath", scope.resource() != null ? scope.resource().getPath() : "");
|
||||
context.put("stage", scope.stageName());
|
||||
|
||||
Map<String, Object> identity = new LinkedHashMap<>();
|
||||
identity.put("sourceIp", "127.0.0.1");
|
||||
identity.put("userAgent", scope.headers().getHeaderString("User-Agent"));
|
||||
context.put("identity", identity);
|
||||
|
||||
Map<String, Object> authorizer = new LinkedHashMap<>();
|
||||
if (authorizerResult.context() != null) {
|
||||
authorizer.putAll(authorizerResult.context());
|
||||
}
|
||||
if (authorizerResult.principalId() != null) {
|
||||
authorizer.put("principalId", authorizerResult.principalId());
|
||||
}
|
||||
context.put("authorizer", authorizer);
|
||||
context.put("identity", restRequestIdentity(scope));
|
||||
return context;
|
||||
}
|
||||
|
||||
private String resolveRequestParameter(String source, Map<String, String> queryParams,
|
||||
Map<String, String> pathParams, Map<String, String> headers,
|
||||
Map<String, Object> context) {
|
||||
private String restDomainName(String apiId, String region, HttpHeaders headers) {
|
||||
String host = headers != null ? headers.getHeaderString("Host") : null;
|
||||
if (host != null) {
|
||||
try {
|
||||
String domain = URI.create("http://" + host).getHost();
|
||||
if (domain != null) {
|
||||
return domain;
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// Invalid client hosts must not break integration events or intended gateway errors.
|
||||
}
|
||||
}
|
||||
return AwsEndpoints.executeApiHost(apiId, region);
|
||||
}
|
||||
|
||||
private Map<String, Object> restRequestIdentity(GatewayResponseScope scope) {
|
||||
ExecuteApiSigV4Authorizer.CallerIdentity caller = scope.iamIdentity();
|
||||
Map<String, Object> identity = new LinkedHashMap<>();
|
||||
identity.put("sourceIp", routeContext.sourceIp());
|
||||
identity.put("userAgent", scope.headers() != null ? scope.headers().getHeaderString("User-Agent") : null);
|
||||
identity.put("apiKey", scope.apiKey() != null ? scope.apiKey().value() : null);
|
||||
identity.put("apiKeyId", scope.apiKey() != null ? scope.apiKey().id() : null);
|
||||
identity.put("accessKey", caller != null ? caller.accessKey() : null);
|
||||
identity.put("accountId", caller != null ? caller.accountId() : null);
|
||||
identity.put("caller", caller != null ? caller.userId() : null);
|
||||
identity.put("user", caller != null ? caller.userId() : null);
|
||||
identity.put("userArn", caller != null ? caller.userArn() : null);
|
||||
return identity;
|
||||
}
|
||||
|
||||
private record HttpRequestParameters(Map<String, List<String>> headers, Map<String, List<String>> query,
|
||||
Map<String, String> path) { }
|
||||
|
||||
private HttpRequestParameters mapHttpRequestParameters(GatewayResponseScope scope, Integration integration,
|
||||
Map<String, Object> context, Map<String, String> path,
|
||||
Map<String, List<String>> headers,
|
||||
Map<String, List<String>> query) {
|
||||
Map<String, List<String>> outHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
outHeaders.putAll(headers);
|
||||
Map<String, List<String>> outQuery = new LinkedHashMap<>(query);
|
||||
Map<String, String> outPath = new LinkedHashMap<>(path);
|
||||
if (integration.getRequestParameters() == null) {
|
||||
return new HttpRequestParameters(outHeaders, outQuery, outPath);
|
||||
}
|
||||
for (Map.Entry<String, String> mapping : integration.getRequestParameters().entrySet()) {
|
||||
String destination = mapping.getKey();
|
||||
String source = mapping.getValue();
|
||||
List<String> values = resolveRequestParameter(source, scope, path, context);
|
||||
if (destination.startsWith("integration.request.header.")) {
|
||||
String name = destination.substring("integration.request.header.".length());
|
||||
// An absent trusted context mapping must never retain a client-provided value.
|
||||
if (source != null && source.startsWith("context.")) {
|
||||
outHeaders.remove(name);
|
||||
}
|
||||
if (values != null) {
|
||||
outHeaders.put(name, values);
|
||||
}
|
||||
} else if (values != null && destination.startsWith("integration.request.querystring.")) {
|
||||
outQuery.put(destination.substring("integration.request.querystring.".length()), values);
|
||||
} else if (values != null && destination.startsWith("integration.request.path.")) {
|
||||
outPath.put(destination.substring("integration.request.path.".length()), String.join(",", values));
|
||||
}
|
||||
}
|
||||
return new HttpRequestParameters(outHeaders, outQuery, outPath);
|
||||
}
|
||||
|
||||
private static Map<String, String> joinedParameterValues(Map<String, List<String>> parameters) {
|
||||
Map<String, String> single = new LinkedHashMap<>();
|
||||
parameters.forEach((name, values) -> single.put(name, String.join(",", values)));
|
||||
return single;
|
||||
}
|
||||
|
||||
private List<String> resolveRequestParameter(String source, GatewayResponseScope scope,
|
||||
Map<String, String> path, Map<String, Object> context) {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
if (source.startsWith("method.request.multivalueheader.")) {
|
||||
return nonemptyValues(scope.headers().getRequestHeader(source.substring("method.request.multivalueheader.".length())));
|
||||
}
|
||||
if (source.startsWith("method.request.multivaluequerystring.")) {
|
||||
return nonemptyValues(scope.uriInfo().getQueryParameters().get(source.substring("method.request.multivaluequerystring.".length())));
|
||||
}
|
||||
String value = resolveScalarRequestParameter(source, scope, path, context);
|
||||
return value != null ? List.of(value) : null;
|
||||
}
|
||||
|
||||
private static List<String> nonemptyValues(List<String> values) {
|
||||
return values != null && !values.isEmpty() ? List.copyOf(values) : null;
|
||||
}
|
||||
|
||||
private String resolveScalarRequestParameter(String source, GatewayResponseScope scope,
|
||||
Map<String, String> path, Map<String, Object> context) {
|
||||
if (source.startsWith("method.request.querystring.")) {
|
||||
return queryParams.get(source.substring("method.request.querystring.".length()));
|
||||
return scope.uriInfo().getQueryParameters().getFirst(source.substring("method.request.querystring.".length()));
|
||||
}
|
||||
if (source.startsWith("method.request.path.")) {
|
||||
return pathParams.get(source.substring("method.request.path.".length()));
|
||||
return path.get(source.substring("method.request.path.".length()));
|
||||
}
|
||||
if (source.startsWith("method.request.header.")) {
|
||||
return headers.get(source.substring("method.request.header.".length()));
|
||||
List<String> values = scope.headers().getRequestHeader(source.substring("method.request.header.".length()));
|
||||
return values != null && !values.isEmpty() ? values.getFirst() : null;
|
||||
}
|
||||
if (source.startsWith("context.")) {
|
||||
Object value = contextValue(context, source.substring("context.".length()));
|
||||
return value instanceof String || value instanceof Number || value instanceof Boolean
|
||||
? value.toString() : null;
|
||||
return value instanceof String || value instanceof Number || value instanceof Boolean ? value.toString() : null;
|
||||
}
|
||||
// Static value
|
||||
if (source.startsWith("'") && source.endsWith("'")) {
|
||||
if (source.startsWith("stageVariables.")) {
|
||||
return scope.stage().getVariables().get(source.substring("stageVariables.".length()));
|
||||
}
|
||||
if (source.startsWith("method.request.body")) {
|
||||
return resolveRequestBodyParameter(source, scope.body());
|
||||
}
|
||||
if (source.length() >= 2 && source.startsWith("'") && source.endsWith("'")) {
|
||||
return source.substring(1, source.length() - 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String resolveRequestBodyParameter(String source, byte[] body) {
|
||||
if (body == null) {
|
||||
return null;
|
||||
}
|
||||
if (source.equals("method.request.body")) {
|
||||
return new String(body, StandardCharsets.UTF_8);
|
||||
}
|
||||
if (!source.startsWith("method.request.body.") && !source.startsWith("method.request.body[")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(body);
|
||||
if (root == null) {
|
||||
return null;
|
||||
}
|
||||
String path = "$" + source.substring("method.request.body".length());
|
||||
Object resolved = JsonPath.using(jsonPathConfiguration).parse(root).read(path);
|
||||
JsonNode value = resolved instanceof JsonNode node ? node : objectMapper.valueToTree(resolved);
|
||||
if (value.isMissingNode() || value.isNull()) {
|
||||
return null;
|
||||
}
|
||||
return value.isContainerNode() ? value.toString() : value.asText();
|
||||
} catch (IOException | InvalidPathException exception) {
|
||||
LOG.debugv("Request body parameter {0} could not be resolved: {1}", source, exception.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── MOCK ────────────────────────────
|
||||
|
||||
private Response invokeMock(GatewayResponseScope scope, String region, String httpMethod, String path,
|
||||
String stageName, ApiGatewayResource resource, Integration integration,
|
||||
HttpHeaders headers, UriInfo uriInfo, byte[] body,
|
||||
AuthorizerResult authorizerResult) {
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String requestId = routeContext.requestId(headers);
|
||||
String bodyStr = body != null && body.length > 0 ? new String(body) : null;
|
||||
|
||||
Map<String, String> headerMap = new HashMap<>();
|
||||
@@ -2161,8 +2261,9 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
|
||||
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext(authorizerResult.principalId(), authorizerResult.context()));
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), scope.stage().getVariables(),
|
||||
vtlAuthorizerContext(authorizerResult.principalId(), authorizerResult.context()),
|
||||
httpRequestMappingContext(scope, requestId, authorizerResult));
|
||||
|
||||
// A MOCK has no backend: the request template *is* the integration response, and the
|
||||
// "statusCode" it renders is what the integration responses' selectionPatterns are
|
||||
@@ -3673,32 +3774,9 @@ public class ApiGatewayExecuteController {
|
||||
*/
|
||||
private Map<String, Object> gatewayResponseContext(GatewayResponseScope scope, GatewayResponseType type,
|
||||
int status, String message, String validationError) {
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String region = scope.region() != null ? scope.region() : regionResolver.getDefaultRegion();
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
|
||||
Map<String, Object> context = new LinkedHashMap<>();
|
||||
context.put("accountId", regionResolver.getAccountId());
|
||||
context.put("apiId", scope.apiId());
|
||||
context.put("domainName", AwsEndpoints.executeApiHost(scope.apiId(), region));
|
||||
context.put("domainPrefix", scope.apiId());
|
||||
context.put("extendedRequestId", requestId);
|
||||
context.put("httpMethod", scope.httpMethod());
|
||||
context.put("path", "/" + scope.stageName() + scope.path());
|
||||
context.put("protocol", "HTTP/1.1");
|
||||
context.put("requestId", requestId);
|
||||
context.put("requestTime", GATEWAY_REQUEST_TIME.format(now));
|
||||
context.put("requestTimeEpoch", now.toInstant().toEpochMilli());
|
||||
context.put("resourceId", scope.resource() != null ? scope.resource().getId() : "");
|
||||
context.put("resourcePath", scope.resource() != null ? scope.resource().getPath() : "");
|
||||
context.put("stage", scope.stageName());
|
||||
Map<String, Object> context = restRequestContext(scope, routeContext.requestId(scope.headers()));
|
||||
context.put("status", status);
|
||||
|
||||
Map<String, Object> identity = new LinkedHashMap<>();
|
||||
identity.put("sourceIp", routeContext.sourceIp());
|
||||
identity.put("userAgent", scope.headers() != null ? scope.headers().getHeaderString("User-Agent") : null);
|
||||
context.put("identity", identity);
|
||||
|
||||
String messageString;
|
||||
try {
|
||||
messageString = objectMapper.writeValueAsString(message);
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import jakarta.annotation.Priority;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Priorities;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerResponseContext;
|
||||
import jakarta.ws.rs.container.ContainerResponseFilter;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
/** Gives REST execution responses the request identifiers used by authorizers and integrations. */
|
||||
@Provider
|
||||
@Priority(Priorities.HEADER_DECORATOR)
|
||||
public class ApiGatewayExecuteResponseFilter implements ContainerResponseFilter {
|
||||
private final ApiGatewayExecuteRouteContext routeContext;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayExecuteResponseFilter(ApiGatewayExecuteRouteContext routeContext) {
|
||||
this.routeContext = routeContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
|
||||
if (!routeContext.isRestApiRoute()) {
|
||||
return;
|
||||
}
|
||||
MultivaluedMap<String, Object> headers = response.getHeaders();
|
||||
headers.keySet().removeIf(name -> name.equalsIgnoreCase("x-amzn-RequestId") || name.equalsIgnoreCase("x-amz-apigw-id"));
|
||||
headers.putSingle("x-amzn-RequestId", routeContext.requestIdFromOverride(request.getHeaderString("x-amzn-RequestId")));
|
||||
headers.putSingle("x-amz-apigw-id", routeContext.extendedRequestId());
|
||||
}
|
||||
}
|
||||
+41
@@ -4,8 +4,12 @@ import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import jakarta.enterprise.context.RequestScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Carries routing information established by pre-matching execute-api filters to the
|
||||
* execute controller without changing the AWS-compatible request.
|
||||
@@ -29,6 +33,43 @@ public class ApiGatewayExecuteRouteContext {
|
||||
return context != null ? context.request().connection().remoteAddress().hostAddress() : "127.0.0.1";
|
||||
}
|
||||
|
||||
private final Instant requestTime = Instant.now();
|
||||
private final String extendedRequestId = UUID.randomUUID().toString();
|
||||
private String requestId;
|
||||
|
||||
String requestId(HttpHeaders headers) {
|
||||
return requestIdFromOverride(headers != null ? headers.getHeaderString("x-amzn-RequestId") : null);
|
||||
}
|
||||
|
||||
String requestIdFromOverride(String override) {
|
||||
if (requestId != null) {
|
||||
return requestId;
|
||||
}
|
||||
requestId = UUID.randomUUID().toString();
|
||||
if (override == null) {
|
||||
return requestId;
|
||||
}
|
||||
try {
|
||||
if (UUID.fromString(override).toString().equalsIgnoreCase(override)) {
|
||||
requestId = override;
|
||||
} else {
|
||||
requestId += "_REPLACED_INVALID_REQUEST_ID";
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// AWS replaces invalid overrides and marks them in the request ID.
|
||||
requestId += "_REPLACED_INVALID_REQUEST_ID";
|
||||
}
|
||||
return requestId;
|
||||
}
|
||||
|
||||
String extendedRequestId() {
|
||||
return extendedRequestId;
|
||||
}
|
||||
|
||||
Instant requestTime() {
|
||||
return requestTime;
|
||||
}
|
||||
|
||||
private String httpApiRegion;
|
||||
private boolean restApiRoute;
|
||||
private String signedRequestPath;
|
||||
|
||||
Reference in new issue
Block a user