Light, fluffy, and always free - The AWS Local Emulator alternative
feat(s3): add presigned POST upload support (#120)
Matej Šnuderl1e59f8dc5916
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 71d0cc0341..852f2739cc 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@@ -29,6 +29,7 @@ import java.nio.charset.StandardCharsets;import java.time.Instant;import java.time.ZoneId;import java.time.format.DateTimeFormatter;+import java.util.Arrays;import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;@@ -552,12 +553,16 @@ public class S3Controller {@Path("/{bucket}")@Produces(MediaType.APPLICATION_XML)public Response handleBucketPost(@PathParam("bucket") String bucket,+ @HeaderParam("Content-Type") String contentType,@Context UriInfo uriInfo,byte[] body) {try {if (hasQueryParam(uriInfo, "delete")) {return handleDeleteObjects(bucket, body);}+ if (contentType != null && contentType.startsWith("multipart/form-data")) {+ return handlePresignedPost(bucket, contentType, body);+ }return xmlErrorResponse(new AwsException("InvalidArgument","POST on bucket requires ?delete parameter.", 400));} catch (AwsException e) {@@ -1256,6 +1261,258 @@ public class S3Controller {}}+ private Response handlePresignedPost(String bucket, String contentType, byte[] body) {+ String boundary = extractBoundary(contentType);+ if (boundary == null) {+ throw new AwsException("InvalidArgument",+ "Could not determine multipart boundary from Content-Type.", 400);+ }++ Map<String, String> fields = new LinkedHashMap<>();+ byte[] fileData = null;+ String fileContentType = null;++ byte[] boundaryBytes = ("--" + boundary).getBytes(StandardCharsets.UTF_8);+ List<byte[]> parts = splitMultipartParts(body, boundaryBytes);++ for (byte[] part : parts) {+ int headerEnd = indexOfDoubleNewline(part);+ if (headerEnd < 0) {+ continue;+ }+ String headers = new String(part, 0, headerEnd, StandardCharsets.UTF_8);+ int bodyStart = headerEnd + 4; // skip \r\n\r\n+ byte[] partBody = Arrays.copyOfRange(part, bodyStart, part.length);++ // Trim trailing \r\n from part body+ if (partBody.length >= 2+ && partBody[partBody.length - 2] == '\r'+ && partBody[partBody.length - 1] == '\n') {+ partBody = Arrays.copyOf(partBody, partBody.length - 2);+ }++ String disposition = extractHeaderValue(headers, "Content-Disposition");+ if (disposition == null) {+ continue;+ }+ String fieldName = extractDispositionParam(disposition, "name");+ if (fieldName == null) {+ continue;+ }++ String filename = extractDispositionParam(disposition, "filename");+ if (filename != null) {+ fileData = partBody;+ String partContentType = extractHeaderValue(headers, "Content-Type");+ if (partContentType != null) {+ fileContentType = partContentType.trim();+ }+ } else {+ fields.put(fieldName, new String(partBody, StandardCharsets.UTF_8));+ }+ }++ String key = fields.get("key");+ if (key == null || key.isEmpty()) {+ throw new AwsException("InvalidArgument",+ "Bucket POST must contain a field named 'key'.", 400);+ }++ if (fileData == null) {+ throw new AwsException("InvalidArgument",+ "Bucket POST must contain a file field.", 400);+ }++ // Validate content-length-range from policy if present+ String policy = fields.get("policy");+ if (policy != null && !policy.isEmpty()) {+ validateContentLengthRange(policy, fileData.length);+ }++ // Use Content-Type from form fields, fall back to file part Content-Type+ String objectContentType = fields.get("Content-Type");+ if (objectContentType == null || objectContentType.isEmpty()) {+ objectContentType = fileContentType;+ }+ if (objectContentType == null || objectContentType.isEmpty()) {+ objectContentType = "application/octet-stream";+ }++ S3Object obj = s3Service.putObject(bucket, key, fileData, objectContentType, null);+ LOG.infov("Presigned POST upload: {0}/{1} ({2} bytes)", bucket, key, fileData.length);++ String xml = new XmlBuilder()+ .raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")+ .start("PostResponse")+ .elem("Location", bucket + "/" + key)+ .elem("Bucket", bucket)+ .elem("Key", key)+ .elem("ETag", obj.getETag())+ .end("PostResponse")+ .build();+ return Response.status(204)+ .header("ETag", obj.getETag())+ .header("Location", bucket + "/" + key)+ .build();+ }++ private void validateContentLengthRange(String policyBase64, int contentLength) {+ try {+ String decoded = new String(java.util.Base64.getDecoder().decode(policyBase64), StandardCharsets.UTF_8);+ // Parse conditions array from the policy JSON to find content-length-range+ int condIdx = decoded.indexOf("\"conditions\"");+ if (condIdx < 0) {+ return;+ }+ // Look for content-length-range condition: ["content-length-range", min, max]+ String lower = decoded.toLowerCase(Locale.ROOT);+ int rangeIdx = lower.indexOf("content-length-range");+ if (rangeIdx < 0) {+ return;+ }+ // Find the enclosing array bracket+ int bracketStart = decoded.lastIndexOf('[', rangeIdx);+ int bracketEnd = decoded.indexOf(']', rangeIdx);+ if (bracketStart < 0 || bracketEnd < 0) {+ return;+ }+ String rangeArray = decoded.substring(bracketStart, bracketEnd + 1);+ // Extract min and max values+ String[] tokens = rangeArray.replaceAll("[\\[\\]\"]", "").split(",");+ if (tokens.length >= 3) {+ long min = Long.parseLong(tokens[1].trim());+ long max = Long.parseLong(tokens[2].trim());+ if (contentLength < min || contentLength > max) {+ throw new AwsException("EntityTooLarge",+ "Your proposed upload exceeds the maximum allowed size.", 400);+ }+ }+ } catch (AwsException e) {+ throw e;+ } catch (Exception e) {+ // If policy parsing fails, skip validation (match AWS lenient behavior for emulator)+ LOG.debugv("Failed to parse presigned POST policy: {0}", e.getMessage());+ }+ }++ private static String extractBoundary(String contentType) {+ if (contentType == null) {+ return null;+ }+ for (String part : contentType.split(";")) {+ String trimmed = part.trim();+ if (trimmed.toLowerCase(Locale.ROOT).startsWith("boundary=")) {+ String boundary = trimmed.substring("boundary=".length()).trim();+ if (boundary.startsWith("\"") && boundary.endsWith("\"")) {+ boundary = boundary.substring(1, boundary.length() - 1);+ }+ return boundary;+ }+ }+ return null;+ }++ private static List<byte[]> splitMultipartParts(byte[] body, byte[] boundary) {+ java.util.ArrayList<byte[]> parts = new java.util.ArrayList<>();+ int pos = indexOf(body, boundary, 0);+ if (pos < 0) {+ return parts;+ }+ // Skip past the first boundary line+ pos += boundary.length;+ // Skip the CRLF or -- after boundary+ if (pos < body.length - 1 && body[pos] == '-' && body[pos + 1] == '-') {+ return parts; // closing boundary immediately+ }+ if (pos < body.length - 1 && body[pos] == '\r' && body[pos + 1] == '\n') {+ pos += 2;+ }++ while (pos < body.length) {+ int nextBoundary = indexOf(body, boundary, pos);+ if (nextBoundary < 0) {+ break;+ }+ parts.add(Arrays.copyOfRange(body, pos, nextBoundary));+ pos = nextBoundary + boundary.length;+ // Check for closing boundary --+ if (pos < body.length - 1 && body[pos] == '-' && body[pos + 1] == '-') {+ break;+ }+ // Skip CRLF after boundary+ if (pos < body.length - 1 && body[pos] == '\r' && body[pos + 1] == '\n') {+ pos += 2;+ }+ }+ return parts;+ }++ private static int indexOf(byte[] data, byte[] pattern, int fromIndex) {+ outer:+ for (int i = fromIndex; i <= data.length - pattern.length; i++) {+ for (int j = 0; j < pattern.length; j++) {+ if (data[i + j] != pattern[j]) {+ continue outer;+ }+ }+ return i;+ }+ return -1;+ }++ private static int indexOfDoubleNewline(byte[] data) {+ for (int i = 0; i < data.length - 3; i++) {+ if (data[i] == '\r' && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n') {+ return i;+ }+ }+ return -1;+ }++ private static String extractHeaderValue(String headers, String headerName) {+ String lowerHeaders = headers.toLowerCase(Locale.ROOT);+ String lowerName = headerName.toLowerCase(Locale.ROOT) + ":";+ int idx = lowerHeaders.indexOf(lowerName);+ if (idx < 0) {+ return null;+ }+ int valueStart = idx + lowerName.length();+ int lineEnd = headers.indexOf('\r', valueStart);+ if (lineEnd < 0) {+ lineEnd = headers.indexOf('\n', valueStart);+ }+ if (lineEnd < 0) {+ lineEnd = headers.length();+ }+ return headers.substring(valueStart, lineEnd).trim();+ }++ private static String extractDispositionParam(String disposition, String paramName) {+ String search = paramName + "=";+ int idx = disposition.indexOf(search);+ if (idx < 0) {+ return null;+ }+ int valueStart = idx + search.length();+ if (valueStart >= disposition.length()) {+ return null;+ }+ if (disposition.charAt(valueStart) == '"') {+ valueStart++;+ int valueEnd = disposition.indexOf('"', valueStart);+ if (valueEnd < 0) {+ return disposition.substring(valueStart);+ }+ return disposition.substring(valueStart, valueEnd);+ } else {+ int valueEnd = disposition.indexOf(';', valueStart);+ if (valueEnd < 0) {+ valueEnd = disposition.length();+ }+ return disposition.substring(valueStart, valueEnd).trim();+ }+ }+private boolean hasQueryParam(UriInfo uriInfo, String param) {if (uriInfo.getQueryParameters().containsKey(param)) return true;String query = uriInfo.getRequestUri().getQuery();diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostIntegrationTest.javanew file mode 100644index 0000000000..c574d48727--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedPostIntegrationTest.java@@ -0,0 +1,291 @@+package io.github.hectorvent.floci.services.s3;++import io.quarkus.test.junit.QuarkusTest;+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 static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.*;++@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class S3PresignedPostIntegrationTest {++ private static final String BUCKET = "presigned-post-bucket";+ private static final DateTimeFormatter AMZ_DATE_FORMAT =+ DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);++ @Test+ @Order(1)+ void createBucket() {+ given()+ .when()+ .put("/" + BUCKET)+ .then()+ .statusCode(200);+ }++ @Test+ @Order(10)+ void presignedPostUploadsObject() {+ String key = "uploads/test-file.txt";+ String fileContent = "Hello from presigned POST!";+ String contentType = "text/plain";++ String policy = buildPolicy(BUCKET, key, contentType, 0, 10485760);+ String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));++ given()+ .multiPart("key", key)+ .multiPart("Content-Type", contentType)+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", "AKIAIOSFODNN7EXAMPLE/20260330/us-east-1/s3/aws4_request")+ .multiPart("x-amz-date", AMZ_DATE_FORMAT.format(Instant.now()))+ .multiPart("x-amz-signature", "dummysignature")+ .multiPart("file", "test-file.txt", fileContent.getBytes(StandardCharsets.UTF_8), contentType)+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(204)+ .header("ETag", notNullValue());++ // Verify the object was stored correctly+ given()+ .when()+ .get("/" + BUCKET + "/" + key)+ .then()+ .statusCode(200)+ .header("Content-Type", equalTo(contentType))+ .body(equalTo(fileContent));+ }++ @Test+ @Order(20)+ void presignedPostWithBinaryData() {+ String key = "uploads/binary-data.bin";+ byte[] binaryData = new byte[256];+ for (int i = 0; i < 256; i++) {+ binaryData[i] = (byte) i;+ }++ String policy = buildPolicy(BUCKET, key, "application/octet-stream", 0, 10485760);+ String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));++ given()+ .multiPart("key", key)+ .multiPart("Content-Type", "application/octet-stream")+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", "AKIAIOSFODNN7EXAMPLE/20260330/us-east-1/s3/aws4_request")+ .multiPart("x-amz-date", AMZ_DATE_FORMAT.format(Instant.now()))+ .multiPart("x-amz-signature", "dummysignature")+ .multiPart("file", "binary-data.bin", binaryData, "application/octet-stream")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(204)+ .header("ETag", notNullValue());++ // Verify the binary object was stored correctly+ byte[] retrieved = given()+ .when()+ .get("/" + BUCKET + "/" + key)+ .then()+ .statusCode(200)+ .extract().body().asByteArray();++ org.junit.jupiter.api.Assertions.assertArrayEquals(binaryData, retrieved);+ }++ @Test+ @Order(30)+ void presignedPostRejectsExceedingContentLength() {+ String key = "uploads/too-large.txt";+ // Create data that exceeds the max content-length-range of 10 bytes+ String fileContent = "This content is definitely longer than 10 bytes";++ String policy = buildPolicy(BUCKET, key, "text/plain", 0, 10);+ String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));++ given()+ .multiPart("key", key)+ .multiPart("Content-Type", "text/plain")+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", "AKIAIOSFODNN7EXAMPLE/20260330/us-east-1/s3/aws4_request")+ .multiPart("x-amz-date", AMZ_DATE_FORMAT.format(Instant.now()))+ .multiPart("x-amz-signature", "dummysignature")+ .multiPart("file", "too-large.txt", fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(400)+ .body(containsString("EntityTooLarge"));+ }++ @Test+ @Order(40)+ void presignedPostRequiresKeyField() {+ given()+ .multiPart("Content-Type", "text/plain")+ .multiPart("policy", "dummypolicy")+ .multiPart("file", "test.txt", "content".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(400)+ .body(containsString("InvalidArgument"));+ }++ @Test+ @Order(50)+ void presignedPostRequiresFileField() {+ given()+ .multiPart("key", "uploads/no-file.txt")+ .multiPart("Content-Type", "text/plain")+ .multiPart("policy", "dummypolicy")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(400)+ .body(containsString("InvalidArgument"));+ }++ @Test+ @Order(60)+ void presignedPostWithoutPolicySkipsValidation() {+ String key = "uploads/no-policy.txt";+ String fileContent = "Uploaded without policy";++ given()+ .multiPart("key", key)+ .multiPart("Content-Type", "text/plain")+ .multiPart("file", "no-policy.txt", fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(204)+ .header("ETag", notNullValue());++ // Verify the object was stored+ given()+ .when()+ .get("/" + BUCKET + "/" + key)+ .then()+ .statusCode(200)+ .body(equalTo(fileContent));+ }++ @Test+ @Order(70)+ void presignedPostContentTypeFromFormField() {+ String key = "uploads/typed-file.json";+ String fileContent = "{\"test\": true}";++ String policy = buildPolicy(BUCKET, key, "application/json", 0, 10485760);+ String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));++ given()+ .multiPart("key", key)+ .multiPart("Content-Type", "application/json")+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", "AKIAIOSFODNN7EXAMPLE/20260330/us-east-1/s3/aws4_request")+ .multiPart("x-amz-date", AMZ_DATE_FORMAT.format(Instant.now()))+ .multiPart("x-amz-signature", "dummysignature")+ .multiPart("file", "typed-file.json", fileContent.getBytes(StandardCharsets.UTF_8), "application/octet-stream")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(204);++ // Content-Type should come from the form field, not the file part+ given()+ .when()+ .get("/" + BUCKET + "/" + key)+ .then()+ .statusCode(200)+ .header("Content-Type", equalTo("application/json"));+ }++ @Test+ @Order(80)+ void presignedPostToNonExistentBucketFails() {+ given()+ .multiPart("key", "test.txt")+ .multiPart("file", "test.txt", "data".getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/nonexistent-presigned-bucket")+ .then()+ .statusCode(404)+ .body(containsString("NoSuchBucket"));+ }++ @Test+ @Order(90)+ void presignedPostWithContentLengthWithinRange() {+ String key = "uploads/within-range.txt";+ // Exactly 5 bytes, within range [1, 100]+ String fileContent = "12345";++ String policy = buildPolicy(BUCKET, key, "text/plain", 1, 100);+ String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));++ given()+ .multiPart("key", key)+ .multiPart("Content-Type", "text/plain")+ .multiPart("policy", policyBase64)+ .multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")+ .multiPart("x-amz-credential", "AKIAIOSFODNN7EXAMPLE/20260330/us-east-1/s3/aws4_request")+ .multiPart("x-amz-date", AMZ_DATE_FORMAT.format(Instant.now()))+ .multiPart("x-amz-signature", "dummysignature")+ .multiPart("file", "within-range.txt", fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")+ .when()+ .post("/" + BUCKET)+ .then()+ .statusCode(204);+ }++ @Test+ @Order(100)+ void cleanupBucket() {+ // Delete all objects+ given().delete("/" + BUCKET + "/uploads/test-file.txt");+ given().delete("/" + BUCKET + "/uploads/binary-data.bin");+ given().delete("/" + BUCKET + "/uploads/no-policy.txt");+ given().delete("/" + BUCKET + "/uploads/typed-file.json");+ given().delete("/" + BUCKET + "/uploads/within-range.txt");++ given()+ .when()+ .delete("/" + BUCKET)+ .then()+ .statusCode(204);+ }++ private String buildPolicy(String bucket, String key, String contentType, long minSize, long maxSize) {+ String expiration = Instant.now().plusSeconds(3600)+ .atZone(ZoneOffset.UTC)+ .format(DateTimeFormatter.ISO_INSTANT);+ return """+ {+ "expiration": "%s",+ "conditions": [+ {"bucket": "%s"},+ {"key": "%s"},+ {"Content-Type": "%s"},+ ["content-length-range", %d, %d]+ ]+ }+ """.formatted(expiration, bucket, key, contentType, minSize, maxSize);+ }+}