mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -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
@@ -340,8 +340,11 @@ than `proxy` are supported, including in `integration.request.path.*` mappings.
|
||||
REST `HTTP_PROXY` and `HTTP` integrations also accept `context.*` sources in header, query
|
||||
and path parameter mappings. Supported request fields are `accountId`, `apiId`, `deploymentId`,
|
||||
`httpMethod`, `path` (including the stage), `protocol`, `requestId`, `resourceId`, `resourcePath`,
|
||||
`stage`, `identity.sourceIp` and `identity.userAgent`. `context.requestId` uses the same ID as
|
||||
the HTTP integration's VTL templates. `context.authorizer.principalId` and
|
||||
`stage`, `domainName`, `domainPrefix`, `extendedRequestId`, `requestTime` and `requestTimeEpoch`.
|
||||
Identity fields include the immediate TCP peer's `sourceIp`, `userAgent`, a resolved API key's
|
||||
`apiKey` and `apiKeyId`, and the verified IAM caller's `accessKey`, `accountId`, `caller`, `user`
|
||||
and `userArn`. `context.requestId` uses the same ID as the authorizer and integration templates.
|
||||
A valid UUID in `x-amzn-RequestId` overrides that ID; `extendedRequestId` is generated independently. `context.authorizer.principalId` and
|
||||
`context.authorizer.<property>` come from the successful authorizer result; authenticated Cognito
|
||||
claims are available as `context.authorizer.claims.<property>`. String, number and boolean values
|
||||
are forwarded as strings. Missing values and objects are not mapped. An explicit header mapping
|
||||
@@ -354,6 +357,11 @@ HTTP proxy passthrough behavior.
|
||||
|
||||
`method.request.*` sources always read the original inbound headers, query parameters and path
|
||||
parameters. Mapped destinations do not change another mapping's source, regardless of mapping order.
|
||||
Scalar `method.request.header.*` and `method.request.querystring.*` sources select the first
|
||||
inbound value.
|
||||
`method.request.multivalueheader.*` and `method.request.multivaluequerystring.*` preserve repeated
|
||||
values in either HTTP integration type. `stageVariables.*`, the raw `method.request.body` and
|
||||
`method.request.body.<JSONPath>` are supported too.
|
||||
|
||||
Use alphanumeric or underscore authorizer context keys, as required by the
|
||||
[AWS mapping contract](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html).
|
||||
|
||||
+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;
|
||||
|
||||
+6
-2
@@ -1002,10 +1002,12 @@ class ApiGatewayAwsIntegrationTest {
|
||||
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem");
|
||||
ObjectNode reqParams = mapper.createObjectNode();
|
||||
reqParams.put("integration.request.querystring.itemId", "method.request.querystring.itemId");
|
||||
reqParams.put("integration.request.header.X-Mapped", "method.request.header.X-Source");
|
||||
integrationNode.set("requestParameters", reqParams);
|
||||
ObjectNode rt = mapper.createObjectNode();
|
||||
rt.put("application/json",
|
||||
"{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"$input.params('itemId')\"}, \"source\": {\"S\": \"req-param-mapped\"}}}");
|
||||
"{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"$input.params('itemId')\"}, "
|
||||
+ "\"source\": {\"S\": \"req-param-mapped\"}, \"header\": {\"S\": \"$input.params('X-Mapped')\"}}}");
|
||||
integrationNode.set("requestTemplates", rt);
|
||||
|
||||
given()
|
||||
@@ -1027,7 +1029,8 @@ class ApiGatewayAwsIntegrationTest {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{}")
|
||||
.queryParam("itemId", "param-123")
|
||||
.queryParam("itemId", "param-123", "second-id")
|
||||
.header("X-Source", "first-header", "second-header")
|
||||
.when().post("/execute-api/" + apiId + "/test/req-param")
|
||||
.then().statusCode(200);
|
||||
|
||||
@@ -1044,6 +1047,7 @@ class ApiGatewayAwsIntegrationTest {
|
||||
assertTrue(result.has("Item"), "Item should exist with param-mapped key");
|
||||
assertEquals("param-123", result.path("Item").path("id").path("S").asText());
|
||||
assertEquals("req-param-mapped", result.path("Item").path("source").path("S").asText());
|
||||
assertEquals("first-header", result.path("Item").path("header").path("S").asText());
|
||||
}
|
||||
|
||||
// ──────────────── Test: Response body JSONPath (deep) ────────────────
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ApiGatewayExecuteRouteContextTest {
|
||||
@Test
|
||||
void requestIdOverrideDoesNotReplaceExtendedIdOrChangeMidRequest() {
|
||||
ApiGatewayExecuteRouteContext context = new ApiGatewayExecuteRouteContext();
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
assertEquals(requestId, context.requestIdFromOverride(requestId));
|
||||
assertEquals(requestId, context.requestIdFromOverride(UUID.randomUUID().toString()));
|
||||
assertNotEquals(requestId, context.extendedRequestId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedUuidIsReplacedAndMarked() {
|
||||
ApiGatewayExecuteRouteContext context = new ApiGatewayExecuteRouteContext();
|
||||
String requestId = context.requestIdFromOverride("1-1-1-1-1");
|
||||
String marker = "_REPLACED_INVALID_REQUEST_ID";
|
||||
assertTrue(requestId.endsWith(marker));
|
||||
assertDoesNotThrow(() -> UUID.fromString(requestId.substring(0, requestId.length() - marker.length())));
|
||||
}
|
||||
}
|
||||
+256
-2
@@ -7,14 +7,19 @@ import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
@@ -22,6 +27,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -30,6 +36,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -135,6 +142,20 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void rejectsObjectAuthorizerContextBeforeReachingBackend(String type) throws Exception {
|
||||
configureAuthorizer(0, Map.of("objectKey", Map.of("nested", "value")));
|
||||
configureIntegration(type, "GET", Map.of(
|
||||
"integration.request.header.X-Object", "context.authorizer.objectKey",
|
||||
"integration.request.path.principal", "context.authorizer.principalId",
|
||||
"integration.request.path.proxy", "method.request.path.proxy"));
|
||||
deploy();
|
||||
given().header("Authorization", "Bearer allowed").header("X-Object", "forged")
|
||||
.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(500);
|
||||
assertEquals(0, backendRequests.get());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void missingAuthorizerClaimDoesNotFallBackToClientHeader(String type) throws Exception {
|
||||
@@ -260,6 +281,234 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
assertDoesNotThrow(() -> UUID.fromString(response.path("headers").path("x-request-id").path(0).asText()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void mapsDocumentedRequestMetadataAndValidClientRequestId(String type) throws Exception {
|
||||
configureAuthorizer(0);
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
for (String field : List.of("requestId", "extendedRequestId", "domainName", "domainPrefix",
|
||||
"requestTime", "requestTimeEpoch", "identity.sourceIp")) {
|
||||
parameters.put("integration.request.header.X-" + field.replace('.', '-'), "context." + field);
|
||||
}
|
||||
parameters.put("integration.request.path.principal", "context.authorizer.principalId");
|
||||
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
|
||||
configureIntegration(type, "GET", parameters);
|
||||
deploy();
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
long before = System.currentTimeMillis();
|
||||
JsonNode response = MAPPER.readTree(given().header("Authorization", "Bearer allowed")
|
||||
.header("x-amzn-RequestId", requestId).header("X-Forwarded-For", "192.0.2.10")
|
||||
.get("/execute-api/" + apiId + "/test/orders/42")
|
||||
.then().statusCode(200).header("x-amzn-RequestId", equalTo(requestId)).extract().asByteArray());
|
||||
JsonNode headers = response.path("headers");
|
||||
assertEquals(requestId, headers.path("x-requestid").path(0).asText());
|
||||
String extendedId = headers.path("x-extendedrequestid").path(0).asText();
|
||||
assertFalse(extendedId.isEmpty());
|
||||
assertNotEquals(requestId, extendedId);
|
||||
assertEquals("localhost", headers.path("x-domainname").path(0).asText());
|
||||
assertEquals("localhost", headers.path("x-domainprefix").path(0).asText());
|
||||
long requestTime = Long.parseLong(headers.path("x-requesttimeepoch").path(0).asText());
|
||||
assertTrue(requestTime >= before && requestTime <= System.currentTimeMillis());
|
||||
assertFalse(headers.path("x-requesttime").path(0).asText().isEmpty());
|
||||
assertEquals("127.0.0.1", headers.path("x-identity-sourceip").path(0).asText());
|
||||
if ("HTTP".equals(type)) {
|
||||
assertEquals(requestId, MAPPER.readTree(response.path("body").asText()).path("requestId").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"bad_host", "bad_host:8080"})
|
||||
void malformedHostDoesNotBreakMappingOrGatewayErrors(String host) throws Exception {
|
||||
configureAuthorizer(0);
|
||||
configureIntegration("HTTP_PROXY", "GET", Map.of(
|
||||
"integration.request.header.X-Domain", "context.domainName",
|
||||
"integration.request.path.principal", "context.authorizer.principalId",
|
||||
"integration.request.path.proxy", "method.request.path.proxy"));
|
||||
deploy();
|
||||
given().header("Host", host).header("Authorization", "Bearer allowed")
|
||||
.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(200)
|
||||
.body("headers.x-domain[0]", equalTo(apiId + ".execute-api.us-east-1.amazonaws.com"));
|
||||
given().contentType(ContentType.JSON).body(Map.of("responseParameters", Map.of(
|
||||
"gatewayresponse.header.X-Domain", "context.domainName")))
|
||||
.put("/restapis/" + apiId + "/gatewayresponses/ACCESS_DENIED").then().statusCode(201);
|
||||
given().header("Host", host).header("Authorization", "Bearer forged")
|
||||
.get("/execute-api/" + apiId + "/test/orders/42")
|
||||
.then().statusCode(403).header("X-Domain", equalTo(apiId + ".execute-api.us-east-1.amazonaws.com"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/execute-api/missing-api/test/orders", "/restapis/missing-api/test/_user_request_/orders"})
|
||||
void missingRestApiErrorsHaveRequestIdentifiers(String path) {
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
Response response = given().header("x-amzn-RequestId", requestId)
|
||||
.get(path).then().statusCode(404).header("x-amzn-RequestId", equalTo(requestId)).extract().response();
|
||||
assertDoesNotThrow(() -> UUID.fromString(response.header("x-amz-apigw-id")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void mapsStageRepeatedValuesAndOriginalBodyFields(String type) throws Exception {
|
||||
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE"))
|
||||
.put(methodPath + "POST").then().statusCode(201);
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("integration.request.header.X-Header-Copy", "method.request.multivalueheader.X-Source");
|
||||
parameters.put("integration.request.header.X-Scalar-Header", "method.request.header.X-Source");
|
||||
parameters.put("integration.request.querystring.copied", "method.request.multivaluequerystring.source");
|
||||
parameters.put("integration.request.querystring.scalar", "method.request.querystring.source");
|
||||
parameters.put("integration.request.header.X-Raw-Body", "method.request.body");
|
||||
parameters.put("integration.request.header.X-Body-Number", "method.request.body.items[0].number");
|
||||
parameters.put("integration.request.header.X-Body-Items", "method.request.body.items[*]");
|
||||
parameters.put("integration.request.header.X-Body-Numbers", "method.request.body.items[*].number");
|
||||
parameters.put("integration.request.header.X-Body-Missing", "method.request.body.missing");
|
||||
parameters.put("integration.request.header.X-Body-Invalid", "method.request.body.items[invalid]");
|
||||
parameters.put("integration.request.header.X-Body-Boolean", "method.request.body.enabled");
|
||||
parameters.put("integration.request.querystring.owner", "stageVariables.owner");
|
||||
parameters.put("integration.request.path.principal", "stageVariables.owner");
|
||||
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
|
||||
configureIntegration(type, "POST", parameters);
|
||||
deploy();
|
||||
given().contentType(ContentType.JSON).body(Map.of("patchOperations", List.of(Map.of(
|
||||
"op", "add", "path", "/variables/owner", "value", "stage-owner"))))
|
||||
.patch("/restapis/" + apiId + "/stages/test").then().statusCode(200);
|
||||
String body = "{\"items\":[{\"number\":42},{\"number\":7}],\"enabled\":true}";
|
||||
JsonNode response = MAPPER.readTree(given().contentType(ContentType.JSON).body(body)
|
||||
.header("X-Source", "first", "second").queryParam("source", "one", "two")
|
||||
.post("/execute-api/" + apiId + "/test/orders/42")
|
||||
.then().statusCode(200).extract().asByteArray());
|
||||
assertEquals(MAPPER.valueToTree(List.of("first", "second")), response.path("headers").path("x-header-copy"));
|
||||
assertEquals(MAPPER.valueToTree(List.of("first")), response.path("headers").path("x-scalar-header"));
|
||||
assertEquals(body, response.path("headers").path("x-raw-body").path(0).asText());
|
||||
assertEquals("42", response.path("headers").path("x-body-number").path(0).asText());
|
||||
assertEquals("[{\"number\":42},{\"number\":7}]", response.path("headers").path("x-body-items").path(0).asText());
|
||||
assertEquals("[42,7]", response.path("headers").path("x-body-numbers").path(0).asText());
|
||||
assertFalse(response.path("headers").has("x-body-missing"));
|
||||
assertFalse(response.path("headers").has("x-body-invalid"));
|
||||
assertEquals("true", response.path("headers").path("x-body-boolean").path(0).asText());
|
||||
assertTrue(response.path("query").asText().contains("copied=one&copied=two"));
|
||||
assertTrue(List.of(response.path("query").asText().split("&")).contains("scalar=one"));
|
||||
assertTrue(response.path("query").asText().contains("owner=stage-owner"));
|
||||
assertEquals("/users/stage-owner/orders/42", response.path("path").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void mapsArrayRootBodyFields(String type) throws Exception {
|
||||
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE"))
|
||||
.put(methodPath + "POST").then().statusCode(201);
|
||||
configureIntegration(type, "POST", Map.of(
|
||||
"integration.request.header.X-First-Price", "method.request.body[0].price",
|
||||
"integration.request.header.X-Prices", "method.request.body[*].price",
|
||||
"integration.request.path.principal", "'array'",
|
||||
"integration.request.path.proxy", "method.request.path.proxy"));
|
||||
deploy();
|
||||
JsonNode response = MAPPER.readTree(given().contentType(ContentType.JSON)
|
||||
.body("[{\"price\":42},{\"price\":7}]")
|
||||
.post("/execute-api/" + apiId + "/test/orders/42")
|
||||
.then().statusCode(200).extract().asByteArray());
|
||||
assertEquals("42", response.path("headers").path("x-first-price").path(0).asText());
|
||||
assertEquals("[42,7]", response.path("headers").path("x-prices").path(0).asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void mapsCustomDomainAndPrefix(String type) throws Exception {
|
||||
configureAuthorizer(0);
|
||||
configureIntegration(type, "GET", Map.of("integration.request.header.X-Domain", "context.domainName",
|
||||
"integration.request.header.X-Prefix", "context.domainPrefix",
|
||||
"integration.request.path.principal", "context.authorizer.principalId",
|
||||
"integration.request.path.proxy", "method.request.path.proxy"));
|
||||
deploy();
|
||||
String domain = apiId + ".example.test";
|
||||
given().contentType(ContentType.JSON).body(Map.of("domainName", domain,
|
||||
"certificateArn", "arn:aws:acm:us-east-1:000000000000:certificate/example"))
|
||||
.post("/domainnames").then().statusCode(201);
|
||||
try {
|
||||
given().contentType(ContentType.JSON).body(Map.of("basePath", "v1", "restApiId", apiId, "stage", "test"))
|
||||
.post("/domainnames/" + domain + "/basepathmappings").then().statusCode(201);
|
||||
JsonNode response = MAPPER.readTree(given().header("Host", domain).header("Authorization", "Bearer allowed")
|
||||
.get("/v1/orders/42").then().statusCode(200).extract().asByteArray());
|
||||
assertEquals(domain, response.path("headers").path("x-domain").path(0).asText());
|
||||
assertEquals(apiId, response.path("headers").path("x-prefix").path(0).asText());
|
||||
} finally {
|
||||
given().delete("/domainnames/" + domain).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void requestAuthorizerAndBackendShareRequestMetadata(String type) throws Exception {
|
||||
configureAuthorizer(0, Map.of("userClaims", "verified-claims"), "REQUEST");
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
for (String field : List.of("requestId", "extendedRequestId", "requestTimeEpoch")) {
|
||||
parameters.put("integration.request.header.X-" + field, "context." + field);
|
||||
}
|
||||
parameters.put("integration.request.path.principal", "context.authorizer.principalId");
|
||||
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
|
||||
configureIntegration(type, "GET", parameters);
|
||||
deploy();
|
||||
JsonNode response = MAPPER.readTree(given().header("Authorization", "Bearer allowed")
|
||||
.get("/execute-api/" + apiId + "/test/orders/42")
|
||||
.then().statusCode(200).extract().asByteArray());
|
||||
ArgumentCaptor<byte[]> invocation = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invoke(eq("us-east-1"), eq(FUNCTION), invocation.capture(), eq(InvocationType.RequestResponse));
|
||||
JsonNode authorizerContext = MAPPER.readTree(invocation.getValue()).path("requestContext");
|
||||
for (String field : List.of("requestId", "extendedRequestId", "requestTimeEpoch")) {
|
||||
assertEquals(authorizerContext.path(field).asText(), response.path("headers").path("x-" + field.toLowerCase(Locale.ROOT)).path(0).asText());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void mapsVerifiedIamIdentity(String type) throws Exception {
|
||||
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "AWS_IAM"))
|
||||
.put(methodPath + "GET").then().statusCode(201);
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
for (String field : List.of("accessKey", "accountId", "caller", "user", "userArn")) {
|
||||
parameters.put("integration.request.header.X-" + field, "context.identity." + field);
|
||||
}
|
||||
parameters.put("integration.request.path.principal", "'iam'");
|
||||
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
|
||||
configureIntegration(type, "GET", parameters);
|
||||
deploy();
|
||||
String path = "/execute-api/" + apiId + "/test/orders/42";
|
||||
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders("GET", path, Map.of(),
|
||||
"localhost:" + RestAssured.port, null, "test", "test", "us-east-1", Instant.now());
|
||||
JsonNode response = MAPPER.readTree(given().headers(signed).get(path)
|
||||
.then().statusCode(200).extract().asByteArray());
|
||||
assertEquals("test", response.path("headers").path("x-accesskey").path(0).asText());
|
||||
assertEquals("000000000000", response.path("headers").path("x-accountid").path(0).asText());
|
||||
assertFalse(response.path("headers").path("x-userarn").path(0).asText().isEmpty());
|
||||
assertEquals(response.path("headers").path("x-caller"), response.path("headers").path("x-user"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
|
||||
void mapsResolvedApiKey(String type) throws Exception {
|
||||
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE", "apiKeyRequired", true))
|
||||
.put(methodPath + "GET").then().statusCode(201);
|
||||
configureIntegration(type, "GET", Map.of("integration.request.header.X-Key", "context.identity.apiKey",
|
||||
"integration.request.header.X-Key-Id", "context.identity.apiKeyId",
|
||||
"integration.request.path.principal", "'key'", "integration.request.path.proxy", "method.request.path.proxy"));
|
||||
deploy();
|
||||
JsonNode key = MAPPER.readTree(given().contentType(ContentType.JSON).body(Map.of("name", "mapping-key", "enabled", true))
|
||||
.post("/apikeys").then().statusCode(201).extract().asByteArray());
|
||||
String plan = given().contentType(ContentType.JSON).body(Map.of("name", "mapping-plan", "apiStages",
|
||||
List.of(Map.of("apiId", apiId, "stage", "test"))))
|
||||
.post("/usageplans").then().statusCode(201).extract().path("id");
|
||||
try {
|
||||
given().contentType(ContentType.JSON).body(Map.of("keyId", key.path("id").asText(), "keyType", "API_KEY"))
|
||||
.post("/usageplans/" + plan + "/keys").then().statusCode(201);
|
||||
JsonNode response = MAPPER.readTree(given().header("X-Api-Key", key.path("value").asText())
|
||||
.get("/execute-api/" + apiId + "/test/orders/42")
|
||||
.then().statusCode(200).extract().asByteArray());
|
||||
assertEquals(key.path("value").asText(), response.path("headers").path("x-key").path(0).asText());
|
||||
assertEquals(key.path("id").asText(), response.path("headers").path("x-key-id").path(0).asText());
|
||||
} finally {
|
||||
given().delete("/usageplans/" + plan).then().statusCode(202);
|
||||
given().delete("/apikeys/" + key.path("id").asText()).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
|
||||
private void assertMappedContext(JsonNode response) {
|
||||
JsonNode headers = response.path("headers");
|
||||
assertEquals(MAPPER.valueToTree(List.of("verified-claims")), headers.path("x-user-claims"));
|
||||
@@ -279,8 +528,12 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
}
|
||||
|
||||
private void configureAuthorizer(int ttl, Map<String, Object> context) throws Exception {
|
||||
configureAuthorizer(ttl, context, "TOKEN");
|
||||
}
|
||||
|
||||
private void configureAuthorizer(int ttl, Map<String, Object> context, String type) throws Exception {
|
||||
String authorizerId = given().contentType(ContentType.JSON)
|
||||
.body(Map.of("name", "claims", "type", "TOKEN", "authorizerUri", AUTHORIZER_URI,
|
||||
.body(Map.of("name", "claims", "type", type, "authorizerUri", AUTHORIZER_URI,
|
||||
"identitySource", "method.request.header.Authorization", "authorizerResultTtlInSeconds", ttl))
|
||||
.post("/restapis/" + apiId + "/authorizers")
|
||||
.then().statusCode(201).extract().path("id");
|
||||
@@ -290,7 +543,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenAnswer(invocation -> {
|
||||
JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
|
||||
String effect = "Bearer allowed".equals(event.path("authorizationToken").asText()) ? "Allow" : "Deny";
|
||||
String effect = "REQUEST".equals(type) || "Bearer allowed".equals(event.path("authorizationToken").asText()) ? "Allow" : "Deny";
|
||||
byte[] payload = MAPPER.writeValueAsBytes(Map.of("principalId", "verified-user",
|
||||
"policyDocument", Map.of("Version", "2012-10-17", "Statement", List.of(Map.of(
|
||||
"Action", "execute-api:Invoke", "Effect", effect, "Resource", "*"))),
|
||||
@@ -306,6 +559,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
|
||||
parameters.put("integration.request.header.X-Number", "context.authorizer.numberKey");
|
||||
parameters.put("integration.request.header.X-Boolean", "context.authorizer.booleanKey");
|
||||
parameters.put("integration.request.header.X-Missing", "context.authorizer.missing");
|
||||
// REST authorizer context rejects objects, so use the identity map to test non-scalar mappings.
|
||||
parameters.put("integration.request.header.X-Object", "context.identity");
|
||||
parameters.put("integration.request.header.X-Request-Id", "context.requestId");
|
||||
parameters.put("integration.request.header.X-Context-Stage", "context.stage");
|
||||
|
||||
+14
@@ -9,6 +9,8 @@ import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
@@ -77,6 +79,18 @@ class ProxyEventIamIdentityTest {
|
||||
assertEquals("arn:aws:iam::000000000000:user/alice", identity.get("userArn").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"bad_host", "[bad", "", "bad host"})
|
||||
void invalidHostFallsBackToExecuteApiDomainInRestProxyEvent(String host) throws Exception {
|
||||
when(headers.getHeaderString("Host")).thenReturn(host);
|
||||
JsonNode context = MAPPER.readTree(controller.buildProxyEvent(
|
||||
"us-east-1", "api1", "GET", "/iam", "/iam", "res1", "test", null,
|
||||
headers, uriInfo, null, "req-1", null, null, null, CALLER))
|
||||
.path("requestContext");
|
||||
assertEquals("api1.execute-api.us-east-1.amazonaws.com", context.path("domainName").asText());
|
||||
assertEquals("api1", context.path("domainPrefix").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restIdentityStaysExplicitlyNullWithoutIamAuthorization() throws Exception {
|
||||
JsonNode identity = MAPPER.readTree(controller.buildProxyEvent(
|
||||
|
||||
Reference in new issue
Block a user