diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 216eefb13e..6d6aba5515 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -173,6 +173,12 @@ A verified caller reaches the integration as `requestContext.identity.{accessKey user, userArn}` on a REST proxy event, and as `requestContext.authorizer.iam` on an HTTP API 2.0 event. +As on AWS, a REST (v1) `AWS_PROXY` or `HTTP_PROXY` integration never receives the caller's +`Authorization` header when the method is `AWS_IAM`, and on any method the header is dropped if it +carries a SigV4 signature. `X-Amz-Date`, `X-Amz-Security-Token` and every other header still pass +through, and a `Bearer` token on a method without `AWS_IAM` reaches the integration unchanged. +HTTP API (v2) integrations receive `Authorization` as the caller sent it. + Sign with any access key the emulator has issued (`CreateAccessKey`, or the temporary credentials from `AssumeRole`), or with the well-known local-dev `test`/`test` pair that Floci accepts across S3, RDS, and ElastiCache. No other unregistered key is accepted: an unknown key cannot sign for diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java index 5e6c4bc908..be91f37771 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsErrorResponse; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.common.auth.SigV4AuthorizationHeader; import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource; import io.github.hectorvent.floci.services.apigateway.model.ApiKey; import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse; @@ -458,7 +459,7 @@ public class ApiGatewayExecuteController { case "AWS" -> invokeAwsIntegration(scope, region, httpMethod, path, stageName, matched, integration, headers, uriInfo, body, authorizerResult); case "HTTP_PROXY" -> invokeHttpProxy(scope, apiId, httpMethod, path, proxy, stageName, - matched, integration, headers, uriInfo, body); + matched, integration, headers, uriInfo, body, iamIdentity); case "HTTP" -> invokeHttpIntegration(scope, region, apiId, httpMethod, path, proxy, stageName, matched, integration, headers, uriInfo, body, authorizerResult); case "MOCK" -> invokeMock(scope, region, httpMethod, path, stageName, @@ -534,7 +535,8 @@ public class ApiGatewayExecuteController { private Response invokeHttpProxy(GatewayResponseScope scope, String apiId, String httpMethod, String path, String proxy, String stageName, ApiGatewayResource resource, Integration integration, HttpHeaders headers, - UriInfo uriInfo, byte[] body) { + UriInfo uriInfo, byte[] body, + ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) { String uri = integration.getUri(); if (uri == null || uri.isBlank()) { return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500, @@ -545,11 +547,10 @@ public class ApiGatewayExecuteController { // proxy integration passes the request through, so "?tag=a&tag=b" has to arrive as two // tag parameters and not as "tag=a,b". The joined single-value maps are only the lookup // surface for method.request.* parameter mapping, which resolves to one value in AWS too. - Map> multiValueHeaders = new LinkedHashMap<>(); + Map> multiValueHeaders = integrationRequestHeaders(headers, iamIdentity); Map headerMap = new LinkedHashMap<>(); for (Map.Entry> e : headers.getRequestHeaders().entrySet()) { if (e.getValue().isEmpty()) continue; - multiValueHeaders.put(e.getKey(), List.copyOf(e.getValue())); headerMap.put(e.getKey(), String.join(",", e.getValue())); } Map> multiValueQuery = new LinkedHashMap<>(); @@ -1137,8 +1138,8 @@ public class ApiGatewayExecuteController { node.put("resource", resourcePath); node.put("path", preservedPath); node.put("httpMethod", httpMethod); - putSingleValueHeaders(node, headers); - putMultiValueHeaders(node, headers); + putSingleValueHeaders(node, headers.getRequestHeaders()); + putMultiValueHeaders(node, headers.getRequestHeaders()); putQueryStringParameters(node, uriInfo); putMultiValueQueryStringParameters(node, uriInfo); @@ -1262,8 +1263,9 @@ public class ApiGatewayExecuteController { event.put("path", requestPath); event.put("httpMethod", httpMethod); - putSingleValueHeaders(event, headers); - putMultiValueHeaders(event, headers); + Map> integrationHeaders = integrationRequestHeaders(headers, iamIdentity); + putSingleValueHeaders(event, integrationHeaders); + putMultiValueHeaders(event, integrationHeaders); putQueryStringParameters(event, uriInfo); putMultiValueQueryStringParameters(event, uriInfo); @@ -1376,10 +1378,42 @@ public class ApiGatewayExecuteController { } } + /** + * The inbound headers a REST integration receives. AWS drops {@code Authorization} on the way + * to a Lambda or HTTP integration when the method is AWS_IAM ({@code iamIdentity} is non-null + * only then) or the header carries a SigV4 signature, so a function behind a signed call never + * sees the caller's signature. Every other header, {@code X-Amz-Date} and + * {@code X-Amz-Security-Token} included, passes through. + */ + static Map> integrationRequestHeaders(HttpHeaders headers, + ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) { + Map> forwarded = new LinkedHashMap<>(); + for (Map.Entry> e : headers.getRequestHeaders().entrySet()) { + if (e.getValue().isEmpty()) { + continue; + } + if (HttpHeaders.AUTHORIZATION.equalsIgnoreCase(e.getKey()) + && (iamIdentity != null || isSigV4Authorization(e.getValue()))) { + continue; + } + forwarded.put(e.getKey(), e.getValue()); + } + return forwarded; + } + + private static boolean isSigV4Authorization(List values) { + for (String value : values) { + if (SigV4AuthorizationHeader.parse(value) != null) { + return true; + } + } + return false; + } + // Package-private for unit testing (see ApiGatewayExecuteControllerTest). - void putSingleValueHeaders(ObjectNode event, HttpHeaders headers) { + void putSingleValueHeaders(ObjectNode event, Map> headers) { ObjectNode headersNode = event.putObject("headers"); - headers.getRequestHeaders().forEach((name, values) -> { + headers.forEach((name, values) -> { // AWS collapses duplicate request headers to the LAST value in the single-value `headers` // map (multiValueHeaders keeps every value). Taking the first value diverged from AWS. if (!values.isEmpty()) { @@ -1388,9 +1422,9 @@ public class ApiGatewayExecuteController { }); } - void putMultiValueHeaders(ObjectNode event, HttpHeaders headers) { + void putMultiValueHeaders(ObjectNode event, Map> headers) { ObjectNode mvHeaders = event.putObject("multiValueHeaders"); - headers.getRequestHeaders().forEach((name, values) -> { + headers.forEach((name, values) -> { ArrayNode arr = mvHeaders.putArray(name); values.forEach(arr::add); }); @@ -2906,8 +2940,8 @@ public class ApiGatewayExecuteController { event.put("path", preservedPath); event.put("httpMethod", httpMethod); - putSingleValueHeaders(event, headers); - putMultiValueHeaders(event, headers); + putSingleValueHeaders(event, headers.getRequestHeaders()); + putMultiValueHeaders(event, headers.getRequestHeaders()); putQueryStringParameters(event, uriInfo); putMultiValueQueryStringParameters(event, uriInfo); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java index 1246229ce8..a71722f0e6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java @@ -123,14 +123,12 @@ class ApiGatewayExecuteControllerTest { requestHeaders.add("X-Dup", "first"); requestHeaders.add("X-Dup", "second"); requestHeaders.add("X-Dup", "third"); - HttpHeaders headers = mock(HttpHeaders.class); - when(headers.getRequestHeaders()).thenReturn(requestHeaders); ObjectMapper objectMapper = new ObjectMapper(); ObjectNode event = objectMapper.createObjectNode(); ApiGatewayExecuteController controller = controller(objectMapper); - controller.putSingleValueHeaders(event, headers); - controller.putMultiValueHeaders(event, headers); + controller.putSingleValueHeaders(event, requestHeaders); + controller.putMultiValueHeaders(event, requestHeaders); assertEquals("third", event.path("headers").path("X-Dup").asText()); assertEquals( diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyIntegrationTest.java index 695b101074..5512e16bb5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyIntegrationTest.java @@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.apigateway; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; import io.restassured.http.ContentType; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -13,6 +15,7 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -23,6 +26,7 @@ import java.util.concurrent.atomic.AtomicReference; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -49,6 +53,8 @@ class ApiGatewayHttpProxyIntegrationTest { private static final AtomicReference lastBody = new AtomicReference<>(); private static final AtomicReference lastForwardedHeader = new AtomicReference<>(); private static final AtomicReference lastAuthorization = new AtomicReference<>(); + private static final AtomicReference lastAmzDate = new AtomicReference<>(); + private static final AtomicReference lastCallerAuthorization = new AtomicReference<>(); private static final AtomicReference lastHost = new AtomicReference<>(); private static final AtomicReference> lastTraceHeaders = new AtomicReference<>(); @@ -78,6 +84,8 @@ class ApiGatewayHttpProxyIntegrationTest { lastBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); lastForwardedHeader.set(exchange.getRequestHeaders().getFirst("X-Forwarded-Tenant")); lastAuthorization.set(exchange.getRequestHeaders().getFirst("Authorization")); + lastAmzDate.set(exchange.getRequestHeaders().getFirst("X-Amz-Date")); + lastCallerAuthorization.set(exchange.getRequestHeaders().getFirst("X-Caller-Authorization")); lastHost.set(exchange.getRequestHeaders().getFirst("Host")); List trace = exchange.getRequestHeaders().get("X-Trace"); lastTraceHeaders.set(trace == null ? null : List.copyOf(trace)); @@ -105,6 +113,8 @@ class ApiGatewayHttpProxyIntegrationTest { lastBody.set(null); lastForwardedHeader.set(null); lastAuthorization.set(null); + lastAmzDate.set(null); + lastCallerAuthorization.set(null); lastHost.set(null); lastTraceHeaders.set(null); } @@ -114,6 +124,11 @@ class ApiGatewayHttpProxyIntegrationTest { * HTTP_PROXY integration pointing at {@code targetUri}, deployed to stage {@code test}. */ private String createProxyApi(String name, String targetUri, String requestParametersJson) { + return createProxyApi(name, targetUri, requestParametersJson, "NONE"); + } + + private String createProxyApi(String name, String targetUri, String requestParametersJson, + String authorizationType) { String apiId = given() .contentType(ContentType.JSON) .body("{\"name\":\"" + name + "\"}") @@ -132,7 +147,7 @@ class ApiGatewayHttpProxyIntegrationTest { .then().statusCode(201).extract().path("id"); given().contentType(ContentType.JSON) - .body("{\"authorizationType\":\"NONE\"}") + .body("{\"authorizationType\":\"" + authorizationType + "\"}") .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/ANY") .then().statusCode(201); @@ -317,6 +332,65 @@ class ApiGatewayHttpProxyIntegrationTest { assertEquals("Bearer caller-supplied-token", lastAuthorization.get()); } + @Test + void dropsAuthorizationHeaderOnAwsIamRoute() throws Exception { + resetRecordings(); + String apiId = createProxyApi("http-proxy-iam-auth-api", backendUri(), null, "AWS_IAM"); + String path = "/execute-api/" + apiId + "/test/orders"; + Map signed = ExecuteApiRequestSigner.signedHeaders( + "GET", path, Map.of(), "localhost:" + RestAssured.port, null, + "test", "test", "us-east-1", Instant.now()); + + // AWS drops Authorization on its way to the integration when the method is AWS_IAM; the + // rest of the signed request, X-Amz-Date included, still reaches the backend. + given().headers(signed) + .when().get(path) + .then().statusCode(200); + + assertEquals("/orders", lastPath.get()); + assertNull(lastAuthorization.get()); + assertEquals(signed.get("X-Amz-Date"), lastAmzDate.get()); + } + + @Test + void methodRequestAuthorizationStillResolvesInParameterMappingOnAwsIamRoute() throws Exception { + resetRecordings(); + String apiId = createProxyApi("http-proxy-iam-auth-mapping-api", backendUri(), + "{\"integration.request.header.X-Caller-Authorization\":\"method.request.header.Authorization\"}", + "AWS_IAM"); + String path = "/execute-api/" + apiId + "/test/orders"; + Map signed = ExecuteApiRequestSigner.signedHeaders( + "GET", path, Map.of(), "localhost:" + RestAssured.port, null, + "test", "test", "us-east-1", Instant.now()); + + // Only the header the integration receives is dropped: the method request still carries + // Authorization, so an explicit mapping from it resolves as it did before. + given().headers(signed) + .when().get(path) + .then().statusCode(200); + + assertEquals(signed.get("Authorization"), lastCallerAuthorization.get()); + assertNull(lastAuthorization.get()); + } + + @Test + void dropsSigV4AuthorizationHeaderOnNoneAuthRoute() { + resetRecordings(); + String apiId = createProxyApi("http-proxy-sigv4-none-api", backendUri(), null); + + // No signature is verified on a NONE route, but AWS still drops an Authorization header + // that carries one. + given() + .header("Authorization", "AWS4-HMAC-SHA256 " + + "Credential=test/20260928/us-east-1/execute-api/aws4_request, " + + "SignedHeaders=host;x-amz-date, Signature=abc123") + .when().get("/execute-api/" + apiId + "/test/orders") + .then().statusCode(200); + + assertEquals("/orders", lastPath.get()); + assertNull(lastAuthorization.get()); + } + @Test void doesNotForwardTheInboundHostHeaderToTheBackend() { resetRecordings(); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java index 3e256f74c0..e5b3ae1d52 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.RegionResolver; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.UriInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,6 +22,10 @@ import static org.mockito.Mockito.when; * REST renders it under {@code requestContext.identity}, HTTP APIs under * {@code requestContext.authorizer.iam}. Both were unreachable before AWS_IAM was enforced at * all: REST's identity fields were hardcoded to null with a comment saying so. + * + *

The caller's signature itself must not: AWS drops the {@code Authorization} header before a + * REST Lambda proxy integration when the method is AWS_IAM or the header carries a SigV4 signature + * ("Amazon API Gateway important notes for REST APIs", header table footnote). */ class ProxyEventIamIdentityTest { @@ -29,8 +34,12 @@ class ProxyEventIamIdentityTest { new ExecuteApiSigV4Authorizer.CallerIdentity( "AKIAIOSFODNN7EXAMPLE", "000000000000", "arn:aws:iam::000000000000:user/alice", "AIDAEXAMPLEUSERID"); + private static final String SIGV4 = "AWS4-HMAC-SHA256 " + + "Credential=AKIAIOSFODNN7EXAMPLE/20260928/us-east-1/execute-api/aws4_request, " + + "SignedHeaders=host;x-amz-date, Signature=abc123"; private ApiGatewayExecuteController controller; + private MultivaluedMap requestHeaders; private HttpHeaders headers; private UriInfo uriInfo; @@ -40,8 +49,9 @@ class ProxyEventIamIdentityTest { when(regionResolver.getAccountId()).thenReturn("000000000000"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); + requestHeaders = new MultivaluedHashMap<>(); headers = mock(HttpHeaders.class); - when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>()); + when(headers.getRequestHeaders()).thenReturn(requestHeaders); uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>()); @@ -107,4 +117,69 @@ class ProxyEventIamIdentityTest { assertTrue(requestContext.path("authorizer").isMissingNode(), "a route with no authorizer must not grow an authorizer node"); } + + @Test + void awsIamMethodDropsTheSignatureButKeepsTheOtherSigningHeaders() throws Exception { + requestHeaders.add("Authorization", SIGV4); + requestHeaders.add("X-Amz-Date", "20260928T120000Z"); + requestHeaders.add("X-Amz-Security-Token", "session-token"); + + JsonNode event = restEvent(CALLER); + + assertAuthorizationAbsent(event); + assertEquals("20260928T120000Z", event.path("headers").path("X-Amz-Date").asText()); + assertEquals("session-token", event.path("headers").path("X-Amz-Security-Token").asText()); + assertEquals("session-token", + event.path("multiValueHeaders").path("X-Amz-Security-Token").path(0).asText()); + } + + @Test + void awsIamMethodDropsAnAuthorizationHeaderThatIsNotSigV4() throws Exception { + // A presigned-URL caller is authenticated by the query string, so its Authorization header + // can be anything. AWS still drops it: the method is AWS_IAM. + requestHeaders.add("Authorization", "Bearer user-token"); + + assertAuthorizationAbsent(restEvent(CALLER)); + } + + @Test + void noneMethodDropsASigV4AuthorizationHeader() throws Exception { + requestHeaders.add("Authorization", SIGV4); + + assertAuthorizationAbsent(restEvent(null)); + } + + @Test + void noneMethodPassesABearerAuthorizationHeaderThrough() throws Exception { + requestHeaders.add("Authorization", "Bearer user-token"); + + JsonNode event = restEvent(null); + + assertEquals("Bearer user-token", event.path("headers").path("Authorization").asText()); + assertEquals("Bearer user-token", + event.path("multiValueHeaders").path("Authorization").path(0).asText()); + } + + @Test + void authorizationHeaderNameIsMatchedCaseInsensitively() throws Exception { + requestHeaders.add("authorization", SIGV4); + + JsonNode event = restEvent(null); + + assertTrue(event.path("headers").path("authorization").isMissingNode()); + assertTrue(event.path("multiValueHeaders").path("authorization").isMissingNode()); + } + + private JsonNode restEvent(ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) throws Exception { + return MAPPER.readTree(controller.buildProxyEvent( + "us-east-1", "api1", "GET", "/iam", "/iam", "res1", "test", null, + headers, uriInfo, null, "req-1", null, null, null, iamIdentity)); + } + + private static void assertAuthorizationAbsent(JsonNode event) { + assertTrue(event.path("headers").path("Authorization").isMissingNode(), + "headers must not carry Authorization"); + assertTrue(event.path("multiValueHeaders").path("Authorization").isMissingNode(), + "multiValueHeaders must not carry Authorization"); + } }