fix(s3): verify SigV4 signature on presigned URLs when enforce-auth is enabled (#1842)

* fix(s3): verify SigV4 signature on presigned URLs when enforce-auth is enabled

* test(s3): use real SigV4 signatures in presigned URL auth enforcement tests

* test(s3): assert tampered presigned signature is rejected

* fix(s3): construct presigned canonical query per SigV4 encoding rules

* test(s3): cover presigned canonical query edge cases

Extract canonical query construction into a package-private buildCanonicalQueryString method and add unit tests for the SigV4 encoding, ordering, empty-value, duplicate-name, and signature-exclusion branches.

* test(s3): add SDK-signed presigned URL regression tests

Add integration tests that generate presigned URLs with the AWS SDK S3Presigner (an independent signer) under enforce-auth: both original URLs succeed, transplanting object A's path onto object B's query is rejected with 403 SignatureDoesNotMatch, reordered and special-character queries still verify, expired URLs and malformed credentials are rejected, and an IAM-issued access key verifies. Adds the aws-sdk s3 test dependency.

* fix(s3): collapse sequential spaces in signed header values per SigV4

Canonical values for non-host signed headers were only trimmed. SigV4 also collapses sequential spaces to a single space, so a valid presigned request carrying such a header could be rejected. Extract canonicalizeHeaderValue and add unit coverage.

* style(s3): log caught exception in presigned SigV4 verification

The catch block silently returned false. Log at debug per repo style so a swallowed exception can be diagnosed.

* test(s3): move SDK presigned URL tests to compatibility-tests

Move S3PresignedUrlSdkIntegrationTest from the main project to
compatibility-tests/sdk-test-java and remove the aws-sdk s3 test
dependency from the main pom.xml per CONTRIBUTING.md guidelines.

* fix(s3): read X-Amz-Content-Sha256 instead of hardcoding UNSIGNED-PAYLOAD

* fix(s3): reject presigned URLs with X-Amz-Expires outside 1-604800

* fix(s3): reject presigned URLs with unsupported X-Amz-Algorithm
This commit is contained in:
JinHwanKim authored and GitHub committed 2026-08-14 23:52:46 -05:00
1 parent e4010ec12f
commit 3fe836aa16
4 files changed
+761 -7

No files matched your search

@@ -1,21 +1,44 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.iam.IamService;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@Provider
public class PreSignedUrlFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(PreSignedUrlFilter.class);
private static final String LEGACY_ACCESS_KEY_ID = "test";
private static final String LEGACY_SECRET_KEY = "test";
private final PreSignedUrlGenerator presignGenerator;
private final S3Service s3Service;
private final IamService iamService;
@Inject
public PreSignedUrlFilter(PreSignedUrlGenerator presignGenerator) {
public PreSignedUrlFilter(PreSignedUrlGenerator presignGenerator,
S3Service s3Service,
IamService iamService) {
this.presignGenerator = presignGenerator;
this.s3Service = s3Service;
this.iamService = iamService;
}
@Override
@@ -28,6 +51,17 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
return;
}
if (!"AWS4-HMAC-SHA256".equals(algorithm)) {
requestContext.abortWith(
errorResponse(
400,
"AuthorizationQueryParametersError",
"Unsupported X-Amz-Algorithm value: " + algorithm
)
);
return;
}
if (S3RequestAuthorizationParser.isMissingRequiredPresignedParameter(queryParams)) {
requestContext.abortWith(errorResponse(
S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_STATUS,
@@ -49,6 +83,17 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
return;
}
if (expires < 1 || expires > 604800) {
requestContext.abortWith(
errorResponse(
400,
"AuthorizationQueryParametersError",
"X-Amz-Expires must be between 1 and 604800 seconds."
)
);
return;
}
// Check expiration
if (presignGenerator.isExpired(amzDate, expires)) {
requestContext.abortWith(errorResponse(403, "AccessDenied",
@@ -56,8 +101,30 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
return;
}
// Optionally verify signature (if validateSignatures is enabled)
if (presignGenerator.shouldValidateSignatures()) {
// Verify signature: SigV4 when enforce-auth is enabled, custom when validateSignatures is enabled
if (s3Service.isAuthEnforced()) {
String credential = queryParams.getFirst("X-Amz-Credential");
String decodedCredential = URLDecoder.decode(credential, StandardCharsets.UTF_8);
String[] credParts = decodedCredential.split("/");
if (credParts.length < 5) {
requestContext.abortWith(errorResponse(403, "InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records."));
return;
}
String accessKeyId = credParts[0];
String secretKey = resolveSecretKey(accessKeyId);
if (secretKey == null) {
requestContext.abortWith(errorResponse(403, "InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records."));
return;
}
if (!verifySigV4Signature(requestContext, signature, secretKey)) {
requestContext.abortWith(errorResponse(403, "SignatureDoesNotMatch",
"The request signature we calculated does not match the signature you provided."));
}
} else if (presignGenerator.shouldValidateSignatures()) {
String path = requestContext.getUriInfo().getPath();
String[] parts = path.split("/", 3);
if (parts.length < 3) {
@@ -76,6 +143,159 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
}
}
private boolean verifySigV4Signature(ContainerRequestContext requestContext,
String signature, String secretKey) {
try {
var queryParams = requestContext.getUriInfo().getQueryParameters();
String credential = queryParams.getFirst("X-Amz-Credential");
String amzDate = queryParams.getFirst("X-Amz-Date");
String signedHeaders = queryParams.getFirst("X-Amz-SignedHeaders");
String decodedCredential = URLDecoder.decode(credential, StandardCharsets.UTF_8);
String[] credParts = decodedCredential.split("/");
if (credParts.length < 5) {
return false;
}
String date = credParts[1];
String region = credParts[2];
String service = credParts[3];
String credentialScope = date + "/" + region + "/" + service + "/aws4_request";
// Build canonical headers from signed headers
String host = requestContext.getUriInfo().getRequestUri().getHost();
int port = requestContext.getUriInfo().getRequestUri().getPort();
String authority = (port > 0 && port != 80 && port != 443) ? host + ":" + port : host;
StringBuilder canonicalHeaders = new StringBuilder();
for (String header : signedHeaders.split(";")) {
if ("host".equals(header)) {
canonicalHeaders.append("host:").append(authority).append("\n");
} else {
String canonicalValue = canonicalizeHeaderValue(requestContext.getHeaderString(header));
canonicalHeaders.append(header).append(":").append(canonicalValue).append("\n");
}
}
// Canonical request
String path = requestContext.getUriInfo().getRequestUri().getRawPath();
String canonicalQueryString = buildCanonicalQueryString(queryParams);
String payloadHash = requestContext.getHeaderString("x-amz-content-sha256");
if (payloadHash == null) {
payloadHash = queryParams.getFirst("X-Amz-Content-Sha256");
}
if (payloadHash == null) {
payloadHash = "UNSIGNED-PAYLOAD";
}
String canonicalRequest = requestContext.getMethod() + "\n"
+ path + "\n"
+ canonicalQueryString + "\n"
+ canonicalHeaders + "\n"
+ signedHeaders + "\n"
+ payloadHash;
// String to sign
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ sha256Hex(canonicalRequest);
// Derive signing key and compute expected signature
byte[] signingKey = deriveSigningKey(secretKey, date, region, service);
String expectedSignature = hexEncode(hmacSha256(signingKey, stringToSign));
return MessageDigest.isEqual(
expectedSignature.getBytes(StandardCharsets.UTF_8),
signature.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
LOG.debugv("Presigned SigV4 signature verification failed: {0}", e.getMessage());
return false;
}
}
private String resolveSecretKey(String accessKeyId) {
if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {
return LEGACY_SECRET_KEY;
}
if (iamService != null) {
return iamService.findSecretKey(accessKeyId).orElse(null);
}
return null;
}
/**
* Builds the SigV4 canonical query string from the framework's decoded query parameters:
* URI-encode each name and value, exclude {@code X-Amz-Signature}, and sort by encoded
* name and then by encoded value. Package-private for unit testing.
*/
static String buildCanonicalQueryString(MultivaluedMap<String, String> decodedParams) {
List<String[]> encodedParams = new ArrayList<>();
for (var entry : decodedParams.entrySet()) {
if ("X-Amz-Signature".equals(entry.getKey())) {
continue;
}
String encodedName = awsUriEncode(entry.getKey());
for (String value : entry.getValue()) {
encodedParams.add(new String[]{encodedName, awsUriEncode(value)});
}
}
encodedParams.sort(Comparator.comparing((String[] p) -> p[0]).thenComparing(p -> p[1]));
return encodedParams.stream()
.map(p -> p[0] + "=" + p[1])
.collect(Collectors.joining("&"));
}
/**
* Canonicalizes a signed header value per SigV4: trim, then collapse sequential spaces to
* a single space. Package-private for unit testing.
*/
static String canonicalizeHeaderValue(String value) {
return value == null ? "" : value.trim().replaceAll(" +", " ");
}
static String awsUriEncode(String value) {
StringBuilder encoded = new StringBuilder();
for (byte b : value.getBytes(StandardCharsets.UTF_8)) {
int c = b & 0xFF;
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| c == '-' || c == '_' || c == '.' || c == '~') {
encoded.append((char) c);
} else {
encoded.append('%').append(String.format("%02X", c));
}
}
return encoded.toString();
}
private static byte[] deriveSigningKey(String secretKey, String date, String region,
String service) throws Exception {
byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
byte[] kDate = hmacSha256(kSecret, date);
byte[] kRegion = hmacSha256(kDate, region);
byte[] kService = hmacSha256(kRegion, service);
return hmacSha256(kService, "aws4_request");
}
private static byte[] hmacSha256(byte[] key, String data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
}
private static String hexEncode(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
private Response errorResponse(int status, String code, String message) {
String xml = new XmlBuilder()
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")