mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(s3): honor success_action_redirect and success_action_status on a presigned POST (#9680)
A presigned or browser POST upload answered 204 whatever the form asked. It now honors success_action_redirect and the deprecated redirect field with a 303 whose Location is that URL plus bucket, key and etag query parameters, and ignores a URL S3 cannot interpret, as AWS does. Without a redirect, success_action_status 201 returns the PostResponse XML with the object's absolute Location, 200 an empty body, and 204 or any other value the default. The 201 Location follows the bucket the virtual-host routing chose and the forwarded host and scheme. SigV4Canonicalization.percentEncode now shares uriEncode's byte loop.
This commit is contained in:
1 parent
a95afb8994
commit
7b096e99d9
7 files changed
+543
-22
No files matched your search
@@ -49,6 +49,13 @@ Browser and presigned POST uploads emit `s3:ObjectCreated:Post`, matching AWS S3
|
||||
`s3:ObjectCreated:Put`; use `s3:ObjectCreated:*` to subscribe to objects created by either method.
|
||||
Annotation changes emit `s3:ObjectAnnotation:Put` and `s3:ObjectAnnotation:Delete`.
|
||||
|
||||
A successful browser form upload honors `success_action_redirect` and the deprecated `redirect`
|
||||
field: the response is `303 See Other` with a `Location` set to the given URL plus `bucket`, `key`
|
||||
and `etag` query parameters, and a URL that cannot be interpreted is ignored as AWS does. Otherwise
|
||||
`success_action_status` selects the response: `201` returns the `PostResponse` XML document with
|
||||
an absolute object `Location`, `200` an empty body, and `204` the empty default, which also applies
|
||||
to any other value.
|
||||
|
||||
`PutBucketNotificationConfiguration` checks SQS, SNS, and Lambda destination ARNs and verifies
|
||||
that each destination exists before replacing a bucket's configuration. A failed check leaves
|
||||
the prior configuration unchanged. Accepted configurations send an `s3:TestEvent` message to
|
||||
|
||||
@@ -16,6 +16,7 @@ public class RequestContext {
|
||||
private String accessKeyId;
|
||||
private String sessionToken;
|
||||
private Boolean iamGovernanceBypass;
|
||||
private String s3VirtualHostBucket;
|
||||
/**
|
||||
* What this request's MFA members amounted to, or null until something asks. Held here because
|
||||
* the enforcement filter and the STS operation both read it and a code is spent when it
|
||||
@@ -89,4 +90,17 @@ public class RequestContext {
|
||||
public void setIamGovernanceBypass(Boolean iamGovernanceBypass) {
|
||||
this.iamGovernanceBypass = iamGovernanceBypass;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bucket S3VirtualHostFilter routed this request to, or null for a path-style request.
|
||||
* Held here because the controller derives response URLs from the routing decision, which
|
||||
* can come from an existing-bucket lookup that is not reproducible from the host alone.
|
||||
*/
|
||||
public String getS3VirtualHostBucket() {
|
||||
return s3VirtualHostBucket;
|
||||
}
|
||||
|
||||
public void setS3VirtualHostBucket(String s3VirtualHostBucket) {
|
||||
this.s3VirtualHostBucket = s3VirtualHostBucket;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/**
|
||||
@@ -163,13 +164,19 @@ public final class SigV4Canonicalization {
|
||||
|
||||
/** RFC 3986 percent-encoding as SigV4 defines it: {@code /} is escaped, {@code -._~} are not. */
|
||||
public static String uriEncode(String value) {
|
||||
return percentEncode(value, SigV4Canonicalization::isSigV4Unreserved);
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent-encodes every byte of {@code value} that {@code keep} rejects, using upper-case hex.
|
||||
* Callers whose safe character set differs from SigV4's unreserved set share this byte loop.
|
||||
*/
|
||||
public static String percentEncode(String value, IntPredicate keep) {
|
||||
StringBuilder encoded = new StringBuilder(value.length());
|
||||
for (byte raw : value.getBytes(StandardCharsets.UTF_8)) {
|
||||
int b = raw & 0xFF;
|
||||
char ch = (char) b;
|
||||
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')
|
||||
|| ch == '-' || ch == '.' || ch == '_' || ch == '~') {
|
||||
encoded.append(ch);
|
||||
if (keep.test(b)) {
|
||||
encoded.append((char) b);
|
||||
} else {
|
||||
encoded.append('%')
|
||||
.append(Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16)))
|
||||
@@ -179,6 +186,11 @@ public final class SigV4Canonicalization {
|
||||
return encoded.toString();
|
||||
}
|
||||
|
||||
private static boolean isSigV4Unreserved(int b) {
|
||||
return (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9')
|
||||
|| b == '-' || b == '.' || b == '_' || b == '~';
|
||||
}
|
||||
|
||||
private static String decodeQueryComponent(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
|
||||
@@ -311,7 +311,7 @@ public class PreSignedUrlGenerator {
|
||||
return Base64Url.encode(bytes);
|
||||
}
|
||||
|
||||
private static String awsUriEncodePath(String value) {
|
||||
static String awsUriEncodePath(String value) {
|
||||
return Arrays.stream(value.split("/", -1))
|
||||
.map(SigV4Canonicalization::uriEncode)
|
||||
.collect(Collectors.joining("/"));
|
||||
|
||||
@@ -73,7 +73,10 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigInteger;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -1632,7 +1635,14 @@ public class S3Controller {
|
||||
return handleDeleteObjects(bucket, body, httpHeaders, uriInfo);
|
||||
}
|
||||
if (contentType != null && contentType.startsWith("multipart/form-data")) {
|
||||
return handlePresignedPost(bucket, contentType, body);
|
||||
String effectiveHost = S3VirtualHostFilter.resolveHost(
|
||||
httpHeaders.getHeaderString("Host"),
|
||||
httpHeaders.getHeaderString("X-Forwarded-Host"),
|
||||
uriInfo.getRequestUri());
|
||||
boolean virtualHosted = bucket.equalsIgnoreCase(requestContext.getS3VirtualHostBucket());
|
||||
return handlePresignedPost(bucket, contentType, body,
|
||||
postObjectBaseUrl(uriInfo, effectiveScheme(httpHeaders, uriInfo), effectiveHost,
|
||||
bucket, virtualHosted));
|
||||
}
|
||||
if (hasQueryParam(uriInfo, "uploads") || hasQueryParam(uriInfo, "uploadId")) {
|
||||
String actualBucket = resolveActualBucket(httpHeaders, uriInfo);
|
||||
@@ -4115,9 +4125,9 @@ public class S3Controller {
|
||||
}
|
||||
}
|
||||
|
||||
private Response handlePresignedPost(String bucket, String contentType, byte[] body) {
|
||||
private Response handlePresignedPost(String bucket, String contentType, byte[] body, String objectBaseUrl) {
|
||||
try {
|
||||
return doHandlePresignedPost(bucket, contentType, body);
|
||||
return doHandlePresignedPost(bucket, contentType, body, objectBaseUrl);
|
||||
} catch (AwsException e) {
|
||||
// Presigned POST errors must be returned as XML (matching LocalStack/AWS),
|
||||
// not JSON which is what the global AwsExceptionMapper would produce.
|
||||
@@ -4125,7 +4135,7 @@ public class S3Controller {
|
||||
}
|
||||
}
|
||||
|
||||
private Response doHandlePresignedPost(String bucket, String contentType, byte[] body) {
|
||||
private Response doHandlePresignedPost(String bucket, String contentType, byte[] body, String objectBaseUrl) {
|
||||
String boundary = MultipartFormParser.extractBoundary(contentType).orElseThrow(() ->
|
||||
new AwsException("InvalidArgument",
|
||||
"Could not determine multipart boundary from Content-Type.", 400));
|
||||
@@ -4221,18 +4231,27 @@ public class S3Controller {
|
||||
.withSseCustomerKeyMd5(lcFields.get("x-amz-server-side-encryption-customer-key-md5")));
|
||||
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();
|
||||
var response = Response.status(204)
|
||||
.header("ETag", obj.getETag())
|
||||
.header("Location", bucket + "/" + key);
|
||||
String redirectLocation = successRedirectLocation(lcFields, bucket, key, obj.getETag());
|
||||
int status = redirectLocation != null
|
||||
? 303
|
||||
: successActionStatusCode(lcFields.get("success_action_status"));
|
||||
Response.ResponseBuilder response = Response.status(status).header("ETag", obj.getETag());
|
||||
if (status == 201) {
|
||||
String location = objectBaseUrl + "/" + PreSignedUrlGenerator.awsUriEncodePath(key);
|
||||
response.header("Location", location)
|
||||
.entity(new XmlBuilder()
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
.start("PostResponse")
|
||||
.elem("Location", location)
|
||||
.elem("Bucket", bucket)
|
||||
.elem("Key", key)
|
||||
.elem("ETag", obj.getETag())
|
||||
.end("PostResponse")
|
||||
.build())
|
||||
.type(MediaType.APPLICATION_XML);
|
||||
} else {
|
||||
response.header("Location", redirectLocation != null ? redirectLocation : bucket + "/" + key);
|
||||
}
|
||||
if (obj.getServerSideEncryption() != null) {
|
||||
response.header("x-amz-server-side-encryption", obj.getServerSideEncryption());
|
||||
}
|
||||
@@ -4265,6 +4284,112 @@ public class S3Controller {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The scheme the client used when a proxy forwards the upload over a different one. Only
|
||||
* http and https are trusted; anything else falls back to the request's own scheme.
|
||||
*/
|
||||
private static String effectiveScheme(HttpHeaders httpHeaders, UriInfo uriInfo) {
|
||||
String forwarded = httpHeaders.getHeaderString("X-Forwarded-Proto");
|
||||
if (forwarded != null && !forwarded.isBlank()) {
|
||||
String first = forwarded.split(",", -1)[0].trim();
|
||||
if ("https".equalsIgnoreCase(first) || "http".equalsIgnoreCase(first)) {
|
||||
return first.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
return uriInfo.getBaseUri().getScheme();
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL an object is reachable at, without the key: the request's own host for a
|
||||
* virtual-hosted request, whose host already names the bucket, and the bucket as the
|
||||
* first path segment otherwise.
|
||||
*/
|
||||
private static String postObjectBaseUrl(UriInfo uriInfo, String scheme, String effectiveHost, String bucket,
|
||||
boolean virtualHosted) {
|
||||
String authority = effectiveHost != null ? effectiveHost : uriInfo.getBaseUri().getAuthority();
|
||||
String baseUrl = scheme + "://" + authority;
|
||||
return virtualHosted ? baseUrl : baseUrl + "/" + SigV4Canonicalization.uriEncode(bucket);
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code Location} a successful POST answers with when the form carries
|
||||
* {@code success_action_redirect} or the deprecated {@code redirect}: the client's
|
||||
* absolute URL with {@code bucket}, {@code key} and {@code etag} appended, per the
|
||||
* POST Object reference. Null when the field is absent or not an interpretable
|
||||
* absolute URL, which S3 treats as if the field were not present.
|
||||
*/
|
||||
private static String successRedirectLocation(Map<String, String> fields, String bucket, String key, String eTag) {
|
||||
String redirect = fields.get("success_action_redirect");
|
||||
if (redirect == null || redirect.isBlank()) {
|
||||
redirect = fields.get("redirect");
|
||||
}
|
||||
if (redirect == null || redirect.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String url = escapeIllegalUriCharacters(redirect.trim());
|
||||
try {
|
||||
URI parsed = new URI(url);
|
||||
// The authority need not be a DNS name: a Docker Compose service such as
|
||||
// http://my_app:3000/done is a URL a browser follows, and so does S3.
|
||||
if (!parsed.isAbsolute() || parsed.getRawAuthority() == null) {
|
||||
return null;
|
||||
}
|
||||
} catch (URISyntaxException expected) {
|
||||
// "If Amazon S3 cannot interpret the URL, it acts as if the field is not present."
|
||||
return null;
|
||||
}
|
||||
String fragment = null;
|
||||
int fragmentStart = url.indexOf('#');
|
||||
if (fragmentStart >= 0) {
|
||||
fragment = url.substring(fragmentStart + 1);
|
||||
url = url.substring(0, fragmentStart);
|
||||
}
|
||||
int queryStart = url.indexOf('?');
|
||||
String separator = "?";
|
||||
if (queryStart >= 0) {
|
||||
separator = queryStart == url.length() - 1 || url.charAt(url.length() - 1) == '&' ? "" : "&";
|
||||
}
|
||||
StringBuilder location = new StringBuilder(url)
|
||||
.append(separator)
|
||||
.append("bucket=").append(formEncode(bucket))
|
||||
.append("&key=").append(formEncode(key))
|
||||
.append("&etag=").append(formEncode(eTag));
|
||||
if (fragment != null) {
|
||||
location.append('#').append(fragment);
|
||||
}
|
||||
return location.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* A browser escapes characters it cannot send literally in a URL before following it, and so
|
||||
* does S3 when interpreting a {@code success_action_redirect} form value.
|
||||
*/
|
||||
private static String escapeIllegalUriCharacters(String value) {
|
||||
return SigV4Canonicalization.percentEncode(value,
|
||||
b -> b > 0x20 && b < 0x7F && "\"<>\\^`{|}".indexOf(b) < 0);
|
||||
}
|
||||
|
||||
private static String formEncode(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
}
|
||||
|
||||
/**
|
||||
* The status a successful POST answers with when no redirect applies. The POST Object
|
||||
* reference accepts {@code 200}, {@code 201} or {@code 204}, the default; any other
|
||||
* value is treated as absent and answers 204 with an empty body.
|
||||
*/
|
||||
private static int successActionStatusCode(String successActionStatus) {
|
||||
if (successActionStatus == null) {
|
||||
return 204;
|
||||
}
|
||||
return switch (successActionStatus) {
|
||||
case "200" -> 200;
|
||||
case "201" -> 201;
|
||||
case "204" -> 204;
|
||||
default -> 204;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A presigned POST carries its credential in the form, which AccountContextFilter never sees, so a closed
|
||||
* account's POST is refused here as the filter refuses its other requests.
|
||||
|
||||
@@ -4,6 +4,7 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.config.LocalStackParity;
|
||||
import io.floci.aws.core.common.AwsPartitions;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.core.common.RequestHost;
|
||||
import io.floci.aws.core.common.RequestUriRewrite;
|
||||
import io.floci.aws.core.common.ResteasyRequests;
|
||||
@@ -38,6 +39,7 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
|
||||
private final String baseHostname;
|
||||
private final Instance<S3Service> s3ServiceInstance;
|
||||
private final RequestContext requestState;
|
||||
|
||||
/**
|
||||
* Hostname suffixes for which a bare {@code s3.<suffix>} Host header is Floci's own
|
||||
@@ -76,13 +78,14 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
|
||||
@Inject
|
||||
public S3VirtualHostFilter(EmulatorConfig config, ContainerDetector containerDetector,
|
||||
Instance<S3Service> s3ServiceInstance) {
|
||||
Instance<S3Service> s3ServiceInstance, RequestContext requestState) {
|
||||
this.baseHostname = config.hostname()
|
||||
.orElseGet(() -> containerDetector.isRunningInContainer()
|
||||
? EmbeddedDnsServer.DEFAULT_SUFFIX
|
||||
: extractHostnameFromUrl(config.baseUrl()));
|
||||
this.serviceHostSuffixes = buildServiceHostSuffixes(config.hostname(), LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()));
|
||||
this.s3ServiceInstance = s3ServiceInstance;
|
||||
this.requestState = requestState;
|
||||
}
|
||||
|
||||
S3VirtualHostFilter() {
|
||||
@@ -93,12 +96,14 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
this.baseHostname = hostname.orElse("localhost");
|
||||
this.serviceHostSuffixes = buildServiceHostSuffixes(hostname, extraSuffixes);
|
||||
this.s3ServiceInstance = null;
|
||||
this.requestState = new RequestContext();
|
||||
}
|
||||
|
||||
S3VirtualHostFilter(Instance<S3Service> s3ServiceInstance) {
|
||||
this.baseHostname = "localhost";
|
||||
this.serviceHostSuffixes = buildServiceHostSuffixes(Optional.empty(), Optional.empty());
|
||||
this.s3ServiceInstance = s3ServiceInstance;
|
||||
this.requestState = new RequestContext();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,6 +200,7 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
.build();
|
||||
|
||||
requestContext.setProperty(ORIGINAL_REQUEST_URI_PROPERTY, uri);
|
||||
requestState.setS3VirtualHostBucket(bucket);
|
||||
RequestUriRewrite.apply(requestContext, newUri);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
package io.floci.aws.services.s3;
|
||||
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
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 org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -716,6 +720,346 @@ class S3PresignedPostIntegrationTest {
|
||||
.header("x-amz-meta-owner", equalTo("test-user"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@Order(98)
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"success_action_redirect|http://localhost:8000/done|uploads/redirected.txt|http://localhost:8000/done?bucket=<BUCKET>&key=uploads%2Fredirected.txt&etag=%22<ETAG>%22",
|
||||
"redirect|http://localhost:8000/legacy|uploads/legacy-redirect.txt|http://localhost:8000/legacy?bucket=<BUCKET>&key=uploads%2Flegacy-redirect.txt&etag=%22<ETAG>%22",
|
||||
"success_action_redirect|http://localhost:8000/done?src=form#top|uploads/redirect-query.txt|http://localhost:8000/done?src=form&bucket=<BUCKET>&key=uploads%2Fredirect-query.txt&etag=%22<ETAG>%22#top",
|
||||
"success_action_redirect|http://localhost:8000/done|uploads/redirect dir/file one.txt|http://localhost:8000/done?bucket=<BUCKET>&key=uploads%2Fredirect%20dir%2Ffile%20one.txt&etag=%22<ETAG>%22"
|
||||
})
|
||||
void presignedPostRedirectHonorsFormFields(String field, String redirect, String key, String expectedTemplate) {
|
||||
String fileContent = "redirect " + key;
|
||||
String fileName = key.substring(key.lastIndexOf('/') + 1);
|
||||
|
||||
String location =
|
||||
given()
|
||||
.redirects().follow(false)
|
||||
.multiPart("key", key)
|
||||
.multiPart(field, redirect)
|
||||
.multiPart("file", fileName, fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(303)
|
||||
.header("ETag", equalTo("\"" + Digests.md5Hex(fileContent.getBytes(StandardCharsets.UTF_8)) + "\""))
|
||||
.extract().header("Location");
|
||||
|
||||
assertThat(location, equalTo(expectedTemplate
|
||||
.replace("<BUCKET>", BUCKET)
|
||||
.replace("<ETAG>", Digests.md5Hex(fileContent.getBytes(StandardCharsets.UTF_8)))));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "/" + key)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo(fileContent));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPostRedirectTakesPrecedenceOverSuccessActionStatus() {
|
||||
// A specified redirect wins over success_action_status, per the POST Object reference:
|
||||
// the status only applies when success_action_redirect is not specified.
|
||||
given()
|
||||
.redirects().follow(false)
|
||||
.multiPart("key", "uploads/redirected.txt")
|
||||
.multiPart("success_action_redirect", "http://localhost:8000/done")
|
||||
.multiPart("success_action_status", "201")
|
||||
.multiPart("file", "redirected.txt", "again".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(303)
|
||||
.header("Location", startsWith("http://localhost:8000/done?bucket=" + BUCKET + "&"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@Order(98)
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"https://example.com/done& | https://example.com/done&?",
|
||||
"https://example.com/done?next=? | https://example.com/done?next=?&",
|
||||
"https://example.com/done? | https://example.com/done?",
|
||||
"https://example.com/done?from=a& | https://example.com/done?from=a&",
|
||||
"http://my_app:3000/done | http://my_app:3000/done?",
|
||||
"http://localhost:3000/cb?x=a b | http://localhost:3000/cb?x=a%20b&",
|
||||
"http://localhost:3000/cb?q={x} | http://localhost:3000/cb?q=%7Bx%7D&"
|
||||
})
|
||||
void presignedPostRedirectBuildsLocationForVariousUrls(String redirect, String expectedPrefix) {
|
||||
String key = "uploads/redirect-variants.txt";
|
||||
String fileContent = "redirect variant " + redirect;
|
||||
|
||||
given()
|
||||
.redirects().follow(false)
|
||||
.multiPart("key", key)
|
||||
.multiPart("success_action_redirect", redirect)
|
||||
.multiPart("file", "redirect-variants.txt", fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(303)
|
||||
.header("Location", equalTo(expectedPrefix + "bucket=" + BUCKET
|
||||
+ "&key=uploads%2Fredirect-variants.txt&etag=%22" + Digests.md5Hex(fileContent.getBytes(StandardCharsets.UTF_8)) + "%22"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPostPolicyCanConstrainTheRedirectField() {
|
||||
String key = "uploads/policy-redirect-ok.txt";
|
||||
String fileContent = "policy redirect ok";
|
||||
String policy = redirectPolicy(key, "http://localhost:8000/");
|
||||
|
||||
given()
|
||||
.redirects().follow(false)
|
||||
.multiPart("key", key)
|
||||
.multiPart("policy", Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8)))
|
||||
.multiPart("success_action_redirect", "http://localhost:8000/done")
|
||||
.multiPart("file", "policy-redirect-ok.txt", fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(303)
|
||||
.header("Location", startsWith("http://localhost:8000/done?bucket=" + BUCKET + "&"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPostRejectsRedirectOutsideThePolicy() {
|
||||
String key = "uploads/policy-redirect-bad.txt";
|
||||
String policy = redirectPolicy(key, "http://localhost:8000/");
|
||||
|
||||
given()
|
||||
.redirects().follow(false)
|
||||
.multiPart("key", key)
|
||||
.multiPart("policy", Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8)))
|
||||
.multiPart("success_action_redirect", "https://evil.example.com/done")
|
||||
.multiPart("file", "policy-redirect-bad.txt", "blocked".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.contentType("application/xml")
|
||||
.body(hasXPath("/Error/Code", equalTo("AccessDenied")))
|
||||
.body(hasXPath("/Error/Message", containsString("\"$success_action_redirect\"")));
|
||||
|
||||
given().head("/" + BUCKET + "/" + key).then().statusCode(404);
|
||||
}
|
||||
|
||||
private String redirectPolicy(String key, String redirectPrefix) {
|
||||
return """
|
||||
{"expiration": "%s", "conditions": [
|
||||
{"bucket": "%s"},
|
||||
{"key": "%s"},
|
||||
["starts-with", "$success_action_redirect", "%s"]
|
||||
]}
|
||||
""".formatted(Instant.now().plusSeconds(3600), BUCKET, key, redirectPrefix);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPostUninterpretableRedirectFallsBackToSuccessActionStatus() {
|
||||
// A redirect that is not an absolute URL is treated as if the field were not present.
|
||||
given()
|
||||
.multiPart("key", "uploads/fallback-status.txt")
|
||||
.multiPart("success_action_redirect", "/relative/path")
|
||||
.multiPart("success_action_status", "201")
|
||||
.multiPart("file", "fallback-status.txt", "fallback".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.contentType("application/xml")
|
||||
.body(hasXPath("/PostResponse/Bucket", equalTo(BUCKET)))
|
||||
.body(hasXPath("/PostResponse/Key", equalTo("uploads/fallback-status.txt")));
|
||||
|
||||
// A redirect that cannot be parsed with no status given answers the default 204.
|
||||
given()
|
||||
.multiPart("key", "uploads/garbage-redirect.txt")
|
||||
.multiPart("success_action_redirect", "not a url")
|
||||
.multiPart("file", "garbage-redirect.txt", "garbage".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPostSuccessActionStatus201ReturnsPostResponseXml() {
|
||||
String key = "uploads/status-201.txt";
|
||||
String fileContent = "created 201";
|
||||
|
||||
Response response = postFor201("/" + BUCKET, null, null, null, key, "status-201.txt", fileContent);
|
||||
response.then().contentType("application/xml")
|
||||
.header("ETag", equalTo("\"" + Digests.md5Hex(fileContent.getBytes(StandardCharsets.UTF_8)) + "\""));
|
||||
|
||||
assert201Location(response, "https?://[^/]+/" + BUCKET + "/uploads/status-201\\.txt");
|
||||
assertThat(response.asString(), allOf(
|
||||
containsString("<PostResponse>"),
|
||||
containsString("<Bucket>" + BUCKET + "</Bucket>"),
|
||||
containsString("<Key>" + key + "</Key>"),
|
||||
containsString("<ETag>"" + Digests.md5Hex(fileContent.getBytes(StandardCharsets.UTF_8)) + ""</ETag>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPost201LocationEncodesTheKeyPath() {
|
||||
String key = "uploads/status 201/a#b?c.txt";
|
||||
String fileContent = "encoded location";
|
||||
|
||||
Response response = postFor201("/" + BUCKET, null, null, null, key, "encoded-location.txt", fileContent);
|
||||
assert201Location(response, "https?://[^/]+/" + BUCKET + "/uploads/status%20201/a%23b%3Fc\\.txt");
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(response.header("Location"))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo(fileContent));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPost201LocationForVirtualHostedBucket() {
|
||||
String fileContent = "virtual hosted 201";
|
||||
|
||||
Response response = postFor201("/", BUCKET + ".localhost", null, null,
|
||||
"uploads/virtual hosted.txt", "virtual-hosted.txt", fileContent);
|
||||
assert201Location(response, "https?://" + BUCKET + "\\.localhost(:\\d+)?/uploads/virtual%20hosted\\.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPost201LocationUsesTheForwardedHostAndScheme() {
|
||||
String bucket = "presigned-post-forwarded-bucket";
|
||||
String key = "uploads/proxied.txt";
|
||||
String untrustedKey = "uploads/untrusted-proto.txt";
|
||||
|
||||
given().put("/" + bucket).then().statusCode(200);
|
||||
|
||||
try {
|
||||
Response response = postFor201("/", "localhost:4566", bucket + ".localhost", "https",
|
||||
key, "proxied.txt", "proxied 201");
|
||||
assert201Location(response, "https://" + bucket + "\\.localhost/uploads/proxied\\.txt");
|
||||
|
||||
// Only http and https are trusted from a proxy; anything else falls back to the backend scheme.
|
||||
Response untrusted = postFor201("/", "localhost:4566", bucket + ".localhost", "ws",
|
||||
untrustedKey, "untrusted-proto.txt", "untrusted 201");
|
||||
assert201Location(untrusted, "http://" + bucket + "\\.localhost/uploads/untrusted-proto\\.txt");
|
||||
} finally {
|
||||
given().delete("/" + bucket + "/" + key).then().statusCode(204);
|
||||
given().delete("/" + bucket + "/" + untrustedKey).then().statusCode(204);
|
||||
given().delete("/" + bucket).then().statusCode(204);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPost201LocationForDottedVirtualHostedBucket() {
|
||||
String routedBucket = "presigned-post-dotted";
|
||||
String dottedBucket = routedBucket + ".s3";
|
||||
String key = "uploads/dotted.txt";
|
||||
|
||||
given().put("/" + routedBucket).then().statusCode(200);
|
||||
given().put("/" + dottedBucket).then().statusCode(200);
|
||||
|
||||
try {
|
||||
Response response = postFor201("/", dottedBucket + ".localhost", null, null,
|
||||
key, "dotted.txt", "dotted 201");
|
||||
assert201Location(response, "https?://" + dottedBucket + "\\.localhost/uploads/dotted\\.txt");
|
||||
} finally {
|
||||
given().delete("/" + routedBucket + "/" + key).then().statusCode(204);
|
||||
given().delete("/" + dottedBucket).then().statusCode(204);
|
||||
given().delete("/" + routedBucket).then().statusCode(204);
|
||||
}
|
||||
}
|
||||
|
||||
private Response postFor201(String path, String host, String forwardedHost, String forwardedProto,
|
||||
String key, String fileName, String fileContent) {
|
||||
RequestSpecification request = given()
|
||||
.multiPart("key", key)
|
||||
.multiPart("success_action_status", "201")
|
||||
.multiPart("file", fileName, fileContent.getBytes(StandardCharsets.UTF_8), "text/plain");
|
||||
if (host != null) {
|
||||
request.header("Host", host);
|
||||
}
|
||||
if (forwardedHost != null) {
|
||||
request.header("X-Forwarded-Host", forwardedHost);
|
||||
}
|
||||
if (forwardedProto != null) {
|
||||
request.header("X-Forwarded-Proto", forwardedProto);
|
||||
}
|
||||
return request.when().post(path).then().statusCode(201).extract().response();
|
||||
}
|
||||
|
||||
private void assert201Location(Response response, String locationRegex) {
|
||||
String location = response.header("Location");
|
||||
assertThat(location, matchesRegex(locationRegex));
|
||||
assertThat(response.xmlPath().getString("PostResponse.Location"), equalTo(location));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPost201LocationForCustomHostRoutedViaExistingBucket() {
|
||||
String bucket = "presigned-post-custom-host";
|
||||
String key = "uploads/custom-host.txt";
|
||||
|
||||
given().put("/" + bucket).then().statusCode(200);
|
||||
|
||||
try {
|
||||
Response response =
|
||||
given()
|
||||
.header("Host", bucket + ".example.test")
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260330/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=dummy")
|
||||
.multiPart("key", key)
|
||||
.multiPart("success_action_status", "201")
|
||||
.multiPart("file", "custom-host.txt", "custom 201".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().response();
|
||||
|
||||
assert201Location(response, "https?://" + bucket + "\\.example\\.test/uploads/custom-host\\.txt");
|
||||
} finally {
|
||||
given().delete("/" + bucket + "/" + key).then().statusCode(204);
|
||||
given().delete("/" + bucket).then().statusCode(204);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPostSuccessActionStatus200ReturnsEmptyBody() {
|
||||
given()
|
||||
.multiPart("key", "uploads/status-200.txt")
|
||||
.multiPart("success_action_status", "200")
|
||||
.multiPart("file", "status-200.txt", "ok 200".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.header("ETag", notNullValue())
|
||||
.body(equalTo(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(98)
|
||||
void presignedPostUnknownSuccessActionStatusAnswersTheDefault() {
|
||||
// The POST Object reference accepts 200, 201 or 204 only; anything else is treated as absent.
|
||||
given()
|
||||
.multiPart("key", "uploads/status-unknown.txt")
|
||||
.multiPart("success_action_status", "301")
|
||||
.multiPart("file", "status-unknown.txt", "unknown".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(204)
|
||||
.header("ETag", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(100)
|
||||
void cleanupBucket() {
|
||||
@@ -730,6 +1074,19 @@ class S3PresignedPostIntegrationTest {
|
||||
given().delete("/" + BUCKET + "/uploads/prefix-test.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/capital-p-ok.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/with-metadata.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/redirected.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/legacy-redirect.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/redirect-query.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/redirect-variants.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/redirect dir/file one.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/policy-redirect-ok.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/fallback-status.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/garbage-redirect.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/status-201.txt");
|
||||
given().urlEncodingEnabled(false).delete("/" + BUCKET + "/uploads/status%20201/a%23b%3Fc.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/virtual hosted.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/status-200.txt");
|
||||
given().delete("/" + BUCKET + "/uploads/status-unknown.txt");
|
||||
|
||||
given()
|
||||
.when()
|
||||
|
||||
Reference in new issue
Block a user