refactor(s3): move website folder-resolution policy into S3Service (#2189)

S3Controller carried the website endpoint's index resolution, folder
redirect, exact-object precedence and error-document fallback, reading the
raw Vert.x request path to do it. Introduce S3Service.WebsiteResolution and
resolveWebsiteRequest/resolveWebsiteError so the service decides what to
serve and the controller only renders it as HTTP.

The controller keeps the one thing it alone can answer — whether the client
asked for a directory — and passes it in, so S3Service stays free of
jakarta.ws.rs and io.vertx types.

Fold the duplicated isWebsiteErrorDocumentTrigger predicate into the service
as the single source of truth, and drop an unreachable xmlErrorResponse
fallback (serveErrorDocument never returned null).

Behaviour is unchanged: S3WebsiteIntegrationTest's 25 tests pass untouched.
Add 11 S3ServiceTest cases covering the policy directly, which now needs no
HTTP layer to exercise.

Closes #2140
This commit is contained in:
David authored and GitHub committed 2026-08-18 07:01:06 -04:00
1 parent 75c8cfc4d9
commit 96288c104a
3 files changed
+303 -86

No files matched your search

@@ -836,7 +836,7 @@ public class S3Controller {
return fullObjectResponse(bucket, key, versionId, obj, overrides, includeChecksum);
} catch (AwsException e) {
emitCloudTrailEvent("GetObject", bucket, key, 0L, 0L, e.getErrorCode(), e.getMessage());
if (isWebsiteErrorDocumentTrigger(e) && isWebsiteRequest(httpHeaders, uriInfo)) {
if (S3Service.isWebsiteErrorDocumentTrigger(e) && isWebsiteRequest(httpHeaders, uriInfo)) {
Response websiteError = serveWebsiteErrorResponse(bucket, authorization, e);
if (websiteError != null) {
return websiteError;
@@ -1023,7 +1023,7 @@ public class S3Controller {
return resp.build();
} catch (AwsException e) {
emitCloudTrailEvent("HeadObject", bucket, key, 0L, 0L, e.getErrorCode(), e.getMessage());
if (isWebsiteErrorDocumentTrigger(e) && isWebsiteRequest(httpHeaders, uriInfo)) {
if (S3Service.isWebsiteErrorDocumentTrigger(e) && isWebsiteRequest(httpHeaders, uriInfo)) {
Response websiteError = serveWebsiteErrorResponse(bucket, authorization, e);
if (websiteError != null) {
return headOnlyResponse(websiteError);
@@ -2302,96 +2302,56 @@ public class S3Controller {
*/
private Response serveWebsiteObject(String bucket, String key,
S3Service.RequestAuthorization authorization) {
WebsiteConfiguration cfg;
try {
cfg = s3Service.getBucketWebsite(bucket);
} catch (AwsException e) {
// Only "no website configuration" means fall through to normal handling; a real error
// (e.g. NoSuchBucket) must propagate rather than be masked as "not a website".
if (!"NoSuchWebsiteConfiguration".equals(e.getErrorCode())) {
throw e;
}
return null;
}
String index = cfg.getIndexDocument();
if (index == null) {
return null;
}
// The routing layer strips a trailing slash from the object key, so recover the "directory"
// intent from the raw request path: a trailing slash (or the site root) means "serve this
// prefix's index document"; the prefix is the key without any trailing slash.
var request = currentVertxRequest.getCurrent().request();
String rawPath = request.path();
boolean directory = key.isEmpty() || rawPath.endsWith("/");
String prefix = key.endsWith("/") ? key.substring(0, key.length() - 1) : key;
if (directory) {
String indexKey = prefix.isEmpty() ? index : prefix + "/" + index;
try {
s3Service.authorizeGetObject(bucket, indexKey, null, authorization);
S3Object indexObj = s3Service.headObject(bucket, indexKey, null);
// A website endpoint serves the index document with no response-header overrides and no
// checksum headers (no viewer sends response-* or x-amz-checksum-mode to a website endpoint).
return fullObjectResponse(bucket, indexKey, null, indexObj,
new ResponseHeaderOverrides(null, null, null, null, null, null), false);
} catch (AwsException e) {
if (!isWebsiteErrorDocumentTrigger(e)) {
throw e;
}
Response err = serveErrorDocument(bucket, cfg, authorization, e.getHttpStatus());
return err != null ? err : xmlErrorResponse(e);
}
}
// Not slash-terminated: an exact object is served by the normal path; a prefix that exists only
// as a "folder" (an index document lives beneath it) 302-redirects to the slash-terminated form
// so the page's relative asset URLs resolve against the right base (matching real S3).
if (!s3Service.objectExists(bucket, prefix) && s3Service.objectExists(bucket, prefix + "/" + index)) {
// The query string is deliberately dropped: real S3 answers
// GET /photos?code=abc&state=xyz with a bare "Location: /photos/" (verified against a
// live website endpoint in us-east-1, same for HEAD and for nested prefixes).
return Response.status(Response.Status.FOUND)
.header("Location", rawPath + "/")
.build();
}
return null;
// The routing layer strips a trailing slash from the object key, so the "directory" intent
// has to be recovered from the raw request path before handing off to the service.
String rawPath = currentVertxRequest.getCurrent().request().path();
return renderWebsiteResolution(bucket,
s3Service.resolveWebsiteRequest(bucket, key, rawPath.endsWith("/"), authorization),
rawPath);
}
private Response serveWebsiteErrorResponse(String bucket,
S3Service.RequestAuthorization authorization,
AwsException cause) {
try {
WebsiteConfiguration webConfig = s3Service.getBucketWebsite(bucket);
return serveErrorDocument(bucket, webConfig, authorization, cause.getHttpStatus());
return renderWebsiteResolution(bucket,
s3Service.resolveWebsiteError(bucket, authorization, cause.getHttpStatus()), null);
} catch (AwsException websiteException) {
if (!"NoSuchWebsiteConfiguration".equals(websiteException.getErrorCode())) {
return xmlErrorResponse(websiteException);
}
return null;
return xmlErrorResponse(websiteException);
}
}
private Response serveErrorDocument(String bucket, WebsiteConfiguration cfg,
S3Service.RequestAuthorization authorization, int status) {
int responseStatus = status == 403 ? 403 : 404;
if (cfg.getErrorDocument() == null) {
return defaultWebsiteErrorResponse(responseStatus);
}
try {
s3Service.authorizeGetObject(bucket, cfg.getErrorDocument(), null, authorization);
S3Object err = s3Service.getObject(bucket, cfg.getErrorDocument());
return Response.status(responseStatus)
.entity(err.getData())
.type(err.getContentType())
.header("Content-Length", err.getSize())
.header("x-amz-error-code", websiteErrorCode(responseStatus))
.header("x-amz-error-message", websiteErrorMessage(responseStatus))
.build();
} catch (AwsException e) {
if (!isWebsiteErrorDocumentTrigger(e)) {
throw e;
}
return defaultWebsiteErrorResponse(responseStatus);
}
/**
* Render a {@link S3Service.WebsiteResolution} as HTTP. {@code rawPath} is only needed for the
* directory redirect; pass {@code null} where that outcome cannot occur. Returns {@code null}
* for {@code NotAWebsite}, meaning "fall through to the normal object path".
*/
private Response renderWebsiteResolution(String bucket, S3Service.WebsiteResolution resolution,
String rawPath) {
return switch (resolution) {
// A website endpoint serves the index document with no response-header overrides and no
// checksum headers (no viewer sends response-* or x-amz-checksum-mode to a website endpoint).
case S3Service.WebsiteResolution.ServeObject(String key, S3Object object) ->
fullObjectResponse(bucket, key, null, object,
new ResponseHeaderOverrides(null, null, null, null, null, null), false);
// The query string is deliberately dropped: real S3 answers
// GET /photos?code=abc&state=xyz with a bare "Location: /photos/" (verified against a
// live website endpoint in us-east-1, same for HEAD and for nested prefixes).
case S3Service.WebsiteResolution.RedirectToDirectory() ->
Response.status(Response.Status.FOUND)
.header("Location", rawPath + "/")
.build();
case S3Service.WebsiteResolution.ErrorDocument(S3Object object, int status) ->
Response.status(status)
.entity(object.getData())
.type(object.getContentType())
.header("Content-Length", object.getSize())
.header("x-amz-error-code", websiteErrorCode(status))
.header("x-amz-error-message", websiteErrorMessage(status))
.build();
case S3Service.WebsiteResolution.DefaultError(int status) -> defaultWebsiteErrorResponse(status);
case S3Service.WebsiteResolution.NotAWebsite() -> null;
};
}
private static Response defaultWebsiteErrorResponse(int status) {
@@ -2405,10 +2365,6 @@ public class S3Controller {
.build();
}
private static boolean isWebsiteErrorDocumentTrigger(AwsException e) {
return "NoSuchKey".equals(e.getErrorCode()) || "AccessDenied".equals(e.getErrorCode());
}
private static String websiteErrorCode(int status) {
return status == 403 ? "AccessDenied" : "NoSuchKey";
}
@@ -1498,6 +1498,133 @@ public class S3Service implements Resettable {
LOG.infov("Deleted website configuration for bucket: {0}", bucketName);
}
/**
* What a website-endpoint request resolves to. The service decides <em>what</em> to serve;
* the controller decides how to render it as HTTP. Keeping the decision here means the policy
* is unit-testable without standing up the HTTP layer.
*/
public sealed interface WebsiteResolution {
/** Serve {@code object} (already read and authorized) as the response body. */
record ServeObject(String key, S3Object object) implements WebsiteResolution {}
/**
* The request names a "folder" that only exists as a prefix with an index document
* beneath it: redirect to the slash-terminated form so the page's relative asset URLs
* resolve against the right base. The target is built by the caller, which is the only
* layer that knows the raw request path.
*/
record RedirectToDirectory() implements WebsiteResolution {}
/** Serve the bucket's custom error document with {@code status}. */
record ErrorDocument(S3Object object, int status) implements WebsiteResolution {}
/** No usable custom error document: render S3's built-in error page with {@code status}. */
record DefaultError(int status) implements WebsiteResolution {}
/** Not a website request — fall through to the normal object path. */
record NotAWebsite() implements WebsiteResolution {}
}
/**
* Resolve a request against a bucket's website configuration.
* <p>
* {@code directoryRequest} is the caller's answer to "did the client ask for a directory?" —
* the routing layer strips the trailing slash from the object key, so only the caller can see
* the slash that distinguishes {@code /docs/} (serve {@code docs/index.html}) from
* {@code /docs} (redirect to {@code /docs/}). The site root is always a directory request.
* <p>
* Returns {@link WebsiteResolution.NotAWebsite} when the request should be served by the
* normal object path — an exact object hit, or a bucket with no website configuration. The
* index read is authorized (a no-op unless S3 auth enforcement is enabled), matching the
* object-serving path.
*/
public WebsiteResolution resolveWebsiteRequest(String bucket, String key, boolean directoryRequest,
RequestAuthorization authorization) {
WebsiteConfiguration cfg;
try {
cfg = getBucketWebsite(bucket);
} catch (AwsException e) {
// Only "no website configuration" means fall through to normal handling; a real error
// (e.g. NoSuchBucket) must propagate rather than be masked as "not a website".
if (!"NoSuchWebsiteConfiguration".equals(e.getErrorCode())) {
throw e;
}
return new WebsiteResolution.NotAWebsite();
}
String index = cfg.getIndexDocument();
if (index == null) {
return new WebsiteResolution.NotAWebsite();
}
boolean directory = key.isEmpty() || directoryRequest;
String prefix = key.endsWith("/") ? key.substring(0, key.length() - 1) : key;
if (directory) {
String indexKey = prefix.isEmpty() ? index : prefix + "/" + index;
try {
authorizeGetObject(bucket, indexKey, null, authorization);
return new WebsiteResolution.ServeObject(indexKey, headObject(bucket, indexKey, null));
} catch (AwsException e) {
if (!isWebsiteErrorDocumentTrigger(e)) {
throw e;
}
return resolveErrorDocument(bucket, cfg, authorization, e.getHttpStatus());
}
}
// Not slash-terminated: an exact object is served by the normal path; a prefix that exists
// only as a "folder" (an index document lives beneath it) redirects to the slash-terminated
// form, matching real S3.
if (!objectExists(bucket, prefix) && objectExists(bucket, prefix + "/" + index)) {
return new WebsiteResolution.RedirectToDirectory();
}
return new WebsiteResolution.NotAWebsite();
}
/**
* Resolve the error response for a website request that already failed, so a website endpoint
* answers with the bucket's error document rather than S3's REST XML.
* <p>
* Returns {@link WebsiteResolution.NotAWebsite} when the bucket has no website configuration.
* Any other failure propagates, so the caller renders the real error instead of hiding it
* behind an error document.
*/
public WebsiteResolution resolveWebsiteError(String bucket, RequestAuthorization authorization, int status) {
try {
return resolveErrorDocument(bucket, getBucketWebsite(bucket), authorization, status);
} catch (AwsException e) {
if (!"NoSuchWebsiteConfiguration".equals(e.getErrorCode())) {
throw e;
}
return new WebsiteResolution.NotAWebsite();
}
}
private WebsiteResolution resolveErrorDocument(String bucket, WebsiteConfiguration cfg,
RequestAuthorization authorization, int status) {
int responseStatus = status == 403 ? 403 : 404;
if (cfg.getErrorDocument() == null) {
return new WebsiteResolution.DefaultError(responseStatus);
}
try {
authorizeGetObject(bucket, cfg.getErrorDocument(), null, authorization);
return new WebsiteResolution.ErrorDocument(getObject(bucket, cfg.getErrorDocument()), responseStatus);
} catch (AwsException e) {
if (!isWebsiteErrorDocumentTrigger(e)) {
throw e;
}
return new WebsiteResolution.DefaultError(responseStatus);
}
}
/**
* Whether a failure should be answered with the bucket's website error document rather than
* S3's REST XML error. Callers use this to decide whether the website error path is worth
* attempting at all.
*/
public static boolean isWebsiteErrorDocumentTrigger(AwsException e) {
return "NoSuchKey".equals(e.getErrorCode()) || "AccessDenied".equals(e.getErrorCode());
}
public void deleteBucketTagging(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",