Light, fluffy, and always free - The AWS Local Emulator alternative
fix(s3): avoid misrouting presigned PUTs with tagging (#932) (#995)
nblomquist894b39f44612
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3PresignTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3PresignTest.javanew file mode 100644index 0000000000..11860ccc7c--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3PresignTest.java@@ -0,0 +1,133 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;+import software.amazon.awssdk.regions.Region;+import software.amazon.awssdk.services.s3.S3Client;+import software.amazon.awssdk.services.s3.S3Configuration;+import software.amazon.awssdk.services.s3.model.CreateBucketRequest;+import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;+import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;+import software.amazon.awssdk.services.s3.model.GetObjectRequest;+import software.amazon.awssdk.services.s3.model.PutObjectRequest;+import software.amazon.awssdk.services.s3.presigner.S3Presigner;+import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest;+import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;++import java.io.InputStream;+import java.io.OutputStream;+import java.net.HttpURLConnection;+import java.nio.charset.StandardCharsets;+import java.time.Duration;+import java.util.List;+import java.util.Map;++import static org.assertj.core.api.Assertions.assertThat;++@DisplayName("S3 Pre-signed URLs")+class S3PresignTest {++ private static final StaticCredentialsProvider CREDENTIALS =+ StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"));++ private static S3Client s3;+ private static S3Presigner presigner;+ private static final String BUCKET = TestFixtures.uniqueName("sdk-s3-presign");+ private static final String KEY = "presigned-tagged-put.txt";++ @BeforeAll+ static void setup() {+ s3 = TestFixtures.s3Client();+ presigner = S3Presigner.builder()+ .endpointOverride(TestFixtures.endpoint())+ .region(Region.US_EAST_1)+ .credentialsProvider(CREDENTIALS)+ .serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build())+ .build();++ s3.createBucket(CreateBucketRequest.builder().bucket(BUCKET).build());+ }++ @AfterAll+ static void cleanup() {+ if (s3 != null) {+ try {+ s3.deleteObject(DeleteObjectRequest.builder().bucket(BUCKET).key(KEY).build());+ } catch (Exception ignored) {+ }+ try {+ s3.deleteBucket(DeleteBucketRequest.builder().bucket(BUCKET).build());+ } catch (Exception ignored) {+ }+ s3.close();+ }+ if (presigner != null) {+ presigner.close();+ }+ }++ @Test+ @DisplayName("#932 presigned PUT with tagging signed header uploads successfully")+ void presignedPutWithTaggingSignedHeaderUploadsSuccessfully() throws Exception {+ String content = "uploaded via presigned PUT with tagging signed header";++ PutObjectRequest putObjectRequest = PutObjectRequest.builder()+ .bucket(BUCKET)+ .key(KEY)+ .tagging("tag=test")+ .build();++ PresignedPutObjectRequest presigned = presigner.presignPutObject(+ PutObjectPresignRequest.builder()+ .signatureDuration(Duration.ofMinutes(10))+ .putObjectRequest(putObjectRequest)+ .build()+ );++ String rawQuery = presigned.url().toURI().getRawQuery();+ assertThat(rawQuery).contains("X-Amz-SignedHeaders=");+ assertThat(rawQuery).contains("x-amz-tagging");+ assertThat(presigned.httpRequest().headers()).containsKey("x-amz-tagging");++ HttpURLConnection connection = (HttpURLConnection) presigned.url().openConnection();+ connection.setRequestMethod("PUT");+ connection.setDoOutput(true);++ for (Map.Entry<String, List<String>> entry : presigned.httpRequest().headers().entrySet()) {+ for (String value : entry.getValue()) {+ connection.addRequestProperty(entry.getKey(), value);+ }+ }++ byte[] body = content.getBytes(StandardCharsets.UTF_8);+ connection.setFixedLengthStreamingMode(body.length);+ try (OutputStream os = connection.getOutputStream()) {+ os.write(body);+ }++ int status = connection.getResponseCode();+ String responseBody;+ InputStream stream = status >= 400 ? connection.getErrorStream() : connection.getInputStream();+ if (stream == null) {+ responseBody = "";+ } else {+ try (InputStream is = stream) {+ responseBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);+ }+ }++ assertThat(status)+ .withFailMessage("Expected presigned PUT with x-amz-tagging signed header to succeed, got %s: %s", status, responseBody)+ .isEqualTo(200);++ String downloaded = new String(+ s3.getObject(GetObjectRequest.builder().bucket(BUCKET).key(KEY).build()).readAllBytes(),+ StandardCharsets.UTF_8+ );+ assertThat(downloaded).isEqualTo(content);+ }+}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 6da2ab9457..0b6d6ccabf 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@@ -1,5 +1,7 @@package io.github.hectorvent.floci.services.s3;+import static io.github.hectorvent.floci.services.s3.S3RequestParser.hasQueryParam;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsNamespaces;import io.github.hectorvent.floci.core.common.XmlBuilder;@@ -2269,13 +2271,6 @@ public class S3Controller {}}- private boolean hasQueryParam(UriInfo uriInfo, String param) {- if (uriInfo.getQueryParameters().containsKey(param)) return true;- String query = uriInfo.getRequestUri().getQuery();- if (query == null) return false;- return query.equals(param) || query.contains(param + "&") || query.contains("&" + param);- }-/*** Extracts the object key from the raw Vert.x request URI, preserving leading slashes* that JAX-RS path normalization would otherwise strip.diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestParser.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestParser.javanew file mode 100644index 0000000000..f92bf92a0a--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestParser.java@@ -0,0 +1,46 @@+package io.github.hectorvent.floci.services.s3;++import jakarta.ws.rs.core.UriInfo;++/**+ * Package-private utility for parsing S3 request elements.+ * Methods are static and stateless for direct testability.+ *+ * <p>Created in Phase 1 (#932) with {@link #hasQueryParam(UriInfo, String)}.+ * Extended in Phase 2 (#986) with {@link #parseTaggingHeader(String)}.+ */+final class S3RequestParser {++ private S3RequestParser() {+ }++ /**+ * Returns {@code true} if the request URI contains a query parameter with the given name.+ * Checks {@link UriInfo#getQueryParameters()} first; if that does not contain the param,+ * falls back to parsing the raw query string by splitting on {@code &} and extracting+ * the parameter name (everything before the first {@code =}).+ *+ * <p>This avoids false positives from substring matches inside parameter <em>values</em>+ * (e.g. {@code X-Amz-SignedHeaders=host%3Bx-amz-tagging} would falsely match+ * {@code "tagging"} with naive {@code String.contains()}).+ */+ static boolean hasQueryParam(UriInfo uriInfo, String param) {+ if (uriInfo.getQueryParameters().containsKey(param)) return true;+ String query = uriInfo.getRequestUri().getQuery();+ return hasQueryParamInString(query, param);+ }++ /**+ * Direct string-based variant for testing without UriInfo mocking.+ * Package-private so unit tests in the same package can call it.+ */+ static boolean hasQueryParamInString(String query, String param) {+ if (query == null) return false;+ for (String pair : query.split("&")) {+ int eq = pair.indexOf('=');+ String name = eq >= 0 ? pair.substring(0, eq) : pair;+ if (name.equals(param)) return true;+ }+ return false;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPutTaggingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPutTaggingIntegrationTest.javanew file mode 100644index 0000000000..21125fb1a2--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPutTaggingIntegrationTest.java@@ -0,0 +1,82 @@+package io.github.hectorvent.floci.services.s3;++import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Test;++import java.net.URI;+import java.util.Arrays;+import java.util.stream.Collectors;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.assertTrue;++@QuarkusTest+class S3PresignedPutTaggingIntegrationTest {++ private static final String BUCKET = "presigned-tagging-bucket";++ @Inject+ PreSignedUrlGenerator presignGenerator;++ /**+ * Regression test for #932: a presigned PUT URL whose {@code X-Amz-SignedHeaders}+ * includes {@code x-amz-tagging} must NOT be misrouted to the+ * {@code ?tagging} sub-resource handler (PutObjectTagging).+ *+ * <p>The fix was in {@link S3RequestParser#hasQueryParamInString}: the old+ * {@code String.contains()} implementation falsely matched "tagging" inside the+ * <em>value</em> of {@code X-Amz-SignedHeaders} (e.g.+ * {@code host%3Bx-amz-tagging}), causing a 404. The new implementation correctly+ * splits on {@code &} and extracts parameter names before {@code =}.+ */+ @Test+ void presignedPutWithTaggingSignedHeaderDoesNotMisrouteToPutObjectTagging() {+ given()+ .when()+ .put("/" + BUCKET)+ .then()+ .statusCode(200);++ int port = io.restassured.RestAssured.port;+ String fullBaseUrl = "http://localhost:" + port;+ String presignedUrl = presignGenerator.generatePresignedUrl(+ fullBaseUrl, BUCKET, "tagged-via-presign.txt", "PUT", 3600);++ URI uri = URI.create(presignedUrl);+ String rawQuery = uri.getRawQuery();+ assertTrue(rawQuery.contains("X-Amz-SignedHeaders=host"),+ "expected generated presigned URL to include X-Amz-SignedHeaders=host");++ // Add x-amz-tagging to X-Amz-SignedHeaders by properly parsing and reconstructing+ // the query string — avoids the fragility of raw String.replace().+ String taggingSignedHeadersQuery = Arrays.stream(rawQuery.split("&"))+ .map(pair -> {+ if (pair.startsWith("X-Amz-SignedHeaders=")) {+ return pair + "%3Bx-amz-tagging";+ }+ return pair;+ })+ .collect(Collectors.joining("&"));++ given()+ .urlEncodingEnabled(false)+ .contentType("text/plain")+ .header("x-amz-tagging", "tag=test")+ .body("uploaded via presigned PUT with tagging")+ .when()+ .put(uri.getRawPath() + "?" + taggingSignedHeadersQuery)+ .then()+ .statusCode(200)+ .header("ETag", notNullValue());++ given()+ .when()+ .get("/" + BUCKET + "/tagged-via-presign.txt")+ .then()+ .statusCode(200)+ .body(equalTo("uploaded via presigned PUT with tagging"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTaggingTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTaggingTest.javanew file mode 100644index 0000000000..7669ee7f24--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTaggingTest.java@@ -0,0 +1,74 @@+package io.github.hectorvent.floci.services.s3;++import static org.junit.jupiter.api.Assertions.*;++import org.junit.jupiter.api.Test;++/**+ * Tests for S3 tagging: service-layer behavior and {@link S3RequestParser} utility methods.+ *+ * <p>Phase 1 (#932): tests 10+ cover {@code hasQueryParam} false-positive fix.+ * Phase 2 (#986): tests 1-9 cover inline tagging header parsing and persistence.+ */+class S3ServiceTaggingTest {++ // ========== Phase 2: Inline tagging header parsing ==========++ // (Tests 1-9 will be added in Phase 2 — fix/s3-putobject-inline-tagging)++ // ========== Phase 1: hasQueryParam false-positive fix ==========++ @Test+ void hasQueryParamReturnsTrueForExactParamName() {+ assertTrue(S3RequestParser.hasQueryParamInString("tagging", "tagging"));+ }++ @Test+ void hasQueryParamReturnsTrueForParamWithValue() {+ assertTrue(S3RequestParser.hasQueryParamInString("tagging=", "tagging"));+ }++ @Test+ void hasQueryParamReturnsTrueForParamAmongOthers() {+ assertTrue(S3RequestParser.hasQueryParamInString(+ "versionId=abc&tagging&acl", "tagging"));+ }++ @Test+ void hasQueryParamReturnsFalseForNullQuery() {+ assertFalse(S3RequestParser.hasQueryParamInString(null, "tagging"));+ }++ @Test+ void hasQueryParamReturnsFalseForEmptyQuery() {+ assertFalse(S3RequestParser.hasQueryParamInString("", "tagging"));+ }++ @Test+ void hasQueryParamNoFalsePositiveOnValueContainingParamName() {+ // This is the actual #932 bug: X-Amz-SignedHeaders value contains "x-amz-tagging"+ // but there is no "tagging" query parameter. The old code would falsely match.+ String query = "X-Amz-SignedHeaders=host%3Bx-amz-tagging&X-Amz-Algorithm=AWS4-HMAC-SHA256";+ assertFalse(S3RequestParser.hasQueryParamInString(query, "tagging"));+ }++ @Test+ void hasQueryParamNoFalsePositiveOnPartialPrefix() {+ // "tagging" should not match "tag"+ assertFalse(S3RequestParser.hasQueryParamInString("tagging", "tag"));+ }++ @Test+ void hasQueryParamDetectsParamValueContainsEquals() {+ // Param with = in value — only the first = is the delimiter+ String query = "X-Amz-Credential=test/2024/us-east-1/s3/aws4_request";+ assertTrue(S3RequestParser.hasQueryParamInString(query, "X-Amz-Credential"));+ }++ @Test+ void hasQueryParamNoFalsePositiveOnUnrelatedQuery() {+ String query = "versionId=abc&uploadId=xyz";+ assertFalse(S3RequestParser.hasQueryParamInString(query, "tagging"));+ assertFalse(S3RequestParser.hasQueryParamInString(query, "acl"));+ }+}