feat(lambdaweb): verify SigV4a on IamAuth endpoints (#6956)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-29 22:00:56 -04:00
1 parent 8dbcf6bf17
commit 433989ba3b
15 files changed
+384 -77

No files matched your search

+1 -2
View File
@@ -47,7 +47,6 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A
- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.
- **Page tokens** are base64 cursors that carry the request and the position of the page, not the UUIDs AWS issues. A token reused with other parameters gets the AWS "does not match the request" error, and any other token the "invalid or has expired" error.
- **Domain names** take the form `<id>.001.lambda-web.<region>.<floci host>` and `<id>.lambda-web.global.<floci host>`, with the host and port of `floci.base-url`. A `PerRegion` endpoint gets one domain per region in `regionalEndpoints`, all with the same id, as on AWS.
- **Not implemented yet:** SigV4a on `MultiRegion` endpoints.
### `aws lambda-web deploy`
@@ -80,7 +79,7 @@ Each regional domain of a `PerRegion` endpoint is served in its own region, as o
Requests are forwarded over HTTP/1.1 with the headers AWS adds and drops: `lambda-web-request-id`, `lambda-web-endpoint-name`, `x-forwarded-proto`, `x-forwarded-port` and `Connection: close` are set, the client address is appended as an `X-Forwarded-For` line, and `Connection`, `Keep-Alive`, `Upgrade`, `Expect`, `Trailer`, the `Proxy-*` headers, `X-Real-IP`, the method override headers and any `lambda-web-*` header the client sent are dropped. A body without a `Content-Length` reaches the app chunked. The path reaches the app without dot segments, as on AWS, and repeated slashes stay. Responses carry `lambda-web-request-id` and `lambda-web-logstream`, lose their connection headers and trailers, and stream as the app writes them. Requests with two revisions in `revisionWeights` are split by weight.
An `IamAuth` endpoint takes a request signed with SigV4 for the service `lambda` in the region of the domain, in the `Authorization` header or in a presigned query. The request must carry `X-Amz-Content-SHA256`. Lambda takes its value as the payload hash and does not read the body, so `UNSIGNED-PAYLOAD` works. The signing time must be within five minutes. Floci verifies keys whose secret it holds: `test` with the secret `test`, IAM user keys and STS credentials with their session token. Any other key is refused. When `floci.services.iam.enforcement-enabled` is on, the signer also needs `lambda:InvokeWebFunctionEndpoint` on the endpoint ARN. Within one account the identity policy or the function's resource policy can allow it, and across accounts both must. `lambda:Resource/WebFunctionAuthType` and the function's tags as `aws:ResourceTag/<key>` are in the context, and `aws:RequestedRegion` is the region that serves the request, as on AWS. The `test` key is not evaluated, as elsewhere in Floci. The global domain of a `MultiRegion` endpoint takes SigV4 for the region that serves the request, as on AWS. Its SigV4a requests are refused, because Floci does not verify SigV4a yet. On every endpoint, an `Authorization` that is an AWS signature is removed before the request reaches the app, together with the `X-Amz-Security-Token` header. Other `Authorization` values pass. A presigned query reaches the app unchanged, as on AWS.
An `IamAuth` endpoint takes a request signed with SigV4 for the service `lambda` in the region of the domain, in the `Authorization` header or in a presigned query. The request must carry `X-Amz-Content-SHA256`. Lambda takes its value as the payload hash and does not read the body, so `UNSIGNED-PAYLOAD` works. The signing time must be within five minutes. Floci verifies keys whose secret it holds: `test` with the secret `test`, IAM user keys and STS credentials with their session token. Any other key is refused. When `floci.services.iam.enforcement-enabled` is on, the signer also needs `lambda:InvokeWebFunctionEndpoint` on the endpoint ARN. Within one account the identity policy or the function's resource policy can allow it, and across accounts both must. `lambda:Resource/WebFunctionAuthType` and the function's tags as `aws:ResourceTag/<key>` are in the context, and `aws:RequestedRegion` is the region that serves the request, as on AWS. The `test` key is not evaluated, as elsewhere in Floci. The global domain of a `MultiRegion` endpoint takes SigV4 for the region that serves the request, as on AWS. Every endpoint also takes SigV4a (`AWS4-ECDSA-P256-SHA256`), as AWS does, though AWS [documents it](https://docs.aws.amazon.com/lambda/latest/dg/web-functions-endpoint-access-control.html#web-functions-endpoint-access-control-signing) for `MultiRegion` endpoints only. Its region set must cover the region that serves the request. The set is read from `X-Amz-Region-Set` where the signature is: the header for a signed header, even when the header is not signed, and the query for a presigned query. It is split on commas without trimming, a set with an empty entry is refused, and each entry matches ignoring case, with `*` as the only wildcard. So `*`, `us-*` and `us-east-1,us-west-2` all cover `us-west-2`. SigV4a from temporary credentials is refused, as on AWS, while SigV4 takes them. On every endpoint, an `Authorization` that is an AWS signature is removed before the request reaches the app, together with the `X-Amz-Security-Token` header. Other `Authorization` values pass. A presigned query reaches the app unchanged, as on AWS.
The revision's `timeoutSeconds` bounds the whole exchange, as on AWS: a response that has not started by then is the 504 page, and one that is still streaming is cut. The request body is taken in full before the answer, so a slow upload gets its 504 once the body is in.
@@ -0,0 +1,41 @@
package io.github.hectorvent.floci.core.common;
/** Patterns whose only wildcard is a star. */
public final class StarWildcard {
private StarWildcard() {
}
/**
* Anchored, case-sensitive glob. Each {@code *} matches any run of characters, including an
* empty one, and every other character matches only itself. This is a scan, not a regular
* expression, so {@code .} and other metacharacters stay literal. A star retries from the last
* one only, so the work stays within the product of the two lengths however many stars the
* pattern holds. A caller that wants a case-insensitive match passes both in one case.
*/
public static boolean matches(String pattern, String value) {
int patternIndex = 0;
int valueIndex = 0;
int starPattern = -1;
int starValue = -1;
while (valueIndex < value.length()) {
if (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
starPattern = patternIndex++;
starValue = valueIndex;
} else if (patternIndex < pattern.length()
&& pattern.charAt(patternIndex) == value.charAt(valueIndex)) {
patternIndex++;
valueIndex++;
} else if (starPattern >= 0) {
patternIndex = starPattern + 1;
valueIndex = ++starValue;
} else {
return false;
}
}
while (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
patternIndex++;
}
return patternIndex == pattern.length();
}
}
@@ -14,8 +14,11 @@ public record CredentialScope(String accessKeyId, String date, String region, St
private static final String TERMINATOR = "aws4_request";
/** The scope as it is signed. A SigV4a scope has no region segment. */
public String credentialScope() {
return date + "/" + region + "/" + service + "/" + TERMINATOR;
return region == null
? date + "/" + service + "/" + TERMINATOR
: date + "/" + region + "/" + service + "/" + TERMINATOR;
}
/**
@@ -35,4 +38,22 @@ public record CredentialScope(String accessKeyId, String date, String region, St
}
return new CredentialScope(parts[0], parts[1], parts[2], parts[3].toLowerCase(Locale.ROOT));
}
/**
* A SigV4a scope, {@code accessKeyId/date/service/aws4_request}, whose region is null: the
* regions the signature is good for travel in its region set instead.
*/
public static CredentialScope parseSigV4a(String credential) {
if (credential == null) {
return null;
}
String[] parts = credential.split("/");
if (parts.length != 4 || !TERMINATOR.equals(parts[3])) {
return null;
}
if (parts[0].isBlank() || parts[1].length() != 8 || parts[2].isBlank()) {
return null;
}
return new CredentialScope(parts[0], parts[1], null, parts[2].toLowerCase(Locale.ROOT));
}
}
@@ -24,16 +24,21 @@ public record SigV4AuthorizationHeader(String credential, String signedHeaders,
* {@code X-Amz-Date} it reads from a different source than this header).
*/
public static SigV4AuthorizationHeader parse(String authorization) {
return parse(authorization, ALGORITHM);
}
/** The same parameters from a header of {@code algorithm}, such as SigV4a's. */
public static SigV4AuthorizationHeader parse(String authorization, String algorithm) {
if (authorization == null) {
return null;
}
String trimmed = authorization.trim();
if (!trimmed.regionMatches(true, 0, ALGORITHM, 0, ALGORITHM.length())) {
if (!trimmed.regionMatches(true, 0, algorithm, 0, algorithm.length())) {
return null;
}
Map<String, String> parameters = new LinkedHashMap<>();
boolean missingEqualSign = false;
for (String part : trimmed.substring(ALGORITHM.length()).split(",")) {
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());
@@ -26,13 +26,15 @@ public final class SigV4Canonicalization {
/**
* Whether {@code signature} is the one {@code secretKey} produces for this request under any of
* {@link #canonicalUriCandidates(String) the canonical URIs} a signer could have produced for
* {@code rawPath}, compared in constant time.
* {@code rawPath}, compared in constant time. A scope with no region is a SigV4a one, checked
* with {@link SigV4aSignature}.
*/
public static boolean signatureMatches(String method, String rawPath, String canonicalQueryString,
String canonicalHeaders, String signedHeaders, String payloadHash,
String amzDate, CredentialScope scope, String secretKey,
String signature) throws Exception {
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(
boolean asymmetric = scope.region() == null;
byte[] signingKey = asymmetric ? null : SigV4RequestValidator.deriveSigningKey(
secretKey, scope.date(), scope.region(), scope.service());
for (String canonicalUri : canonicalUriCandidates(rawPath)) {
String canonicalRequest = method + "\n"
@@ -41,10 +43,16 @@ public final class SigV4Canonicalization {
+ canonicalHeaders + "\n"
+ signedHeaders + "\n"
+ payloadHash;
String stringToSign = ALGORITHM + "\n"
String stringToSign = (asymmetric ? SigV4aSignature.ALGORITHM : ALGORITHM) + "\n"
+ amzDate + "\n"
+ scope.credentialScope() + "\n"
+ Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
if (asymmetric) {
if (SigV4aSignature.verify(secretKey, scope.accessKeyId(), stringToSign, signature)) {
return true;
}
continue;
}
String expected = SigV4RequestValidator.hexEncode(
SigV4RequestValidator.hmacSha256(signingKey, stringToSign));
if (MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
@@ -37,7 +37,12 @@ public record SigV4SignedRequest(String credential, String signedHeaders, String
/** The signature in an {@code Authorization} header, or null when it is not a complete SigV4 one. */
public static SigV4SignedRequest fromHeader(String authorization, String amzDate) {
SigV4AuthorizationHeader parsed = SigV4AuthorizationHeader.parse(authorization);
return fromHeader(authorization, amzDate, ALGORITHM);
}
/** The signature in an {@code Authorization} header of {@code algorithm}, or null when it is not complete. */
public static SigV4SignedRequest fromHeader(String authorization, String amzDate, String algorithm) {
SigV4AuthorizationHeader parsed = SigV4AuthorizationHeader.parse(authorization, algorithm);
if (parsed == null || isBlank(parsed.credential()) || isBlank(parsed.signedHeaders())
|| isBlank(parsed.signature()) || isBlank(amzDate)) {
return null;
@@ -5,12 +5,14 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.common.StarWildcard;
import io.github.hectorvent.floci.core.common.auth.CredentialScope;
import io.github.hectorvent.floci.core.common.auth.SessionTokenCheck;
import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest;
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest.Freshness;
import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
@@ -34,16 +36,19 @@ import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
/**
* The checks an {@code IamAuth} endpoint makes before a request reaches the function: a SigV4
* signature for the service {@code lambda} in the endpoint's region, then
* {@code lambda:InvokeWebFunctionEndpoint} on the endpoint ARN. The signature is always checked.
* signature for the service {@code lambda} in the endpoint's region, or a SigV4a one whose region
* set covers it, then {@code lambda:InvokeWebFunctionEndpoint} on the endpoint ARN. The signature
* is always checked.
* The policies are evaluated when IAM enforcement is on, as everywhere else in Floci.
*
* <p>CloudFront signs for a distribution under an {@code always-amz-auth} origin access control.
@@ -57,6 +62,7 @@ public class LambdaWebIamAuth {
private static final Logger LOG = Logger.getLogger(LambdaWebIamAuth.class);
private static final String SERVICE = "lambda";
private static final String SECURITY_TOKEN = "X-Amz-Security-Token";
private static final String REGION_SET = "X-Amz-Region-Set";
private static final String TEST_ACCESS_KEY = "test";
private static final String CLOUDFRONT_SOURCE_ARN = "lambda-web-cloudfront-source-arn";
private static final String CLOUDFRONT_KEY = "lambda-web-cloudfront-key";
@@ -99,8 +105,8 @@ public class LambdaWebIamAuth {
}
}
/** A signature and the session token that came with it. */
private record Signed(SigV4SignedRequest request, String sessionToken) {
/** A signature and the session token and, for SigV4a, the region set that came with it. */
private record Signed(SigV4SignedRequest request, String sessionToken, boolean asymmetric, String regionSet) {
}
/**
@@ -158,13 +164,19 @@ public class LambdaWebIamAuth {
return null;
}
SigV4SignedRequest signed = found.request();
CredentialScope scope = CredentialScope.parse(signed.credential());
if (scope == null || !SERVICE.equals(scope.service()) || !region.equals(scope.region())
CredentialScope scope = found.asymmetric()
? CredentialScope.parseSigV4a(signed.credential()) : CredentialScope.parse(signed.credential());
if (scope == null || !SERVICE.equals(scope.service())
|| !(found.asymmetric() ? regionSetCovers(found.regionSet(), region) : region.equals(scope.region()))
|| !signed.amzDate().startsWith(scope.date())
|| !SigV4RequestValidator.containsHeader(signed.signedHeaders(), "host")
|| signed.freshness(Instant.now()) != Freshness.FRESH) {
return null;
}
// AWS refuses SigV4a from temporary credentials, which it takes in SigV4.
if (found.asymmetric() && IamService.isTemporaryAccessKey(scope.accessKeyId())) {
return null;
}
String secretKey = secretKey(scope.accessKeyId(), found.sessionToken());
if (secretKey == null) {
LOG.debugv("A request to a Lambda Web endpoint names an unknown access key {0}",
@@ -213,20 +225,48 @@ public class LambdaWebIamAuth {
/**
* The header signature, or the presigned query when there is no {@code Authorization} header.
* The header wins over the query, as on AWS.
* The header wins over the query, as on AWS. The session token and the region set are read
* from where the signature is.
*/
private static Signed signed(Inbound request) {
String authorization = request.headers().get("Authorization");
if (isBlank(authorization)) {
MultiMap params = request.params();
if (!SigV4SignedRequest.ALGORITHM.equals(params.get("X-Amz-Algorithm"))) {
String algorithm = params.get("X-Amz-Algorithm");
boolean asymmetric = SigV4aSignature.ALGORITHM.equals(algorithm);
if (!asymmetric && !SigV4SignedRequest.ALGORITHM.equals(algorithm)) {
return null;
}
SigV4SignedRequest presigned = SigV4SignedRequest.fromQuery(params::get);
return presigned == null ? null : new Signed(presigned, params.get(SECURITY_TOKEN));
return presigned == null ? null
: new Signed(presigned, params.get(SECURITY_TOKEN), asymmetric, params.get(REGION_SET));
}
SigV4SignedRequest header = SigV4SignedRequest.fromHeader(authorization, request.headers().get("X-Amz-Date"));
return header == null ? null : new Signed(header, request.headers().get(SECURITY_TOKEN));
String amzDate = request.headers().get("X-Amz-Date");
SigV4SignedRequest header = SigV4SignedRequest.fromHeader(authorization, amzDate);
if (header != null) {
return new Signed(header, request.headers().get(SECURITY_TOKEN), false, null);
}
SigV4SignedRequest asymmetric = SigV4SignedRequest.fromHeader(authorization, amzDate,
SigV4aSignature.ALGORITHM);
return asymmetric == null ? null : new Signed(asymmetric, request.headers().get(SECURITY_TOKEN), true,
request.headers().get(REGION_SET));
}
/**
* Whether a SigV4a region set covers {@code region}. AWS splits it on commas without trimming,
* refuses a set with an empty entry, and matches each entry ignoring case with {@code *} as the
* only wildcard.
*/
static boolean regionSetCovers(String regionSet, String region) {
if (regionSet == null) {
return false;
}
List<String> entries = Arrays.asList(regionSet.split(",", -1));
if (entries.contains("")) {
return false;
}
String lowerRegion = region.toLowerCase(Locale.ROOT);
return entries.stream().anyMatch(entry -> StarWildcard.matches(entry.toLowerCase(Locale.ROOT), lowerRegion));
}
/**
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.common.SsrfProtection;
import io.github.hectorvent.floci.core.common.StarWildcard;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
@@ -2132,7 +2133,7 @@ public class SnsService implements Resettable, ResourceProvider {
case "prefix" -> value.startsWith(expected);
case "suffix" -> value.endsWith(expected);
case "equals-ignore-case" -> value.equalsIgnoreCase(expected);
case "wildcard" -> wildcardMatches(expected, value);
case "wildcard" -> StarWildcard.matches(expected, value);
case "cidr" -> cidrContains(expected, value);
default -> false;
};
@@ -2178,37 +2179,6 @@ public class SnsService implements Resettable, ResourceProvider {
return matched.isPresent() && !matched.get();
}
/**
* Anchored, case-sensitive glob. Each {@code *} matches any run of characters, including an
* empty one, and every other character matches only itself. This is a scan, not a regular
* expression, so {@code .} and other metacharacters stay literal.
*/
private static boolean wildcardMatches(String pattern, String value) {
int patternIndex = 0;
int valueIndex = 0;
int starPattern = -1;
int starValue = -1;
while (valueIndex < value.length()) {
if (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
starPattern = patternIndex++;
starValue = valueIndex;
} else if (patternIndex < pattern.length()
&& pattern.charAt(patternIndex) == value.charAt(valueIndex)) {
patternIndex++;
valueIndex++;
} else if (starPattern >= 0) {
patternIndex = starPattern + 1;
valueIndex = ++starValue;
} else {
return false;
}
}
while (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
patternIndex++;
}
return patternIndex == pattern.length();
}
/**
* True when {@code value} is a literal IP in the same address family as {@code cidr} and the
* two share the prefix bits. Host bits in the CIDR address are masked off. A zone id, a prefix
@@ -0,0 +1,31 @@
package io.github.hectorvent.floci.core.common.auth;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class CredentialScopeTest {
@Test
void aSigV4ScopeNamesItsRegion() {
CredentialScope scope = CredentialScope.parse("AKIDEXAMPLE/20261017/us-east-1/Lambda/aws4_request");
assertEquals("us-east-1", scope.region());
assertEquals("lambda", scope.service());
assertEquals("20261017/us-east-1/lambda/aws4_request", scope.credentialScope());
assertNull(CredentialScope.parse("AKIDEXAMPLE/20261017/lambda/aws4_request"));
}
@Test
void aSigV4aScopeHasNoRegion() {
CredentialScope scope = CredentialScope.parseSigV4a("AKIDEXAMPLE/20261017/Lambda/aws4_request");
assertEquals("AKIDEXAMPLE", scope.accessKeyId());
assertNull(scope.region());
assertEquals("lambda", scope.service());
assertEquals("20261017/lambda/aws4_request", scope.credentialScope());
assertNull(CredentialScope.parseSigV4a("AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request"));
assertNull(CredentialScope.parseSigV4a("AKIDEXAMPLE/2026101/lambda/aws4_request"));
assertNull(CredentialScope.parseSigV4a("AKIDEXAMPLE/20261017/lambda/aws4"));
assertNull(CredentialScope.parseSigV4a(null));
}
}
@@ -37,6 +37,18 @@ class SigV4SignedRequestTest {
+ " SignedHeaders=host", "20261017T120000Z"));
}
@Test
void aSigV4aHeaderIsReadOnlyForItsOwnAlgorithm() {
String authorization = "AWS4-ECDSA-P256-SHA256 Credential=AKIDEXAMPLE/20261017/lambda/aws4_request,"
+ " SignedHeaders=host;x-amz-date;x-amz-region-set, Signature=3044";
assertNull(SigV4SignedRequest.fromHeader(authorization, "20261017T120000Z"));
SigV4SignedRequest signed = SigV4SignedRequest.fromHeader(authorization, "20261017T120000Z",
SigV4aSignature.ALGORITHM);
assertEquals("AKIDEXAMPLE/20261017/lambda/aws4_request", signed.credential());
assertEquals("host;x-amz-date;x-amz-region-set", signed.signedHeaders());
assertNull(SigV4SignedRequest.fromHeader(AUTHORIZATION, "20261017T120000Z", SigV4aSignature.ALGORITHM));
}
@Test
void thePresignedSignatureNeedsEveryPartAndKeepsAnExpiryItCannotRead() {
Map<String, String> query = presigned(NOW, "300");
@@ -371,6 +371,14 @@ class LambdaWebDataPlaneDockerIntegrationTest {
.when().get(presigned.pathAndQuery())
.then().statusCode(200)
.body("url", equalTo(presigned.pathAndQuery()));
// SigV4a for a region set that covers the region passes, and loses its signature the same way.
LambdaWebRequestSigner.Signed asymmetric = new LambdaWebRequestSigner().sigV4a("us-*").sign("GET", domain, "/a");
given().header("Host", domain).headers(asymmetric.headers())
.when().get("/a")
.then().statusCode(200)
.body("headers.authorization", nullValue())
.body("headers.x-amz-region-set", equalTo("us-*"));
}
@Test
@@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -28,6 +29,7 @@ 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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -41,6 +43,7 @@ class LambdaWebIamAuthTest {
private static final String OTHER_ACCOUNT = "222222222222";
private static final String HOST = "abcdefghijklmnop.001.lambda-web.us-east-1.localhost:4566";
private static final String WEST_HOST = "abcdefghijklmnop.001.lambda-web.us-west-2.localhost:4566";
private static final String GLOBAL_HOST = "abcdefghijklmnop.lambda-web.global.localhost:4566";
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":web-function/app";
private static final String ENDPOINT_ARN = FUNCTION_ARN + "/endpoint/prod";
private static final String USER_KEY = "AKIAUSERKEY000000001";
@@ -132,6 +135,59 @@ class LambdaWebIamAuthTest {
assertFalse(allows(signer().sign("GET", WEST_HOST, "/"), WEST_HOST, "us-west-2"));
}
@Test
void sigV4aPassesOnEveryEndpointWhenItsRegionSetCoversTheRegionThatServes() {
assertTrue(allows(signer().sigV4a("*").sign("GET", HOST, "/items?b=2&a=1")));
assertTrue(allows(signer().sigV4a("*").presigned().sign("GET", HOST, "/q?x=1")));
assertTrue(allows(signer().sigV4a("us-*").sign("GET", WEST_HOST, "/"), WEST_HOST, "us-west-2"));
assertTrue(allows(signer().sigV4a("us-west-2").sign("GET", GLOBAL_HOST, "/"), GLOBAL_HOST, "us-west-2"));
assertFalse(allows(signer().sigV4a("us-east-1").sign("GET", GLOBAL_HOST, "/"), GLOBAL_HOST, "us-west-2"));
assertFalse(allows(signer().sigV4a("us-east-1").presigned().sign("GET", GLOBAL_HOST, "/"),
GLOBAL_HOST, "us-west-2"));
assertFalse(allows(signer().sigV4a("*").service("execute-api").sign("GET", HOST, "/")));
assertFalse(allows(signer().sigV4a("*").credentials("test", "other", null).sign("GET", HOST, "/")));
assertFalse(allows(signer().sigV4a("*").sign("GET", HOST, "/").withHeader("X-Amz-Content-SHA256", null)));
assertFalse(allows(signer().sigV4a("*").signedAt(Instant.now().minus(Duration.ofMinutes(6)))
.sign("GET", HOST, "/")));
}
@Test
void aRegionSetIsCommaSeparatedPatternsWhereOnlyAStarIsAWildcard() {
for (String covering : List.of("*", "**", "us-*", "*-west-2", "us-*-2", "u*-w*-2", "us-west-2*", "US-WEST-2",
"us-east-1,us-west-2", "us-west-2, us-east-1", "eu-*,us-west-*")) {
assertTrue(LambdaWebIamAuth.regionSetCovers(covering, "us-west-2"), covering);
}
for (String other : Arrays.asList(null, "", "us-east-1", "us-east-*", "us-west-?", "us-west", "us-west-2a",
"aws-global", "us-west-2;us-east-1", "us-east-1, us-west-2", "us-west-2,", ",us-west-2")) {
assertFalse(LambdaWebIamAuth.regionSetCovers(other, "us-west-2"), other);
}
String manyStars = "*".repeat(5000) + "Z";
assertFalse(assertTimeoutPreemptively(Duration.ofSeconds(1),
() -> LambdaWebIamAuth.regionSetCovers(manyStars, "us-west-2")));
}
@Test
void theRegionSetIsReadFromWhereTheSignatureIs() {
assertTrue(allows(signer().sigV4a("*").sign("GET", GLOBAL_HOST, "/q?X-Amz-Region-Set=us-east-1"),
GLOBAL_HOST, "us-west-2"));
assertFalse(allows(signer().sigV4a("us-east-1").sign("GET", GLOBAL_HOST, "/q?X-Amz-Region-Set=us-west-2"),
GLOBAL_HOST, "us-west-2"));
assertTrue(allows(signer().sigV4a("*").presigned().sign("GET", GLOBAL_HOST, "/")
.withHeader("X-Amz-Region-Set", "us-east-1"), GLOBAL_HOST, "us-west-2"));
assertFalse(allows(signer().sigV4a("us-east-1").presigned().sign("GET", GLOBAL_HOST, "/")
.withHeader("X-Amz-Region-Set", "*"), GLOBAL_HOST, "us-west-2"));
}
@Test
void sigV4aFromTemporaryCredentialsIsRefused() {
assertTrue(allows(signer().credentials(SESSION_KEY, "session-secret", "token").sign("GET", HOST, "/")));
assertFalse(allows(signer().credentials(SESSION_KEY, "session-secret", "token").sigV4a("*")
.sign("GET", HOST, "/")));
assertFalse(allows(signer().credentials(SESSION_KEY, "session-secret", "token").sigV4a("*").presigned()
.sign("GET", HOST, "/")));
assertTrue(allows(signer().credentials(USER_KEY, USER_SECRET, null).sigV4a("*").sign("GET", HOST, "/")));
}
@Test
void theSigningTimeMustBeWithinFiveMinutes() {
Instant now = Instant.now();
@@ -1,5 +1,8 @@
package io.github.hectorvent.floci.services.lambdaweb;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
import io.github.hectorvent.floci.testutil.SigV4aSigning;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
@@ -10,17 +13,25 @@ import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/** Signs a request to a Lambda Web endpoint with the AWS SDK signer, as a client would. */
final class LambdaWebRequestSigner {
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
/** What goes on the wire: the method, the path with its query, and the headers to add. */
record Signed(String method, String pathAndQuery, Map<String, String> headers) {
@@ -48,6 +59,7 @@ final class LambdaWebRequestSigner {
private boolean presigned;
private boolean normalizePath = true;
private String contentSha256 = "UNSIGNED-PAYLOAD";
private String regionSet;
LambdaWebRequestSigner credentials(String accessKeyId, String secretKey, String sessionToken) {
this.accessKeyId = accessKeyId;
@@ -88,7 +100,16 @@ final class LambdaWebRequestSigner {
return this;
}
/** Signs with SigV4a for {@code regionSet} instead of SigV4 for the region. */
LambdaWebRequestSigner sigV4a(String regionSet) {
this.regionSet = regionSet;
return this;
}
Signed sign(String method, String host, String pathAndQuery) {
if (regionSet != null) {
return signV4a(method, host, pathAndQuery);
}
URI uri = URI.create("http://" + host + pathAndQuery);
SdkHttpFullRequest.Builder builder = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.fromValue(method))
@@ -121,4 +142,71 @@ final class LambdaWebRequestSigner {
String query = signed.encodedQueryParameters().map(encoded -> "?" + encoded).orElse("");
return new Signed(method, signed.encodedPath() + query, headers);
}
/**
* A SigV4a signature built by hand, since the SDK signs SigV4a only through aws-crt. It takes a
* path without dot segments or escapes and a query of plain names and values.
*/
private Signed signV4a(String method, String host, String pathAndQuery) {
URI uri = URI.create("http://" + host + pathAndQuery);
String path = uri.getRawPath().isEmpty() ? "/" : uri.getRawPath();
String amzDate = AMZ_DATE.format(signedAt);
String scope = amzDate.substring(0, 8) + "/" + service + "/aws4_request";
Map<String, String> query = new TreeMap<>();
if (uri.getRawQuery() != null) {
for (String pair : uri.getRawQuery().split("&")) {
int equals = pair.indexOf('=');
query.put(equals < 0 ? pair : pair.substring(0, equals), equals < 0 ? "" : pair.substring(equals + 1));
}
}
Map<String, String> signedHeaders = new TreeMap<>(Map.of("host", host));
Map<String, String> headers = new LinkedHashMap<>();
if (presigned) {
query.put("X-Amz-Algorithm", SigV4aSignature.ALGORITHM);
query.put("X-Amz-Credential", encode(accessKeyId + "/" + scope));
query.put("X-Amz-Date", amzDate);
query.put("X-Amz-Expires", "300");
query.put("X-Amz-Region-Set", encode(regionSet));
query.put("X-Amz-SignedHeaders", "host");
if (sessionToken != null) {
query.put("X-Amz-Security-Token", encode(sessionToken));
}
} else {
signedHeaders.put("x-amz-date", amzDate);
signedHeaders.put("x-amz-region-set", regionSet);
headers.put("X-Amz-Date", amzDate);
headers.put("X-Amz-Region-Set", regionSet);
if (contentSha256 != null) {
signedHeaders.put("x-amz-content-sha256", contentSha256);
}
if (sessionToken != null) {
signedHeaders.put("x-amz-security-token", sessionToken);
headers.put("X-Amz-Security-Token", sessionToken);
}
}
String canonicalQuery = query.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
String names = String.join(";", signedHeaders.keySet());
String canonicalRequest = method + "\n" + path + "\n" + canonicalQuery + "\n"
+ signedHeaders.entrySet().stream().map(entry -> entry.getKey() + ":" + entry.getValue() + "\n")
.collect(Collectors.joining())
+ "\n" + names + "\n" + (contentSha256 == null ? "UNSIGNED-PAYLOAD" : contentSha256);
String signature = SigV4aSigning.sign(accessKeyId, secretKey, SigV4aSignature.ALGORITHM + "\n" + amzDate
+ "\n" + scope + "\n" + Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8)));
if (contentSha256 != null) {
headers.put("X-Amz-Content-SHA256", contentSha256);
}
if (presigned) {
return new Signed(method, path + "?" + canonicalQuery + "&X-Amz-Signature=" + signature, headers);
}
headers.put("Authorization", SigV4aSignature.ALGORITHM + " Credential=" + accessKeyId + "/" + scope
+ ", SignedHeaders=" + names + ", Signature=" + signature);
return new Signed(method, pathAndQuery, headers);
}
private static String encode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
}
}
@@ -7,18 +7,8 @@ import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.ec.CustomNamedCurves;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.util.encoders.Hex;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
@@ -42,9 +32,6 @@ public final class S3SigV4aRequestSigner implements Filter {
private static final String SERVICE = "s3";
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private static final X9ECParameters CURVE = CustomNamedCurves.getByName("secp256r1");
private static final ECDomainParameters DOMAIN = new ECDomainParameters(
CURVE.getCurve(), CURVE.getG(), CURVE.getN(), CURVE.getH());
private final String accessKeyId;
private final String secretKey;
@@ -155,18 +142,7 @@ public final class S3SigV4aRequestSigner implements Filter {
String stringToSign = SigV4aSignature.ALGORITHM + "\n" + amzDate + "\n"
+ scopeDate + "/" + SERVICE + "/aws4_request\n"
+ Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
BigInteger privateScalar = SigV4aSignature.derivePrivateScalar(secretKey, accessKeyId);
ECDSASigner signer = new ECDSASigner();
signer.init(true, new ECPrivateKeyParameters(privateScalar, DOMAIN));
BigInteger[] rs = signer.generateSignature(Digests.sha256(stringToSign.getBytes(StandardCharsets.UTF_8)));
ASN1EncodableVector sequence = new ASN1EncodableVector();
sequence.add(new ASN1Integer(rs[0]));
sequence.add(new ASN1Integer(rs[1]));
try {
return Hex.toHexString(new DERSequence(sequence).getEncoded());
} catch (IOException e) {
throw new IllegalStateException("could not encode the signature", e);
}
return SigV4aSigning.sign(accessKeyId, secretKey, stringToSign);
}
private static String rawPath(URI uri) {
@@ -0,0 +1,47 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.ec.CustomNamedCurves;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.util.encoders.Hex;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
/**
* Signs a SigV4A string to sign the way a client does: a DER-encoded ECDSA P-256 signature, hex
* encoded, by the key pair derived from the secret. Shared by the test signers of the services
* that take SigV4A.
*/
public final class SigV4aSigning {
private static final X9ECParameters CURVE = CustomNamedCurves.getByName("secp256r1");
private static final ECDomainParameters DOMAIN = new ECDomainParameters(
CURVE.getCurve(), CURVE.getG(), CURVE.getN(), CURVE.getH());
private SigV4aSigning() {
}
public static String sign(String accessKeyId, String secretKey, String stringToSign) {
BigInteger privateScalar = SigV4aSignature.derivePrivateScalar(secretKey, accessKeyId);
ECDSASigner signer = new ECDSASigner();
signer.init(true, new ECPrivateKeyParameters(privateScalar, DOMAIN));
BigInteger[] rs = signer.generateSignature(Digests.sha256(stringToSign.getBytes(StandardCharsets.UTF_8)));
ASN1EncodableVector sequence = new ASN1EncodableVector();
sequence.add(new ASN1Integer(rs[0]));
sequence.add(new ASN1Integer(rs[1]));
try {
return Hex.toHexString(new DERSequence(sequence).getEncoded());
} catch (IOException e) {
throw new IllegalStateException("could not encode the signature", e);
}
}
}