fix(apigateway): enforce AWS_IAM authorization on the execute-api data plane (#2895)

A method (REST) or route (HTTP API) with authorizationType AWS_IAM was
recorded but never enforced, so an unsigned request reached the integration as
if it were NONE. ExecuteApiSigV4Authorizer now verifies the caller's signature
over the request as it arrived, for both the Authorization header and the
presigned query string, and surfaces the verified caller on the proxy event:
requestContext.identity on REST, requestContext.authorizer.iam on HTTP API.
The signature must cover host, and expired or inactive credentials are
rejected.

Temporary credentials must also present the session token STS issued with
them, compared against the value the session store records since #2912.

Authentication only: execute-api:Invoke is not evaluated against IAM policies.

Closes #2810

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-03 22:23:44 -04:00
1 parent 69e8bf1ac3
commit 06349c8d88
22 files changed
+2005 -50

No files matched your search

@@ -35,7 +35,7 @@ class ApiGatewayExecuteControllerTest {
return new ApiGatewayExecuteController(
null, null, null,
regionResolver, objectMapper, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
}
@Test
@@ -251,7 +251,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
Response response = controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
@@ -281,7 +281,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
@@ -315,7 +315,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
controller.dispatch("GET", "restapi1", "prod", "hello", headers, null, null);
@@ -0,0 +1,193 @@
package io.github.hectorvent.floci.services.apigateway;
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.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
/**
* The REST (v1) half: a method with {@code authorizationType: AWS_IAM} was recorded and
* returned by {@code GetMethod}, but v1 dispatch only ever invoked a CUSTOM authorizer, so an
* unsigned request ran the integration as if the method were {@code NONE}.
*
* <p>A MOCK integration stands in for the backend: it needs no Lambda runtime, and a {@code 200}
* from it is proof the request got past authorization, which is all these assertions are about.
* Both the {@code /restapis/…/_user_request_/…} and {@code /execute-api/…} entry points are
* exercised, because they reach {@code dispatch} by different routes.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayIamAuthorizationTest {
private static final String REGION = "us-east-1";
private static final String ACCESS_KEY = "test";
private static final String SECRET_KEY = "test";
private static final String STAGE = "test";
private static String apiId;
private static String iamResourceId;
@Test
@Order(0)
void setup() {
apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"rest-iam-auth-test\"}")
.when().post("/restapis")
.then().statusCode(201)
.body("id", notNullValue())
.extract().path("id");
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200)
.extract().path("item[0].id");
iamResourceId = createMockMethod(rootId, "iam", "AWS_IAM");
createMockMethod(rootId, "open", "NONE");
String deploymentId = given().contentType(ContentType.JSON)
.body("{\"description\":\"v1\"}")
.when().post("/restapis/" + apiId + "/deployments")
.then().statusCode(201)
.extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"stageName\":\"" + STAGE + "\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages")
.then().statusCode(201);
}
private static String createMockMethod(String rootId, String pathPart, String authorizationType) {
String resourceId = given().contentType(ContentType.JSON)
.body("{\"pathPart\":\"" + pathPart + "\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201)
.extract().path("id");
String methodPath = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
given().contentType(ContentType.JSON)
.body("{\"authorizationType\":\"" + authorizationType + "\"}")
.when().put(methodPath)
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"responseParameters\":{}}")
.when().put(methodPath + "/responses/200")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
.when().put(methodPath + "/integration")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"\",\"responseTemplates\":"
+ "{\"application/json\":\"{\\\"reached\\\":\\\"integration\\\"}\"}}")
.when().put(methodPath + "/integration/responses/200")
.then().statusCode(201);
return resourceId;
}
@Test
@Order(1)
void methodStillReportsAwsIamAuthorization() {
given().when().get("/restapis/" + apiId + "/resources/" + iamResourceId + "/methods/GET")
.then().statusCode(200)
.body("authorizationType", equalTo("AWS_IAM"));
}
@Test
@Order(10)
void unsignedUserRequestIsRejectedWithMissingAuthenticationToken() {
given().when().get(userRequestPath("iam"))
.then().statusCode(403)
.header("x-amzn-ErrorType", "MissingAuthenticationTokenException")
.body("message", equalTo("Missing Authentication Token"));
}
@Test
@Order(11)
void unsignedExecuteApiRequestIsRejectedToo() {
given().when().get("/execute-api/" + apiId + "/" + STAGE + "/iam")
.then().statusCode(403)
.body("message", equalTo("Missing Authentication Token"));
}
@Test
@Order(12)
void validlySignedRequestReachesTheIntegration() throws Exception {
given().headers(signedHeaders(userRequestPath("iam"), Instant.now()))
.when().get(userRequestPath("iam"))
.then().statusCode(200)
.body("reached", equalTo("integration"));
}
@Test
@Order(13)
void signatureForAnotherPathIsRejected() throws Exception {
given().headers(signedHeaders(userRequestPath("open"), Instant.now()))
.when().get(userRequestPath("iam"))
.then().statusCode(403)
.header("x-amzn-ErrorType", "InvalidSignatureException");
}
@Test
@Order(14)
void staleSignatureIsRejectedAsExpired() throws Exception {
given().headers(signedHeaders(userRequestPath("iam"), Instant.now().minus(2, ChronoUnit.HOURS)))
.when().get(userRequestPath("iam"))
.then().statusCode(403)
.header("x-amzn-ErrorType", "InvalidSignatureException")
.body("message", equalTo("Signature expired"));
}
@Test
@Order(15)
void unregisteredAccessKeyIsRejectedAsAnInvalidToken() throws Exception {
Map<String, String> headers = ExecuteApiRequestSigner.signedHeaders(
"GET", userRequestPath("iam"), Map.of(), host(), null,
"AKIANOTREGISTERED", "AKIANOTREGISTERED", REGION, Instant.now());
given().headers(headers)
.when().get(userRequestPath("iam"))
.then().statusCode(403)
.header("x-amzn-ErrorType", "UnrecognizedClientException");
}
@Test
@Order(16)
void methodWithoutIamAuthorizationStillAcceptsUnsignedRequests() {
given().when().get(userRequestPath("open"))
.then().statusCode(200)
.body("reached", equalTo("integration"));
}
@Test
@Order(999)
void cleanup() {
if (apiId != null) {
given().when().delete("/restapis/" + apiId);
}
}
private static String userRequestPath(String pathPart) {
return "/restapis/" + apiId + "/" + STAGE + "/_user_request_/" + pathPart;
}
private static String host() {
return "localhost:" + RestAssured.port;
}
private static Map<String, String> signedHeaders(String path, Instant signedAt) throws Exception {
return ExecuteApiRequestSigner.signedHeaders(
"GET", path, Map.of(), host(), null, ACCESS_KEY, SECRET_KEY, REGION, signedAt);
}
}
@@ -36,7 +36,7 @@ class ApiGatewayProxyMatchTest {
ctrl = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, lambdaService,
new RegionResolver("us-east-1", "000000000000"),
new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null,
new ApiGatewayExecuteRouteContext(), null, null);
new ApiGatewayExecuteRouteContext(), null, null, null);
}
private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) {
@@ -47,7 +47,7 @@ class BuildV2AuthorizerEventTrailingSlashTest {
null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null
null, null
);
}
@@ -50,7 +50,7 @@ class BuildV2ProxyEventBodyEncodingTest {
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, objectMapper, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
);
}
@@ -46,7 +46,7 @@ class BuildV2ProxyEventJwtClaimsTest {
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
);
}
@@ -50,7 +50,7 @@ class BuildV2ProxyEventLambdaAuthorizerTest {
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
);
}
@@ -41,7 +41,7 @@ class BuildV2ProxyEventPathParametersTest {
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
);
}
@@ -46,7 +46,7 @@ class BuildV2ProxyEventTrailingSlashTest {
null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null
null, null
);
}
@@ -0,0 +1,379 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
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;
import java.net.URI;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit coverage for the cases the end-to-end AWS_IAM tests cannot reach through RestAssured: the
* presigned query-string form, a credential scoped to another service, a registered IAM user's
* identity, and the virtual-host path rewrite that would otherwise make every signature mismatch.
*/
class ExecuteApiSigV4AuthorizerTest {
private static final String HOST = "localhost:4566";
private static final String PATH = "/execute-api/api1/test/iam";
private static final String REGION = "us-east-1";
private static final String ISSUED_TOKEN = "issued-session-token";
private IamService iamService;
private ExecuteApiSigV4Authorizer authorizer;
@BeforeEach
void setUp() {
iamService = mock(IamService.class);
when(iamService.findSecretKey(anyString())).thenReturn(Optional.empty());
when(iamService.resolveAccountId(anyString())).thenReturn(Optional.empty());
when(iamService.resolveCallerArn(anyString())).thenReturn(Optional.empty());
when(iamService.findAccessKey(anyString())).thenReturn(Optional.empty());
when(iamService.findSessionToken(anyString())).thenReturn(Optional.empty());
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
authorizer = new ExecuteApiSigV4Authorizer(iamService, regionResolver);
}
@Test
void unsignedRequestIsReportedAsMissingRatherThanMismatched() {
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(Map.of()), uriInfo(PATH, null), null, null);
assertFalse(result.authorized());
assertEquals(ExecuteApiSigV4Authorizer.Failure.MISSING, result.failure());
}
@Test
void presignedRequestIsAccepted() throws Exception {
String query = ExecuteApiRequestSigner.presignedQueryString(
"GET", PATH, HOST, "test", "test", REGION, Instant.now(), 900);
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(Map.of()), uriInfo(PATH, query), null, null);
assertTrue(result.authorized(), String.valueOf(result.detail()));
assertEquals("test", result.identity().accessKey());
}
@Test
void expiredPresignedRequestIsRejected() throws Exception {
String query = ExecuteApiRequestSigner.presignedQueryString(
"GET", PATH, HOST, "test", "test", REGION,
Instant.now().minus(1, ChronoUnit.HOURS), 60);
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(Map.of()), uriInfo(PATH, query), null, null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.EXPIRED, result.failure());
}
@Test
void credentialScopedToAnotherServiceIsRejected() throws Exception {
// A signature the caller legitimately produced for S3 must not authorize execute-api.
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null, "test", "test", REGION, Instant.now());
String s3Scoped = signed.get("Authorization").replace("/execute-api/", "/s3/");
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(Map.of("X-Amz-Date", signed.get("X-Amz-Date"),
HttpHeaders.AUTHORIZATION, s3Scoped)),
uriInfo(PATH, null), null, null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.MALFORMED, result.failure());
}
@Test
void unregisteredAccessKeyCannotSignForItself() throws Exception {
// The self-signing bypass fixed in the ElastiCache and RDS validators: an access key that
// was never issued must not be usable as its own secret.
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null,
"AKIAUNKNOWN", "AKIAUNKNOWN", REGION, Instant.now());
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed), uriInfo(PATH, null), null, null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY, result.failure());
}
@Test
void signatureThatDoesNotCoverHostIsRejected() throws Exception {
// A virtual-host request carries its apiId only in the Host header, and the path it signs
// (/{stage}/{route}) is identical across every API here. A signature that leaves host out
// of SignedHeaders is therefore bound to no particular API and would replay across them.
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null, "test", "test", REGION, Instant.now(), false);
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed), uriInfo(PATH, null), null, null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.MALFORMED, result.failure());
}
@Test
void expiredSessionCredentialIsRejected() throws Exception {
// findSecretKey hands back an STS session's secret without consulting its expiration, so
// the liveness check has to come from resolveAccountId, which returns empty once the
// session has lapsed. Without it an expired AssumeRole credential still authenticates.
when(iamService.findSecretKey("ASIAEXPIRED")).thenReturn(Optional.of("session-secret"));
when(iamService.resolveAccountId("ASIAEXPIRED")).thenReturn(Optional.empty());
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null,
"ASIAEXPIRED", "session-secret", REGION, Instant.now());
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed), uriInfo(PATH, null), null, null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY, result.failure());
}
@Test
void liveSessionCredentialIsAccepted() throws Exception {
// The mirror of the case above: a session that has not lapsed still authenticates, so the
// liveness check does not lock out every temporary credential.
liveSession("ASIALIVE", ISSUED_TOKEN);
when(iamService.resolveCallerArn("ASIALIVE")).thenReturn(
Optional.of("arn:aws:sts::111122223333:assumed-role/app/floci-session"));
Map<String, String> signed = signedWithSessionToken("ASIALIVE", ISSUED_TOKEN);
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed), uriInfo(PATH, null), null, null);
assertTrue(result.authorized(), String.valueOf(result.detail()));
assertEquals("arn:aws:sts::111122223333:assumed-role/app/floci-session",
result.identity().userArn());
}
@Test
void temporaryCredentialWithoutASessionTokenIsRejected() throws Exception {
// The null issued token stands for a session stored before Floci recorded them: presence
// is required even where the value cannot be compared.
liveSession("ASIANOTOKEN", null);
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null,
"ASIANOTOKEN", "session-secret", REGION, Instant.now());
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed), uriInfo(PATH, null), null, null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY, result.failure());
}
@Test
void fabricatedSessionTokenIsRejected() throws Exception {
// Presence alone would let a caller holding the key and secret invent a token.
liveSession("ASIAFORGED", ISSUED_TOKEN);
Map<String, String> signed = signedWithSessionToken("ASIAFORGED", "forged-session-token");
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed), uriInfo(PATH, null), null, null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY, result.failure());
}
@Test
void presignedTemporaryCredentialIsCheckedAgainstItsIssuedSessionToken() throws Exception {
// A presigned URL carries the token as a query parameter rather than a header.
liveSession("ASIAPRESIGNED", ISSUED_TOKEN);
String signed = ExecuteApiRequestSigner.presignedQueryString(
"GET", PATH, HOST, "ASIAPRESIGNED", "session-secret", REGION,
Instant.now(), 900, ISSUED_TOKEN);
assertTrue(authorizer.authorize("GET", headers(Map.of()), uriInfo(PATH, signed), null, null)
.authorized());
String forged = ExecuteApiRequestSigner.presignedQueryString(
"GET", PATH, HOST, "ASIAPRESIGNED", "session-secret", REGION,
Instant.now(), 900, "forged-session-token");
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY,
authorizer.authorize("GET", headers(Map.of()), uriInfo(PATH, forged), null, null)
.failure());
}
private void liveSession(String accessKeyId, String issuedToken) {
when(iamService.findSecretKey(accessKeyId)).thenReturn(Optional.of("session-secret"));
when(iamService.resolveAccountId(accessKeyId)).thenReturn(Optional.of("111122223333"));
when(iamService.findSessionToken(accessKeyId)).thenReturn(Optional.ofNullable(issuedToken));
}
/**
* Signs a request with a temporary credential, presenting the session token the way an SDK
* does: as a header outside {@code SignedHeaders}. Nothing binds it to the signature, which is
* the point of comparing it against the issued value instead.
*/
private static Map<String, String> signedWithSessionToken(String accessKeyId, String sessionToken)
throws Exception {
Map<String, String> signed = new java.util.LinkedHashMap<>(ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null, accessKeyId, "session-secret", REGION, Instant.now()));
signed.put("X-Amz-Security-Token", sessionToken);
return signed;
}
@Test
void deactivatedLongTermKeyIsRejected() throws Exception {
// resolveAccountId filters on status Active, so a key deactivated through UpdateAccessKey
// stops authenticating even though its secret is still stored.
when(iamService.findSecretKey("AKIADEACTIVATED")).thenReturn(Optional.of("s3cr3t"));
when(iamService.resolveAccountId("AKIADEACTIVATED")).thenReturn(Optional.empty());
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null,
"AKIADEACTIVATED", "s3cr3t", REGION, Instant.now());
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY,
authorizer.authorize("GET", headers(signed), uriInfo(PATH, null), null, null)
.failure());
}
@Test
void registeredIamUserIsResolvedToItsArnAndUserId() throws Exception {
when(iamService.findSecretKey("AKIAREGISTERED")).thenReturn(Optional.of("s3cr3t"));
when(iamService.resolveAccountId("AKIAREGISTERED")).thenReturn(Optional.of("111122223333"));
when(iamService.resolveCallerArn("AKIAREGISTERED"))
.thenReturn(Optional.of("arn:aws:iam::111122223333:user/alice"));
when(iamService.findAccessKey("AKIAREGISTERED"))
.thenReturn(Optional.of(new AccessKey("AKIAREGISTERED", "s3cr3t", "alice")));
when(iamService.findUser("alice")).thenReturn(Optional.of(
new IamUser("AIDAALICE", "alice", "/", "arn:aws:iam::111122223333:user/alice")));
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null, "AKIAREGISTERED", "s3cr3t", REGION, Instant.now());
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed), uriInfo(PATH, null), null, null);
assertTrue(result.authorized(), String.valueOf(result.detail()));
assertEquals("111122223333", result.identity().accountId());
assertEquals("arn:aws:iam::111122223333:user/alice", result.identity().userArn());
assertEquals("AIDAALICE", result.identity().userId());
}
@Test
void bodyIsCoveredBySoATamperedPayloadIsRejected() throws Exception {
byte[] body = "{\"amount\":1}".getBytes();
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"POST", PATH, Map.of(), HOST, body, "test", "test", REGION, Instant.now());
assertTrue(authorizer.authorize("POST", headers(signed), uriInfo(PATH, null), body, null)
.authorized());
assertEquals(ExecuteApiSigV4Authorizer.Failure.MISMATCH,
authorizer.authorize("POST", headers(signed), uriInfo(PATH, null),
"{\"amount\":9999}".getBytes(), null).failure());
}
@Test
void declaredContentSha256CannotStandInForATamperedBody() throws Exception {
// The signature covers SHA-256(body). Re-presenting the ORIGINAL body's hash in an
// x-amz-content-sha256 header alongside a replaced body must not restore the match:
// the header is not in SignedHeaders, and a literal hash is never taken on trust.
byte[] signedBody = "{\"amount\":1}".getBytes();
Map<String, String> signed = new java.util.LinkedHashMap<>(ExecuteApiRequestSigner.signedHeaders(
"POST", PATH, Map.of(), HOST, signedBody, "test", "test", REGION, Instant.now()));
signed.put("x-amz-content-sha256", sha256Hex(signedBody));
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"POST", headers(signed), uriInfo(PATH, null), "{\"amount\":9999}".getBytes(), null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.MISMATCH, result.failure());
}
@Test
void queryStringIsCoveredBySoAnAddedParameterIsRejected() throws Exception {
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of("limit", "10"), HOST, null, "test", "test", REGION, Instant.now());
assertTrue(authorizer.authorize("GET", headers(signed), uriInfo(PATH, "limit=10"), null, null)
.authorized());
assertEquals(ExecuteApiSigV4Authorizer.Failure.MISMATCH,
authorizer.authorize("GET", headers(signed), uriInfo(PATH, "limit=10&admin=true"),
null, null).failure());
}
@Test
void virtualHostRequestIsVerifiedAgainstThePathTheClientSigned() throws Exception {
// ApiGatewayExecuteApiHostFilter rewrites api1.execute-api.localhost/test/iam to
// /execute-api/api1/test/iam before dispatch sees it. Verifying against the rewritten path
// would reject every correctly signed virtual-host request.
String clientPath = "/test/iam";
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", clientPath, Map.of(), "api1.execute-api.localhost:4566", null,
"test", "test", REGION, Instant.now());
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed, "api1.execute-api.localhost:4566"),
uriInfo(PATH, null), null, clientPath);
assertTrue(result.authorized(), String.valueOf(result.detail()));
}
private static String sha256Hex(byte[] input) throws Exception {
byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(input);
StringBuilder hex = new StringBuilder(digest.length * 2);
for (byte b : digest) {
hex.append(String.format("%02x", b));
}
return hex.toString();
}
private static HttpHeaders headers(Map<String, String> values) {
return headers(values, HOST);
}
private static HttpHeaders headers(Map<String, String> values, String host) {
HttpHeaders headers = mock(HttpHeaders.class);
when(headers.getHeaderString(anyString())).thenAnswer(invocation -> {
String name = invocation.getArgument(0);
if ("Host".equalsIgnoreCase(name)) {
return host;
}
return values.entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(name))
.map(Map.Entry::getValue)
.findFirst().orElse(null);
});
return headers;
}
private static UriInfo uriInfo(String rawPath, String rawQuery) {
UriInfo uriInfo = mock(UriInfo.class);
URI requestUri = URI.create("http://" + HOST + rawPath + (rawQuery == null ? "" : "?" + rawQuery));
when(uriInfo.getRequestUri()).thenReturn(requestUri);
MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>();
if (rawQuery != null) {
for (String pair : rawQuery.split("&")) {
int equals = pair.indexOf('=');
queryParameters.add(equals >= 0 ? pair.substring(0, equals) : pair,
equals >= 0 ? java.net.URLDecoder.decode(pair.substring(equals + 1),
java.nio.charset.StandardCharsets.UTF_8) : "");
}
}
when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
return uriInfo;
}
}
@@ -29,7 +29,7 @@ class JwtClaimsWireFormatTest {
null, null, null,
null, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null
null, null
);
}
@@ -0,0 +1,110 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
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.UriInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The verified SigV4 caller behind an AWS_IAM route has to reach the integration, not just gate it:
* 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.
*/
class ProxyEventIamIdentityTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final ExecuteApiSigV4Authorizer.CallerIdentity CALLER =
new ExecuteApiSigV4Authorizer.CallerIdentity(
"AKIAIOSFODNN7EXAMPLE", "000000000000",
"arn:aws:iam::000000000000:user/alice", "AIDAEXAMPLEUSERID");
private ApiGatewayExecuteController controller;
private HttpHeaders headers;
private UriInfo uriInfo;
@BeforeEach
void setUp() throws Exception {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
headers = mock(HttpHeaders.class);
when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/execute-api/api1/test/iam"));
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
}
@Test
void restIdentityCarriesTheVerifiedIamCaller() throws Exception {
JsonNode identity = MAPPER.readTree(controller.buildProxyEvent(
"us-east-1", "api1", "GET", "/iam", "iam", "/iam", "res1", "test", null,
headers, uriInfo, null, "req-1", null, null, null, CALLER))
.path("requestContext").path("identity");
assertEquals("AKIAIOSFODNN7EXAMPLE", identity.get("accessKey").asText());
assertEquals("000000000000", identity.get("accountId").asText());
assertEquals("AIDAEXAMPLEUSERID", identity.get("caller").asText());
assertEquals("AIDAEXAMPLEUSERID", identity.get("user").asText());
assertEquals("arn:aws:iam::000000000000:user/alice", identity.get("userArn").asText());
}
@Test
void restIdentityStaysExplicitlyNullWithoutIamAuthorization() throws Exception {
JsonNode identity = MAPPER.readTree(controller.buildProxyEvent(
"us-east-1", "api1", "GET", "/open", "open", "/open", "res2", "test", null,
headers, uriInfo, null, "req-2", null, null, null, null))
.path("requestContext").path("identity");
// AWS sends these as explicit JSON null rather than omitting them.
for (String field : new String[]{"accessKey", "accountId", "caller", "user", "userArn"}) {
assertTrue(identity.has(field) && identity.get(field).isNull(),
field + " must be present and null on a non-IAM method");
}
}
@Test
void httpApiRendersTheVerifiedCallerUnderAuthorizerIam() throws Exception {
JsonNode iam = MAPPER.readTree(controller.buildV2ProxyEvent(
"GET", "/iam", "GET /iam", "api1", "us-east-1", "test",
headers, uriInfo, null, "req-3", null, null, null, CALLER))
.path("requestContext").path("authorizer").path("iam");
assertEquals("AKIAIOSFODNN7EXAMPLE", iam.get("accessKey").asText());
assertEquals("000000000000", iam.get("accountId").asText());
assertEquals("AIDAEXAMPLEUSERID", iam.get("callerId").asText());
assertEquals("AIDAEXAMPLEUSERID", iam.get("userId").asText());
assertEquals("arn:aws:iam::000000000000:user/alice", iam.get("userArn").asText());
assertTrue(iam.get("cognitoIdentity").isNull());
assertTrue(iam.get("principalOrgId").isNull());
}
@Test
void httpApiOmitsTheAuthorizerNodeWithoutIamAuthorization() throws Exception {
JsonNode requestContext = MAPPER.readTree(controller.buildV2ProxyEvent(
"GET", "/open", "GET /open", "api1", "us-east-1", "test",
headers, uriInfo, null, "req-4", null, null, null, null))
.path("requestContext");
assertTrue(requestContext.path("authorizer").isMissingNode(),
"a route with no authorizer must not grow an authorizer node");
}
}
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -575,9 +576,10 @@ class ApiGatewayV2OpenApiImportTest {
@Test
@Order(17)
void sigv4ImportsAsAwsIamAndSaysItIsNotEnforced() throws Exception {
// The route records AWS_IAM because that is what AWS records, but this emulator's HTTP API
// dispatch only enforces JWT and CUSTOM, so the document's guarantee does not hold locally.
void sigv4ImportsAsAwsIamWithoutAnUnenforcedWarning() throws Exception {
// The route records AWS_IAM, and dispatch enforces it: an unsigned request to GET /signed
// is rejected before the integration runs, so the import no longer warns that the
// document's guarantee fails to hold locally.
String spec = """
{
"openapi": "3.0.1",
@@ -600,9 +602,9 @@ class ApiGatewayV2OpenApiImportTest {
assertNotNull(route);
assertEquals("AWS_IAM", route.get("authorizationType").asText());
String warnings = get("/v2/apis/" + apiId).get("warnings").toString();
assertTrue(warnings.contains("GET /signed"), warnings);
assertTrue(warnings.contains("does not enforce"), warnings);
JsonNode warnings = get("/v2/apis/" + apiId).get("warnings");
assertFalse(warnings != null && warnings.toString().contains("does not enforce"),
String.valueOf(warnings));
}
@Test
@@ -0,0 +1,258 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
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.assertEquals;
/**
* An HTTP API route whose {@code authorizationType} is {@code AWS_IAM} was recorded
* but never enforced: {@code dispatchV2} branched on JWT and CUSTOM only, so an entirely unsigned
* request reached the integration exactly as if the route were {@code NONE}.
*
* <p>The backend is a fixture HTTP server behind an HTTP_PROXY integration, counting every request
* that reaches it. Asserting the count is what separates "rejected with 403" from "rejected after
* the integration already ran", which is the failure mode the issue describes.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class HttpApiIamAuthorizationTest {
private static final String REGION = "us-east-1";
private static final String ACCESS_KEY = "test";
private static final String SECRET_KEY = "test";
private static HttpServer backendServer;
private static final AtomicInteger backendHits = new AtomicInteger();
private static String httpApiId;
@BeforeAll
static void startBackend() throws Exception {
backendServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backendServer.createContext("/", exchange -> {
backendHits.incrementAndGet();
byte[] body = "reached the integration".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
backendServer.start();
}
@AfterAll
static void stopBackend() {
if (backendServer != null) {
backendServer.stop(0);
}
}
@Test
@Order(1)
void setup() {
httpApiId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"http-api-iam-auth-test","protocolType":"HTTP"}
""")
.when().post("/v2/apis")
.then().statusCode(201)
.extract().path("apiId");
given().contentType(ContentType.JSON)
.body("""
{"stageName":"test"}
""")
.when().post("/v2/apis/" + httpApiId + "/stages")
.then().statusCode(201);
String backendUrl = "http://127.0.0.1:" + backendServer.getAddress().getPort();
String integrationId = given()
.contentType(ContentType.JSON)
.body("""
{"integrationType":"HTTP_PROXY","integrationUri":"%s","payloadFormatVersion":"1.0"}
""".formatted(backendUrl))
.when().post("/v2/apis/" + httpApiId + "/integrations")
.then().statusCode(201)
.extract().path("integrationId");
given().contentType(ContentType.JSON)
.body("""
{"routeKey":"GET /iam","authorizationType":"AWS_IAM","target":"integrations/%s"}
""".formatted(integrationId))
.when().post("/v2/apis/" + httpApiId + "/routes")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("""
{"routeKey":"GET /open","target":"integrations/%s"}
""".formatted(integrationId))
.when().post("/v2/apis/" + httpApiId + "/routes")
.then().statusCode(201);
given().when().get("/v2/apis/" + httpApiId + "/routes")
.then().statusCode(200)
.body("items.find { it.routeKey == 'GET /iam' }.authorizationType", equalTo("AWS_IAM"));
}
@Test
@Order(10)
void unsignedRequestIsRejectedBeforeTheIntegrationRuns() {
backendHits.set(0);
given().when().get(iamPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get(),
"an unsigned request to an AWS_IAM route must not reach the integration");
}
@Test
@Order(11)
void authorizationHeaderThatIsNotSigV4IsRejected() {
backendHits.set(0);
given().header("Authorization", "Bearer not-a-sigv4-credential")
.when().get(iamPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get());
}
@Test
@Order(12)
void validlySignedRequestReachesTheIntegration() throws Exception {
backendHits.set(0);
given().headers(signedHeaders(Instant.now()))
.when().get(iamPath())
.then().statusCode(200)
.body(equalTo("reached the integration"));
assertEquals(1, backendHits.get());
}
@Test
@Order(13)
void tamperedSignatureIsRejected() throws Exception {
backendHits.set(0);
Map<String, String> headers = signedHeaders(Instant.now());
String authorization = headers.get("Authorization");
// Flip the signature's last hex digit: everything else about the request stays valid, so
// only the signature comparison can be what rejects it.
char last = authorization.charAt(authorization.length() - 1);
headers.put("Authorization", authorization.substring(0, authorization.length() - 1)
+ (last == '0' ? '1' : '0'));
given().headers(headers)
.when().get(iamPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get());
}
@Test
@Order(14)
void signatureFromAnotherPathDoesNotAuthorizeThisOne() throws Exception {
backendHits.set(0);
// Signed for /open, replayed against /iam. The path is inside the canonical request, so a
// verifier that only checks "is there a well-formed signature" would let this through.
Map<String, String> headers = ExecuteApiRequestSigner.signedHeaders(
"GET", "/execute-api/" + httpApiId + "/test/open", Map.of(), host(), null,
ACCESS_KEY, SECRET_KEY, REGION, Instant.now());
given().headers(headers)
.when().get(iamPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get());
}
@Test
@Order(15)
void staleSignatureIsRejected() throws Exception {
backendHits.set(0);
given().headers(signedHeaders(Instant.now().minus(2, ChronoUnit.HOURS)))
.when().get(iamPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get());
}
@Test
@Order(16)
void unregisteredAccessKeyIsRejected() throws Exception {
backendHits.set(0);
Map<String, String> headers = ExecuteApiRequestSigner.signedHeaders(
"GET", "/execute-api/" + httpApiId + "/test/iam", Map.of(), host(), null,
"AKIANOTREGISTERED", "AKIANOTREGISTERED", REGION, Instant.now());
given().headers(headers)
.when().get(iamPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get(),
"an unknown access key must not be able to sign for itself");
}
@Test
@Order(17)
void routeWithoutIamAuthorizationStillAcceptsUnsignedRequests() {
backendHits.set(0);
given().when().get("/execute-api/" + httpApiId + "/test/open")
.then().statusCode(200);
assertEquals(1, backendHits.get(), "enforcement must be scoped to AWS_IAM routes");
}
@Test
@Order(999)
void cleanup() {
if (httpApiId != null) {
given().when().delete("/v2/apis/" + httpApiId);
}
}
private static String iamPath() {
return "/execute-api/" + httpApiId + "/test/iam";
}
private static String host() {
return "localhost:" + RestAssured.port;
}
private static Map<String, String> signedHeaders(Instant signedAt) throws Exception {
return ExecuteApiRequestSigner.signedHeaders(
"GET", "/execute-api/" + httpApiId + "/test/iam", Map.of(), host(), null,
ACCESS_KEY, SECRET_KEY, REGION, signedAt);
}
}
@@ -0,0 +1,192 @@
package io.github.hectorvent.floci.testutil;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Signs an execute-api data-plane request the way an AWS SDK signer would, so tests can exercise
* the AWS_IAM enforcement in {@code ExecuteApiSigV4Authorizer} against real signatures rather than
* against fixtures produced by the same code under test.
*/
public final class ExecuteApiRequestSigner {
public static final String SIGNING_SERVICE = "execute-api";
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
// Not BASIC_ISO_DATE: applied to an Instant it appends the zone offset ("20260831Z"), and a
// credential scope date is exactly eight digits.
private static final DateTimeFormatter SCOPE_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC);
private ExecuteApiRequestSigner() {
}
/**
* Returns the {@code X-Amz-Date} and {@code Authorization} headers a header-signed request
* carries. {@code queryParameters} must be the parameters that will actually be sent.
*/
public static Map<String, String> signedHeaders(String httpMethod, String path,
Map<String, String> queryParameters,
String host, byte[] body,
String accessKeyId, String secretKey,
String region, Instant signedAt) throws Exception {
return signedHeaders(httpMethod, path, queryParameters, host, body,
accessKeyId, secretKey, region, signedAt, true);
}
/**
* Signs a request, optionally leaving {@code host} out of {@code SignedHeaders}. No real AWS
* signer omits it, so the false case exists only to exercise the verifier's rejection of a
* signature that is not bound to the endpoint it is presented to.
*/
public static Map<String, String> signedHeaders(String httpMethod, String path,
Map<String, String> queryParameters,
String host, byte[] body,
String accessKeyId, String secretKey,
String region, Instant signedAt,
boolean signHost) throws Exception {
String amzDate = AMZ_DATE.format(signedAt);
String scopeDate = SCOPE_DATE.format(signedAt);
String credentialScope = scopeDate + "/" + region + "/" + SIGNING_SERVICE + "/aws4_request";
String signedHeaderNames = signHost ? "host;x-amz-date" : "x-amz-date";
String canonicalRequest = httpMethod + "\n"
+ path + "\n"
+ canonicalQueryString(queryParameters) + "\n"
+ (signHost ? "host:" + host + "\n" : "")
+ "x-amz-date:" + amzDate + "\n"
+ "\n"
+ signedHeaderNames + "\n"
+ sha256Hex(body == null ? new byte[0] : body);
String signature = sign(secretKey, scopeDate, region, credentialScope, amzDate, canonicalRequest);
Map<String, String> headers = new LinkedHashMap<>();
headers.put("X-Amz-Date", amzDate);
headers.put("Authorization", "AWS4-HMAC-SHA256 "
+ "Credential=" + accessKeyId + "/" + credentialScope + ", "
+ "SignedHeaders=" + signedHeaderNames + ", "
+ "Signature=" + signature);
return headers;
}
/**
* Returns the query string of a presigned execute-api request, {@code X-Amz-Signature} included
* and no leading {@code ?}.
*/
public static String presignedQueryString(String httpMethod, String path, String host,
String accessKeyId, String secretKey, String region,
Instant signedAt, long expiresSeconds) throws Exception {
return presignedQueryString(httpMethod, path, host, accessKeyId, secretKey, region,
signedAt, expiresSeconds, null);
}
/**
* Presigns a request made with temporary credentials, carrying {@code sessionToken} as the
* {@code X-Amz-Security-Token} query parameter the way an SDK signer does: inside the signed
* query string, so altering it in transit breaks the signature as well as the token comparison.
*/
public static String presignedQueryString(String httpMethod, String path, String host,
String accessKeyId, String secretKey, String region,
Instant signedAt, long expiresSeconds,
String sessionToken) throws Exception {
String amzDate = AMZ_DATE.format(signedAt);
String scopeDate = SCOPE_DATE.format(signedAt);
String credentialScope = scopeDate + "/" + region + "/" + SIGNING_SERVICE + "/aws4_request";
Map<String, String> queryParameters = new LinkedHashMap<>();
queryParameters.put("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
queryParameters.put("X-Amz-Credential", accessKeyId + "/" + credentialScope);
queryParameters.put("X-Amz-Date", amzDate);
queryParameters.put("X-Amz-Expires", Long.toString(expiresSeconds));
if (sessionToken != null) {
queryParameters.put("X-Amz-Security-Token", sessionToken);
}
queryParameters.put("X-Amz-SignedHeaders", "host");
String canonicalQuery = canonicalQueryString(queryParameters);
String canonicalRequest = httpMethod + "\n"
+ path + "\n"
+ canonicalQuery + "\n"
+ "host:" + host + "\n"
+ "\n"
+ "host\n"
+ "UNSIGNED-PAYLOAD";
String signature = sign(secretKey, scopeDate, region, credentialScope, amzDate, canonicalRequest);
return canonicalQuery + "&X-Amz-Signature=" + signature;
}
private static String sign(String secretKey, String scopeDate, String region,
String credentialScope, String amzDate, String canonicalRequest)
throws Exception {
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
byte[] signingKey = deriveSigningKey(secretKey, scopeDate, region);
return hexEncode(hmacSha256(signingKey, stringToSign));
}
public static String canonicalQueryString(Map<String, String> queryParameters) {
if (queryParameters == null || queryParameters.isEmpty()) {
return "";
}
Map<String, String> sorted = new TreeMap<>(queryParameters);
List<String> pairs = new ArrayList<>();
sorted.forEach((name, value) -> pairs.add(uriEncode(name) + "=" + uriEncode(value)));
return String.join("&", pairs);
}
public static String uriEncode(String value) {
StringBuilder encoded = new StringBuilder(value.length());
for (byte raw : value.getBytes(StandardCharsets.UTF_8)) {
int b = raw & 0xFF;
char ch = (char) b;
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')
|| ch == '-' || ch == '.' || ch == '_' || ch == '~') {
encoded.append(ch);
} else {
encoded.append('%').append(String.format("%02X", b));
}
}
return encoded.toString();
}
private static byte[] deriveSigningKey(String secretKey, String date, String region) throws Exception {
byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
byte[] kDate = hmacSha256(kSecret, date);
byte[] kRegion = hmacSha256(kDate, region);
byte[] kService = hmacSha256(kRegion, SIGNING_SERVICE);
return hmacSha256(kService, "aws4_request");
}
private static byte[] hmacSha256(byte[] key, String data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(byte[] input) throws Exception {
return hexEncode(MessageDigest.getInstance("SHA-256").digest(input));
}
private static String hexEncode(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
hex.append(String.format("%02x", b));
}
return hex.toString();
}
}