fix(s3): support virtual-hosted routing via X-Forwarded-Host and prevent unintended bucket creation (#3621)

* fix(s3): support virtual-hosted routing via X-Forwarded-Host and prevent unintended bucket creation

- Respect X-Forwarded-Host when resolving host for reverse proxy compatibility
- Support tail-agnostic .s3.<region>.<domain> qualifier and fallback lookup against existing buckets
- Reroute misplaced single-segment object/multipart uploads or reject with InvalidBucketName/MalformedXML
- Add unit and integration tests for virtual-hosted requests forwarded through proxies

* docs(s3): translate virtual host routing comment
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-15 13:01:39 -04:00
1 parent ce5c5b4cfa
commit c63c834c0e
7 files changed
+471 -16

No files matched your search

@@ -166,7 +166,8 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
URI requestUri = requestContext.getProperty(S3VirtualHostFilter.ORIGINAL_REQUEST_URI_PROPERTY) instanceof URI uri
? uri
: requestContext.getUriInfo().getRequestUri();
String authority = S3VirtualHostFilter.resolveHost(requestContext.getHeaderString("Host"), requestUri);
String authority = S3VirtualHostFilter.resolveHost(requestContext.getHeaderString("Host"),
requestContext.getHeaderString("X-Forwarded-Host"), requestUri);
StringBuilder canonicalHeaders = new StringBuilder();
for (String header : signedHeaders.split(";")) {
@@ -369,6 +369,35 @@ public class S3Controller {
return handlePutBucketInventoryConfiguration(bucket, uriInfo, body);
}
// Detect a PutObject request that reached this handler before virtual-host rewriting.
if (isMisplacedObjectPut(httpHeaders, body, bucket)) {
String actualBucket = resolveActualBucket(httpHeaders, uriInfo);
if (actualBucket != null && !actualBucket.equalsIgnoreCase(bucket)) {
LOG.infov("Rerouting misplaced virtual-hosted PutObject to bucket {0}, key {1}", actualBucket, bucket);
return putObject(actualBucket, bucket,
httpHeaders.getHeaderString("Content-Type"),
httpHeaders.getHeaderString("Content-Encoding"),
httpHeaders.getHeaderString("x-amz-content-sha256"),
httpHeaders.getHeaderString("x-amz-copy-source"),
httpHeaders.getHeaderString("x-amz-tagging"),
httpHeaders.getHeaderString("If-Match"),
httpHeaders.getHeaderString("If-None-Match"),
uriInfo.getQueryParameters().getFirst("uploadId"),
uriInfo.getQueryParameters().getFirst("partNumber") != null
? Integer.parseInt(uriInfo.getQueryParameters().getFirst("partNumber")) : null,
uriInfo,
httpHeaders,
body);
}
if (bucket.length() > 63) {
throw new AwsException("InvalidBucketName", "The specified bucket is not valid.", 400);
}
if (body != null && body.length > 0 && !isXmlCreateBucketConfiguration(body)) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema", 400);
}
}
s3Service.authorizeCreateBucket(authorization);
String locationConstraint = null;
if (body != null && body.length > 0) {
@@ -743,7 +772,7 @@ public class S3Controller {
@Context HttpHeaders httpHeaders,
byte[] body) {
try {
key = extractObjectKey(uriInfo, bucket);
key = extractObjectKey(uriInfo, bucket, key);
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
@@ -896,7 +925,7 @@ public class S3Controller {
@Context HttpHeaders httpHeaders) {
S3Service.RequestAuthorization authorization = S3Service.RequestAuthorization.unsigned();
try {
key = extractObjectKey(uriInfo, bucket);
key = extractObjectKey(uriInfo, bucket, key);
authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
@@ -1139,7 +1168,7 @@ public class S3Controller {
@Context HttpHeaders httpHeaders) {
S3Service.RequestAuthorization authorization = S3Service.RequestAuthorization.unsigned();
try {
key = extractObjectKey(uriInfo, bucket);
key = extractObjectKey(uriInfo, bucket, key);
authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
if (isWebsiteRequest(httpHeaders, uriInfo)) {
@@ -1286,7 +1315,7 @@ public class S3Controller {
@Context UriInfo uriInfo,
@Context HttpHeaders httpHeaders) {
try {
key = extractObjectKey(uriInfo, bucket);
key = extractObjectKey(uriInfo, bucket, key);
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
@@ -1348,6 +1377,21 @@ public class S3Controller {
if (contentType != null && contentType.startsWith("multipart/form-data")) {
return handlePresignedPost(bucket, contentType, body);
}
if (hasQueryParam(uriInfo, "uploads") || hasQueryParam(uriInfo, "uploadId")) {
String actualBucket = resolveActualBucket(httpHeaders, uriInfo);
if (actualBucket != null && !actualBucket.equalsIgnoreCase(bucket)) {
LOG.infov("Rerouting misplaced virtual-hosted multipart POST to bucket {0}, key {1}", actualBucket, bucket);
return handleMultipartPost(actualBucket, bucket,
uriInfo.getQueryParameters().getFirst("uploadId"),
uriInfo.getQueryParameters().getFirst("versionId"),
contentType,
httpHeaders.getHeaderString("If-Match"),
httpHeaders.getHeaderString("If-None-Match"),
httpHeaders,
uriInfo,
body);
}
}
return xmlErrorResponse(new AwsException("InvalidArgument",
"POST on bucket requires ?delete parameter.", 400));
} catch (AwsException e) {
@@ -1369,7 +1413,7 @@ public class S3Controller {
@Context UriInfo uriInfo,
byte[] body) {
try {
key = extractObjectKey(uriInfo, bucket);
key = extractObjectKey(uriInfo, bucket, key);
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
@@ -2900,7 +2944,8 @@ public class S3Controller {
// HTTP/2 (RFC 9113) carries no Host header, so fall back to the request URI authority —
// the same resolution S3VirtualHostFilter applies. Without this, a website bucket reached
// over HTTP/2 would be served as an API (XML) response instead of website HTML.
String host = S3VirtualHostFilter.resolveHost(httpHeaders.getHeaderString("Host"), uriInfo.getRequestUri());
String host = S3VirtualHostFilter.resolveHost(httpHeaders.getHeaderString("Host"),
httpHeaders.getHeaderString("X-Forwarded-Host"), uriInfo.getRequestUri());
return host != null && host.contains("s3-website");
}
@@ -3675,6 +3720,10 @@ public class S3Controller {
* that JAX-RS path normalization would otherwise strip.
*/
private String extractObjectKey(UriInfo uriInfo, String bucket) {
return extractObjectKey(uriInfo, bucket, null);
}
private String extractObjectKey(UriInfo uriInfo, String bucket, String fallbackKey) {
validateRawUri();
String rawUri = currentVertxRequest.getCurrent().request().uri();
int qIdx = rawUri.indexOf('?');
@@ -3682,8 +3731,12 @@ public class S3Controller {
String bucketPrefix = "/" + bucket + "/";
int prefixIndex = rawPath.indexOf(bucketPrefix);
if (prefixIndex < 0) {
// Should not happen — route already matched /{bucket}/{key:.+}
return uriInfo.getPathParameters().getFirst("key");
// Should not happen on standard /{bucket}/{key:.+} routes, but can happen when
// requests are rerouted from a single-segment route (e.g. createBucket / handleBucketPost)
String pathKey = uriInfo.getPathParameters().getFirst("key");
String resolvedKey = pathKey != null ? pathKey : fallbackKey;
validateKeyNoTraversal(resolvedKey);
return resolvedKey;
}
String rawKey = rawPath.substring(prefixIndex + bucketPrefix.length());
String key = URLDecoder.decode(rawKey.replace("+", "%2B"), StandardCharsets.UTF_8);
@@ -3972,4 +4025,65 @@ public class S3Controller {
}
return val;
}
private String resolveActualBucket(HttpHeaders httpHeaders, UriInfo uriInfo) {
String host = S3VirtualHostFilter.resolveHost(
httpHeaders.getHeaderString("Host"),
httpHeaders.getHeaderString("X-Forwarded-Host"),
uriInfo.getRequestUri());
if (host == null) {
return null;
}
String bucket = S3VirtualHostFilter.extractBucketFromExisting(host, s3Service);
if (bucket != null) {
return bucket;
}
return S3VirtualHostFilter.extractBucket(host, "localhost", Set.of("localhost"));
}
private static boolean isMisplacedObjectPut(HttpHeaders httpHeaders, byte[] body, String bucket) {
if (bucket != null && bucket.length() > 63) {
return true;
}
String contentSha256 = httpHeaders.getHeaderString("x-amz-content-sha256");
if (contentSha256 != null && contentSha256.startsWith("STREAMING-")) {
return true;
}
String contentEncoding = httpHeaders.getHeaderString("Content-Encoding");
if (contentEncoding != null && contentEncoding.toLowerCase(Locale.ROOT).contains("aws-chunked")) {
return true;
}
if (httpHeaders.getHeaderString("x-amz-decoded-content-length") != null
|| httpHeaders.getHeaderString("x-amz-trailer") != null
|| httpHeaders.getHeaderString("Content-Disposition") != null
|| httpHeaders.getHeaderString("x-amz-storage-class") != null
|| httpHeaders.getHeaderString("x-amz-copy-source") != null) {
return true;
}
MultivaluedMap<String, String> requestHeaders = httpHeaders.getRequestHeaders();
if (requestHeaders != null) {
for (String headerName : requestHeaders.keySet()) {
if (headerName.toLowerCase(Locale.ROOT).startsWith("x-amz-meta-")) {
return true;
}
}
}
String contentType = httpHeaders.getHeaderString("Content-Type");
if (contentType != null && !contentType.isBlank()) {
String lowerType = contentType.toLowerCase(Locale.ROOT);
if (!lowerType.contains("xml") && !lowerType.contains("form-urlencoded")
&& (body != null && body.length > 0 || httpHeaders.getHeaderString("Content-Length") != null)) {
return true;
}
}
return body != null && body.length > 0 && !isXmlCreateBucketConfiguration(body);
}
private static boolean isXmlCreateBucketConfiguration(byte[] body) {
if (body == null || body.length == 0) {
return true;
}
String text = new String(body, StandardCharsets.UTF_8).trim();
return text.startsWith("<") && text.contains("CreateBucketConfiguration");
}
}
@@ -185,7 +185,8 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
URI requestUri = ctx.getProperty(S3VirtualHostFilter.ORIGINAL_REQUEST_URI_PROPERTY) instanceof URI uri
? uri
: ctx.getUriInfo().getRequestUri();
String host = S3VirtualHostFilter.resolveHost(ctx.getHeaderString("Host"), requestUri);
String host = S3VirtualHostFilter.resolveHost(ctx.getHeaderString("Host"),
ctx.getHeaderString("X-Forwarded-Host"), requestUri);
StringBuilder canonicalHeaders = new StringBuilder();
for (String name : signedHeaders.split(";")) {
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontDistributionFilter;
import io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFilter;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
@@ -29,6 +30,7 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
static final String ORIGINAL_REQUEST_URI_PROPERTY = S3VirtualHostFilter.class.getName() + ".originalRequestUri";
private final String baseHostname;
private final Instance<S3Service> s3ServiceInstance;
/**
* Hostname suffixes for which a bare {@code s3.<suffix>} Host header is Floci's own
@@ -64,17 +66,30 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
private static final String DUALSTACK = "dualstack";
@Inject
public S3VirtualHostFilter(EmulatorConfig config, ContainerDetector containerDetector) {
public S3VirtualHostFilter(EmulatorConfig config, ContainerDetector containerDetector,
Instance<S3Service> s3ServiceInstance) {
this.baseHostname = config.hostname()
.orElseGet(() -> containerDetector.isRunningInContainer()
? EmbeddedDnsServer.DEFAULT_SUFFIX
: extractHostnameFromUrl(config.baseUrl()));
this.serviceHostSuffixes = buildServiceHostSuffixes(config.hostname(), config.dns().extraSuffixes());
this.s3ServiceInstance = s3ServiceInstance;
}
S3VirtualHostFilter() {
this(Optional.empty(), Optional.empty());
}
S3VirtualHostFilter(Optional<String> hostname, Optional<List<String>> extraSuffixes) {
this.baseHostname = hostname.orElse("localhost");
this.serviceHostSuffixes = buildServiceHostSuffixes(hostname, extraSuffixes);
this.s3ServiceInstance = null;
}
S3VirtualHostFilter(Instance<S3Service> s3ServiceInstance) {
this.baseHostname = "localhost";
this.serviceHostSuffixes = buildServiceHostSuffixes(Optional.empty(), Optional.empty());
this.s3ServiceInstance = s3ServiceInstance;
}
/**
@@ -102,7 +117,10 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
// ":authority" pseudo-header, surfaced here as the request URI authority.
// Falling back to it keeps virtual-hosted-style routing working when a
// browser negotiates HTTP/2 over HTTPS (where the Host header is absent).
String host = resolveHost(requestContext.getHeaderString("Host"), uri);
// Reverse proxies (e.g. Traefik, Nginx) preserve the client's original host
// in X-Forwarded-Host when Host is rewritten to the internal upstream.
String host = resolveHost(requestContext.getHeaderString("Host"),
requestContext.getHeaderString("X-Forwarded-Host"), uri);
if (host == null) return;
// Do not hijack requests meant for other AWS services
@@ -127,6 +145,9 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
}
String bucket = extractBucket(host, baseHostname, serviceHostSuffixes);
if (bucket == null && signedForS3 && s3ServiceInstance != null && s3ServiceInstance.isResolvable()) {
bucket = extractBucketFromExisting(host, s3ServiceInstance.get());
}
if (bucket == null) return;
String path = uri.getRawPath();
@@ -165,17 +186,33 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
* header is absent we fall back to the URI authority so virtual-hosted-style
* requests are recognized on both protocol versions.
*
* <p>Reverse proxies (e.g. Traefik, Nginx, ALB) often rewrite the {@code Host} header
* to the internal upstream address (e.g. {@code floci:4566}) and forward the client's
* original host in {@code X-Forwarded-Host}. When present, that header takes priority
* so virtual-hosted bucket names survive reverse proxying.
*
* @param hostHeader the value of the {@code Host} header, or {@code null}
* @param xForwardedHost the value of the {@code X-Forwarded-Host} header, or {@code null}
* @param requestUri the request URI, or {@code null}
* @return the effective authority ({@code host[:port]}), or {@code null} if neither is available
*/
static String resolveHost(String hostHeader, URI requestUri) {
if (hostHeader != null) {
return hostHeader;
static String resolveHost(String hostHeader, String xForwardedHost, URI requestUri) {
if (xForwardedHost != null && !xForwardedHost.isBlank()) {
String first = xForwardedHost.split(",", -1)[0].trim();
if (!first.isEmpty()) {
return first;
}
}
if (hostHeader != null && !hostHeader.isBlank()) {
return hostHeader.trim();
}
return requestUri != null ? requestUri.getAuthority() : null;
}
static String resolveHost(String hostHeader, URI requestUri) {
return resolveHost(hostHeader, null, requestUri);
}
/**
* Extracts a bucket name from a virtual-hosted-style Host header.
*
@@ -265,7 +302,12 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
// Website endpoints keep their historical tail-agnostic handling: any
// bucket.s3-website-<region>.<anything> is virtual-hosted.
return bucketBeforeWebsiteQualifier(hostname);
String websiteBucket = bucketBeforeWebsiteQualifier(hostname);
if (websiteBucket != null) {
return websiteBucket;
}
return bucketBeforeS3Qualifier(hostname);
}
/**
@@ -501,6 +543,73 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
return null;
}
/**
* Tail-agnostic S3 qualifier handling: {@code <bucket>.s3.<region>.<domain>} or
* {@code <bucket>.s3-fips.dualstack.<region>.<domain>} on custom or unconfigured domains.
* Recognized when an {@code s3} label appears after the bucket candidate and is followed
* by a valid AWS region id.
*/
static String bucketBeforeS3Qualifier(String hostname) {
String[] labels = hostname.split("\\.", -1);
for (int i = 1; i < labels.length - 1; i++) {
String head = labels[i].toLowerCase();
if ("s3".equals(head) || "s3-fips".equals(head)) {
int next = i + 1;
if (next < labels.length && DUALSTACK.equalsIgnoreCase(labels[next])) {
next++;
}
if (next < labels.length && AwsRegions.isRegionId(labels[next])) {
String candidate = String.join(".", Arrays.copyOfRange(labels, 0, i));
if (isValidCandidateBucket(candidate)) {
return candidate;
}
}
} else if (head.startsWith("s3-") && AwsRegions.isRegionId(head.substring("s3-".length()))) {
String candidate = String.join(".", Arrays.copyOfRange(labels, 0, i));
if (isValidCandidateBucket(candidate)) {
return candidate;
}
}
}
return null;
}
private static boolean isValidCandidateBucket(String candidate) {
if (candidate.isEmpty()) {
return false;
}
String[] labels = candidate.split("\\.", -1);
for (int i = 1; i < labels.length; i++) {
if (NON_S3_SERVICE_LABELS.contains(labels[i].toLowerCase())) {
return false;
}
}
return !isForeignRegionalHost(labels);
}
/**
* Fallback for virtual-hosted requests on custom domains where the hostname does not
* carry standard S3 qualifiers or DNS suffixes, but the leading subdomain matches a
* bucket that already exists in Floci.
*/
static String extractBucketFromExisting(String host, S3Service s3Service) {
if (host == null || s3Service == null) {
return null;
}
String hostname = stripPort(host);
String[] labels = hostname.split("\\.", -1);
if (labels.length < 2) {
return null;
}
for (int i = labels.length - 1; i >= 1; i--) {
String candidate = String.join(".", Arrays.copyOfRange(labels, 0, i));
if (s3Service.bucketExists(candidate)) {
return candidate;
}
}
return null;
}
static boolean isS3ServiceEndpointHost(String firstLabel, String remainder, String baseHostname,
Set<String> serviceHostSuffixes) {
if (!"s3".equalsIgnoreCase(firstLabel)) {