Light, fluffy, and always free - The AWS Local Emulator alternative
fix(s3): verify SigV4 signature on presigned POST uploads (#3081)
Syed Sadiqu Hussainffab3dc1e90a
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.javaindex 08fa27a58c..04c9a45d52 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@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.XmlParser;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.RequestContext;import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.sns.SnsQueryHandler;import io.github.hectorvent.floci.services.s3.model.Bucket;import io.github.hectorvent.floci.services.s3.model.ChecksumAlgorithm;@@ -102,6 +103,7 @@ public class S3Controller {private final CloudTrailService cloudTrailService;private final AccountResolver accountResolver;private final RequestContext requestContext;+ private final IamService iamService;@Injectpublic S3Controller(S3Service s3Service, S3SelectService s3SelectService,@@ -111,7 +113,8 @@ public class S3Controller {io.github.hectorvent.floci.services.floci.ui.UiPages uiPages,CloudTrailService cloudTrailService,AccountResolver accountResolver,- RequestContext requestContext) {+ RequestContext requestContext,+ IamService iamService) {this.s3Service = s3Service;this.s3SelectService = s3SelectService;this.regionResolver = regionResolver;@@ -121,6 +124,7 @@ public class S3Controller {this.cloudTrailService = cloudTrailService;this.accountResolver = accountResolver;this.requestContext = requestContext;+ this.iamService = iamService;}private void emitCloudTrailEvent(String eventName, String bucket, String key,@@ -2821,10 +2825,14 @@ public class S3Controller {lcFields.put(e.getKey().toLowerCase(Locale.ROOT), e.getValue());}- // Validate policy conditions if present- String policy = lcFields.get("policy");- if (policy != null && !policy.isEmpty()) {- validatePolicyConditions(policy, bucket, lcFields, fileData.length);+ if (s3Service.isAuthEnforced()) {+ validatePresignedPostAuth(lcFields, bucket, key, fileData.length);+ } else {+ // Validate policy conditions if present+ String policy = lcFields.get("policy");+ if (policy != null && !policy.isEmpty()) {+ validatePolicyConditions(policy, bucket, lcFields, fileData.length);+ }}// Use Content-Type from form fields, fall back to file part Content-Type@@ -2869,6 +2877,77 @@ public class S3Controller {return response.build();}+ /**+ * Enforces real S3 presigned-POST auth: a {@code policy} field must be present and+ * SigV4-signed by a known secret key referenced through {@code x-amz-credential}, matching+ * real S3's behavior of rejecting fabricated or absent credentials with 403 AccessDenied.+ */+ private void validatePresignedPostAuth(Map<String, String> fields, String bucket, String key, int contentLength) {+ String policy = fields.get("policy");+ String credential = fields.get("x-amz-credential");+ String signature = fields.get("x-amz-signature");+ String algorithm = fields.get("x-amz-algorithm");+ String date = fields.get("x-amz-date");+ if (policy == null || policy.isEmpty()+ || credential == null || credential.isEmpty()+ || signature == null || signature.isEmpty()+ || algorithm == null || algorithm.isEmpty()+ || date == null || date.isEmpty()) {+ throw new AwsException("AccessDenied", "Access Denied", 403);+ }+ if (!"AWS4-HMAC-SHA256".equals(algorithm)) {+ throw new AwsException("AccessDenied", "Access Denied", 403);+ }+ if (!S3PostPolicySigner.isValidS3CredentialScope(credential)) {+ throw new AwsException("AccessDenied", "Access Denied", 403);+ }+ if (!S3PostPolicySigner.isConsistentAmzDate(date, credential)) {+ throw new AwsException("AccessDenied", "Access Denied", 403);+ }++ String accessKeyId = credential.split("/", 2)[0];+ Optional<String> secretKey = S3PostPolicySigner.resolveSecretKey(iamService, accessKeyId);+ if (secretKey.isEmpty()+ || !S3PostPolicySigner.verifySignature(policy, credential, signature, secretKey.get())) {+ throw new AwsException("SignatureDoesNotMatch",+ "The request signature we calculated does not match the signature you provided. "+ + "Check your key and signing method.", 403);+ }++ // Route through the same authorization check every other S3 write path uses, so this+ // path automatically inherits any future strengthening (e.g. per-principal IAM policy+ // evaluation) instead of silently staying behind. Today it only confirms accessKeyId is+ // known - strictly weaker than the signature check just performed above - but that will+ // change if authorizeObjectWrite grows real policy evaluation.+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject",+ new S3Service.RequestAuthorization(true, accessKeyId));++ validatePolicyExpiration(policy);+ validatePolicyConditions(policy, bucket, fields, contentLength);+ }++ private void validatePolicyExpiration(String policyBase64) {+ try {+ byte[] decoded = java.util.Base64.getDecoder().decode(policyBase64);+ JsonNode policy = OBJECT_MAPPER.readTree(decoded);+ JsonNode expirationNode = policy.get("expiration");+ if (expirationNode == null || expirationNode.isNull()) {+ throw new AwsException("AccessDenied",+ "Invalid according to Policy: Policy is missing required field expiration.", 403);+ }+ Instant expiration = Instant.parse(expirationNode.asText());+ if (Instant.now().isAfter(expiration)) {+ throw new AwsException("AccessDenied",+ "Invalid according to Policy: Policy expired.", 403);+ }+ } catch (AwsException e) {+ throw e;+ } catch (Exception e) {+ throw new AwsException("AccessDenied",+ "Invalid according to Policy: unable to parse policy document.", 403);+ }+ }+private void validatePolicyConditions(String policyBase64, String bucket,Map<String, String> fields, int contentLength) {try {diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3PostPolicySigner.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3PostPolicySigner.javanew file mode 100644index 0000000000..09472d1ec2--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3PostPolicySigner.java@@ -0,0 +1,116 @@+package io.github.hectorvent.floci.services.s3;++import io.github.hectorvent.floci.services.iam.IamService;++import javax.crypto.Mac;+import javax.crypto.spec.SecretKeySpec;+import java.nio.charset.StandardCharsets;+import java.security.MessageDigest;+import java.time.format.DateTimeFormatter;+import java.time.format.DateTimeParseException;+import java.time.format.ResolverStyle;+import java.util.Optional;++/**+ * SigV4 verification for presigned POST policy documents. Mirrors the credential/secret-key+ * resolution and signing-key derivation in {@link PreSignedUrlFilter}'s query-string presigned+ * URL verification, but signs the raw base64 policy document directly rather than a canonical+ * request hash, matching how the AWS SDKs sign a presigned POST policy.+ */+final class S3PostPolicySigner {++ static final String LEGACY_ACCESS_KEY_ID = "test";+ static final String LEGACY_SECRET_KEY = "test";++ private S3PostPolicySigner() {+ }++ static Optional<String> resolveSecretKey(IamService iamService, String accessKeyId) {+ if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {+ return Optional.of(LEGACY_SECRET_KEY);+ }+ if (iamService != null) {+ return iamService.findSecretKey(accessKeyId);+ }+ return Optional.empty();+ }++ /**+ * Verifies that {@code credential} is a well-formed S3 SigV4 credential scope:+ * exactly {@code accessKeyId/date/region/s3/aws4_request}, with the service and+ * terminator fixed, matching what a real S3 presigned POST requires.+ */+ static boolean isValidS3CredentialScope(String credential) {+ String[] parts = credential.split("/");+ return parts.length == 5 && "s3".equals(parts[3]) && "aws4_request".equals(parts[4]);+ }++ private static final DateTimeFormatter AMZ_DATE_TIME_FORMAT =+ DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withResolverStyle(ResolverStyle.STRICT);++ /**+ * Verifies that {@code amzDate} (the form's {@code x-amz-date} field) is a genuine calendar+ * timestamp in ISO8601-basic form ({@code yyyyMMdd'T'HHmmss'Z'}) whose date matches the date+ * embedded in {@code credential}'s scope. Real S3 rejects a presigned POST whose form date+ * doesn't agree with the credential scope, even though only the credential's date drives+ * signing-key derivation. Strict parsing (rather than a digit-shape regex) rejects impossible+ * values such as month 13 or hour 99 that a lenient/smart resolver would otherwise accept.+ */+ static boolean isConsistentAmzDate(String amzDate, String credential) {+ try {+ AMZ_DATE_TIME_FORMAT.parse(amzDate);+ } catch (DateTimeParseException e) {+ return false;+ }+ String[] parts = credential.split("/");+ return parts.length == 5 && amzDate.substring(0, 8).equals(parts[1]);+ }++ /**+ * Verifies that {@code signatureHex} is the SigV4 signature of {@code policyBase64},+ * derived from {@code secretKey} using the date/region in {@code credential}+ * (an {@code accessKeyId/date/region/s3/aws4_request} credential scope; validate with+ * {@link #isValidS3CredentialScope(String)} before calling this).+ */+ static boolean verifySignature(String policyBase64, String credential, String signatureHex, String secretKey) {+ try {+ String[] parts = credential.split("/");+ if (!isValidS3CredentialScope(credential)) {+ return false;+ }+ String date = parts[1];+ String region = parts[2];+ String service = parts[3];+ byte[] signingKey = deriveSigningKey(secretKey, date, region, service);+ String expected = hexEncode(hmacSha256(signingKey, policyBase64));+ return MessageDigest.isEqual(+ expected.getBytes(StandardCharsets.UTF_8),+ signatureHex.getBytes(StandardCharsets.UTF_8));+ } catch (Exception e) {+ return false;+ }+ }++ 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 hexEncode(byte[] bytes) {+ StringBuilder sb = new StringBuilder(bytes.length * 2);+ for (byte b : bytes) {+ sb.append(String.format("%02x", b));+ }+ return sb.toString();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostAuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostAuthEnforcementIntegrationTest.javanew file mode 100644index 0000000000..9c2725ad0d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostAuthEnforcementIntegrationTest.java@@ -0,0 +1,383 @@+package io.github.hectorvent.floci.services.s3;++import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+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.nio.charset.StandardCharsets;+import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.util.Base64;+import java.util.Map;+import javax.crypto.Mac;+import javax.crypto.spec.SecretKeySpec;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;++/**+ * Regression coverage for presigned POST (browser-form multipart upload) rejecting fabricated+ * or absent credentials once {@code floci.services.s3.enforce-auth} is enabled: see the fix in+ * {@code S3Controller#validatePresignedPostAuth}.+ */+@QuarkusTest+@TestProfile(S3PresignedPostAuthEnforcementIntegrationTest.S3AuthProfile.class)+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class S3PresignedPostAuthEnforcementIntegrationTest {++ public static final class S3AuthProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.s3.enforce-auth", "true");+ }+ }++ private static final String BUCKET = "presigned-post-auth-bucket";+ private static final String LEGACY_ACCESS_KEY_ID = "test";+ private static final String LEGACY_SECRET_KEY = "test";+ // Matches the "20260101" date embedded in every credential scope built by this test class.+ private static final String AMZ_DATE = "20260101T000000Z";++ @Test+ @Order(1)+ void createBucket() {+ given()+ .when()+ .put("/" + BUCKET)+ .then()+ .statusCode(200);+ }++ @Test+ @Order(10)+ void rejectsUploadWithNoPolicyAndFabricatedCredentials() {+ given()+ .multiPart("key", "anon-upload.txt")+ .multiPart("x-amz-credential", "totally-fake/20260101/us-east-1/s3/aws4_request")+ .multiPart("x-amz-signature", "0000000000000000000000000000000000000000000000000000000000dead")+ .multiPart("file", "anon-upload.txt",+ "uploaded with no real credentials".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));+ }++ @Test+ @Order(11)+ void rejectsUploadWithValidPolicyButFabricatedSignature() {+ String key = "fabricated-signature.txt";+ String policyBase64 = buildPolicyBase64(BUCKET, key);++ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/s3/aws4_request")+ .multiPart("x-amz-date", AMZ_DATE)+ .multiPart("x-amz-signature",+ "0000000000000000000000000000000000000000000000000000000000dead")+ .multiPart("file", "fabricated-signature.txt",+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("SignatureDoesNotMatch"));++ given()+ .header("Authorization", authorizationHeader(LEGACY_ACCESS_KEY_ID))+ .when()+ .get("/" + BUCKET + "/" + key)+ .then()+ .statusCode(404);+ }++ @Test+ @Order(12)+ void rejectsUploadWithUnknownAccessKeyId() {+ String key = "unknown-key.txt";+ String policyBase64 = buildPolicyBase64(BUCKET, key);+ String credential = "AKIAUNKNOWNACCESSKEY/20260101/us-east-1/s3/aws4_request";+ String signature = signPolicy(policyBase64, credential, "some-random-secret");++ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", credential)+ .multiPart("x-amz-date", AMZ_DATE)+ .multiPart("x-amz-signature", signature)+ .multiPart("file", "unknown-key.txt",+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("SignatureDoesNotMatch"));+ }++ @Test+ @Order(13)+ void rejectsUploadMissingRequiredFormFields() {+ String key = "missing-date.txt";+ String policyBase64 = buildPolicyBase64(BUCKET, key);+ String credential = LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/s3/aws4_request";+ String signature = signPolicy(policyBase64, credential, LEGACY_SECRET_KEY);++ // Missing x-amz-date entirely, even though the policy and signature are otherwise genuine.+ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", credential)+ .multiPart("x-amz-signature", signature)+ .multiPart("file", "missing-date.txt",+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));+ }++ @Test+ @Order(14)+ void rejectsUploadWithMalformedCredentialScope() {+ String key = "malformed-scope.txt";+ String policyBase64 = buildPolicyBase64(BUCKET, key);+ // Wrong service ("ec2" instead of "s3") in an otherwise well-formed credential scope.+ String credential = LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/ec2/aws4_request";+ String signature = signPolicy(policyBase64, credential, LEGACY_SECRET_KEY);++ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", credential)+ .multiPart("x-amz-date", AMZ_DATE)+ .multiPart("x-amz-signature", signature)+ .multiPart("file", "malformed-scope.txt",+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));+ }++ @Test+ @Order(15)+ void rejectsUploadWhereFormDateDisagreesWithCredentialScope() {+ String key = "date-mismatch.txt";+ String policyBase64 = buildPolicyBase64(BUCKET, key);+ String credential = LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/s3/aws4_request";+ String signature = signPolicy(policyBase64, credential, LEGACY_SECRET_KEY);++ // x-amz-date's date (20260102) disagrees with the credential scope's date (20260101).+ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", credential)+ .multiPart("x-amz-date", "20260102T000000Z")+ .multiPart("x-amz-signature", signature)+ .multiPart("file", "date-mismatch.txt",+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));+ }++ @Test+ @Order(16)+ void rejectsUploadWithImpossibleFormDate() {+ String key = "impossible-date.txt";+ String policyBase64 = buildPolicyBase64(BUCKET, key);+ // "20261332" has the right digit shape but month 13 / day 32 don't exist; same for the+ // 99:99:99 time. The credential scope's date is made to match digit-for-digit so only+ // strict calendar parsing (not a same-date-string comparison) can catch this.+ String credential = LEGACY_ACCESS_KEY_ID + "/20261332/us-east-1/s3/aws4_request";+ String signature = signPolicy(policyBase64, credential, LEGACY_SECRET_KEY);++ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", credential)+ .multiPart("x-amz-date", "20261332T999999Z")+ .multiPart("x-amz-signature", signature)+ .multiPart("file", "impossible-date.txt",+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));+ }++ @Test+ @Order(20)+ void acceptsUploadWithGenuineSignature() {+ String key = "uploads/genuine.txt";+ String fileContent = "uploaded with a real signature";+ String policyBase64 = buildPolicyBase64(BUCKET, key);+ String credential = LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/s3/aws4_request";+ String signature = signPolicy(policyBase64, credential, LEGACY_SECRET_KEY);++ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", credential)+ .multiPart("x-amz-date", AMZ_DATE)+ .multiPart("x-amz-signature", signature)+ .multiPart("file", "genuine.txt", fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(204)+ .header("ETag", notNullValue());++ given()+ .header("Authorization", authorizationHeader(LEGACY_ACCESS_KEY_ID))+ .when()+ .get("/" + BUCKET + "/" + key)+ .then()+ .statusCode(200)+ .body(org.hamcrest.Matchers.equalTo(fileContent));+ }++ @Test+ @Order(21)+ void rejectsExpiredPolicyEvenWithGenuineSignature() {+ String key = "uploads/expired.txt";+ String expiration = Instant.now().minusSeconds(3600)+ .atZone(ZoneOffset.UTC)+ .format(DateTimeFormatter.ISO_INSTANT);+ String policy = """+ {+ "expiration": "%s",+ "conditions": [+ {"bucket": "%s"},+ {"key": "%s"}+ ]+ }+ """.formatted(expiration, BUCKET, key);+ String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));+ String credential = LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/s3/aws4_request";+ String signature = signPolicy(policyBase64, credential, LEGACY_SECRET_KEY);++ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", credential)+ .multiPart("x-amz-date", AMZ_DATE)+ .multiPart("x-amz-signature", signature)+ .multiPart("file", "expired.txt",+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));+ }++ @Test+ @Order(22)+ void rejectsPolicyWithNoExpirationEvenWithGenuineSignature() {+ String key = "uploads/no-expiration.txt";+ String policy = """+ {+ "conditions": [+ {"bucket": "%s"},+ {"key": "%s"}+ ]+ }+ """.formatted(BUCKET, key);+ String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));+ String credential = LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/s3/aws4_request";+ String signature = signPolicy(policyBase64, credential, LEGACY_SECRET_KEY);++ given()+ .multiPart("key", key)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", credential)+ .multiPart("x-amz-date", AMZ_DATE)+ .multiPart("x-amz-signature", signature)+ .multiPart("file", "no-expiration.txt",+ "should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(403)+ .body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));+ }++ private static String authorizationHeader(String accessKeyId) {+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260101/us-east-1/s3/aws4_request"+ + ", SignedHeaders=host;x-amz-date, Signature=test";+ }++ private static String buildPolicyBase64(String bucket, String key) {+ String expiration = Instant.now().plusSeconds(3600)+ .atZone(ZoneOffset.UTC)+ .format(DateTimeFormatter.ISO_INSTANT);+ String policy = """+ {+ "expiration": "%s",+ "conditions": [+ {"bucket": "%s"},+ {"key": "%s"}+ ]+ }+ """.formatted(expiration, bucket, key);+ return Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));+ }++ private static String signPolicy(String policyBase64, String credential, String secretKey) {+ try {+ String[] parts = credential.split("/");+ String date = parts[1];+ String region = parts[2];+ String service = parts[3];+ byte[] signingKey = deriveSigningKey(secretKey, date, region, service);+ return hexEncode(hmacSha256(signingKey, policyBase64));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }++ 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 hexEncode(byte[] bytes) {+ StringBuilder sb = new StringBuilder(bytes.length * 2);+ for (byte b : bytes) {+ sb.append(String.format("%02x", b));+ }+ return sb.toString();+ }+}