mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(apigateway): populate full APIGatewayRequestAuthorizerEvent for REQUEST authorizers (#1002)
* fix: populate full APIGatewayRequestAuthorizerEvent for REQUEST authorizers Closes #807. Previously, REQUEST-type Lambda authorizers received only 'type' and 'methodArn'. This commit populates the complete event shape matching real AWS behavior: - headers, multiValueHeaders - queryStringParameters, multiValueQueryStringParameters - pathParameters (empty object when none, not null) - stageVariables (from Stage config, null when unconfigured) - requestContext with accountId, apiId, resourceId, resourcePath, path, httpMethod, stage, requestId, requestTimeEpoch - requestContext.identity with sourceIp, userAgent, apiKey, clientCert Also enriches the AWS_PROXY integration event (buildProxyEvent) with: - Full identity object (all null fields matching AWS wire format) - domainName, domainPrefix, protocol, requestTime, extendedRequestId - stageVariables from Stage configuration - API key resolution from usage plan keys Refactors shared logic into reusable helpers: - putSingleValueHeaders, putMultiValueHeaders - putQueryStringParameters, putMultiValueQueryStringParameters Resolves API key once per request (not duplicated across authorizer and proxy event builders). * fix: remove AWS SDK deps from main pom, rewrite test with RestAssured Addresses review feedback: AWS SDK dependencies should not be in the main Floci project. Rewrites ApiGatewayRequestAuthorizerIntegrationTest to use only RestAssured for management-plane and execute-api calls, matching the established pattern of all other @QuarkusTest tests. --------- Co-authored-by: Dixit R Jain <dixitrjain@Dixits-MacBook-Pro.local> Co-authored-by: Dixit R Jain <dixitrjain@Mac.lan>
This commit is contained in:
4 files changed
+1910
-36
No files matched your search
+206
-36
@@ -8,6 +8,9 @@ import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Integration;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Stage;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
@@ -22,6 +25,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.smallrye.common.annotation.Blocking;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -237,9 +241,10 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
// Verify API and stage exist
|
||||
Stage stage;
|
||||
try {
|
||||
apiGatewayService.getRestApi(region, apiId);
|
||||
apiGatewayService.getStage(region, apiId, stageName);
|
||||
stage = apiGatewayService.getStage(region, apiId, stageName);
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.entity(jsonMessage(e.getMessage()))
|
||||
@@ -268,7 +273,8 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
// 1. Authorizer
|
||||
AuthorizerResult authorizerResult = invokeAuthorizer(region, apiId, stageName, httpMethod, path, method, headers, uriInfo);
|
||||
String resolvedApiKey = resolveApiKeyForRequest(region, apiId, stageName, headers);
|
||||
AuthorizerResult authorizerResult = invokeAuthorizer(region, apiId, stageName, httpMethod, path, matched.getPath(), matched.getId(), stage, method, headers, uriInfo, resolvedApiKey);
|
||||
if (authorizerResult.errorResponse() != null) return authorizerResult.errorResponse();
|
||||
|
||||
// 2. Request validation
|
||||
@@ -286,8 +292,8 @@ public class ApiGatewayExecuteController {
|
||||
integration.getType());
|
||||
|
||||
return switch (integration.getType().toUpperCase()) {
|
||||
case "AWS_PROXY" -> invokeProxy(region, httpMethod, path, proxy, stageName,
|
||||
matched, integration, headers, uriInfo, body, authorizerResult);
|
||||
case "AWS_PROXY" -> invokeProxy(region, apiId, httpMethod, path, proxy, stageName,
|
||||
matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey);
|
||||
case "AWS" -> invokeAwsIntegration(region, httpMethod, path, proxy, stageName,
|
||||
matched, integration, headers, uriInfo, body);
|
||||
case "MOCK" -> invokeMock(region, httpMethod, path, stageName, matched, integration, headers, uriInfo, body);
|
||||
@@ -299,11 +305,12 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
// ──────────────────────────── AWS_PROXY ────────────────────────────
|
||||
|
||||
private Response invokeProxy(String region, String httpMethod, String path, String proxy,
|
||||
private Response invokeProxy(String region, String apiId, String httpMethod, String path, String proxy,
|
||||
String stageName, ApiGatewayResource resource,
|
||||
Stage stage,
|
||||
Integration integration, HttpHeaders headers,
|
||||
UriInfo uriInfo, byte[] body,
|
||||
AuthorizerResult authorizerResult) {
|
||||
AuthorizerResult authorizerResult, String resolvedApiKey) {
|
||||
String functionName = functionNameFromUri(integration.getUri());
|
||||
if (functionName == null) {
|
||||
return Response.status(500)
|
||||
@@ -312,9 +319,9 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String eventJson = buildProxyEvent(httpMethod, path, proxy, resource.getPath(),
|
||||
stageName, headers, uriInfo, body, requestId,
|
||||
authorizerResult.principalId(), authorizerResult.context());
|
||||
String eventJson = buildProxyEvent(region, apiId, httpMethod, path, proxy, resource.getPath(),
|
||||
resource.getId(), stageName, stage, headers, uriInfo, body, requestId,
|
||||
authorizerResult.principalId(), authorizerResult.context(), resolvedApiKey);
|
||||
|
||||
try {
|
||||
InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(),
|
||||
@@ -331,8 +338,11 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
private AuthorizerResult invokeAuthorizer(String region, String apiId, String stageName,
|
||||
String httpMethod, String requestPath, MethodConfig method,
|
||||
HttpHeaders headers, UriInfo uriInfo) {
|
||||
String httpMethod, String requestPath, String resourcePath,
|
||||
String resourceId,
|
||||
Stage stage,
|
||||
MethodConfig method,
|
||||
HttpHeaders headers, UriInfo uriInfo, String resolvedApiKey) {
|
||||
if ("CUSTOM".equals(method.getAuthorizationType())) {
|
||||
String authorizerId = method.getAuthorizerId();
|
||||
if (authorizerId == null) {
|
||||
@@ -345,7 +355,7 @@ public class ApiGatewayExecuteController {
|
||||
return new AuthorizerResult(null, null, null);
|
||||
}
|
||||
|
||||
String event = toAuthorizerEvent(auth, headers, region, apiId, stageName, httpMethod, requestPath);
|
||||
String event = toAuthorizerEvent(auth, headers, region, apiId, stageName, httpMethod, requestPath, resourcePath, resourceId, stage, uriInfo, resolvedApiKey);
|
||||
try {
|
||||
InvokeResult result = lambdaService.invoke(region, lambdaName, event.getBytes(), InvocationType.RequestResponse);
|
||||
if (result.getFunctionError() != null) {
|
||||
@@ -471,17 +481,91 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth,
|
||||
HttpHeaders headers, String region, String apiId, String stageName,
|
||||
String httpMethod, String requestPath) {
|
||||
String httpMethod, String requestPath,
|
||||
String resourcePath, String resourceId, Stage stage, UriInfo uriInfo,
|
||||
String resolvedApiKey) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("type", auth.getType());
|
||||
node.put("methodArn", buildMethodArn(region, apiId, stageName, httpMethod, requestPath));
|
||||
if ("TOKEN".equals(auth.getType())) {
|
||||
String headerName = auth.getIdentitySource().replace("method.request.header.", "");
|
||||
node.put("authorizationToken", headers.getHeaderString(headerName));
|
||||
} else if ("REQUEST".equals(auth.getType())) {
|
||||
node.put("resource", resourcePath);
|
||||
node.put("path", requestPath);
|
||||
node.put("httpMethod", httpMethod);
|
||||
putSingleValueHeaders(node, headers);
|
||||
putMultiValueHeaders(node, headers);
|
||||
putQueryStringParameters(node, uriInfo);
|
||||
putMultiValueQueryStringParameters(node, uriInfo);
|
||||
|
||||
Map<String, String> pathParams = extractPathParams(resourcePath, requestPath);
|
||||
ObjectNode ppNode = node.putObject("pathParameters");
|
||||
if (!pathParams.isEmpty()) {
|
||||
pathParams.forEach(ppNode::put);
|
||||
}
|
||||
|
||||
// stageVariables: populate from the Stage object (null if no variables configured)
|
||||
Map<String, String> stageVars = stage != null ? stage.getVariables() : null;
|
||||
if (stageVars != null && !stageVars.isEmpty()) {
|
||||
ObjectNode svNode = node.putObject("stageVariables");
|
||||
stageVars.forEach(svNode::put);
|
||||
} else {
|
||||
node.putNull("stageVariables");
|
||||
}
|
||||
|
||||
ObjectNode ctx = node.putObject("requestContext");
|
||||
ctx.put("accountId", regionResolver.getAccountId());
|
||||
ctx.put("apiId", apiId);
|
||||
ctx.put("resourceId", resourceId != null ? resourceId : "");
|
||||
ctx.put("resourcePath", resourcePath);
|
||||
ctx.put("path", requestPath);
|
||||
ctx.put("httpMethod", httpMethod);
|
||||
ctx.put("stage", stageName);
|
||||
ctx.put("requestId", UUID.randomUUID().toString());
|
||||
ctx.put("requestTimeEpoch", System.currentTimeMillis());
|
||||
|
||||
// identity.apiKey: resolve from usage plans linked to this (apiId, stage)
|
||||
ObjectNode identity = ctx.putObject("identity");
|
||||
identity.put("sourceIp", "127.0.0.1");
|
||||
String userAgent = headers.getHeaderString("User-Agent");
|
||||
identity.put("userAgent", userAgent != null ? userAgent : "");
|
||||
if (resolvedApiKey != null) {
|
||||
identity.put("apiKey", resolvedApiKey);
|
||||
} else {
|
||||
identity.putNull("apiKey");
|
||||
}
|
||||
identity.putNull("clientCert"); // null when mTLS is not configured (Floci does not support mTLS)
|
||||
}
|
||||
return node.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the API key value for a request by matching the {@code x-api-key} header
|
||||
* against usage plan keys linked to this (apiId, stageName) pair.
|
||||
*
|
||||
* <p>Returns the key value string if a matching enabled key is found, {@code null} otherwise.
|
||||
*/
|
||||
private String resolveApiKeyForRequest(String region, String apiId, String stageName, HttpHeaders headers) {
|
||||
String keyHeader = headers.getHeaderString("x-api-key");
|
||||
if (keyHeader == null || keyHeader.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
// Find all usage plans that include this (apiId, stage) pair
|
||||
for (UsagePlan plan : apiGatewayService.getUsagePlans(region)) {
|
||||
boolean planCoversStage = plan.getApiStages().stream()
|
||||
.anyMatch(s -> apiId.equals(s.apiId()) && stageName.equals(s.stage()));
|
||||
if (!planCoversStage) continue;
|
||||
// Check if any key in this plan matches the header value
|
||||
for (UsagePlanKey planKey : apiGatewayService.getUsagePlanKeys(region, plan.getId())) {
|
||||
if (keyHeader.equals(planKey.getValue())) {
|
||||
return planKey.getValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String buildMethodArn(String region, String apiId, String stageName, String httpMethod, String requestPath) {
|
||||
String normalizedPath = requestPath == null ? "" : requestPath.replaceFirst("^/", "");
|
||||
String arnRegion = region == null ? regionResolver.getDefaultRegion() : region;
|
||||
@@ -497,45 +581,91 @@ public class ApiGatewayExecuteController {
|
||||
return LambdaArnUtils.extractFunctionNameFromUri(uri);
|
||||
}
|
||||
|
||||
private String buildProxyEvent(String httpMethod, String path, String proxy,
|
||||
String resourcePath, String stageName,
|
||||
private String buildProxyEvent(String region, String apiId,
|
||||
String httpMethod, String path, String proxy,
|
||||
String resourcePath, String resourceId,
|
||||
String stageName, Stage stage,
|
||||
HttpHeaders headers, UriInfo uriInfo,
|
||||
byte[] body, String requestId,
|
||||
String principalId, Map<String, Object> authorizerContext) {
|
||||
String principalId, Map<String, Object> authorizerContext,
|
||||
String resolvedApiKey) {
|
||||
ObjectNode event = objectMapper.createObjectNode();
|
||||
event.put("resource", resourcePath);
|
||||
event.put("path", path);
|
||||
event.put("httpMethod", httpMethod);
|
||||
|
||||
ObjectNode headersNode = event.putObject("headers");
|
||||
MultivaluedMap<String, String> reqHeaders = headers.getRequestHeaders();
|
||||
for (Map.Entry<String, java.util.List<String>> e : reqHeaders.entrySet()) {
|
||||
if (!e.getValue().isEmpty()) headersNode.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
|
||||
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
|
||||
if (!queryParams.isEmpty()) {
|
||||
ObjectNode qsp = event.putObject("queryStringParameters");
|
||||
for (Map.Entry<String, java.util.List<String>> e : queryParams.entrySet()) {
|
||||
if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
} else {
|
||||
event.putNull("queryStringParameters");
|
||||
}
|
||||
putSingleValueHeaders(event, headers);
|
||||
putMultiValueHeaders(event, headers);
|
||||
putQueryStringParameters(event, uriInfo);
|
||||
putMultiValueQueryStringParameters(event, uriInfo);
|
||||
|
||||
ObjectNode pathParams = event.putObject("pathParameters");
|
||||
if (proxy != null && !proxy.isEmpty()) pathParams.put("proxy", proxy);
|
||||
extractPathParams(resourcePath, path).forEach(pathParams::put);
|
||||
|
||||
event.putNull("stageVariables");
|
||||
// stageVariables: populate from the Stage object (null if no variables configured)
|
||||
Map<String, String> stageVars = stage != null ? stage.getVariables() : null;
|
||||
if (stageVars != null && !stageVars.isEmpty()) {
|
||||
ObjectNode svNode = event.putObject("stageVariables");
|
||||
stageVars.forEach(svNode::put);
|
||||
} else {
|
||||
event.putNull("stageVariables");
|
||||
}
|
||||
|
||||
String arnRegion = region != null ? region : regionResolver.getDefaultRegion();
|
||||
String domainName = apiId + ".execute-api." + arnRegion + ".amazonaws.com";
|
||||
long nowMillis = System.currentTimeMillis();
|
||||
String requestTime = java.time.format.DateTimeFormatter
|
||||
.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
|
||||
.format(java.time.ZonedDateTime.now(java.time.ZoneOffset.UTC));
|
||||
|
||||
ObjectNode ctx = event.putObject("requestContext");
|
||||
ctx.put("resourcePath", resourcePath);
|
||||
ctx.put("accountId", regionResolver.getAccountId());
|
||||
ctx.put("apiId", apiId);
|
||||
ctx.put("domainName", domainName);
|
||||
ctx.put("domainPrefix", apiId);
|
||||
ctx.put("extendedRequestId", requestId);
|
||||
ctx.put("httpMethod", httpMethod);
|
||||
ctx.put("stage", stageName);
|
||||
ctx.put("path", path);
|
||||
ctx.put("protocol", "HTTP/1.1");
|
||||
ctx.put("requestId", requestId);
|
||||
ctx.put("requestTimeEpoch", System.currentTimeMillis());
|
||||
ctx.putObject("identity").put("sourceIp", "127.0.0.1");
|
||||
ctx.put("requestTime", requestTime);
|
||||
ctx.put("requestTimeEpoch", nowMillis);
|
||||
ctx.put("resourceId", resourceId != null ? resourceId : "");
|
||||
ctx.put("resourcePath", resourcePath);
|
||||
ctx.put("stage", stageName);
|
||||
|
||||
// identity — full shape matching AWS proxy event spec.
|
||||
// Fields that require auth mechanisms not implemented in v1 REST API dispatch:
|
||||
// - accessKey, accountId, caller, user, userArn, principalOrgId: only set for AWS_IAM auth
|
||||
// (v1 dispatch does not implement AWS_IAM — invokeAuthorizer only handles CUSTOM)
|
||||
// - cognitoIdentityId, cognitoIdentityPoolId, cognitoAuthenticationType,
|
||||
// cognitoAuthenticationProvider: only set for COGNITO_USER_POOLS auth (not implemented in v1)
|
||||
// - clientCert: only set when mutual TLS is configured (not supported in Floci)
|
||||
// AWS sends these as explicit JSON null (not absent), so we match that wire format.
|
||||
ObjectNode identity = ctx.putObject("identity");
|
||||
identity.putNull("accessKey");
|
||||
identity.putNull("accountId");
|
||||
identity.putNull("caller");
|
||||
identity.putNull("cognitoAuthenticationProvider");
|
||||
identity.putNull("cognitoAuthenticationType");
|
||||
identity.putNull("cognitoIdentityId");
|
||||
identity.putNull("cognitoIdentityPoolId");
|
||||
identity.putNull("principalOrgId");
|
||||
identity.put("sourceIp", "127.0.0.1");
|
||||
identity.putNull("user");
|
||||
String userAgent = headers.getHeaderString("User-Agent");
|
||||
identity.put("userAgent", userAgent != null ? userAgent : "");
|
||||
identity.putNull("userArn");
|
||||
identity.putNull("clientCert"); // null when mTLS is not configured (Floci does not support mTLS)
|
||||
// apiKey: use pre-resolved value from usage plan keys linked to this (apiId, stage)
|
||||
if (resolvedApiKey != null) {
|
||||
identity.put("apiKey", resolvedApiKey);
|
||||
} else {
|
||||
identity.putNull("apiKey");
|
||||
}
|
||||
|
||||
// authorizer context (set by CUSTOM authorizer)
|
||||
if (principalId != null || (authorizerContext != null && !authorizerContext.isEmpty())) {
|
||||
ObjectNode authorizerNode = ctx.putObject("authorizer");
|
||||
if (principalId != null) {
|
||||
@@ -565,6 +695,46 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
}
|
||||
|
||||
private void putSingleValueHeaders(ObjectNode event, HttpHeaders headers) {
|
||||
ObjectNode headersNode = event.putObject("headers");
|
||||
headers.getRequestHeaders().forEach((name, values) -> {
|
||||
if (!values.isEmpty()) headersNode.put(name, values.get(0));
|
||||
});
|
||||
}
|
||||
|
||||
private void putMultiValueHeaders(ObjectNode event, HttpHeaders headers) {
|
||||
ObjectNode mvHeaders = event.putObject("multiValueHeaders");
|
||||
headers.getRequestHeaders().forEach((name, values) -> {
|
||||
ArrayNode arr = mvHeaders.putArray(name);
|
||||
values.forEach(arr::add);
|
||||
});
|
||||
}
|
||||
|
||||
private void putQueryStringParameters(ObjectNode event, UriInfo uriInfo) {
|
||||
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
|
||||
if (!queryParams.isEmpty()) {
|
||||
ObjectNode qsp = event.putObject("queryStringParameters");
|
||||
queryParams.forEach((name, values) -> {
|
||||
if (!values.isEmpty()) qsp.put(name, values.get(0));
|
||||
});
|
||||
} else {
|
||||
event.putNull("queryStringParameters");
|
||||
}
|
||||
}
|
||||
|
||||
private void putMultiValueQueryStringParameters(ObjectNode event, UriInfo uriInfo) {
|
||||
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
|
||||
if (!queryParams.isEmpty()) {
|
||||
ObjectNode mqsp = event.putObject("multiValueQueryStringParameters");
|
||||
queryParams.forEach((name, values) -> {
|
||||
ArrayNode arr = mqsp.putArray(name);
|
||||
values.forEach(arr::add);
|
||||
});
|
||||
} else {
|
||||
event.putNull("multiValueQueryStringParameters");
|
||||
}
|
||||
}
|
||||
|
||||
private Response buildProxyResponse(InvokeResult result) {
|
||||
if (result.getPayload() == null || result.getPayload().length == 0) {
|
||||
return Response.status(result.getFunctionError() != null ? 502 : result.getStatusCode()).build();
|
||||
|
||||
Reference in new issue
Block a user