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

+51
View File
@@ -105,6 +105,53 @@ immediately.
> disabled, or deleted key is still executed — it simply arrives with a null `identity.apiKey` rather
> than being rejected with `403`.
### IAM Authorization (`AWS_IAM`) {#iam-authorization}
A method (v1) or route (v2) whose `authorizationType` is `AWS_IAM` requires a SigV4-signed caller.
Before the integration runs, the signature is verified against the request as it arrived (method,
path, query string, the headers named in `SignedHeaders`, and the SHA-256 of the body). Both
placements AWS accepts are honoured: an `Authorization` header and a presigned query string
(`X-Amz-Algorithm=AWS4-HMAC-SHA256`). The credential must be scoped to the `execute-api` service.
Temporary credentials must also present the session token they were issued with, as
`X-Amz-Security-Token` (a header, or a query parameter on a presigned request). The token is
compared against the value recorded when STS minted the credential, so a missing or fabricated one
is rejected: the secret alone is not the whole credential. Whether the token is covered by
`SignedHeaders` is not required either way, since SigV4 leaves that service-specific.
Rejections are `403`, and never reach the integration:
| Condition | REST (v1) `message` / `x-amzn-ErrorType` | HTTP API (v2) |
|---|---|---|
| No SigV4 credentials at all | `Missing Authentication Token` / `MissingAuthenticationTokenException` | `Forbidden` |
| Credentials present but incomplete, or scoped to another service | `Incomplete Signature` / `IncompleteSignatureException` | `Forbidden` |
| Access key the emulator never issued | `The security token included in the request is invalid.` / `UnrecognizedClientException` | `Forbidden` |
| Temporary credential presenting no `X-Amz-Security-Token`, or one that is not the token it was issued | `The security token included in the request is invalid.` / `UnrecognizedClientException` | `Forbidden` |
| `X-Amz-Date` outside the 5-minute window, or a presigned URL past `X-Amz-Expires` | `Signature expired` / `InvalidSignatureException` | `Forbidden` |
| Signature mismatch | `The request signature we calculated does not match…` / `InvalidSignatureException` | `Forbidden` |
A verified caller reaches the integration as `requestContext.identity.{accessKey, accountId, caller,
user, userArn}` on a REST proxy event, and as `requestContext.authorizer.iam` on an HTTP API 2.0
event.
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
itself. Any AWS SDK sends the session token automatically, so temporary credentials need no special
handling; a hand-rolled signer must include it.
> [!NOTE]
> A session minted before Floci recorded session tokens (one restored from a persisted store
> written by an earlier version) has no issued token to compare against. Such a credential must
> still present a token, but its value cannot be checked. Re-minting it with `AssumeRole` restores
> the full check.
> [!NOTE]
> Floci authenticates the caller but does not authorize the call: it does not evaluate
> `execute-api:Invoke` against the caller's IAM policies or a resource policy, so any validly
> signed, known caller is let through. `principalOrgId` and `cognitoIdentity` are always null -
> Organizations membership and identity-pool federation are not modelled.
### Not Implemented
These management-plane operations have no handler in v1. Calls will return `404` or an error:
@@ -226,6 +273,10 @@ curl http://{apiId}.execute-api.localhost.floci.io:4566/{path}
APIs created or updated with `disableExecuteApiEndpoint` reject requests to
this default hostname with `404 Not Found`, matching AWS HTTP API behavior.
Routes carrying `authorizationType: AWS_IAM`: including those an OpenAPI import resolves from an
`awsSigv4` security scheme: require a signed caller; see
[IAM Authorization](#iam-authorization).
### Supported Operations
| Category | Operations |
@@ -187,6 +187,9 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
.buildFromEncoded();
LOG.debugv("Execute API host routing: {0}{1} -> {2}", host, originalPath, newUri.getRawPath());
routeContext.routeToHttpApi(region);
// AWS_IAM dispatch rebuilds the caller's canonical request, which covers the path they
// signed: the virtual-host path, not the /execute-api/... form this rewrite produces.
routeContext.recordSignedRequestPath(originalPath);
requestContext.setRequestUri(newUri);
}
@@ -97,6 +97,7 @@ public class ApiGatewayExecuteController {
private final ApiGatewayExecuteRouteContext routeContext;
private final JwtSignatureVerifier jwtSignatureVerifier;
private final RequestContext requestContext;
private final ExecuteApiSigV4Authorizer sigV4Authorizer;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
@@ -108,7 +109,8 @@ public class ApiGatewayExecuteController {
SqsQueryHandler sqsQueryHandler,
ApiGatewayExecuteRouteContext routeContext,
JwtSignatureVerifier jwtSignatureVerifier,
RequestContext requestContext) {
RequestContext requestContext,
ExecuteApiSigV4Authorizer sigV4Authorizer) {
this.apiGatewayService = apiGatewayService;
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaService = lambdaService;
@@ -122,6 +124,7 @@ public class ApiGatewayExecuteController {
this.routeContext = routeContext;
this.jwtSignatureVerifier = jwtSignatureVerifier;
this.requestContext = requestContext;
this.sigV4Authorizer = sigV4Authorizer;
}
/** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */
@@ -356,6 +359,20 @@ public class ApiGatewayExecuteController {
// 1. Authorizer
String resolvedApiKey = resolveApiKeyForRequest(region, apiId, stageName, headers);
// AWS_IAM is verified before the CUSTOM authorizer path because it gates the request on the
// caller's signature rather than on a Lambda's verdict, and a method carries one
// authorizationType, so at most one of the two branches applies.
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity = null;
if ("AWS_IAM".equalsIgnoreCase(method.getAuthorizationType())) {
ExecuteApiSigV4Authorizer.Result iamResult =
sigV4Authorizer.authorize(httpMethod, headers, uriInfo, body, routeContext.signedRequestPath());
if (!iamResult.authorized()) {
return restIamRejection(iamResult);
}
iamIdentity = iamResult.identity();
}
AuthorizerResult authorizerResult = invokeAuthorizer(region, apiId, stageName, httpMethod, path, matched.getPath(), matched.getId(), stage, method, headers, uriInfo, resolvedApiKey);
if (authorizerResult.errorResponse() != null) return authorizerResult.errorResponse();
@@ -375,7 +392,8 @@ public class ApiGatewayExecuteController {
return switch (integration.getType().toUpperCase()) {
case "AWS_PROXY" -> invokeProxy(region, apiId, httpMethod, path, proxy, stageName,
matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey);
matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey,
iamIdentity);
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);
@@ -397,7 +415,8 @@ public class ApiGatewayExecuteController {
Stage stage,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body,
AuthorizerResult authorizerResult, String resolvedApiKey) {
AuthorizerResult authorizerResult, String resolvedApiKey,
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) {
String functionName = functionNameFromUri(integration.getUri());
if (functionName == null) {
return Response.status(500)
@@ -408,7 +427,7 @@ public class ApiGatewayExecuteController {
String requestId = UUID.randomUUID().toString();
String eventJson = buildProxyEvent(region, apiId, httpMethod, path, proxy, resource.getPath(),
resource.getId(), stageName, stage, headers, uriInfo, body, requestId,
authorizerResult.principalId(), authorizerResult.context(), resolvedApiKey);
authorizerResult.principalId(), authorizerResult.context(), resolvedApiKey, iamIdentity);
try {
InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(),
@@ -682,14 +701,17 @@ public class ApiGatewayExecuteController {
return LambdaArnUtils.extractFunctionNameFromUri(uri);
}
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 resolvedApiKey) {
// Package-private rather than private so a focused unit test can assert the event's wire shape
// without standing up a Lambda runtime, mirroring the buildV2ProxyEvent tests.
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 resolvedApiKey,
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) {
// The JAX-RS {proxy} binding strips a trailing slash, but a trailing slash is
// significant in the delivered path (routers treat /x and /x/ as distinct routes).
// Recover it from the raw request URI for the event path fields. Resource matching
@@ -747,27 +769,29 @@ public class ApiGatewayExecuteController {
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)
// accessKey, accountId, caller, user and userArn carry the verified SigV4 caller on an
// AWS_IAM method (iamIdentity is non-null only then) and are explicit JSON null otherwise,
// exactly as AWS renders them. Fields that require auth mechanisms Floci does not implement
// are always null:
// - principalOrgId: AWS Organizations membership is not modelled
// - 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");
putOrNull(identity, "accessKey", iamIdentity == null ? null : iamIdentity.accessKey());
putOrNull(identity, "accountId", iamIdentity == null ? null : iamIdentity.accountId());
putOrNull(identity, "caller", iamIdentity == null ? null : iamIdentity.userId());
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");
putOrNull(identity, "user", iamIdentity == null ? null : iamIdentity.userId());
String userAgent = headers.getHeaderString("User-Agent");
identity.put("userAgent", userAgent != null ? userAgent : "");
identity.putNull("userArn");
putOrNull(identity, "userArn", iamIdentity == null ? null : iamIdentity.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) {
@@ -1470,6 +1494,19 @@ public class ApiGatewayExecuteController {
.type(MediaType.APPLICATION_JSON).build();
}
// A route carries exactly one authorizationType, so AWS_IAM, JWT and CUSTOM are mutually
// exclusive branches. AWS_IAM was previously absent here, which let an unsigned request
// through to the integration as if the route were NONE.
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity = null;
if ("AWS_IAM".equalsIgnoreCase(route.getAuthorizationType())) {
ExecuteApiSigV4Authorizer.Result iamResult =
sigV4Authorizer.authorize(httpMethod, headers, uriInfo, body, routeContext.signedRequestPath());
if (!iamResult.authorized()) {
return httpApiIamRejection(iamResult);
}
iamIdentity = iamResult.identity();
}
Map<String, String> jwtClaims = null;
List<String> jwtScopes = null;
if ("JWT".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
@@ -1526,7 +1563,7 @@ public class ApiGatewayExecuteController {
String requestId = UUID.randomUUID().toString();
String eventJson = buildV2ProxyEvent(httpMethod, path, route.getRouteKey(),
apiId, region, stageName, headers, uriInfo, body, requestId, jwtClaims, jwtScopes,
lambdaAuthorizerContext);
lambdaAuthorizerContext, iamIdentity);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName);
@@ -1805,6 +1842,51 @@ public class ApiGatewayExecuteController {
return new JwtAuthorizerResult(null, claims.raw, tokenScopes); // authorized
}
// ──────────────────────────── AWS_IAM (SigV4) rejections ────────────────────────────
private record RestIamError(String errorType, String message) {}
/**
* Renders a failed AWS_IAM check the way a REST API does: always {@code 403}, with the message
* and {@code x-amzn-ErrorType} AWS pairs with that class of failure. The signature-mismatch body
* omits the canonical-string dump real AWS appends, which is a debugging aid rather than part of
* the contract; the reason is logged instead.
*/
private Response restIamRejection(ExecuteApiSigV4Authorizer.Result result) {
LOG.debugv("execute-api AWS_IAM rejected a REST request: {0} ({1})",
result.failure(), result.detail());
RestIamError error = switch (result.failure()) {
case MISSING -> new RestIamError("MissingAuthenticationTokenException",
"Missing Authentication Token");
case MALFORMED -> new RestIamError("IncompleteSignatureException",
"Incomplete Signature");
case UNKNOWN_KEY -> new RestIamError("UnrecognizedClientException",
"The security token included in the request is invalid.");
case EXPIRED -> new RestIamError("InvalidSignatureException",
"Signature expired");
case MISMATCH -> new RestIamError("InvalidSignatureException",
"The request signature we calculated does not match the signature you provided."
+ " Check your AWS Secret Access Key and signing method.");
};
return Response.status(403)
.header("x-amzn-ErrorType", error.errorType())
.entity(jsonMessage(error.message()))
.type(MediaType.APPLICATION_JSON).build();
}
/**
* HTTP APIs collapse every IAM failure into {@code 403 {"message":"Forbidden"}} rather than
* naming the reason, matching both real AWS and the JWT/REQUEST authorizer rejections above.
* The specific reason is logged so a caller debugging a local 403 can still find it.
*/
private Response httpApiIamRejection(ExecuteApiSigV4Authorizer.Result result) {
LOG.debugv("execute-api AWS_IAM rejected an HTTP API request: {0} ({1})",
result.failure(), result.detail());
return Response.status(403)
.entity(jsonMessage("Forbidden"))
.type(MediaType.APPLICATION_JSON).build();
}
// ──────────────────────────── HTTP API v2 Lambda REQUEST authorizer ────────────────────────────
// A null errorResponse means authorized, as in JwtAuthorizerResult.
@@ -2256,6 +2338,18 @@ public class ApiGatewayExecuteController {
HttpHeaders headers, UriInfo uriInfo,
byte[] body, String requestId, Map<String, String> jwtClaims,
List<String> jwtScopes, ObjectNode lambdaAuthorizerContext) {
return buildV2ProxyEvent(httpMethod, path, routeKey, apiId, region, stageName,
headers, uriInfo, body, requestId, jwtClaims, jwtScopes, lambdaAuthorizerContext, null);
}
// iamIdentity is the verified SigV4 caller on an AWS_IAM route, and is mutually exclusive with
// both jwtClaims and lambdaAuthorizerContext for the same reason they are with each other.
String buildV2ProxyEvent(String httpMethod, String path, String routeKey,
String apiId, String region, String stageName,
HttpHeaders headers, UriInfo uriInfo,
byte[] body, String requestId, Map<String, String> jwtClaims,
List<String> jwtScopes, ObjectNode lambdaAuthorizerContext,
ExecuteApiSigV4Authorizer.CallerIdentity iamIdentity) {
// The JAX-RS {proxy} binding strips a trailing slash, but rawPath is by contract the
// raw path and routers treat /x and /x/ as distinct routes. Recover it from the raw
// request URI for the event path fields. Route matching in dispatchV2 and the
@@ -2339,6 +2433,19 @@ public class ApiGatewayExecuteController {
// is not surfaced here, and a context-less allow leaves the authorizer node absent
// rather than rendering "lambda": null.
ctx.putObject("authorizer").set("lambda", lambdaAuthorizerContext);
} else if (iamIdentity != null) {
// AWS's IAM-authorized HTTP API shape: requestContext.authorizer.iam. cognitoIdentity
// and principalOrgId stay null - Floci models neither an identity pool federating into
// execute-api nor Organizations membership. callerId and userId are the same principal
// id AWS repeats across both fields for a long-term IAM user credential.
ObjectNode iamNode = ctx.putObject("authorizer").putObject("iam");
iamNode.put("accessKey", iamIdentity.accessKey());
iamNode.put("accountId", iamIdentity.accountId());
iamNode.put("callerId", iamIdentity.userId());
iamNode.putNull("cognitoIdentity");
iamNode.putNull("principalOrgId");
iamNode.put("userArn", iamIdentity.userArn());
iamNode.put("userId", iamIdentity.userId());
}
if (body != null && body.length > 0) {
@@ -2382,6 +2489,15 @@ public class ApiGatewayExecuteController {
return objectMapper.createObjectNode().put("message", message).toString();
}
/** Writes an explicit JSON null rather than omitting the field, which is what AWS sends. */
private static void putOrNull(ObjectNode node, String field, String value) {
if (value == null) {
node.putNull(field);
} else {
node.put(field, value);
}
}
/**
* Parses an {@code application/x-www-form-urlencoded} body into a {@link MultivaluedMap},
* matching the form parameters an AWS query-protocol handler expects. Both keys and values
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.apigateway;
import jakarta.enterprise.context.RequestScoped;
import jakarta.ws.rs.core.UriInfo;
/**
* Carries routing information established by pre-matching execute-api filters to the
@@ -10,6 +11,7 @@ import jakarta.enterprise.context.RequestScoped;
public class ApiGatewayExecuteRouteContext {
private String httpApiRegion;
private String signedRequestPath;
void routeToHttpApi(String region) {
this.httpApiRegion = region;
@@ -18,4 +20,18 @@ public class ApiGatewayExecuteRouteContext {
String httpApiRegion() {
return httpApiRegion;
}
/**
* Records the raw path as the client sent it, before a pre-matching filter rewrote the request
* URI onto the internal {@code /execute-api/...} form. SigV4 covers the path the caller signed,
* so AWS_IAM verification has to rebuild its canonical request from this value rather than from
* the rewritten {@link UriInfo}.
*/
void recordSignedRequestPath(String rawPath) {
this.signedRequestPath = rawPath;
}
String signedRequestPath() {
return signedRequestPath;
}
}
@@ -0,0 +1,624 @@
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 jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URLDecoder;
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.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Verifies the SigV4 signature on an execute-api data-plane request, so a route or method whose
* {@code authorizationType} is {@code AWS_IAM} actually requires a signed caller instead of merely
* recording that it does.
*
* <p>Both signing placements real API Gateway accepts are handled: an {@code Authorization} header
* and a presigned query string ({@code X-Amz-Algorithm=AWS4-HMAC-SHA256}). The canonical request is
* rebuilt from the request exactly as it arrived (the raw path the client signed, its raw query
* string, the headers named in {@code SignedHeaders}, and the SHA-256 of the body), and the derived
* signature is compared in constant time.
*
* <p>A temporary credential must additionally present the session token it was issued with, which
* is checked by {@link #checkSessionToken}.
*
* <h2>Deliberate deviations from real AWS</h2>
* <ul>
* <li><strong>No authorization, only authentication.</strong> A valid signature from any known
* access key is accepted; {@code execute-api:Invoke} is not evaluated against the caller's
* IAM policies or a resource policy. Floci's IAM policy evaluation is opt-in and off by
* default, so gating the data plane on it would make the common case unusable.</li>
* <li><strong>The credential scope's region is not pinned</strong> to the API's region. Floci
* resolves a request's region <em>from</em> that scope, so pinning it would be circular.</li>
* <li>The well-known local-dev {@code test}/{@code test} credential pair is honoured, mirroring
* the identical fallback in {@code S3Service}, {@code PreSignedUrlFilter} and the
* ElastiCache/RDS validators. No other unregistered access key is accepted.</li>
* </ul>
*/
@ApplicationScoped
public class ExecuteApiSigV4Authorizer {
private static final Logger LOG = Logger.getLogger(ExecuteApiSigV4Authorizer.class);
private static final String ALGORITHM = "AWS4-HMAC-SHA256";
private static final String SIGNING_SERVICE = "execute-api";
private static final String TERMINATOR = "aws4_request";
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
/**
* Real API Gateway rejects a header-signed request whose {@code X-Amz-Date} is more than five
* minutes from the service's clock. Emulating it keeps a captured request from being replayed
* indefinitely against a route the caller is testing authorization on.
*/
private static final long MAX_CLOCK_SKEW_SECONDS = 300;
/** Longest {@code X-Amz-Expires} AWS accepts on a presigned request (7 days). */
private static final long MAX_PRESIGNED_EXPIRY_SECONDS = 604800;
/** Where a temporary credential's session token rides: a header, or a presigned query parameter. */
private static final String SECURITY_TOKEN = "X-Amz-Security-Token";
private static final String LEGACY_ACCESS_KEY_ID = "test";
private static final String LEGACY_SECRET_KEY = "test";
private final IamService iamService;
private final RegionResolver regionResolver;
@Inject
public ExecuteApiSigV4Authorizer(IamService iamService, RegionResolver regionResolver) {
this.iamService = iamService;
this.regionResolver = regionResolver;
}
/** Why a request was rejected. Dispatch maps this onto the wire error its API type uses. */
public enum Failure {
/** Nothing on the request even claims to be SigV4-signed. */
MISSING,
/** SigV4 credentials are present but unparsable, incomplete, or not scoped to execute-api. */
MALFORMED,
/** The credential names an access key this emulator has never issued. */
UNKNOWN_KEY,
/** The signing timestamp is outside the accepted window, or a presigned URL has expired. */
EXPIRED,
/** The signature does not match the one derived from the caller's secret key. */
MISMATCH
}
/**
* The caller behind a verified signature, as API Gateway surfaces it on the proxy event
* ({@code requestContext.identity} on REST, {@code requestContext.authorizer.iam} on HTTP).
*/
public record CallerIdentity(String accessKey, String accountId, String userArn, String userId) {}
/** A {@code null} failure means authorized, mirroring the authorizer results in dispatch. */
public record Result(Failure failure, String detail, CallerIdentity identity) {
public boolean authorized() {
return failure == null;
}
static Result rejected(Failure failure, String detail) {
return new Result(failure, detail, null);
}
}
public Result authorize(String httpMethod, HttpHeaders headers, UriInfo uriInfo, byte[] body,
String signedRequestPath) {
try {
return verify(httpMethod, headers, uriInfo, body, signedRequestPath);
} catch (Exception e) {
// A malformed credential, an unparsable date, an unsupported charset: every one of
// these is a request we could not verify, and an unverifiable request is not
// authorized. Logged rather than swallowed so an operational fault is diagnosable.
LOG.debugv(e, "execute-api SigV4 verification failed to complete: {0}", e.getMessage());
return Result.rejected(Failure.MALFORMED, "signature could not be verified");
}
}
private Result verify(String httpMethod, HttpHeaders headers, UriInfo uriInfo, byte[] body,
String signedRequestPath) throws Exception {
MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
String authorization = headers == null ? null : headers.getHeaderString(HttpHeaders.AUTHORIZATION);
boolean presigned = ALGORITHM.equals(queryParameters.getFirst("X-Amz-Algorithm"));
if (!presigned && (authorization == null || authorization.isBlank())) {
return Result.rejected(Failure.MISSING, "request is not SigV4-signed");
}
SignedRequest signed = presigned
? presignedRequest(queryParameters)
: headerSignedRequest(authorization, headers);
if (signed == null) {
return Result.rejected(Failure.MALFORMED, "SigV4 credentials are incomplete");
}
CredentialScope scope = CredentialScope.parse(signed.credential());
if (scope == null) {
return Result.rejected(Failure.MALFORMED, "credential scope is malformed");
}
if (!SIGNING_SERVICE.equals(scope.service())) {
return Result.rejected(Failure.MALFORMED,
"credential is scoped to service " + scope.service() + ", not " + SIGNING_SERVICE);
}
if (!signed.amzDate().startsWith(scope.date())) {
return Result.rejected(Failure.MALFORMED, "credential scope date does not match X-Amz-Date");
}
// SigV4 requires host to be signed, and here it is what binds a signature to one API.
// A virtual-host request carries its apiId only in the Host header: the path the client
// signed is /{stage}/{route}, identical across every API on this emulator. Without host in
// the canonical request, a signature minted for one API replays against any other API that
// happens to expose the same stage and route.
if (!containsHeader(signed.signedHeaders(), "host")) {
return Result.rejected(Failure.MALFORMED, "SignedHeaders does not cover host");
}
Instant signedAt = Instant.from(AMZ_DATE.parse(signed.amzDate()));
Result expiry = checkExpiry(signedAt, signed.expiresSeconds(), presigned);
if (expiry != null) {
return expiry;
}
String secretKey = resolveSecretKey(scope.accessKeyId());
if (secretKey == null) {
LOG.debugv("execute-api request references unregistered access key={0}",
sanitizeForLog(scope.accessKeyId()));
return Result.rejected(Failure.UNKNOWN_KEY, "access key is not registered");
}
Result sessionToken = checkSessionToken(scope.accessKeyId(), headers, queryParameters);
if (sessionToken != null) {
return sessionToken;
}
String payloadHash = payloadHash(headers, body, presigned, signed.signedHeaders());
String canonicalHeaders = canonicalHeaders(signed.signedHeaders(), headers, uriInfo);
String canonicalQueryString = canonicalQueryString(uriInfo.getRequestUri().getRawQuery(), presigned);
byte[] signingKey = deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service());
String rawPath = signedRequestPath != null
? signedRequestPath
: uriInfo.getRequestUri().getRawPath();
for (String canonicalUri : canonicalUriCandidates(rawPath)) {
String canonicalRequest = httpMethod + "\n"
+ canonicalUri + "\n"
+ canonicalQueryString + "\n"
+ canonicalHeaders + "\n"
+ signed.signedHeaders() + "\n"
+ payloadHash;
String stringToSign = ALGORITHM + "\n"
+ signed.amzDate() + "\n"
+ scope.credentialScope() + "\n"
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String expected = hexEncode(hmacSha256(signingKey, stringToSign));
if (MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
signed.signature().getBytes(StandardCharsets.UTF_8))) {
return new Result(null, null, resolveIdentity(scope.accessKeyId()));
}
}
LOG.debugv("execute-api SigV4 signature mismatch for accessKey={0}",
sanitizeForLog(scope.accessKeyId()));
return Result.rejected(Failure.MISMATCH, "signature does not match");
}
private Result checkExpiry(Instant signedAt, Long expiresSeconds, boolean presigned) {
Instant now = Instant.now();
if (presigned) {
if (expiresSeconds == null || expiresSeconds < 1 || expiresSeconds > MAX_PRESIGNED_EXPIRY_SECONDS) {
return Result.rejected(Failure.MALFORMED, "X-Amz-Expires is missing or out of range");
}
if (now.isAfter(signedAt.plusSeconds(expiresSeconds))) {
return Result.rejected(Failure.EXPIRED, "presigned request expired");
}
// A presigned URL signed in the future is still a forgery attempt, not a slow clock.
if (signedAt.isAfter(now.plusSeconds(MAX_CLOCK_SKEW_SECONDS))) {
return Result.rejected(Failure.EXPIRED, "presigned request is not yet valid");
}
return null;
}
if (Math.abs(now.getEpochSecond() - signedAt.getEpochSecond()) > MAX_CLOCK_SKEW_SECONDS) {
return Result.rejected(Failure.EXPIRED,
"signature date " + AMZ_DATE.format(signedAt) + " is outside the accepted window");
}
return null;
}
/**
* Resolves the secret backing an access key, or {@code null} when the credential is one this
* emulator will not authenticate. Failing closed here is the point: an earlier revision of the
* ElastiCache and RDS validators fell back to the access key id as its own secret, which let
* any caller self-sign a request.
*
* <p>{@code findSecretKey} screens out an expired session and an inactive access key on its
* own. {@code resolveAccountId} is required on top of it because a verified caller has to be
* attributed to an account to reach the integration at all: a credential this emulator cannot
* place in one is not something to authenticate. It rejects the same expired AssumeRole
* credential and deactivated long-term key a second time, which is why those cases stay
* covered whichever of the two gates moves.
*
* <p>The session token a temporary credential carries is checked separately, by
* {@link #checkSessionToken}.
*/
private String resolveSecretKey(String accessKeyId) {
if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {
return LEGACY_SECRET_KEY;
}
String secretKey = iamService.findSecretKey(accessKeyId).orElse(null);
if (secretKey == null) {
return null;
}
if (iamService.resolveAccountId(accessKeyId).isEmpty()) {
LOG.debugv("execute-api request uses an expired or inactive credential: accessKey={0}",
sanitizeForLog(accessKeyId));
return null;
}
return secretKey;
}
/**
* Rejects a temporary credential that does not present the session token Floci issued with it,
* returning {@code null} when there is nothing to object to.
*
* <p>The secret alone is not the whole credential. AWS requires the session token on every
* request made with temporary credentials precisely because it is what confirms the credential
* is live and genuinely STS-issued, so accepting an {@code ASIA...} key on its secret alone
* lets an incomplete credential through a route that is supposed to demand a complete one.
*
* <p>The token is compared against the value recorded at mint time rather than merely required
* to be present, so a fabricated token fails as well as a missing one. Presence is all that can
* be demanded of a session stored before Floci recorded tokens: {@code findSessionToken} is
* empty there, and rejecting it would lock out a credential that is otherwise perfectly valid.
* {@code findSecretKey(accessKeyId, sessionToken)} is the stricter one-step alternative, which
* this deliberately does not use because it cannot tell that case apart from a real mismatch.
*
* <p>Folding the token into the canonical request is deliberately not required. Whether a
* service covers it by {@code SignedHeaders} or appends it after signing is service-specific in
* SigV4, and comparing against the issued value binds the token regardless of where it rode.
*/
private Result checkSessionToken(String accessKeyId, HttpHeaders headers,
MultivaluedMap<String, String> queryParameters) {
if (!IamService.isTemporaryAccessKey(accessKeyId)) {
return null;
}
String presented = queryParameters.getFirst(SECURITY_TOKEN);
if (isBlank(presented) && headers != null) {
presented = headers.getHeaderString(SECURITY_TOKEN);
}
if (isBlank(presented)) {
LOG.debugv("execute-api request uses temporary credential accessKey={0} with no {1}",
sanitizeForLog(accessKeyId), SECURITY_TOKEN);
return Result.rejected(Failure.UNKNOWN_KEY, "temporary credential presents no session token");
}
String issued = iamService.findSessionToken(accessKeyId).orElse(null);
if (issued == null) {
return null;
}
if (!MessageDigest.isEqual(issued.getBytes(StandardCharsets.UTF_8),
presented.getBytes(StandardCharsets.UTF_8))) {
LOG.debugv("execute-api request presents a session token that does not match the one"
+ " issued for accessKey={0}", sanitizeForLog(accessKeyId));
return Result.rejected(Failure.UNKNOWN_KEY, "session token does not match the issued credential");
}
return null;
}
/**
* Builds the caller for a signature that already verified. The {@code orElseGet} fallbacks are
* reachable only for the legacy {@code test} credential: {@link #resolveSecretKey} has proved
* every other accepted key resolves to a live account.
*/
private CallerIdentity resolveIdentity(String accessKeyId) {
String accountId = iamService.resolveAccountId(accessKeyId)
.orElseGet(regionResolver::getAccountId);
String userArn = iamService.resolveCallerArn(accessKeyId)
.orElseGet(() -> "arn:aws:iam::" + accountId + ":root");
String userId = iamService.findAccessKey(accessKeyId)
.map(AccessKey::getUserName)
.flatMap(iamService::findUser)
.map(IamUser::getUserId)
.orElse(accessKeyId);
return new CallerIdentity(accessKeyId, accountId, userArn, userId);
}
// ──────────────────────────── Signed-request parsing ────────────────────────────
private record SignedRequest(String credential, String signedHeaders, String signature,
String amzDate, Long expiresSeconds) {}
private static SignedRequest headerSignedRequest(String authorization, HttpHeaders headers) {
String trimmed = authorization.trim();
if (!trimmed.regionMatches(true, 0, ALGORITHM, 0, ALGORITHM.length())) {
return null;
}
Map<String, String> parameters = new LinkedHashMap<>();
for (String part : trimmed.substring(ALGORITHM.length()).split(",")) {
int equals = part.indexOf('=');
if (equals > 0) {
parameters.put(part.substring(0, equals).trim(), part.substring(equals + 1).trim());
}
}
String credential = parameters.get("Credential");
String signedHeaders = parameters.get("SignedHeaders");
String signature = parameters.get("Signature");
String amzDate = headers.getHeaderString("X-Amz-Date");
if (amzDate == null || amzDate.isBlank()) {
amzDate = headers.getHeaderString("Date");
}
if (isBlank(credential) || isBlank(signedHeaders) || isBlank(signature) || isBlank(amzDate)) {
return null;
}
return new SignedRequest(credential, signedHeaders.toLowerCase(Locale.ROOT), signature, amzDate, null);
}
private static SignedRequest presignedRequest(MultivaluedMap<String, String> queryParameters) {
String credential = queryParameters.getFirst("X-Amz-Credential");
String signedHeaders = queryParameters.getFirst("X-Amz-SignedHeaders");
String signature = queryParameters.getFirst("X-Amz-Signature");
String amzDate = queryParameters.getFirst("X-Amz-Date");
String expires = queryParameters.getFirst("X-Amz-Expires");
if (isBlank(credential) || isBlank(signedHeaders) || isBlank(signature) || isBlank(amzDate)) {
return null;
}
Long expiresSeconds;
try {
expiresSeconds = expires == null ? null : Long.valueOf(expires.trim());
} catch (NumberFormatException e) {
LOG.debugv("execute-api presigned request carries a non-numeric X-Amz-Expires: {0}",
sanitizeForLog(expires));
expiresSeconds = null;
}
return new SignedRequest(credential, signedHeaders.toLowerCase(Locale.ROOT), signature,
amzDate, expiresSeconds);
}
private record CredentialScope(String accessKeyId, String date, String region, String service) {
String credentialScope() {
return date + "/" + region + "/" + service + "/" + TERMINATOR;
}
/** {@code credential} is expected already percent-decoded: a header credential is never
* encoded, and JAX-RS decodes the presigned {@code X-Amz-Credential} before we see it. */
static CredentialScope parse(String credential) {
if (credential == null) {
return null;
}
String[] parts = credential.split("/");
if (parts.length != 5 || !TERMINATOR.equals(parts[4])) {
return null;
}
if (parts[0].isBlank() || parts[1].length() != 8 || parts[2].isBlank() || parts[3].isBlank()) {
return null;
}
return new CredentialScope(parts[0], parts[1], parts[2], parts[3].toLowerCase(Locale.ROOT));
}
}
// ──────────────────────────── Canonical request ────────────────────────────
/**
* The canonical URI candidates a signer could have produced for this raw path. Non-S3 SigV4
* URI-encodes each path segment a second time on top of the encoding already on the wire; for
* an all-ASCII path the two forms are identical, so only paths carrying escapes produce a
* second candidate. Trying both keeps a legitimately signed request from being rejected over
* which convention its signer follows.
*/
private static List<String> canonicalUriCandidates(String rawPath) {
String raw = isBlank(rawPath) ? "/" : rawPath;
List<String> candidates = new ArrayList<>(2);
candidates.add(raw);
String[] segments = raw.split("/", -1);
StringBuilder doubleEncoded = new StringBuilder();
for (int i = 0; i < segments.length; i++) {
if (i > 0) {
doubleEncoded.append('/');
}
doubleEncoded.append(uriEncode(segments[i]));
}
if (!candidates.contains(doubleEncoded.toString())) {
candidates.add(doubleEncoded.toString());
}
return candidates;
}
private static String canonicalQueryString(String rawQuery, boolean dropSignature) {
if (isBlank(rawQuery)) {
return "";
}
List<String[]> pairs = new ArrayList<>();
for (String pair : rawQuery.split("&")) {
if (pair.isEmpty()) {
continue;
}
int equals = pair.indexOf('=');
String name = decodeQueryComponent(equals >= 0 ? pair.substring(0, equals) : pair);
String value = decodeQueryComponent(equals >= 0 ? pair.substring(equals + 1) : "");
if (dropSignature && "X-Amz-Signature".equals(name)) {
continue;
}
pairs.add(new String[]{uriEncode(name), uriEncode(value)});
}
pairs.sort(Comparator.<String[], String>comparing(pair -> pair[0]).thenComparing(pair -> pair[1]));
StringBuilder canonical = new StringBuilder();
for (String[] pair : pairs) {
if (!canonical.isEmpty()) {
canonical.append('&');
}
canonical.append(pair[0]).append('=').append(pair[1]);
}
return canonical.toString();
}
private static String canonicalHeaders(String signedHeaders, HttpHeaders headers, UriInfo uriInfo) {
StringBuilder canonical = new StringBuilder();
for (String name : signedHeaders.split(";")) {
String value = "host".equals(name) ? hostHeader(headers, uriInfo) : headerValue(headers, name);
canonical.append(name).append(':').append(normalizeHeaderValue(value)).append('\n');
}
return canonical.toString();
}
private static String headerValue(HttpHeaders headers, String name) {
String value = headers == null ? null : headers.getHeaderString(name);
return value == null ? "" : value;
}
/**
* The {@code host} value the client signed. Taken from the {@code Host} header the request
* carried rather than from the resolved URI, because that is what the signer hashed; the URI
* is only a fallback for callers (notably unit tests) that build a request without one.
*/
private static String hostHeader(HttpHeaders headers, UriInfo uriInfo) {
String host = headers == null ? null : headers.getHeaderString("Host");
if (host != null && !host.isBlank()) {
return host;
}
URI requestUri = uriInfo.getRequestUri();
int port = requestUri.getPort();
return port > 0 && port != 80 && port != 443
? requestUri.getHost() + ":" + port
: String.valueOf(requestUri.getHost());
}
private static String normalizeHeaderValue(String value) {
return value == null ? "" : value.trim().replaceAll("\\s+", " ");
}
/**
* The payload hash the canonical request must carry.
*
* <p>A literal {@code x-amz-content-sha256} is deliberately <em>not</em> taken on trust: the
* body is hashed instead. For an honest request the two are equal, and for a tampered one they
* are not, which turns a swapped body into a signature mismatch. Trusting the header would let
* a caller keep a valid signature over a body they had replaced, since the header value the
* signer hashed would still be the one presented.
*
* <p>The sentinels ({@code UNSIGNED-PAYLOAD}, the {@code STREAMING-*} forms) mean the caller
* chose not to sign the body, and are honoured only when {@code x-amz-content-sha256} is itself
* in {@code SignedHeaders}: that is, when the choice is covered by the signature. A presigned
* request is unsigned-payload by convention; every AWS presigner emits it that way.
*/
private String payloadHash(HttpHeaders headers, byte[] body, boolean presigned,
String signedHeaders) throws Exception {
String declared = headers == null ? null : headers.getHeaderString("x-amz-content-sha256");
if (declared != null && !declared.isBlank()
&& containsHeader(signedHeaders, "x-amz-content-sha256")
&& !isSha256Hex(declared.trim())) {
return declared.trim();
}
if (presigned) {
return "UNSIGNED-PAYLOAD";
}
return sha256Hex(body == null ? new byte[0] : body);
}
private static boolean containsHeader(String signedHeaders, String name) {
for (String header : signedHeaders.split(";")) {
if (name.equals(header)) {
return true;
}
}
return false;
}
private static boolean isSha256Hex(String value) {
if (value.length() != 64) {
return false;
}
for (int index = 0; index < value.length(); index++) {
if (Character.digit(value.charAt(index), 16) < 0) {
return false;
}
}
return true;
}
// ──────────────────────────── Crypto and encoding helpers ────────────────────────────
private static byte[] deriveSigningKey(String secretKey, String date, String region, String service)
throws Exception {
byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
byte[] kDate = hmacSha256(kSecret, date);
byte[] kRegion = hmacSha256(kDate, region);
byte[] kService = hmacSha256(kRegion, service);
return hmacSha256(kService, TERMINATOR);
}
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(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16));
}
return hex.toString();
}
/** RFC 3986 percent-encoding as SigV4 defines it: {@code /} is escaped, {@code -._~} are not. */
private 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(Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16)))
.append(Character.toUpperCase(Character.forDigit(b & 0xF, 16)));
}
}
return encoded.toString();
}
/**
* Percent-decodes a query-string component without {@code URLDecoder}'s form-encoding rule that
* a literal {@code +} means a space: SigV4 signers escape a space as {@code %20}, so a raw
* {@code +} on the wire is a plus sign and re-encoding it as a space would break the signature.
*/
private static String decodeQueryComponent(String value) {
if (value == null) {
return "";
}
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8);
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
/** Strips control characters from attacker-controlled values before they reach a log line. */
private static String sanitizeForLog(String value) {
return value == null ? null : value.replaceAll("\\p{Cntrl}", "");
}
}
@@ -236,16 +236,10 @@ public class ApiGatewayV2OpenApiImporter {
+ enforced + " is enforced and the remaining schemes are dropped");
});
// AWS_IAM is recorded on the route because that is what AWS records, but the HTTP API
// dispatcher only enforces JWT and CUSTOM, so nothing checks the signature. Say so
// rather than let a sigv4-protected document look enforced locally.
security.stream()
.flatMap(requirement -> requirement.keySet().stream())
.filter(scheme -> "AWS_IAM".equals(bindable.get(scheme)))
.findFirst()
.ifPresent(scheme -> reported.add("Security scheme " + scheme + " on " + routeKey
+ " imports as AWS_IAM, which this emulator records but does not enforce;"
+ " requests reach the integration without a verified SigV4 signature"));
// An awsSigv4 scheme used to warn here, because dispatch recorded AWS_IAM without
// enforcing it. Dispatch now verifies the caller's SigV4 signature before the
// integration runs, so the document's guarantee holds locally and a
// warning would only make failOnWarnings reject a document Floci honours.
};
List<SecurityRequirement> globalSecurity = openAPI.getSecurity();
@@ -1825,6 +1825,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
.map(SessionCredential::getSecretAccessKey));
}
/**
* The session token issued alongside a temporary credential, for callers that must tell a
* missing token apart from one that does not match.
*
* <p>Empty means the token cannot be verified, not that any token is acceptable: the key is
* not a temporary credential, names no session Floci minted, or names a session stored before
* tokens were recorded. A caller that treats the token as required must check
* {@link #isTemporaryAccessKey(String)} separately. Where that distinction does not matter,
* {@link #findSecretKey(String, String)} resolves the secret and matches the token in one step.
*/
public Optional<String> findSessionToken(String accessKeyId) {
return currentSession(accessKeyId)
.map(SessionCredential::getSessionToken)
.filter(token -> !token.isBlank());
}
/** Whether an access key ID identifies Floci's documented public deployer credential. */
public boolean isSeededDeployerAccessKey(String accessKeyId) {
return DEFAULT_DEPLOYER_ACCESS_KEY_ID.equals(accessKeyId);
@@ -2153,7 +2169,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return Optional.empty();
}
private static boolean isTemporaryAccessKey(String accessKeyId) {
/** Temporary credentials are the ones STS mints, distinguished by the {@code ASIA} prefix. */
public static boolean isTemporaryAccessKey(String accessKeyId) {
return accessKeyId != null && accessKeyId.startsWith(TEMPORARY_ACCESS_KEY_PREFIX);
}
@@ -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();
}
}