Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(s3): validate checksum passed via presigned url query parameters (#4254)

Vũ Thế Huy4e3bbe539c61
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
index 64df200689..17d357960a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java
@@ -819,7 +819,7 @@ public class S3Controller {
copySource, bucket, key, uploadId, partNumber, httpHeaders, authorization);
}
byte[] partData = decodeAwsChunked(body, contentEncoding, contentSha256);
- validateChecksumHeaders(httpHeaders, partData, getChecksumAlgorithm(httpHeaders));
+ validateChecksumHeaders(httpHeaders, uriInfo, partData, getChecksumAlgorithm(httpHeaders, uriInfo));
Part part = s3Service.storePart(bucket, key, uploadId, partNumber, partData,
httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-algorithm"),
httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key"),
@@ -838,7 +838,7 @@ public class S3Controller {
if (copySource != null && !copySource.isEmpty()) {
s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization);
- return handleCopyObject(copySource, bucket, key, contentType, httpHeaders, authorization);
+ return handleCopyObject(copySource, bucket, key, contentType, httpHeaders, uriInfo, authorization);
}
Map<String, String> inlineTags = parseInlineTaggingHeader(resolveInlineTaggingSource(tagging, uriInfo));
@@ -849,8 +849,8 @@ public class S3Controller {
Instant retainUntil = retainUntilStr != null ? Instant.parse(retainUntilStr) : null;
byte[] data = decodeAwsChunked(body, contentEncoding, contentSha256);
- String checksumAlgorithm = getChecksumAlgorithm(httpHeaders);
- validateChecksumHeaders(httpHeaders, data, checksumAlgorithm);
+ String checksumAlgorithm = getChecksumAlgorithm(httpHeaders, uriInfo);
+ validateChecksumHeaders(httpHeaders, uriInfo, data, checksumAlgorithm);
String persistedEncoding = toPersistedContentEncoding(contentEncoding);
String contentDisposition = httpHeaders.getHeaderString("Content-Disposition");
String cacheControl = httpHeaders.getHeaderString("Cache-Control");
@@ -882,7 +882,7 @@ public class S3Controller {
.withGrantReadAcp(httpHeaders.getHeaderString("x-amz-grant-read-acp"))
.withGrantWriteAcp(httpHeaders.getHeaderString("x-amz-grant-write-acp"))
.withChecksumAlgorithm(checksumAlgorithm)
- .withClientChecksum(extractChecksumFromHeaders(httpHeaders))
+ .withClientChecksum(extractChecksum(httpHeaders, uriInfo))
.withIfMatch(ifMatch)
.withIfNoneMatch(ifNoneMatch)
.withTagging(inlineTags));
@@ -1012,7 +1012,7 @@ public class S3Controller {
"Request specific response headers cannot be used for anonymous GET requests.", 400));
}
- boolean includeChecksum = "ENABLED".equalsIgnoreCase(checksumMode);
+ boolean includeChecksum = "ENABLED".equalsIgnoreCase(resolveHeaderOrQueryParam(checksumMode, uriInfo, "x-amz-checksum-mode"));
if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
return handleRangeRequest(obj, rangeHeader, overrides, includeChecksum);
}
@@ -1219,7 +1219,7 @@ public class S3Controller {
if (obj.getVersionId() != null) {
resp.header("x-amz-version-id", obj.getVersionId());
}
- boolean includeChecksum = "ENABLED".equalsIgnoreCase(checksumMode);
+ boolean includeChecksum = "ENABLED".equalsIgnoreCase(resolveHeaderOrQueryParam(checksumMode, uriInfo, "x-amz-checksum-mode"));
appendObjectHeaders(resp, obj, overrides, includeChecksum);
emitCloudTrailEvent("HeadObject", bucket, key, 0L, obj.getSize(), null, null);
return resp.build();
@@ -1430,8 +1430,8 @@ public class S3Controller {
httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-algorithm"),
httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key"),
httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key-MD5"),
- getChecksumAlgorithm(httpHeaders),
- httpHeaders.getHeaderString("x-amz-checksum-type"),
+ getChecksumAlgorithm(httpHeaders, uriInfo),
+ resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-type"),
parseInlineTaggingHeader(
resolveInlineTaggingSource(httpHeaders.getHeaderString("x-amz-tagging"), uriInfo)));
String xml = new XmlBuilder()
@@ -1474,8 +1474,8 @@ public class S3Controller {
if (preconditionResponse != null) {
return preconditionResponse;
}
- String checksumType = httpHeaders.getHeaderString("x-amz-checksum-type");
- S3Checksum expectedChecksum = extractChecksumFromHeaders(httpHeaders);
+ String checksumType = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-type");
+ S3Checksum expectedChecksum = extractChecksum(httpHeaders, uriInfo);
S3Object obj = s3Service.completeMultipartUpload(bucket, key, uploadId, partNumbers,
completedPartETags(completedParts), completedPartChecksums(completedParts), checksumType,
expectedChecksum);
@@ -2244,9 +2244,9 @@ public class S3Controller {
httpHeaders.getHeaderString("x-amz-content-sha256"));
String annotationName = uriInfo.getQueryParameters().getFirst("annotationName");
String versionId = uriInfo.getQueryParameters().getFirst("versionId");
- String algorithmHeader = getChecksumAlgorithm(httpHeaders);
+ String algorithmHeader = getChecksumAlgorithm(httpHeaders, uriInfo);
ChecksumAlgorithm algorithm = ChecksumAlgorithm.fromWireValue(algorithmHeader);
- validateChecksumHeaders(httpHeaders, payload, algorithmHeader);
+ validateChecksumHeaders(httpHeaders, uriInfo, payload, algorithmHeader);
validateContentMd5(httpHeaders, payload);
ObjectAnnotation annotation = s3Service.putObjectAnnotation(bucket, key, annotationName,
versionId, payload, httpHeaders.getHeaderString("x-amz-object-if-match"), algorithm);
@@ -2282,7 +2282,7 @@ public class S3Controller {
if (annotation.getVersionId() != null) {
response.header("x-amz-object-version-id", annotation.getVersionId());
}
- if ("ENABLED".equalsIgnoreCase(httpHeaders.getHeaderString("x-amz-checksum-mode"))) {
+ if ("ENABLED".equalsIgnoreCase(resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-mode"))) {
appendAnnotationChecksumHeaders(response, annotation);
}
appendAnnotationSseHeader(response, annotation);
@@ -2636,6 +2636,7 @@ public class S3Controller {
private Response handleCopyObject(String copySource, String destBucket, String destKey,
String contentType, HttpHeaders httpHeaders,
+ UriInfo uriInfo,
S3Service.RequestAuthorization authorization) {
CopySourceRef sourceObject = parseCopySource(copySource);
String sourceBucket = sourceObject.bucket();
@@ -2684,7 +2685,7 @@ public class S3Controller {
.withCopySourceSseCustomerAlgorithm(httpHeaders.getHeaderString("x-amz-copy-source-server-side-encryption-customer-algorithm"))
.withCopySourceSseCustomerKey(httpHeaders.getHeaderString("x-amz-copy-source-server-side-encryption-customer-key"))
.withCopySourceSseCustomerKeyMd5(httpHeaders.getHeaderString("x-amz-copy-source-server-side-encryption-customer-key-MD5"))
- .withChecksumAlgorithm(getChecksumAlgorithm(httpHeaders))
+ .withChecksumAlgorithm(getChecksumAlgorithm(httpHeaders, uriInfo))
.withAnnotationDirective(annotationDirective)
.withAcl(cannedAcl)
.withGrantRead(httpHeaders.getHeaderString("x-amz-grant-read"))
@@ -2887,12 +2888,41 @@ public class S3Controller {
return metadata;
}
- private S3Checksum extractChecksumFromHeaders(HttpHeaders httpHeaders) {
- String crc32 = httpHeaders.getHeaderString("x-amz-checksum-crc32");
- String crc32c = httpHeaders.getHeaderString("x-amz-checksum-crc32c");
- String crc64nvme = httpHeaders.getHeaderString("x-amz-checksum-crc64nvme");
- String sha1 = httpHeaders.getHeaderString("x-amz-checksum-sha1");
- String sha256 = httpHeaders.getHeaderString("x-amz-checksum-sha256");
+ static String resolveHeaderOrQueryParam(HttpHeaders httpHeaders, UriInfo uriInfo, String name) {
+ String headerVal = httpHeaders != null ? httpHeaders.getHeaderString(name) : null;
+ return resolveHeaderOrQueryParam(headerVal, uriInfo, name);
+ }
+
+ static String resolveHeaderOrQueryParam(String headerValue, UriInfo uriInfo, String name) {
+ if (headerValue != null && !headerValue.isBlank()) {
+ return headerValue;
+ }
+ if (uriInfo != null) {
+ MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
+ if (queryParams != null) {
+ String val = queryParams.getFirst(name);
+ if (val != null && !val.isBlank()) {
+ return val;
+ }
+ for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(name) && !entry.getValue().isEmpty()) {
+ String v = entry.getValue().get(0);
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ private S3Checksum extractChecksum(HttpHeaders httpHeaders, UriInfo uriInfo) {
+ String crc32 = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-crc32");
+ String crc32c = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-crc32c");
+ String crc64nvme = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-crc64nvme");
+ String sha1 = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-sha1");
+ String sha256 = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-sha256");
if (crc32 == null && crc32c == null && crc64nvme == null && sha1 == null && sha256 == null) {
return null;
}
@@ -2906,36 +2936,36 @@ public class S3Controller {
return checksum;
}
- private String getChecksumAlgorithm(HttpHeaders httpHeaders) {
- String algorithm = httpHeaders.getHeaderString("x-amz-checksum-algorithm");
+ private String getChecksumAlgorithm(HttpHeaders httpHeaders, UriInfo uriInfo) {
+ String algorithm = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-algorithm");
if (algorithm == null || algorithm.isBlank()) {
- algorithm = httpHeaders.getHeaderString("x-amz-sdk-checksum-algorithm");
+ algorithm = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-sdk-checksum-algorithm");
}
return algorithm;
}
- private void validateChecksumHeaders(HttpHeaders httpHeaders, byte[] data, String algorithm) {
- String sha1 = httpHeaders.getHeaderString("x-amz-checksum-sha1");
+ private void validateChecksumHeaders(HttpHeaders httpHeaders, UriInfo uriInfo, byte[] data, String algorithm) {
+ String sha1 = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-sha1");
if (sha1 != null && !sha1.equals(S3Checksum.sha1Base64(data))) {
throw new AwsException("BadDigest", "The SHA1 checksum you specified did not match the payload.", 400);
}
- String sha256 = httpHeaders.getHeaderString("x-amz-checksum-sha256");
+ String sha256 = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-sha256");
if (sha256 != null && !sha256.equals(S3Checksum.sha256Base64(data))) {
throw new AwsException("BadDigest", "The SHA256 checksum you specified did not match the payload.", 400);
}
- String crc32 = httpHeaders.getHeaderString("x-amz-checksum-crc32");
+ String crc32 = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-crc32");
if (crc32 != null && !crc32.equals(S3Checksum.crc32Base64(data))) {
throw new AwsException("BadDigest", "The CRC32 checksum you specified did not match the payload.", 400);
}
- String crc32c = httpHeaders.getHeaderString("x-amz-checksum-crc32c");
+ String crc32c = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-crc32c");
if (crc32c != null && !crc32c.equals(S3Checksum.crc32cBase64(data))) {
throw new AwsException("BadDigest", "The CRC32C checksum you specified did not match the payload.", 400);
}
- String crc64nvme = httpHeaders.getHeaderString("x-amz-checksum-crc64nvme");
+ String crc64nvme = resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-checksum-crc64nvme");
if (crc64nvme != null && !crc64nvme.equals(S3Checksum.crc64NvmeBase64(data))) {
throw new AwsException("BadDigest", "The CRC64NVME checksum you specified did not match the payload.", 400);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java
new file mode 100644
index 0000000000..95eecc6f67
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java
@@ -0,0 +1,299 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.github.hectorvent.floci.services.s3.model.S3Checksum;
+import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
+import io.github.hectorvent.floci.testutil.S3RequestSigner;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.RestAssured;
+import org.junit.jupiter.api.Test;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
+
+@QuarkusTest
+@TestProfile(S3EnforceAuthProfile.class)
+class S3PresignedChecksumIntegrationTest {
+
+ private static final String BUCKET = "presigned-checksum-bucket";
+ private static final String ACCESS_KEY = "test";
+ private static final String SECRET_KEY = "test";
+ private static final S3RequestSigner LOCAL_SIGNER = S3RequestSigner.signedAs(ACCESS_KEY, SECRET_KEY);
+ private static final DateTimeFormatter AMZ_DATE =
+ DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
+
+ @Test
+ void presignedPutWithMismatchedChecksumCrc32InQueryFailsWith400BadDigest() throws Exception {
+ createBucket();
+ String path = "/" + BUCKET + "/mismatched-crc32.txt";
+ // SDK JS v3 presigner ký CRC32 của empty payload (AAAAAA==) khi chưa có body tại thời điểm ký
+ String emptyPayloadCrc32 = S3Checksum.crc32Base64(new byte[0]);
+ String url = presign("PUT", path, Map.of("x-amz-checksum-crc32", emptyPayloadCrc32), Map.of());
+
+ byte[] body = "not an empty body".getBytes(StandardCharsets.UTF_8);
+ given()
+ .urlEncodingEnabled(false)
+ .body(body)
+ .when()
+ .put(url)
+ .then()
+ .statusCode(400)
+ .body(containsString("BadDigest"))
+ .body(containsString("The CRC32 checksum you specified did not match the payload."));
+
+ // Xác nhận object không được lưu vào storage
+ given()
+ .filter(LOCAL_SIGNER)
+ .when()
+ .get(path)
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchKey"));
+ }
+
+ @Test
+ void presignedPutWithMatchingChecksumCrc32InQuerySucceedsAndStoresChecksum() throws Exception {
+ createBucket();
+ String path = "/" + BUCKET + "/matching-crc32.txt";
+ byte[] body = "hello presigned checksum world".getBytes(StandardCharsets.UTF_8);
+ String expectedCrc32 = S3Checksum.crc32Base64(body);
+ String url = presign("PUT", path, Map.of("x-amz-checksum-crc32", expectedCrc32), Map.of());
+
+ given()
+ .urlEncodingEnabled(false)
+ .body(body)
+ .when()
+ .put(url)
+ .then()
+ .statusCode(200)
+ .header("ETag", notNullValue())
+ .header("x-amz-checksum-crc32", equalTo(expectedCrc32));
+
+ // Kiểm tra HeadObject với x-amz-checksum-mode=ENABLED trả về checksum đã lưu
+ given()
+ .filter(LOCAL_SIGNER)
+ .header("x-amz-checksum-mode", "ENABLED")
+ .when()
+ .head(path)
+ .then()
+ .statusCode(200)
+ .header("x-amz-checksum-crc32", equalTo(expectedCrc32));
+ }
+
+ @Test
+ void presignedPutWithChecksumAlgorithmInQueryComputesAndStoresChecksum() throws Exception {
+ createBucket();
+ String path = "/" + BUCKET + "/algorithm-query.txt";
+ byte[] body = "calculate crc32 from algorithm query param".getBytes(StandardCharsets.UTF_8);
+ String expectedCrc32 = S3Checksum.crc32Base64(body);
+ String url = presign("PUT", path, Map.of("x-amz-checksum-algorithm", "CRC32"), Map.of());
+
+ given()
+ .urlEncodingEnabled(false)
+ .body(body)
+ .when()
+ .put(url)
+ .then()
+ .statusCode(200)
+ .header("x-amz-checksum-crc32", equalTo(expectedCrc32));
+
+ // Query param x-amz-checksum-mode=ENABLED trên presigned GET cũng phải trả về checksum
+ String getUrl = presign("GET", path, Map.of("x-amz-checksum-mode", "ENABLED"), Map.of());
+ given()
+ .urlEncodingEnabled(false)
+ .when()
+ .get(getUrl)
+ .then()
+ .statusCode(200)
+ .header("x-amz-checksum-crc32", equalTo(expectedCrc32))
+ .body(equalTo(new String(body, StandardCharsets.UTF_8)));
+ }
+
+ @Test
+ void presignedPutWithMismatchedSha256InQueryFailsWith400BadDigest() throws Exception {
+ createBucket();
+ String path = "/" + BUCKET + "/mismatched-sha256.txt";
+ String invalidSha256 = S3Checksum.sha256Base64("other content".getBytes(StandardCharsets.UTF_8));
+ String url = presign("PUT", path, Map.of("x-amz-checksum-sha256", invalidSha256), Map.of());
+
+ given()
+ .urlEncodingEnabled(false)
+ .body("real content".getBytes(StandardCharsets.UTF_8))
+ .when()
+ .put(url)
+ .then()
+ .statusCode(400)
+ .body(containsString("BadDigest"))
+ .body(containsString("The SHA256 checksum you specified did not match the payload."));
+ }
+
+ @Test
+ void presignedUploadPartWithMismatchedChecksumQueryParamFailsWith400BadDigest() throws Exception {
+ createBucket();
+ String key = "multipart-checksum.txt";
+ String path = "/" + BUCKET + "/" + key;
+
+ // Khởi tạo multipart upload
+ String uploadId = given()
+ .filter(LOCAL_SIGNER)
+ .when()
+ .post(path + "?uploads")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
+
+ // Tạo presigned URL cho upload part có x-amz-checksum-crc32 sai
+ String partPath = path;
+ String wrongCrc32 = S3Checksum.crc32Base64(new byte[0]);
+ String partUrl = presign("PUT", partPath,
+ Map.of("uploadId", uploadId, "partNumber", "1", "x-amz-checksum-crc32", wrongCrc32),
+ Map.of());
+
+ given()
+ .urlEncodingEnabled(false)
+ .body("part data not matching empty crc32".getBytes(StandardCharsets.UTF_8))
+ .when()
+ .put(partUrl)
+ .then()
+ .statusCode(400)
+ .body(containsString("BadDigest"))
+ .body(containsString("The CRC32 checksum you specified did not match the payload."));
+ }
+
+ @Test
+ void presignedCopyObjectWithChecksumAlgorithmInQueryComputesAndStoresChecksum() throws Exception {
+ createBucket();
+ String sourcePath = "/" + BUCKET + "/copy-source.txt";
+ byte[] body = "copy source content for checksum test".getBytes(StandardCharsets.UTF_8);
+ given()
+ .filter(LOCAL_SIGNER)
+ .body(body)
+ .when()
+ .put(sourcePath)
+ .then()
+ .statusCode(200);
+
+ String destPath = "/" + BUCKET + "/copy-dest.txt";
+ String expectedSha256 = S3Checksum.sha256Base64(body);
+ String copyUrl = presign("PUT", destPath,
+ Map.of("x-amz-checksum-algorithm", "SHA256"),
+ Map.of("x-amz-copy-source", "/" + BUCKET + "/copy-source.txt"));
+
+ given()
+ .urlEncodingEnabled(false)
+ .header("x-amz-copy-source", "/" + BUCKET + "/copy-source.txt")
+ .when()
+ .put(copyUrl)
+ .then()
+ .statusCode(200)
+ .body(containsString("CopyObjectResult"))
+ .body(containsString("<ChecksumSHA256>" + expectedSha256 + "</ChecksumSHA256>"));
+
+ given()
+ .filter(LOCAL_SIGNER)
+ .header("x-amz-checksum-mode", "ENABLED")
+ .when()
+ .head(destPath)
+ .then()
+ .statusCode(200)
+ .header("x-amz-checksum-sha256", equalTo(expectedSha256));
+ }
+
+ private static void createBucket() {
+ given()
+ .filter(LOCAL_SIGNER)
+ .when()
+ .put("/" + BUCKET)
+ .then()
+ .statusCode(200);
+ }
+
+ private static String presign(String method, String path, Map<String, String> queryParams,
+ Map<String, String> signedHeaders) throws Exception {
+ String amzDate = AMZ_DATE.format(Instant.now());
+ String date = amzDate.substring(0, 8);
+ String credentialScope = date + "/us-east-1/s3/aws4_request";
+
+ TreeMap<String, String> headers = new TreeMap<>(signedHeaders);
+ headers.put("host", "localhost:" + RestAssured.port);
+ String signedHeaderNames = String.join(";", headers.keySet());
+
+ TreeMap<String, String> params = new TreeMap<>(queryParams);
+ params.put("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
+ params.put("X-Amz-Credential", ACCESS_KEY + "/" + credentialScope);
+ params.put("X-Amz-Date", amzDate);
+ params.put("X-Amz-Expires", "3600");
+ params.put("X-Amz-SignedHeaders", signedHeaderNames);
+ String canonicalQuery = params.entrySet().stream()
+ .map(entry -> uriEncode(entry.getKey()) + "=" + uriEncode(entry.getValue()))
+ .collect(Collectors.joining("&"));
+ String canonicalHeaders = headers.entrySet().stream()
+ .map(entry -> entry.getKey() + ":" + entry.getValue().trim() + "\n")
+ .collect(Collectors.joining());
+
+ String canonicalRequest = method + "\n"
+ + path + "\n"
+ + canonicalQuery + "\n"
+ + canonicalHeaders + "\n"
+ + signedHeaderNames + "\n"
+ + "UNSIGNED-PAYLOAD";
+ String stringToSign = "AWS4-HMAC-SHA256\n"
+ + amzDate + "\n"
+ + credentialScope + "\n"
+ + sha256Hex(canonicalRequest);
+
+ byte[] kDate = hmacSha256(("AWS4" + SECRET_KEY).getBytes(StandardCharsets.UTF_8), date);
+ byte[] kRegion = hmacSha256(kDate, "us-east-1");
+ byte[] kService = hmacSha256(kRegion, "s3");
+ byte[] signingKey = hmacSha256(kService, "aws4_request");
+ String signature = hexEncode(hmacSha256(signingKey, stringToSign));
+
+ return path + "?" + canonicalQuery + "&X-Amz-Signature=" + signature;
+ }
+
+ private static String uriEncode(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[] 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 hex = new StringBuilder(bytes.length * 2);
+ for (byte b : bytes) {
+ hex.append(String.format("%02x", b));
+ }
+ return hex.toString();
+ }
+}