Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(s3): verify SigV4A (AWS4-ECDSA-P256-SHA256) request signatures (#6092)

Vũ Thế Huy6355474ad290
diff --git a/docs/services/s3.md b/docs/services/s3.md
index 37b44abc68..ebd4cab94d 100644
--- a/docs/services/s3.md
+++ b/docs/services/s3.md
@@ -343,7 +343,8 @@ For a signed request, verification rebuilds the canonical request from the wire
- temporary credentials past their expiry, sent with their own session token, with `400 ExpiredToken`, whichever placement carries the signature. Once Floci has removed an expired session it no longer knows the key, and answers as for one that is not registered
- a header-signed request more than 15 minutes from server time, with `403 RequestTimeTooSkewed`
- a body that does not match a declared `x-amz-content-sha256` digest, with `400 XAmzContentSHA256Mismatch`
-- an `Authorization` header whose algorithm is not `AWS4-HMAC-SHA256`, with `400 AuthorizationHeaderMalformed`. This includes SigV4A (`AWS4-ECDSA-P256-SHA256`), which AWS accepts, for example on multi-region access points: Floci does not verify ECDSA signatures yet, so it refuses the request instead of serving it unverified
+- an `Authorization` header whose algorithm is neither `AWS4-HMAC-SHA256` nor `AWS4-ECDSA-P256-SHA256` (SigV4A), with `400 AuthorizationHeaderMalformed`
+- a SigV4A request, which is verified the way AWS does it: Floci derives the ECDSA P-256 key pair from the access key's secret and checks the signature against the public half. The `Authorization` header and a presigned URL (`X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256`) are both verified. Its credential scope has no region, so the request must sign the region set: a header request without a signed `x-amz-region-set` is `400 AuthorizationHeaderMalformed`, and a presigned URL without `X-Amz-Region-Set` is `400 AuthorizationQueryParametersError`. A set naming one region serves that region, and a wildcard or a list serves the default region. Floci does not check the set against the bucket's region. A browser POST signed with SigV4A is not accepted
- a presigned URL that carries any of `X-Amz-Algorithm`, `X-Amz-Credential` or `X-Amz-Signature` but lacks one of `X-Amz-Algorithm`, `X-Amz-Credential`, `X-Amz-Signature`, `X-Amz-Date`, `X-Amz-SignedHeaders` or `X-Amz-Expires`, with `400 AuthorizationQueryParametersError`
`FLOCI_AUTH_VALIDATE_SIGNATURES` is authentication alone: use it when forged or stale credentials must fail but buckets should stay reachable without policies. It is not specific to S3: the same flag verifies the `Authorization` header signature of every other service (see [Signature Validation](../configuration/multi-account.md#signature-validation)). `FLOCI_SERVICES_S3_ENFORCE_AUTH` adds authorization, so it also decides anonymous access the way AWS does: a bucket that anonymous clients read needs a public-read bucket policy or ACL.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
index 62485aaf28..2947ffc7d0 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
import io.github.hectorvent.floci.services.s3.PreSignedUrlFilter;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
@@ -85,7 +86,11 @@ public class AccountContextFilter implements ContainerRequestFilter {
requestContext.setAccountId(resolveAccount(akid, accountResolver.resolve(auth)));
requestContext.setAccessKeyId(akid);
requestContext.setSessionToken(sessionToken);
- String region = regionResolver.resolveRegionFromAuth(auth);
+ // A SigV4A scope has no region segment; the regions come from the signed region set.
+ boolean sigV4a = auth.trim().startsWith(SigV4aSignature.ALGORITHM + " ");
+ String region = sigV4a
+ ? regionResolver.resolveRegionFromRegionSet(ctx.getHeaderString("X-Amz-Region-Set"))
+ : regionResolver.resolveRegionFromAuth(auth);
applyRegion(region);
if (rejectUnknownRegion(ctx, region, SigV4CredentialScope.serviceName(auth))) {
return;
@@ -104,7 +109,12 @@ public class AccountContextFilter implements ContainerRequestFilter {
resolveAccount(presignedAkid, accountResolver.resolveFromPresignedCredential(credential)));
requestContext.setAccessKeyId(presignedAkid);
requestContext.setSessionToken(sessionToken);
- String region = regionResolver.resolveRegionFromPresignedCredential(credential);
+ boolean sigV4a = SigV4aSignature.ALGORITHM.equals(
+ ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Algorithm"));
+ String region = sigV4a
+ ? regionResolver.resolveRegionFromRegionSet(
+ ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Region-Set"))
+ : regionResolver.resolveRegionFromPresignedCredential(credential);
applyRegion(region);
if (rejectUnknownRegion(ctx, region, SigV4CredentialScope.serviceNameFromCredential(credential))) {
return;
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index 31c2d42849..b772fffa18 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -90,10 +90,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(IamEnforcementFilter.class);
- /** Extracts the credential-scope service name (e.g. "s3", "lambda"). */
- private static final Pattern SERVICE_PATTERN =
- Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
-
/** AWS's wording for a credential it does not recognise. */
private static final String INVALID_SECURITY_TOKEN = "The security token included in the request is invalid.";
@@ -842,9 +838,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* maps to an action: AppSync, CodeArtifact's package endpoints, Identity Store's SCIM endpoint
* and API Gateway's authorizers take Bearer and Basic tokens of their own, and this filter
* cannot tell the API Gateway execute path, Lambda function URLs and the other paths it sees
- * that are unsigned by design from the rest. A SigV4a scope, which has no region segment, does
- * not get here: {@link AccountContextFilter} reads its service name as the region and refuses
- * it, unless unknown regions are allowed.
+ * that are unsigned by design from the rest. A SigV4a scope has no region segment; every
+ * service takes its region from the signed set (see {@link AccountContextFilter}), and the
+ * shared {@link SigV4HeaderSignatureFilter} turns non-S3 ones away when signature validation is on.
*/
private void refuseUnreadableCredential(ContainerRequestContext ctx, String auth) {
if (ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
@@ -1556,8 +1552,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
private String extractCredentialScope(String auth) {
- Matcher m = SERVICE_PATTERN.matcher(auth);
- return m.find() ? m.group(1) : null;
+ return SigV4CredentialScope.serviceName(auth).orElse(null);
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java
index b285f74f55..18f9b06fc1 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.enterprise.inject.Instance;
@@ -83,7 +84,12 @@ public class RegionResolver {
if (headers == null) {
return defaultRegion;
}
- return resolveRegionFromAuth(headers.getHeaderString("Authorization"));
+ String authorization = headers.getHeaderString("Authorization");
+ if (authorization != null
+ && authorization.trim().startsWith(SigV4aSignature.ALGORITHM + " ")) {
+ return resolveRegionFromRegionSet(headers.getHeaderString("X-Amz-Region-Set"));
+ }
+ return resolveRegionFromAuth(authorization);
}
/**
@@ -151,6 +157,27 @@ public class RegionResolver {
}
+ /**
+ * The region a SigV4A ({@code AWS4-ECDSA-P256-SHA256}) request is served in. Its credential
+ * scope names no region; the signed {@code X-Amz-Region-Set} lists the ones the signature is
+ * good for. A set of exactly one concrete region selects it. A wildcard, a list, or no set
+ * leaves the choice to the server, which serves the default region.
+ */
+ public String resolveRegionFromRegionSet(String regionSet) {
+ if (regionSet == null || regionSet.isBlank()) {
+ return defaultRegion;
+ }
+ String[] regions = regionSet.split(",", -1);
+ if (regions.length != 1) {
+ return defaultRegion;
+ }
+ String only = regions[0].trim();
+ if (only.isEmpty() || only.contains("*")) {
+ return defaultRegion;
+ }
+ return withoutPseudoRegion(only);
+ }
+
/**
* Resolves the region from a SigV4 Authorization credential scope, or
* null when the header is absent or carries no parseable credential —
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java b/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java
index 5c110b21db..5571541c9a 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java
@@ -12,7 +12,11 @@ import java.util.regex.Pattern;
*/
public final class SigV4CredentialScope {
- private static final Pattern SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
+ private static final Pattern SERVICE_PATTERN =
+ Pattern.compile("Credential=[^,\\s]+/\\d{8}/[^/,\\s]+/([^/,\\s]+)/aws4_request");
+ // SigV4A drops the region segment: Credential=<key>/<date>/<service>/aws4_request
+ private static final Pattern SIGV4A_SERVICE_PATTERN =
+ Pattern.compile("Credential=[^,\\s]+/\\d{8}/([^/,\\s]+)/aws4_request");
private static final Pattern ACCESS_KEY_PATTERN = Pattern.compile("Credential=([^/\\s,]+)/");
private SigV4CredentialScope() {
@@ -26,7 +30,8 @@ public final class SigV4CredentialScope {
if (matcher.find()) {
return Optional.of(matcher.group(1).toLowerCase(Locale.ROOT));
}
- return Optional.empty();
+ Matcher sigV4a = SIGV4A_SERVICE_PATTERN.matcher(authorization);
+ return sigV4a.find() ? Optional.of(sigV4a.group(1).toLowerCase(Locale.ROOT)) : Optional.empty();
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java
index 41a6e5ffa8..9b5cf1dbe4 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.auth.CredentialScope;
import io.github.hectorvent.floci.core.common.auth.SigV4AuthorizationHeader;
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.SigV4aSignature;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayAwsExecuteController;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayExecuteController;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayUserRequestController;
@@ -162,6 +163,10 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
signed = new SigV4AuthorizationHeader(query.getFirst("X-Amz-Credential"),
query.getFirst("X-Amz-SignedHeaders"), query.getFirst("X-Amz-Signature"), false);
} else {
+ if (authorization != null && authorization.trim().startsWith(SigV4aSignature.ALGORITHM + " ")) {
+ incompleteSignature(ctx, resource, "The authorization mechanism you have provided is not supported.");
+ return;
+ }
signed = SigV4AuthorizationHeader.parse(authorization);
if (signed == null) {
return;
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4aSignature.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4aSignature.java
new file mode 100644
index 0000000000..de566f558c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4aSignature.java
@@ -0,0 +1,112 @@
+package io.github.hectorvent.floci.core.common.auth;
+
+import io.github.hectorvent.floci.core.common.Digests;
+import org.bouncycastle.asn1.ASN1Integer;
+import org.bouncycastle.asn1.ASN1Sequence;
+import org.bouncycastle.asn1.x9.X9ECParameters;
+import org.bouncycastle.crypto.ec.CustomNamedCurves;
+import org.bouncycastle.crypto.params.ECDomainParameters;
+import org.bouncycastle.crypto.params.ECPublicKeyParameters;
+import org.bouncycastle.crypto.signers.ECDSASigner;
+import org.bouncycastle.math.ec.ECPoint;
+import org.bouncycastle.util.encoders.DecoderException;
+import org.bouncycastle.util.encoders.Hex;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.util.Locale;
+
+/**
+ * Verification of a SigV4A ({@code AWS4-ECDSA-P256-SHA256}) signature.
+ *
+ * <p>SigV4A signs with an ECDSA P-256 key pair derived from the caller's secret access key, so
+ * a service that holds the secret derives the same pair and checks the signature against the
+ * public half. The derivation is the NIST SP 800-108 counter-mode KDF over HMAC-SHA256 that the
+ * IAM User Guide describes: the input key is {@code "AWS4A" + secretKey}, the fixed input is
+ * {@code 0x00000001 || "AWS4-ECDSA-P256-SHA256" || 0x00 || accessKeyId || counter || 0x00000100},
+ * and the first counter (from 1 to 254) whose output is at most {@code N - 2} yields the private
+ * scalar {@code output + 1}. The signature is the DER-encoded ECDSA signature over the SHA-256 of
+ * the string to sign, hex encoded.
+ */
+public final class SigV4aSignature {
+
+ public static final String ALGORITHM = "AWS4-ECDSA-P256-SHA256";
+
+ private static final String KDF_LABEL = "AWS4-ECDSA-P256-SHA256";
+ private static final int MAX_COUNTER = 254;
+ private static final X9ECParameters CURVE = CustomNamedCurves.getByName("secp256r1");
+ private static final ECDomainParameters DOMAIN = new ECDomainParameters(
+ CURVE.getCurve(), CURVE.getG(), CURVE.getN(), CURVE.getH());
+
+ private SigV4aSignature() {
+ }
+
+ /**
+ * Whether {@code signatureHex} is a valid SigV4A signature of {@code stringToSign} by the key
+ * pair derived from {@code secretKey} and {@code accessKeyId}. Malformed hex or DER is simply
+ * not a match.
+ */
+ public static boolean verify(String secretKey, String accessKeyId, String stringToSign,
+ String signatureHex) {
+ BigInteger[] rs = decodeSignature(signatureHex);
+ if (rs == null) {
+ return false;
+ }
+ BigInteger privateScalar = derivePrivateScalar(secretKey, accessKeyId);
+ ECPoint publicPoint = DOMAIN.getG().multiply(privateScalar).normalize();
+ ECDSASigner verifier = new ECDSASigner();
+ verifier.init(false, new ECPublicKeyParameters(publicPoint, DOMAIN));
+ byte[] digest = Digests.sha256(stringToSign.getBytes(StandardCharsets.UTF_8));
+ return verifier.verifySignature(digest, rs[0], rs[1]);
+ }
+
+ /** The P-256 private scalar the KDF derives for a secret and access key id. */
+ public static BigInteger derivePrivateScalar(String secretKey, String accessKeyId) {
+ byte[] inputKey = ("AWS4A" + secretKey).getBytes(StandardCharsets.UTF_8);
+ byte[] label = KDF_LABEL.getBytes(StandardCharsets.UTF_8);
+ byte[] accessKey = accessKeyId.getBytes(StandardCharsets.UTF_8);
+ BigInteger limit = CURVE.getN().subtract(BigInteger.TWO);
+ for (int counter = 1; counter <= MAX_COUNTER; counter++) {
+ ByteBuffer fixedInput = ByteBuffer.allocate(4 + label.length + 1 + accessKey.length + 1 + 4);
+ fixedInput.putInt(1).put(label).put((byte) 0).put(accessKey).put((byte) counter).putInt(256);
+ BigInteger candidate = new BigInteger(1, hmacSha256(inputKey, fixedInput.array()));
+ if (candidate.compareTo(limit) <= 0) {
+ return candidate.add(BigInteger.ONE);
+ }
+ }
+ throw new IllegalStateException("SigV4A key derivation found no candidate in " + MAX_COUNTER + " rounds");
+ }
+
+ private static BigInteger[] decodeSignature(String signatureHex) {
+ if (signatureHex == null || signatureHex.isEmpty()) {
+ return null;
+ }
+ try {
+ ASN1Sequence sequence = ASN1Sequence.getInstance(Hex.decode(signatureHex.toLowerCase(Locale.ROOT)));
+ if (sequence.size() != 2) {
+ return null;
+ }
+ return new BigInteger[] {
+ ASN1Integer.getInstance(sequence.getObjectAt(0)).getPositiveValue(),
+ ASN1Integer.getInstance(sequence.getObjectAt(1)).getPositiveValue()
+ };
+ } catch (DecoderException | IllegalArgumentException expected) {
+ // Non-hex or non-DER input is a bad signature from the caller, not a server fault.
+ return null;
+ }
+ }
+
+ private static byte[] hmacSha256(byte[] key, byte[] data) {
+ try {
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(new SecretKeySpec(key, "HmacSHA256"));
+ return mac.doFinal(data);
+ } catch (GeneralSecurityException e) {
+ throw new IllegalStateException("HmacSHA256 is unavailable", e);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java
index c3c68f6f4e..4254e1268e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
+import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
import io.github.hectorvent.floci.services.iam.IamService;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import jakarta.annotation.Priority;
@@ -118,7 +119,8 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
return;
}
- if (!"AWS4-HMAC-SHA256".equals(algorithm)) {
+ boolean asymmetric = SigV4aSignature.ALGORITHM.equals(algorithm);
+ if (!asymmetric && !"AWS4-HMAC-SHA256".equals(algorithm)) {
requestContext.abortWith(
errorResponse(
400,
@@ -178,7 +180,7 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
String credential = queryParams.getFirst("X-Amz-Credential");
String decodedCredential = URLDecoder.decode(credential, StandardCharsets.UTF_8);
String[] credParts = decodedCredential.split("/");
- if (credParts.length < 5) {
+ if (credParts.length < (asymmetric ? 4 : 5)) {
if (authEnforced || generatedCredential) {
requestContext.abortWith(errorResponse(403, "InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records."));
@@ -209,7 +211,7 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
}
}
- if (authEnforced || generatedCredential) {
+ if (authEnforced || generatedCredential || asymmetric) {
requestContext.abortWith(errorResponse(403, "InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records."));
return;
@@ -255,13 +257,17 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
String decodedCredential = URLDecoder.decode(credential, StandardCharsets.UTF_8);
String[] credParts = decodedCredential.split("/");
- if (credParts.length < 5) {
+ boolean asymmetric = SigV4aSignature.ALGORITHM.equals(queryParams.getFirst("X-Amz-Algorithm"));
+ if (credParts.length < (asymmetric ? 4 : 5)) {
return false;
}
+ // A SigV4A scope is <akid>/<date>/<service>/aws4_request, with no region segment.
String date = credParts[1];
- String region = credParts[2];
- String service = credParts[3];
- String credentialScope = date + "/" + region + "/" + service + "/aws4_request";
+ String region = asymmetric ? null : credParts[2];
+ String service = asymmetric ? credParts[2] : credParts[3];
+ String credentialScope = asymmetric
+ ? date + "/" + service + "/aws4_request"
+ : date + "/" + region + "/" + service + "/aws4_request";
// Build canonical headers from signed headers
URI requestUri = requestContext.getProperty(S3VirtualHostFilter.ORIGINAL_REQUEST_URI_PROPERTY) instanceof URI uri
@@ -285,6 +291,12 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
requestContext.getMethod(), path, canonicalQueryString, signedHeaders,
header -> "host".equals(header) ? authority : requestContext.getHeaderString(header),
payloadHash);
+ if (asymmetric) {
+ return SigV4aSignature.verify(secretKey, credParts[0],
+ S3PresignedCanonicalRequest.stringToSign(
+ SigV4aSignature.ALGORITHM, amzDate, credentialScope, canonicalRequest),
+ signature);
+ }
String stringToSign = S3PresignedCanonicalRequest.stringToSign(
amzDate, credentialScope, canonicalRequest);
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
index 46b24ee608..501d4fe7fd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilter.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
+import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
import io.github.hectorvent.floci.services.iam.IamService;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.ext.web.RoutingContext;
@@ -25,6 +26,8 @@ import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
+import java.util.LinkedHashMap;
+import java.util.Map;
import java.util.Optional;
/**
@@ -41,6 +44,11 @@ import java.util.Optional;
* {@code STREAMING-*} sentinel, the body is hashed too, so a signed request cannot be replayed
* with a different payload.
*
+ * <p>A SigV4A ({@code AWS4-ECDSA-P256-SHA256}) header is verified over the same canonical request,
+ * with the region-less scope {@code <date>/s3/aws4_request} and the signed {@code x-amz-region-set}
+ * header, by checking its ECDSA signature against the key pair derived from the secret
+ * ({@link SigV4aSignature}).
+ *
* <p>Error codes, statuses and ordering follow real S3: a structurally bad header is
* {@code 400 AuthorizationHeaderMalformed}; a request with no date is {@code 403 AccessDenied};
* a missing {@code x-amz-content-sha256} is {@code 400 InvalidRequest}; an unregistered key is
@@ -79,6 +87,7 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
private static final String ALGORITHM = "AWS4-HMAC-SHA256";
private static final String SIGNING_SERVICE = "s3";
private static final String TERMINATOR = "aws4_request";
+ private static final String REGION_SET_HEADER = "x-amz-region-set";
private static final Duration MAX_CLOCK_SKEW = Duration.ofMinutes(15);
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
@@ -119,37 +128,51 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
if (authorization == null || authorization.isBlank()) {
return;
}
- if (!authorization.startsWith(ALGORITHM + " ")) {
+ boolean asymmetric = authorization.startsWith(SigV4aSignature.ALGORITHM + " ");
+ if (!asymmetric && !authorization.startsWith(ALGORITHM + " ")) {
abort(ctx, 400, "AuthorizationHeaderMalformed",
"The authorization header you provided is invalid.");
return;
}
- String credential = component(authorization, "Credential");
- String signedHeaders = component(authorization, "SignedHeaders");
- String signature = component(authorization, "Signature");
- if (credential == null || signedHeaders == null || signature == null) {
+ Map<String, String> components = parseComponents(authorization);
+ String credential = components != null ? components.get("Credential") : null;
+ String signedHeaders = components != null ? components.get("SignedHeaders") : null;
+ String signature = components != null ? components.get("Signature") : null;
+ if (components == null || credential == null || signedHeaders == null || signature == null) {
abort(ctx, 400, "AuthorizationHeaderMalformed", "The authorization header is malformed; "
+ "the authorization header requires three components: "
+ "Credential, SignedHeaders, and Signature.");
return;
}
+ // A SigV4A scope names no region: the regions the signature is good for travel in the
+ // signed x-amz-region-set header instead.
String[] scope = credential.split("/");
- if (scope.length != 5 || !TERMINATOR.equals(scope[4])) {
+ int terminatorIndex = asymmetric ? 3 : 4;
+ if (scope.length != terminatorIndex + 1 || !TERMINATOR.equals(scope[terminatorIndex])) {
abort(ctx, 400, "AuthorizationHeaderMalformed", "The authorization header is malformed; "
+ "the Credential is mal-formed; expecting "
- + "\"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".");
+ + (asymmetric ? "\"<YOUR-AKID>/YYYYMMDD/SERVICE/aws4_request\"."
+ : "\"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\"."));
return;
}
String accessKeyId = scope[0];
String scopeDate = scope[1];
- String region = scope[2];
- if (!SIGNING_SERVICE.equals(scope[3])) {
+ String region = asymmetric ? null : scope[2];
+ String scopeService = scope[terminatorIndex - 1];
+ if (!SIGNING_SERVICE.equals(scopeService)) {
abort(ctx, 400, "AuthorizationHeaderMalformed", "The authorization header is malformed; "
- + "incorrect service \"" + scope[3] + "\". This endpoint belongs to \""
+ + "incorrect service \"" + scopeService + "\". This endpoint belongs to \""
+ SIGNING_SERVICE + "\".");
return;
}
+ if (asymmetric && (!SigV4RequestValidator.containsHeader(signedHeaders, REGION_SET_HEADER)
+ || isBlank(ctx.getHeaderString(REGION_SET_HEADER)))) {
+ abort(ctx, 400, "AuthorizationHeaderMalformed", "The authorization header is malformed; "
+ + "a " + SigV4aSignature.ALGORITHM + " request must sign the "
+ + REGION_SET_HEADER + " header.");
+ return;
+ }
Instant requestTime = requestTime(ctx);
if (requestTime == null) {
@@ -192,7 +215,8 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
boolean matches;
try {
matches = SigV4RequestValidator.containsHeader(signedHeaders, "host") && signatureMatches(
- ctx, secretKey.get(), scopeDate, region, amzDate, signedHeaders, declaredHash, signature);
+ ctx, accessKeyId, secretKey.get(), scopeDate, region, amzDate, signedHeaders,
+ declaredHash, signature);
} catch (Exception e) {
LOG.debugv(e, "S3 header SigV4 verification failed to complete for accessKey={0}", accessKeyId);
matches = false;
@@ -209,8 +233,9 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
}
}
- private boolean signatureMatches(ContainerRequestContext ctx, String secretKey, String scopeDate,
- String region, String amzDate, String signedHeaders,
+ /** A {@code null} {@code region} marks a SigV4A request, whose scope has no region segment. */
+ private boolean signatureMatches(ContainerRequestContext ctx, String accessKeyId, String secretKey,
+ String scopeDate, String region, String amzDate, String signedHeaders,
String payloadHash, String signature) throws Exception {
URI requestUri = ctx.getProperty(S3VirtualHostFilter.ORIGINAL_REQUEST_URI_PROPERTY) instanceof URI uri
? uri
@@ -231,6 +256,13 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
+ canonicalHeaders + "\n"
+ signedHeaders + "\n"
+ payloadHash;
+ if (region == null) {
+ String stringToSign = SigV4aSignature.ALGORITHM + "\n"
+ + amzDate + "\n"
+ + scopeDate + "/" + SIGNING_SERVICE + "/" + TERMINATOR + "\n"
+ + Digests.sha256Hex(canonicalRequest);
+ return SigV4aSignature.verify(secretKey, accessKeyId, stringToSign, signature);
+ }
String stringToSign = ALGORITHM + "\n"
+ amzDate + "\n"
+ scopeDate + "/" + region + "/" + SIGNING_SERVICE + "/" + TERMINATOR + "\n"
@@ -298,17 +330,31 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
return null;
}
- /** The value of one {@code Name=value} component of a SigV4 {@code Authorization} header. */
- private static String component(String authorization, String name) {
- String parameters = authorization.substring(ALGORITHM.length() + 1);
+ /** Parses the {@code Name=value} components of a SigV4 {@code Authorization} header. */
+ private static Map<String, String> parseComponents(String authorization) {
+ int space = authorization.indexOf(' ');
+ if (space < 0) {
+ return null;
+ }
+ String parameters = authorization.substring(space + 1).trim();
+ Map<String, String> components = new LinkedHashMap<>();
for (String part : parameters.split(",")) {
String trimmed = part.trim();
- if (trimmed.startsWith(name + "=")) {
- String value = trimmed.substring(name.length() + 1).trim();
- return value.isEmpty() ? null : value;
+ int eq = trimmed.indexOf('=');
+ if (eq <= 0) {
+ return null;
+ }
+ String name = trimmed.substring(0, eq).trim();
+ String value = trimmed.substring(eq + 1).trim();
+ if (value.isEmpty() || components.putIfAbsent(name, value) != null) {
+ return null;
}
}
- return null;
+ return components;
+ }
+
+ private static boolean isBlank(String value) {
+ return value == null || value.isBlank();
}
private static void abort(ContainerRequestContext ctx, int status, String code, String message) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3PresignedCanonicalRequest.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3PresignedCanonicalRequest.java
index 575c755b4f..d5fcf142d2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3PresignedCanonicalRequest.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3PresignedCanonicalRequest.java
@@ -23,7 +23,12 @@ final class S3PresignedCanonicalRequest {
}
static String stringToSign(String amzDate, String credentialScope, String canonicalRequest) throws Exception {
- return "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
+ return stringToSign("AWS4-HMAC-SHA256", amzDate, credentialScope, canonicalRequest);
+ }
+
+ static String stringToSign(String algorithm, String amzDate, String credentialScope,
+ String canonicalRequest) throws Exception {
+ return algorithm + "\n" + amzDate + "\n" + credentialScope + "\n"
+ Digests.sha256Hex(canonicalRequest);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParser.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParser.java
index 9b95a41456..4060f5de04 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParser.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParser.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.UriInfo;
@@ -95,25 +96,28 @@ final class S3RequestAuthorizationParser {
private static String extractAuthorizationHeaderAccessKeyId(String authorization) {
String trimmed = authorization.trim();
- if (!trimmed.startsWith(SIGV4_ALGORITHM + " ")) {
+ boolean asymmetric = trimmed.startsWith(SigV4aSignature.ALGORITHM + " ");
+ if (!asymmetric && !trimmed.startsWith(SIGV4_ALGORITHM + " ")) {
return null;
}
- Map<String, String> parameters = authorizationParameters(trimmed.substring(SIGV4_ALGORITHM.length()).trim());
+ Map<String, String> parameters = authorizationParameters(trimmed.substring(trimmed.indexOf(' ')).trim());
if (isBlank(parameters.get("SignedHeaders")) || isBlank(parameters.get("Signature"))) {
return null;
}
- return extractCredentialAccessKeyId(parameters.get("Credential"));
+ return extractCredentialAccessKeyId(parameters.get("Credential"), asymmetric);
}
private static String extractPresignedAccessKeyId(MultivaluedMap<String, String> queryParameters) {
- if (!SIGV4_ALGORITHM.equals(queryParameters.getFirst("X-Amz-Algorithm"))) {
+ String algorithm = queryParameters.getFirst("X-Amz-Algorithm");
+ boolean asymmetric = SigV4aSignature.ALGORITHM.equals(algorithm);
+ if (!asymmetric && !SIGV4_ALGORITHM.equals(algorithm)) {
return null;
}
if (isMissingRequiredPresignedParameter(queryParameters)) {
return null;
}
- return extractCredentialAccessKeyId(queryParameters.getFirst("X-Amz-Credential"));
+ return extractCredentialAccessKeyId(queryParameters.getFirst("X-Amz-Credential"), asymmetric);
}
static boolean isMissingRequiredPresignedParameter(MultivaluedMap<String, String> queryParameters) {
@@ -122,7 +126,8 @@ final class S3RequestAuthorizationParser {
return true;
}
}
- return false;
+ return SigV4aSignature.ALGORITHM.equals(queryParameters.getFirst("X-Amz-Algorithm"))
+ && isBlank(queryParameters.getFirst("X-Amz-Region-Set"));
}
private static Map<String, String> authorizationParameters(String parameters) {
@@ -130,25 +135,31 @@ final class S3RequestAuthorizationParser {
for (String part : parameters.split(",")) {
int equals = part.indexOf('=');
if (equals <= 0) {
- continue;
+ return Map.of();
+ }
+ String key = part.substring(0, equals).trim();
+ String value = part.substring(equals + 1).trim();
+ if (parsed.putIfAbsent(key, value) != null) {
+ return Map.of();
}
- parsed.put(part.substring(0, equals).trim(), part.substring(equals + 1).trim());
}
return parsed;
}
- private static String extractCredentialAccessKeyId(String credential) {
+ /** A SigV4A scope drops the region segment: {@code <akid>/<date>/s3/aws4_request}. */
+ private static String extractCredentialAccessKeyId(String credential, boolean asymmetric) {
if (isBlank(credential)) {
return null;
}
String[] parts = credential.split("/", -1);
- if (parts.length != 5) {
+ int serviceIndex = asymmetric ? 2 : 3;
+ if (parts.length != serviceIndex + 2) {
return null;
}
- if (parts[0].isBlank() || !isEightDigitDate(parts[1]) || parts[2].isBlank()) {
+ if (parts[0].isBlank() || !isEightDigitDate(parts[1]) || (!asymmetric && parts[2].isBlank())) {
return null;
}
- if (!"s3".equals(parts[3]) || !"aws4_request".equals(parts[4])) {
+ if (!"s3".equals(parts[serviceIndex]) || !"aws4_request".equals(parts[serviceIndex + 1])) {
return null;
}
return parts[0];
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
index 44ca35d68c..e3ec1a336a 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
@@ -26,6 +26,7 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.BeforeEach;
@@ -187,6 +188,88 @@ class IamEnforcementFilterTest {
verify(arnBuilder).buildResources("lambda", containerRequest, "us-east-1", "222233334444");
}
+ @Test
+ void filterAcceptsSigV4aCredentialScope() {
+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
+
+ String auth = "AWS4-ECDSA-P256-SHA256 Credential=ASIAP256KEY/20260629/s3/aws4_request, "
+ + "SignedHeaders=host, Signature=abc";
+ requestContext.setAccountId("222233334444");
+ requestContext.setRegion("us-east-1");
+
+ when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIAP256KEY");
+ when(accountResolver.resolve(auth)).thenReturn("000000000000");
+ when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
+ when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
+ when(iamService.resolveCallerContext(eq("ASIAP256KEY"), any()))
+ .thenReturn(CallerContext.of(List.of("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:GetObject",
+ "Resource":"arn:aws:s3:::mybucket/obj"}
+ ]}""")));
+ when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ .thenReturn(List.of("arn:aws:s3:::mybucket/obj"));
+ when(evaluator.evaluateResolvedResourcePolicy(
+ any(),
+ eq(ResourcePolicyDecision.NEUTRAL),
+ eq(ResourceAccountRelationship.SAME_ACCOUNT),
+ eq("s3:GetObject"),
+ eq("arn:aws:s3:::mybucket/obj"),
+ any()))
+ .thenReturn(IamPolicyEvaluator.Decision.ALLOW);
+ when(conditionContextResolver.resolve("s3", "s3:GetObject", containerRequest))
+ .thenReturn(null);
+
+ IamEnforcementFilter filter = newFilter();
+
+ filter.filter(containerRequest);
+
+ verify(containerRequest, never()).abortWith(any());
+ verify(evaluator).evaluateResolvedResourcePolicy(
+ any(), any(), any(), eq("s3:GetObject"), eq("arn:aws:s3:::mybucket/obj"), any());
+ }
+
+ @Test
+ void filterAcceptsSigV4aPresignedCredentialScope() {
+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
+ UriInfo uriInfo = mock(UriInfo.class);
+ MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
+ query.add("X-Amz-Algorithm", "AWS4-ECDSA-P256-SHA256");
+ query.add("X-Amz-Credential", "ASIAP256KEY/20260629/s3/aws4_request");
+ when(containerRequest.getUriInfo()).thenReturn(uriInfo);
+ when(uriInfo.getQueryParameters()).thenReturn(query);
+
+ String synthesizedAuth = "Credential=ASIAP256KEY/20260629/s3/aws4_request";
+ requestContext.setAccountId("222233334444");
+ requestContext.setRegion("us-east-1");
+
+ when(accountResolver.extractAccessKeyId(synthesizedAuth)).thenReturn("ASIAP256KEY");
+ when(accountResolver.resolve(synthesizedAuth)).thenReturn("000000000000");
+ when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
+ when(iamService.resolveCallerContext(eq("ASIAP256KEY"), any()))
+ .thenReturn(CallerContext.of(List.of("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"s3:GetObject",
+ "Resource":"arn:aws:s3:::mybucket/obj"}
+ ]}""")));
+ when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ .thenReturn(List.of("arn:aws:s3:::mybucket/obj"));
+ when(evaluator.evaluateResolvedResourcePolicy(
+ any(),
+ eq(ResourcePolicyDecision.NEUTRAL),
+ eq(ResourceAccountRelationship.SAME_ACCOUNT),
+ eq("s3:GetObject"),
+ eq("arn:aws:s3:::mybucket/obj"),
+ isNull()))
+ .thenReturn(IamPolicyEvaluator.Decision.ALLOW);
+
+ IamEnforcementFilter filter = newFilter();
+
+ filter.filter(containerRequest);
+
+ verify(containerRequest, never()).abortWith(any());
+ }
+
@Test
void jsonProtocolActionComesFromTheTargetNotTheSignedScope() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RegionResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RegionResolverTest.java
index 44aa114182..1eab8c6cf5 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/RegionResolverTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/RegionResolverTest.java
@@ -28,6 +28,32 @@ class RegionResolverTest {
assertEquals("us-west-2", resolver.resolveRegion(headers));
}
+ @Test
+ void sigV4aRegionSetOfOneRegionSelectsIt() {
+ assertEquals("eu-west-1", resolver.resolveRegionFromRegionSet("eu-west-1"));
+ assertEquals("eu-west-1", resolver.resolveRegionFromRegionSet(" eu-west-1 "));
+ }
+
+ @Test
+ void sigV4aWildcardListOrMissingRegionSetServesTheDefaultRegion() {
+ assertEquals("us-east-1", resolver.resolveRegionFromRegionSet("*"));
+ assertEquals("us-east-1", resolver.resolveRegionFromRegionSet("eu-*"));
+ assertEquals("us-east-1", resolver.resolveRegionFromRegionSet("eu-west-1,us-west-2"));
+ assertEquals("us-east-1", resolver.resolveRegionFromRegionSet(""));
+ assertEquals("us-east-1", resolver.resolveRegionFromRegionSet(null));
+ assertEquals("us-east-1", resolver.resolveRegionFromRegionSet(","));
+ assertEquals("us-east-1", resolver.resolveRegionFromRegionSet(",,"));
+ assertEquals("us-east-1", resolver.resolveRegionFromRegionSet(" , , "));
+ }
+
+ @Test
+ void sigV4aAuthorizationResolvesFromRegionSet() {
+ HttpHeaders headers = stubHeaders(
+ "AWS4-ECDSA-P256-SHA256 Credential=AKID/20260215/sqs/aws4_request, SignedHeaders=host, Signature=abc",
+ "eu-west-1");
+ assertEquals("eu-west-1", resolver.resolveRegion(headers));
+ }
+
@Test
void resolveRegionFromDifferentRegion() {
HttpHeaders headers = stubHeaders(
@@ -291,15 +317,23 @@ class RegionResolverTest {
}
private static HttpHeaders stubHeaders(String authorizationValue) {
+ return stubHeaders(authorizationValue, null);
+ }
+
+ private static HttpHeaders stubHeaders(String authorizationValue, String regionSetValue) {
return new HttpHeaders() {
@Override public List<String> getRequestHeader(String name) {
if ("Authorization".equalsIgnoreCase(name) && authorizationValue != null) {
return List.of(authorizationValue);
}
+ if ("X-Amz-Region-Set".equalsIgnoreCase(name) && regionSetValue != null) {
+ return List.of(regionSetValue);
+ }
return List.of();
}
@Override public String getHeaderString(String name) {
if ("Authorization".equalsIgnoreCase(name)) return authorizationValue;
+ if ("X-Amz-Region-Set".equalsIgnoreCase(name)) return regionSetValue;
return null;
}
@Override public MultivaluedMap<String, String> getRequestHeaders() { return new MultivaluedHashMap<>(); }
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SigV4CredentialScopeTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SigV4CredentialScopeTest.java
index 1cdf5c34ad..121b8883be 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/SigV4CredentialScopeTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/SigV4CredentialScopeTest.java
@@ -34,12 +34,29 @@ class SigV4CredentialScopeTest {
}
@Test
- void ignoresSigV4aBecauseItsCredentialOmitsTheRegion() {
+ void readsTheServiceOfASigV4aCredentialThatOmitsTheRegion() {
// SigV4a carries the region in X-Amz-Region-Set, so its credential is
- // <key>/<date>/<service>/aws4_request — one segment shorter than SigV4.
- assertTrue(SigV4CredentialScope.serviceName(
+ // <key>/<date>/<service>/aws4_request, one segment shorter than SigV4.
+ assertEquals(Optional.of("s3"), SigV4CredentialScope.serviceName(
"AWS4-ECDSA-P256-SHA256 Credential=AKID/20260707/s3/aws4_request,"
- + " SignedHeaders=host;x-amz-region-set, Signature=deadbeef").isEmpty());
+ + " SignedHeaders=host;x-amz-region-set, Signature=deadbeef"));
+ assertEquals(Optional.of("s3"), SigV4CredentialScope.serviceNameFromCredential(
+ "AKID/20260707/s3/aws4_request"));
+ }
+
+ @Test
+ void parsesNestedCredentials() {
+ assertEquals(Optional.of("monitoring"), SigV4CredentialScope.serviceName(
+ "AWS4-HMAC-SHA256 Credential=AKID/20261015/us-east-1/20261015/eu-west-1/monitoring/aws4_request,"
+ + " SignedHeaders=host, Signature=deadbeef"));
+ }
+
+ @Test
+ void parsesFirstCredentialWhenDuplicateCredentialComponentsPresent() {
+ assertEquals(Optional.of("s3"), SigV4CredentialScope.serviceName(
+ "AWS4-ECDSA-P256-SHA256 Credential=test/20260101/s3/aws4_request, "
+ + "SignedHeaders=host;x-amz-date;x-amz-region-set, Signature=3006020101020101, "
+ + "Credential=test2/20260101/s3/aws4_request"));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java
index 582fe6c53d..57b41a1acb 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java
@@ -103,6 +103,24 @@ class SigV4HeaderSignatureIntegrationTest {
.body("__type", equalTo("InvalidSignatureException"));
}
+ @Test
+ void sigV4aHeaderToNonS3ServiceIsRefused() {
+ given()
+ .header("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=test/20260101/sqs/aws4_request, "
+ + "SignedHeaders=content-type;host;x-amz-date;x-amz-region-set;x-amz-target, "
+ + "Signature=3006020101020101")
+ .header("X-Amz-Region-Set", "us-east-1")
+ .header("X-Amz-Date", "20260101T000000Z")
+ .contentType(JSON_1_0)
+ .header("X-Amz-Target", "AmazonSQS.ListQueues")
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("IncompleteSignatureException"));
+ }
+
@Test
@Order(3)
void queryRequestWithTheWrongSecretIsRefusedInXml() {
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/auth/SigV4aSignatureTest.java b/src/test/java/io/github/hectorvent/floci/core/common/auth/SigV4aSignatureTest.java
new file mode 100644
index 0000000000..b292683fa8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/auth/SigV4aSignatureTest.java
@@ -0,0 +1,94 @@
+package io.github.hectorvent.floci.core.common.auth;
+
+import io.github.hectorvent.floci.core.common.Digests;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The signatures below were produced by aws-crt 0.38.0 ({@code aws_sign_request} with
+ * {@code V4_ASYMMETRIC}), the signer botocore and the Java SDK use for SigV4A, so a pass shows the
+ * key derivation and the ECDSA check agree with a real client rather than with this class.
+ */
+class SigV4aSignatureTest {
+
+ private static final String ACCESS_KEY = "AKIDEXAMPLE";
+ private static final String SECRET_KEY = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
+
+ private static final String HEADER_SIGNATURE =
+ "3046022100ec92e3c742fbe8094521b20b589ae7dfc1a6c5fc2d3523b7fdeee15f198b63400221009f5650d65aad41ea98a8436959e99de1092f36397ce451d4f71cc4bd9d8e7e81";
+ private static final String QUERY_SIGNATURE =
+ "3044022056e9132df415ef4f4baa299e3bbee5ea6ec30c13001774bd081d7b93933880160220342a98931bb4ff05da584e7dafa82dc772a4c3f1a21c2e4cabf3fc13799561c6";
+
+ private static String headerStringToSign() {
+ String canonicalRequest = "GET\n/bucket/key.txt\nx=1\n"
+ + "host:localhost:4566\nx-amz-content-sha256:UNSIGNED-PAYLOAD\n"
+ + "x-amz-date:20261020T120000Z\nx-amz-region-set:*\n\n"
+ + "host;x-amz-content-sha256;x-amz-date;x-amz-region-set\nUNSIGNED-PAYLOAD";
+ return stringToSign(canonicalRequest);
+ }
+
+ private static String queryStringToSign() {
+ String canonicalRequest = "GET\n/bucket/key.txt\n"
+ + "X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256"
+ + "&X-Amz-Credential=AKIDEXAMPLE%2F20261020%2Fs3%2Faws4_request"
+ + "&X-Amz-Date=20261020T120000Z&X-Amz-Expires=900"
+ + "&X-Amz-Region-Set=us-east-1%2Ceu-west-1&X-Amz-SignedHeaders=host\n"
+ + "host:localhost:4566\n\nhost\nUNSIGNED-PAYLOAD";
+ return stringToSign(canonicalRequest);
+ }
+
+ private static String stringToSign(String canonicalRequest) {
+ return "AWS4-ECDSA-P256-SHA256\n20261020T120000Z\n20261020/s3/aws4_request\n"
+ + Digests.sha256Hex(canonicalRequest);
+ }
+
+ @Test
+ void verifiesAnAuthorizationHeaderSignatureFromAwsCrt() {
+ assertTrue(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, headerStringToSign(), HEADER_SIGNATURE));
+ }
+
+ @Test
+ void verifiesAPresignedQuerySignatureFromAwsCrt() {
+ assertTrue(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, queryStringToSign(), QUERY_SIGNATURE));
+ }
+
+ @Test
+ void acceptsAnUpperCaseHexSignature() {
+ assertTrue(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, headerStringToSign(),
+ HEADER_SIGNATURE.toUpperCase()));
+ }
+
+ @Test
+ void rejectsAWrongSecret() {
+ assertFalse(SigV4aSignature.verify("another-secret", ACCESS_KEY, headerStringToSign(), HEADER_SIGNATURE));
+ }
+
+ @Test
+ void rejectsAWrongAccessKeyBecauseTheKeyPairIsBoundToIt() {
+ assertFalse(SigV4aSignature.verify(SECRET_KEY, "AKIDOTHER", headerStringToSign(), HEADER_SIGNATURE));
+ }
+
+ @Test
+ void rejectsATamperedStringToSign() {
+ assertFalse(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY,
+ headerStringToSign().replace("20261020T120000Z", "20261020T120001Z"), HEADER_SIGNATURE));
+ }
+
+ @Test
+ void rejectsASignatureThatIsNotHexDerOrIsTruncated() {
+ assertFalse(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, headerStringToSign(), "not-hex"));
+ assertFalse(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, headerStringToSign(), "3046"));
+ assertFalse(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, headerStringToSign(), ""));
+ assertFalse(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, headerStringToSign(), null));
+ assertFalse(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, headerStringToSign(),
+ HEADER_SIGNATURE.substring(0, HEADER_SIGNATURE.length() - 2)));
+ }
+
+ @Test
+ void rejectsAnHmacSigV4Signature() {
+ assertFalse(SigV4aSignature.verify(SECRET_KEY, ACCESS_KEY, headerStringToSign(),
+ "5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilterTest.java
index 811fb63232..b3b6d549ce 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3HeaderSignatureFilterTest.java
@@ -107,7 +107,7 @@ class S3HeaderSignatureFilterTest {
}
@Test
- void abortsSigV4AAuthorizationHeaderWhenValidationEnabled() throws IOException {
+ void abortsSigV4AAuthorizationHeaderWhoseScopeStillCarriesARegion() throws IOException {
when(ctx.getHeaderString("Authorization"))
.thenReturn("AWS4-ECDSA-P256-SHA256 Credential=111122223333/20261001/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=abc");
@@ -119,6 +119,23 @@ class S3HeaderSignatureFilterTest {
assertEquals(400, response.getStatus());
String entity = (String) response.getEntity();
assertTrue(entity.contains("<Code>AuthorizationHeaderMalformed</Code>"), entity);
- assertTrue(entity.contains("The authorization header you provided is invalid."), entity);
+ assertTrue(entity.contains("YYYYMMDD/SERVICE/aws4_request"), entity);
+ }
+
+ @Test
+ void abortsWhenAuthorizationHeaderContainsDuplicateComponent() throws IOException {
+ when(ctx.getHeaderString("Authorization"))
+ .thenReturn("AWS4-HMAC-SHA256 Credential=AKID/20261001/us-east-1/s3/aws4_request, "
+ + "SignedHeaders=host, Signature=abc, "
+ + "Credential=AKID2/20261001/us-east-1/s3/aws4_request");
+
+ filter.filter(ctx);
+
+ ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
+ verify(ctx).abortWith(captor.capture());
+ Response response = captor.getValue();
+ assertEquals(400, response.getStatus());
+ String entity = (String) response.getEntity();
+ assertTrue(entity.contains("<Code>AuthorizationHeaderMalformed</Code>"), entity);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParserTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParserTest.java
index 4b99b2c88e..8d816715e1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParserTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParserTest.java
@@ -142,6 +142,61 @@ class S3RequestAuthorizationParserTest {
assertTrue(S3RequestAuthorizationParser.isSigned(null, query));
}
+ @Test
+ void parsesSigV4aAuthorizationHeaderAccessKeyFromARegionlessScope() {
+ S3Service.RequestAuthorization authorization = parse(
+ "AWS4-ECDSA-P256-SHA256 Credential=AKIDEXAMPLE/20260702/s3/aws4_request, "
+ + "SignedHeaders=host;x-amz-region-set, Signature=test", query());
+
+ assertTrue(authorization.signed());
+ assertEquals("AKIDEXAMPLE", authorization.accessKeyId());
+ }
+
+ @Test
+ void rejectsASigV4aHeaderWhoseScopeStillCarriesARegion() {
+ assertThrows(AwsException.class, () -> parse(
+ "AWS4-ECDSA-P256-SHA256 Credential=AKIDEXAMPLE/20260702/us-east-1/s3/aws4_request, "
+ + "SignedHeaders=host, Signature=test", query()));
+ }
+
+ @Test
+ void parsesSigV4aPresignedQueryAccessKey() {
+ MultivaluedMap<String, String> query = sigV4aPresignedQuery();
+
+ assertEquals("AKIDEXAMPLE", parse(null, query).accessKeyId());
+ }
+
+ @Test
+ void rejectsASigV4aPresignedQueryWithoutARegionSet() {
+ MultivaluedMap<String, String> query = sigV4aPresignedQuery();
+ query.remove("X-Amz-Region-Set");
+
+ assertThrows(AwsException.class, () -> parse(null, query));
+ }
+
+ @Test
+ void rejectsAuthorizationHeaderWithDuplicateCredentialComponent() {
+ String authorization = "AWS4-HMAC-SHA256 Credential=KEY1/20260702/us-east-1/s3/aws4_request, "
+ + "SignedHeaders=host, Signature=test, "
+ + "Credential=KEY2/20260702/us-east-1/s3/aws4_request";
+
+ AwsException e = assertThrows(AwsException.class, () -> parse(authorization, query()));
+ assertEquals("AuthorizationHeaderMalformed", e.getErrorCode());
+ assertEquals(400, e.getHttpStatus());
+ }
+
+ private static MultivaluedMap<String, String> sigV4aPresignedQuery() {
+ MultivaluedMap<String, String> query = query();
+ query.add("X-Amz-Algorithm", "AWS4-ECDSA-P256-SHA256");
+ query.add("X-Amz-Credential", "AKIDEXAMPLE/20260702/s3/aws4_request");
+ query.add("X-Amz-Date", "20260702T120000Z");
+ query.add("X-Amz-Expires", "3600");
+ query.add("X-Amz-Region-Set", "*");
+ query.add("X-Amz-SignedHeaders", "host");
+ query.add("X-Amz-Signature", "test");
+ return query;
+ }
+
private static S3Service.RequestAuthorization parse(String authorization, MultivaluedMap<String, String> query) {
return S3RequestAuthorizationParser.parse(authorization, query);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3SigV4aIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3SigV4aIntegrationTest.java
new file mode 100644
index 0000000000..e3d0ebca55
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3SigV4aIntegrationTest.java
@@ -0,0 +1,163 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
+import io.github.hectorvent.floci.testutil.S3SigV4aRequestSigner;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.RestAssured;
+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.URI;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * With {@code floci.auth.validate-signatures} on, an S3 request signed with SigV4A
+ * ({@code AWS4-ECDSA-P256-SHA256}) is served when its signature verifies and refused, with S3's
+ * own error codes, when it does not, in both the {@code Authorization} header and a presigned URL.
+ */
+@QuarkusTest
+@TestProfile(ValidateSignaturesProfile.class)
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class S3SigV4aIntegrationTest {
+
+ private static final String BUCKET = "sigv4a-bucket";
+ private static final String KEY = "object.txt";
+ private static final String PATH = "/" + BUCKET + "/" + KEY;
+ private static final S3SigV4aRequestSigner SIGNER = S3SigV4aRequestSigner.signedAs("test", "test");
+
+ private static URI uri(String path) {
+ return URI.create("http://localhost:" + RestAssured.port + path);
+ }
+
+ @Test
+ @Order(1)
+ void headerSignedRequestsForAllRegionsAreServed() {
+ given().filter(SIGNER).when().put("/" + BUCKET).then().statusCode(200);
+ given().filter(SIGNER).body("sigv4a body").when().put(PATH).then().statusCode(200);
+ given().filter(SIGNER).when().get(PATH).then().statusCode(200).body(equalTo("sigv4a body"));
+ }
+
+ @Test
+ @Order(2)
+ void headerSignedRequestForOneRegionIsServed() {
+ given().filter(SIGNER.forRegions("us-east-1")).when().get(PATH).then()
+ .statusCode(200).body(equalTo("sigv4a body"));
+ }
+
+ @Test
+ @Order(3)
+ void headerSignedRequestForAListOfRegionsIsServed() {
+ given().filter(SIGNER.forRegions("us-east-1,eu-west-1")).when().get(PATH).then()
+ .statusCode(200).body(equalTo("sigv4a body"));
+ }
+
+ @Test
+ @Order(4)
+ void headerSignedQueryParametersAreCovered() {
+ given().filter(SIGNER).when().get("/" + BUCKET + "?list-type=2&prefix=obj").then()
+ .statusCode(200).body("ListBucketResult.KeyCount", equalTo("1"));
+ }
+
+ @Test
+ @Order(5)
+ void headerSignatureThatDoesNotVerifyIsRejected() {
+ given().filter(SIGNER.withSignature("3006020101020101")).when().get(PATH).then()
+ .statusCode(403).body("Error.Code", equalTo("SignatureDoesNotMatch"));
+ }
+
+ @Test
+ @Order(6)
+ void headerSignedWithAnotherSecretIsRejected() {
+ given().filter(S3SigV4aRequestSigner.signedAs("test", "not-the-secret")).when().get(PATH).then()
+ .statusCode(403).body("Error.Code", equalTo("SignatureDoesNotMatch"));
+ }
+
+ @Test
+ @Order(7)
+ void headerSignedWithAnUnknownKeyIsRejected() {
+ given().filter(S3SigV4aRequestSigner.signedAs("AKIAUNKNOWNACCESSKEY", "some-secret")).when().get(PATH).then()
+ .statusCode(403).body("Error.Code", equalTo("InvalidAccessKeyId"));
+ }
+
+ @Test
+ @Order(8)
+ void headerWithoutASignedRegionSetIsMalformed() {
+ given().filter(SIGNER.withoutSignedRegionSet()).when().get(PATH).then()
+ .statusCode(400).body("Error.Code", equalTo("AuthorizationHeaderMalformed"));
+ }
+
+ @Test
+ @Order(9)
+ void headerNamingAnUnknownRegionIsMalformed() {
+ given().filter(SIGNER.forRegions("mars-1")).when().get(PATH).then()
+ .statusCode(400).body("Error.Code", equalTo("AuthorizationHeaderMalformed"));
+ }
+
+ @Test
+ @Order(10)
+ void presignedUrlForAllRegionsIsServed() throws Exception {
+ given().urlEncodingEnabled(false).when()
+ .get(PATH + "?" + SIGNER.presignedQuery("GET", uri(PATH), 300))
+ .then().statusCode(200).body(equalTo("sigv4a body"));
+ }
+
+ @Test
+ @Order(11)
+ void presignedUrlForOneRegionIsServed() throws Exception {
+ given().urlEncodingEnabled(false).when()
+ .get(PATH + "?" + SIGNER.forRegions("us-east-1").presignedQuery("GET", uri(PATH), 300))
+ .then().statusCode(200).body(equalTo("sigv4a body"));
+ }
+
+ @Test
+ @Order(12)
+ void presignedUrlSignedForAnotherMethodIsRejected() throws Exception {
+ given().urlEncodingEnabled(false).when()
+ .get(PATH + "?" + SIGNER.presignedQuery("PUT", uri(PATH), 300))
+ .then().statusCode(403).body("Error.Code", equalTo("SignatureDoesNotMatch"));
+ }
+
+ @Test
+ @Order(13)
+ void presignedUrlSignedWithAnotherSecretIsRejected() throws Exception {
+ S3SigV4aRequestSigner forged = S3SigV4aRequestSigner.signedAs("test", "not-the-secret");
+ given().urlEncodingEnabled(false).when()
+ .get(PATH + "?" + forged.presignedQuery("GET", uri(PATH), 300))
+ .then().statusCode(403).body("Error.Code", equalTo("SignatureDoesNotMatch"));
+ }
+
+ @Test
+ @Order(14)
+ void presignedUrlWithAnUnknownKeyIsRejected() throws Exception {
+ S3SigV4aRequestSigner unknown = S3SigV4aRequestSigner.signedAs("AKIAUNKNOWNACCESSKEY", "some-secret");
+ given().urlEncodingEnabled(false).when()
+ .get(PATH + "?" + unknown.presignedQuery("GET", uri(PATH), 300))
+ .then().statusCode(403).body("Error.Code", equalTo("InvalidAccessKeyId"));
+ }
+
+ @Test
+ @Order(15)
+ void presignedUrlWithoutARegionSetIsRejected() throws Exception {
+ String query = SIGNER.presignedQuery("GET", uri(PATH), 300).replaceAll("&X-Amz-Region-Set=[^&]*", "");
+ given().urlEncodingEnabled(false).when().get(PATH + "?" + query).then()
+ .statusCode(400).body("Error.Code", equalTo("AuthorizationQueryParametersError"));
+ }
+
+ @Test
+ @Order(16)
+ void headerWithDuplicateCredentialIsRejected() {
+ given()
+ .header("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=test/20260101/s3/aws4_request, "
+ + "SignedHeaders=host;x-amz-date;x-amz-region-set, Signature=3006020101020101, "
+ + "Credential=test2/20260101/s3/aws4_request")
+ .header("X-Amz-Region-Set", "*")
+ .header("x-amz-date", "20260101T000000Z")
+ .when().get(PATH).then()
+ .statusCode(400).body("Error.Code", equalTo("AuthorizationHeaderMalformed"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
index e31e111bf8..752509e6b4 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/S3RequestSigner.java
@@ -238,7 +238,7 @@ public final class S3RequestSigner implements Filter {
return query + "&X-Amz-Signature=" + signature;
}
- private static String host(URI uri) {
+ static String host(URI uri) {
return uri.getPort() > 0 && uri.getPort() != 80 && uri.getPort() != 443
? uri.getHost() + ":" + uri.getPort()
: uri.getHost();
@@ -251,7 +251,7 @@ public final class S3RequestSigner implements Filter {
return hmacSha256(kService, "aws4_request");
}
- private static byte[] bodyBytes(Object body) {
+ static byte[] bodyBytes(Object body) {
if (body == null) {
return new byte[0];
}
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/S3SigV4aRequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/S3SigV4aRequestSigner.java
new file mode 100644
index 0000000000..e7206cf7f3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/testutil/S3SigV4aRequestSigner.java
@@ -0,0 +1,175 @@
+package io.github.hectorvent.floci.testutil;
+
+import io.github.hectorvent.floci.core.common.Digests;
+import io.github.hectorvent.floci.core.common.auth.SigV4aSignature;
+import io.restassured.filter.Filter;
+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;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/**
+ * A RestAssured filter that header-signs an S3 request with SigV4A ({@code AWS4-ECDSA-P256-SHA256}),
+ * the way {@link S3RequestSigner} does for SigV4. The signature covers the method, raw path, query,
+ * {@code host}, {@code x-amz-content-sha256}, {@code x-amz-date} and {@code x-amz-region-set}.
+ * {@link #presignedQuery} signs the same credential into a presigned URL's query string instead.
+ *
+ * <p>The signing here is independent of the code under test apart from the key derivation, which
+ * {@code SigV4aSignatureTest} checks against signatures produced by aws-crt.
+ */
+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;
+ private final String regionSet;
+ private final String signatureOverride;
+ private final boolean signRegionSet;
+
+ private S3SigV4aRequestSigner(String accessKeyId, String secretKey, String regionSet,
+ String signatureOverride, boolean signRegionSet) {
+ this.accessKeyId = accessKeyId;
+ this.secretKey = secretKey;
+ this.regionSet = regionSet;
+ this.signatureOverride = signatureOverride;
+ this.signRegionSet = signRegionSet;
+ }
+
+ public static S3SigV4aRequestSigner signedAs(String accessKeyId, String secretKey) {
+ return new S3SigV4aRequestSigner(accessKeyId, secretKey, "*", null, true);
+ }
+
+ /** Signs for {@code regionSet} (comma separated, or {@code *}) instead of every region. */
+ public S3SigV4aRequestSigner forRegions(String regionSet) {
+ return new S3SigV4aRequestSigner(accessKeyId, secretKey, regionSet, signatureOverride, signRegionSet);
+ }
+
+ /** Sends {@code signature} in place of the computed one, everything else intact. */
+ public S3SigV4aRequestSigner withSignature(String signature) {
+ return new S3SigV4aRequestSigner(accessKeyId, secretKey, regionSet, signature, signRegionSet);
+ }
+
+ /** Leaves {@code x-amz-region-set} out of {@code SignedHeaders}, which no real signer does. */
+ public S3SigV4aRequestSigner withoutSignedRegionSet() {
+ return new S3SigV4aRequestSigner(accessKeyId, secretKey, regionSet, signatureOverride, false);
+ }
+
+ @Override
+ public Response filter(FilterableRequestSpecification request,
+ FilterableResponseSpecification response, FilterContext ctx) {
+ try {
+ headersFor(request.getMethod(), URI.create(request.getURI()),
+ S3RequestSigner.bodyBytes(request.getBody()))
+ .forEach(request::header);
+ } catch (Exception e) {
+ throw new IllegalStateException("could not sign the request", e);
+ }
+ return ctx.next(request, response);
+ }
+
+ public Map<String, String> headersFor(String method, URI uri, byte[] body) throws IOException {
+ String amzDate = AMZ_DATE.format(Instant.now());
+ String scopeDate = amzDate.substring(0, 8);
+ String contentSha256 = Digests.sha256Hex(body);
+
+ Map<String, String> signed = new LinkedHashMap<>();
+ signed.put("host", S3RequestSigner.host(uri));
+ signed.put("x-amz-content-sha256", contentSha256);
+ signed.put("x-amz-date", amzDate);
+ if (signRegionSet) {
+ signed.put("x-amz-region-set", regionSet);
+ }
+ String signedHeaders = String.join(";", signed.keySet());
+ String canonicalHeaders = signed.entrySet().stream()
+ .map(header -> header.getKey() + ":" + header.getValue() + "\n")
+ .collect(Collectors.joining());
+ String canonicalRequest = method + "\n" + rawPath(uri) + "\n"
+ + S3RequestSigner.canonicalQueryString(uri.getRawQuery()) + "\n"
+ + canonicalHeaders + "\n" + signedHeaders + "\n" + contentSha256;
+ String signature = signature(amzDate, scopeDate, canonicalRequest);
+
+ Map<String, String> headers = new LinkedHashMap<>();
+ headers.put("x-amz-date", amzDate);
+ headers.put("x-amz-content-sha256", contentSha256);
+ headers.put("X-Amz-Region-Set", regionSet);
+ headers.put("Authorization", SigV4aSignature.ALGORITHM + " Credential=" + accessKeyId + "/" + scopeDate
+ + "/" + SERVICE + "/aws4_request, SignedHeaders=" + signedHeaders + ", Signature=" + signature);
+ return headers;
+ }
+
+ /**
+ * The query string of a SigV4A presigned URL: the {@code X-Amz-*} parameters including
+ * {@code X-Amz-Region-Set}, {@code host} as the only signed header, an unsigned payload and the
+ * signature last. Send it with URL encoding off, since it is already encoded.
+ */
+ public String presignedQuery(String method, URI uri, int expiresSeconds) throws IOException {
+ String amzDate = AMZ_DATE.format(Instant.now());
+ String scopeDate = amzDate.substring(0, 8);
+ Map<String, String> params = new LinkedHashMap<>();
+ params.put("X-Amz-Algorithm", SigV4aSignature.ALGORITHM);
+ params.put("X-Amz-Credential", accessKeyId + "/" + scopeDate + "/" + SERVICE + "/aws4_request");
+ params.put("X-Amz-Date", amzDate);
+ params.put("X-Amz-Expires", Integer.toString(expiresSeconds));
+ params.put("X-Amz-Region-Set", regionSet);
+ params.put("X-Amz-SignedHeaders", "host");
+ String query = params.entrySet().stream()
+ .map(param -> S3RequestSigner.uriEncode(param.getKey()) + "="
+ + S3RequestSigner.uriEncode(param.getValue()))
+ .collect(Collectors.joining("&"));
+ String canonicalRequest = method + "\n" + rawPath(uri) + "\n"
+ + S3RequestSigner.canonicalQueryString(query) + "\n"
+ + "host:" + S3RequestSigner.host(uri) + "\n\nhost\nUNSIGNED-PAYLOAD";
+ return query + "&X-Amz-Signature=" + signature(amzDate, scopeDate, canonicalRequest);
+ }
+
+ private String signature(String amzDate, String scopeDate, String canonicalRequest) {
+ if (signatureOverride != null) {
+ return signatureOverride;
+ }
+ 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);
+ }
+ }
+
+ private static String rawPath(URI uri) {
+ return uri.getRawPath() == null || uri.getRawPath().isEmpty() ? "/" : uri.getRawPath();
+ }
+}