fix(s3): route the accelerate subresource instead of falling through (#2330)

* fix(s3): route the accelerate subresource instead of falling through

PUT /{bucket}?accelerate fell through to CreateBucket: outside the
default region it failed with BucketAlreadyOwnedByYou, and inside it
the idempotent-create path returned a silent 200 without storing
anything, so PutBucketAccelerateConfiguration could not be applied
either way. GET /{bucket}?accelerate fell through to ListObjects and
returned a ListBucketResult, which the SDK silently parses as "not
configured". DELETE /{bucket}?accelerate fell through to DeleteBucket
and deleted an empty bucket outright.

Store the Transfer Acceleration status on the bucket, following the
requestPayment pair as the closest-shaped precedent: PUT requires the
body to parse to the AccelerateConfiguration root (checked with a new
XmlParser.rootElementName primitive, so an absent, truncated, non-XML
or wrong-root body is MalformedXML on every branch) and validates
Enabled/Suspended, while a configuration without the optional Status
element is accepted and leaves the stored state unchanged; GET
returns the stored status, or an AccelerateConfiguration with no
Status element for a bucket that has never been configured; DELETE,
which AWS does not define for this subresource, returns
MethodNotAllowed instead of falling through.

Closes #2295

* fix(s3): resolve accelerate requests to their own IAM actions

The subresource override in IamActionRegistry covered only acl and
tagging, so with auth enforcement enabled a PUT /{bucket}?accelerate
resolved to s3:CreateBucket through the generic bucket rule - a
principal allowed only to create buckets could reconfigure
acceleration on an existing bucket. Map bucket-level GET and PUT to
their own actions instead.

The mapping applies only when the path is bucket-level and no acl or
tagging parameter is present: the object routes ignore ?accelerate,
so an object request keeps resolving to its object action, and a
stricter acl or tagging resolution can never be downgraded by
appending an inert parameter. A bare DELETE stays on the rule table,
since AWS defines no delete action for this subresource.

* fix(s3): yield the accelerate IAM mapping to earlier subresources

A request carrying ?accelerate plus a subresource the controller
dispatches earlier - ?requestPayment, say - executes that other
operation while resolving to the accelerate action, so a principal
holding only the accelerate permission could read or change an
unrelated configuration. Wire-probed: PUT with both parameters
stores the request-payment payer, not an acceleration state.

The accelerate mapping now yields whenever such a subresource rides
along, falling back to the standard rule table - exactly what a
plain ?requestPayment request resolves to today. The yield lists
are method-aware because the dispatch chains are: ?uploads blocks
accelerate on GET but is inert on PUT, where accelerate still
executes and keeps its own action.
This commit is contained in:
soreavis authored and GitHub committed 2026-08-15 18:25:05 -04:00
1 parent 7a4fc45fdf
commit 833de25c08
8 files changed
+483 -8

No files matched your search

@@ -72,6 +72,34 @@ public final class XmlParser {
return sb.toString();
}
/**
* Returns the local name of the document's root element, parsing the whole body —
* so trailing garbage or any well-formedness error yields {@code null}.
*
* <pre>{@code
* boolean valid = "AccelerateConfiguration".equals(XmlParser.rootElementName(body));
* }</pre>
*/
public static String rootElementName(String xml) {
if (xml == null || xml.isEmpty()) {
return null;
}
String root = null;
try {
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
while (r.hasNext()) {
if (r.next() == XMLStreamConstants.START_ELEMENT && root == null) {
root = r.getLocalName();
}
}
r.close();
} catch (Exception e) {
LOG.debugv("Ignoring malformed XML during parse: {0}", e.getMessage());
return null;
}
return root;
}
/**
* Extracts the text content of every element whose local name matches {@code elementName}.
*
@@ -158,6 +158,19 @@ public class IamActionRegistry {
return null;
}
// Subresources S3Controller dispatches ahead of accelerate in its PUT and GET
// chains (acl and tagging are resolved above). When one rides along, that
// operation is what executes, so the accelerate mapping must not claim the
// request. Mirrors the controller's dispatch order — extend together.
private static final List<String> PUT_SUBRESOURCES_BEFORE_ACCELERATE = List.of(
"notification", "versioning", "object-lock", "website", "logging", "policy",
"cors", "lifecycle", "encryption", "publicAccessBlock", "ownershipControls",
"requestPayment");
private static final List<String> GET_SUBRESOURCES_BEFORE_ACCELERATE = List.of(
"uploads", "notification", "versioning", "versions", "location", "object-lock",
"website", "logging", "policy", "cors", "lifecycle", "encryption",
"publicAccessBlock", "ownershipControls", "requestPayment");
/**
* Resolves S3 sub-resource ops (ACL, tagging, retention, etc.) that
* cannot be distinguished from the parent op by HTTP method + path alone.
@@ -168,7 +181,8 @@ public class IamActionRegistry {
var params = ctx.getUriInfo().getQueryParameters();
boolean acl = params.containsKey("acl");
boolean tagging = params.containsKey("tagging");
if (!acl && !tagging) {
boolean accelerate = params.containsKey("accelerate");
if (!acl && !tagging && !accelerate) {
return null;
}
// /{bucket}?acl → bucket-level; /{bucket}/{key}?acl → object-level
@@ -193,18 +207,40 @@ public class IamActionRegistry {
default -> null;
};
}
if (isBucketLevel) {
if (tagging) {
if (isBucketLevel) {
return switch (method) {
case "GET" -> "s3:GetBucketTagging";
case "PUT" -> "s3:PutBucketTagging";
case "DELETE" -> "s3:DeleteBucketTagging";
default -> null;
};
}
return switch (method) {
case "GET" -> "s3:GetBucketTagging";
case "PUT" -> "s3:PutBucketTagging";
case "DELETE" -> "s3:DeleteBucketTagging";
case "GET" -> "s3:GetObjectTagging";
case "PUT" -> "s3:PutObjectTagging";
case "DELETE" -> "s3:DeleteObjectTagging";
default -> null;
};
}
// Accelerate is a bucket-only subresource, and ?accelerate on an object path is
// inert — the object routes ignore it — so only a bucket-level request maps here;
// everything else falls through to the standard rule table.
if (!isBucketLevel) {
return null;
}
List<String> dispatchedFirst = "PUT".equals(method)
? PUT_SUBRESOURCES_BEFORE_ACCELERATE
: GET_SUBRESOURCES_BEFORE_ACCELERATE;
for (String subresource : dispatchedFirst) {
if (params.containsKey(subresource)) {
return null;
}
}
return switch (method) {
case "GET" -> "s3:GetObjectTagging";
case "PUT" -> "s3:PutObjectTagging";
case "DELETE" -> "s3:DeleteObjectTagging";
case "GET" -> "s3:GetAccelerateConfiguration";
case "PUT" -> "s3:PutAccelerateConfiguration";
// AWS defines no DELETE for the subresource.
default -> null;
};
}
@@ -320,6 +320,10 @@ public class S3Controller {
s3Service.putBucketRequestPayment(bucket, new String(body, StandardCharsets.UTF_8));
return Response.ok().build();
}
if (hasQueryParam(uriInfo, "accelerate")) {
s3Service.putBucketAccelerateConfiguration(bucket, new String(body, StandardCharsets.UTF_8));
return Response.ok().build();
}
String locationConstraint = null;
if (body != null && body.length > 0) {
@@ -403,6 +407,12 @@ public class S3Controller {
// handled here so it does NOT fall through to deleting the whole bucket.
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "accelerate")) {
// AWS defines no DELETE for the accelerate subresource; reject it here so
// it does NOT fall through to deleting the whole bucket.
throw new AwsException("MethodNotAllowed",
"The specified method is not allowed against this resource.", 405);
}
s3Service.deleteBucket(bucket);
return Response.noContent().build();
} catch (AwsException e) {
@@ -504,6 +514,10 @@ public class S3Controller {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketRequestPayment", authorization);
return Response.ok(s3Service.getBucketRequestPayment(bucket)).build();
}
if (hasQueryParam(uriInfo, "accelerate")) {
s3Service.authorizeBucketRead(bucket, "s3:GetAccelerateConfiguration", authorization);
return Response.ok(s3Service.getBucketAccelerateConfiguration(bucket)).build();
}
// --- S3 static-website index resolution (site root) ---
// A website endpoint has no S3 REST API, so it serves the index document for the site root
@@ -2135,6 +2135,50 @@ public class S3Service implements Resettable {
.build();
}
/**
* Stores the bucket Transfer Acceleration state. The AccelerateConfiguration root
* is required, so a body that does not parse to one is rejected with
* {@code MalformedXML}; the Status element inside it is optional in the AWS schema,
* so a configuration without one is accepted and leaves the stored state unchanged.
* AWS only allows the values {@code Enabled} and {@code Suspended}.
*/
public void putBucketAccelerateConfiguration(String bucketName, String accelerateXml) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
if (!"AccelerateConfiguration".equals(XmlParser.rootElementName(accelerateXml))) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema.",
400);
}
String status = XmlParser.extractFirst(accelerateXml, "Status", null);
if (status == null) {
return;
}
status = status.trim();
if (!"Enabled".equals(status) && !"Suspended".equals(status)) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema.",
400);
}
bucket.setAccelerateStatus(status);
bucketStore.put(bucketName, bucket);
}
/**
* Returns the bucket Transfer Acceleration state as XML. A bucket that has never
* been configured returns an {@code AccelerateConfiguration} with no Status element
* rather than an error, matching real S3.
*/
public String getBucketAccelerateConfiguration(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
return new XmlBuilder()
.start("AccelerateConfiguration", AwsNamespaces.S3)
.elem("Status", bucket.getAccelerateStatus())
.end("AccelerateConfiguration")
.build();
}
public void restoreObject(String bucketName, String key, String versionId, String restoreXml) {
// Validation only - stub implementation
getObject(bucketName, key, versionId);
@@ -28,6 +28,7 @@ public class Bucket {
private String publicAccessBlockConfiguration; // XML string
private String ownershipControlsConfiguration; // XML string
private String requestPaymentPayer; // "BucketOwner" (default) or "Requester"; null until first PUT
private String accelerateStatus; // "Enabled" or "Suspended"; null until first PUT
private String region;
private WebsiteConfiguration websiteConfiguration;
@@ -108,6 +109,9 @@ public class Bucket {
public String getRequestPaymentPayer() { return requestPaymentPayer; }
public void setRequestPaymentPayer(String requestPaymentPayer) { this.requestPaymentPayer = requestPaymentPayer; }
public String getAccelerateStatus() { return accelerateStatus; }
public void setAccelerateStatus(String accelerateStatus) { this.accelerateStatus = accelerateStatus; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
@@ -213,4 +213,25 @@ class XmlParserTest {
assertTrue(filters.get(0).isEmpty());
assertEquals("logs/", filters.get(1).get("prefix"));
}
// --- rootElementName: root identification and well-formedness ---
@Test
void rootElementNameReturnsTheRootLocalName() {
assertEquals("AccelerateConfiguration", XmlParser.rootElementName(
"<AccelerateConfiguration><Status>Enabled</Status></AccelerateConfiguration>"));
assertEquals("AccelerateConfiguration", XmlParser.rootElementName(
"<ns:AccelerateConfiguration xmlns:ns=\"urn:x\"/>"));
assertEquals("Wrapper", XmlParser.rootElementName(
"<Wrapper><AccelerateConfiguration/></Wrapper>"));
}
@Test
void rootElementNameReturnsNullForBodiesThatDoNotParse() {
assertNull(XmlParser.rootElementName(null));
assertNull(XmlParser.rootElementName(""));
assertNull(XmlParser.rootElementName("garbage {} not xml"));
assertNull(XmlParser.rootElementName("<AccelerateConfiguration><Status>Enabled"));
assertNull(XmlParser.rootElementName("<AccelerateConfiguration/>trailing"));
}
}
@@ -147,6 +147,72 @@ class IamActionRegistryTest {
assertEquals("s3:GetBucketAcl", registry.resolve("s3", ctx));
}
@Test
void s3AccelerateResolvesToItsOwnActions() {
// Without the override, PUT ?accelerate resolves to s3:CreateBucket — a
// principal allowed only to create buckets could reconfigure acceleration.
MultivaluedMap<String, String> accelerate = new MultivaluedHashMap<>();
accelerate.add("accelerate", "");
assertEquals("s3:PutAccelerateConfiguration",
registry.resolve("s3", mockCtx("PUT", "/bucket", accelerate, null, "")));
assertEquals("s3:GetAccelerateConfiguration",
registry.resolve("s3", mockCtx("GET", "/bucket", accelerate, null, "")));
// AWS defines no DELETE for the subresource, so it stays on the rule table.
assertEquals("s3:DeleteBucket",
registry.resolve("s3", mockCtx("DELETE", "/bucket", accelerate, null, "")));
}
@Test
void s3AccelerateOnAnObjectPathKeepsTheObjectActions() {
// The object routes ignore ?accelerate, so mapping it there would let a
// principal with only accelerate permissions read or write arbitrary objects.
MultivaluedMap<String, String> accelerate = new MultivaluedHashMap<>();
accelerate.add("accelerate", "");
assertEquals("s3:GetObject",
registry.resolve("s3", mockCtx("GET", "/bucket/secret.txt", accelerate, null, "")));
assertEquals("s3:PutObject",
registry.resolve("s3", mockCtx("PUT", "/bucket/key.txt", accelerate, null, "")));
}
@Test
void s3AccelerateYieldsToSubresourcesDispatchedFirst() {
// The controller executes the requestPayment operation for this request, so the
// accelerate mapping must not claim it; resolution falls back to the rule table,
// exactly like a plain ?requestPayment request today.
MultivaluedMap<String, String> withRequestPayment = new MultivaluedHashMap<>();
withRequestPayment.add("requestPayment", "");
withRequestPayment.add("accelerate", "");
assertEquals("s3:CreateBucket",
registry.resolve("s3", mockCtx("PUT", "/bucket", withRequestPayment, null, "")));
MultivaluedMap<String, String> withLocation = new MultivaluedHashMap<>();
withLocation.add("location", "");
withLocation.add("accelerate", "");
assertEquals("s3:ListBucket",
registry.resolve("s3", mockCtx("GET", "/bucket", withLocation, null, "")));
// uploads is a GET-only dispatch branch; on PUT it is inert and accelerate executes,
// so the mapping must still claim the request there.
MultivaluedMap<String, String> withUploads = new MultivaluedHashMap<>();
withUploads.add("uploads", "");
withUploads.add("accelerate", "");
assertEquals("s3:PutAccelerateConfiguration",
registry.resolve("s3", mockCtx("PUT", "/bucket", withUploads, null, "")));
}
@Test
void s3AccelerateDoesNotPreemptAclOrTagging() {
// Appending an inert ?accelerate must not downgrade a stricter resolution.
MultivaluedMap<String, String> withAcl = new MultivaluedHashMap<>();
withAcl.add("accelerate", "");
withAcl.add("acl", "");
assertEquals("s3:PutBucketAcl",
registry.resolve("s3", mockCtx("PUT", "/bucket", withAcl, null, "")));
MultivaluedMap<String, String> withTagging = new MultivaluedHashMap<>();
withTagging.add("accelerate", "");
withTagging.add("tagging", "");
assertEquals("s3:DeleteObjectTagging",
registry.resolve("s3", mockCtx("DELETE", "/bucket/key.txt", withTagging, null, "")));
}
// -------------------------------------------------------------------------
private static ContainerRequestContext mockCtx(String method, String path,
@@ -0,0 +1,262 @@
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 static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class S3AccelerateConfigurationIntegrationTest {
private static final String BUCKET = "accelerate-int-test";
private static final String ENABLED_XML = """
<AccelerateConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Status>Enabled</Status>
</AccelerateConfiguration>
""";
private static final String SUSPENDED_XML = """
<AccelerateConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Status>Suspended</Status>
</AccelerateConfiguration>
""";
@Test
@Order(1)
void createBucket() {
given()
.when()
.put("/" + BUCKET)
.then()
.statusCode(200);
}
/**
* A bucket that has never had acceleration configured returns an
* {@code AccelerateConfiguration} with no Status element. Before the accelerate
* subresource was routed this fell through to ListObjects and returned a
* {@code ListBucketResult}, which the SDK silently parsed as "not configured".
*/
@Test
@Order(2)
void getAccelerateBeforePutReturnsConfigurationWithoutStatus() {
given()
.when()
.get("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.body(containsString("<AccelerateConfiguration"))
.body(not(containsString("<Status>")))
.body(not(containsString("ListBucketResult")));
}
/**
* Regression test for the Terraform-breaking bug where {@code PUT /{bucket}?accelerate}
* fell through to the bucket-creation handler: outside the default region it returned
* {@code BucketAlreadyOwnedByYou}, and inside it the idempotent-create path answered a
* silent 200 with a {@code Location} header without storing anything — so the absent
* header is what distinguishes the routed response from the fall-through here.
*/
@Test
@Order(3)
void putAccelerateEnabledOnExistingBucketReturns200() {
given()
.body(ENABLED_XML)
.when()
.put("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.header("Location", nullValue())
.body(not(containsString("BucketAlreadyOwnedByYou")));
}
@Test
@Order(4)
void getAccelerateReturnsStoredStatus() {
given()
.when()
.get("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.body(containsString("<Status>Enabled</Status>"));
}
@Test
@Order(5)
void putAccelerateSuspendedOverwritesStoredStatus() {
given()
.body(SUSPENDED_XML)
.when()
.put("/" + BUCKET + "?accelerate")
.then()
.statusCode(200);
given()
.when()
.get("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.body(containsString("<Status>Suspended</Status>"));
}
/**
* The Status element is optional in the AWS schema (Required: No), so a
* configuration without one is accepted and leaves the stored state unchanged.
*/
@Test
@Order(6)
void putAccelerateWithoutStatusIsAcceptedAndLeavesStateUnchanged() {
given()
.body("""
<AccelerateConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
</AccelerateConfiguration>
""")
.when()
.put("/" + BUCKET + "?accelerate")
.then()
.statusCode(200);
given()
.when()
.get("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.body(containsString("<Status>Suspended</Status>"));
}
/** The AccelerateConfiguration root is Required: Yes, so a body that does not parse to one is malformed. */
@Test
@Order(7)
void putAccelerateRejectsAnUnparseableBody() {
for (String body : new String[] {
"",
"garbage {} not xml",
"""
<AccelerateConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Status>Enabled""" }) {
given()
.body(body)
.when()
.put("/" + BUCKET + "?accelerate")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
}
given()
.when()
.get("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.body(containsString("<Status>Suspended</Status>"));
}
/** A Status inside the wrong root must not configure anything — the required root is checked on both branches. */
@Test
@Order(8)
void putAccelerateRejectsAWrongRootElement() {
given()
.body("""
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Status>Enabled</Status>
</VersioningConfiguration>
""")
.when()
.put("/" + BUCKET + "?accelerate")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
given()
.when()
.get("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.body(containsString("<Status>Suspended</Status>"));
}
/** Same normalization as the requestPayment sibling. */
@Test
@Order(9)
void putAccelerateTrimsWhitespacePaddedStatus() {
given()
.body("""
<AccelerateConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Status> Enabled </Status>
</AccelerateConfiguration>
""")
.when()
.put("/" + BUCKET + "?accelerate")
.then()
.statusCode(200);
given()
.when()
.get("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.body(containsString("<Status>Enabled</Status>"));
}
@Test
@Order(10)
void putAccelerateRejectsInvalidStatus() {
given()
.body("""
<AccelerateConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Status>Paused</Status>
</AccelerateConfiguration>
""")
.when()
.put("/" + BUCKET + "?accelerate")
.then()
.statusCode(400)
.body(containsString("MalformedXML"));
}
@Test
@Order(11)
void putAccelerateOnMissingBucketReturns404() {
given()
.body(ENABLED_XML)
.when()
.put("/this-bucket-does-not-exist-accel?accelerate")
.then()
.statusCode(404)
.body(containsString("NoSuchBucket"));
}
@Test
@Order(12)
void getAccelerateOnMissingBucketReturns404() {
given()
.when()
.get("/this-bucket-does-not-exist-accel?accelerate")
.then()
.statusCode(404)
.body(containsString("NoSuchBucket"));
}
/**
* AWS defines no DELETE for the accelerate subresource. Before it was routed, a
* {@code DELETE /{bucket}?accelerate} fell through to {@code DeleteBucket} and
* deleted an empty bucket outright.
*/
@Test
@Order(13)
void deleteAccelerateReturns405AndLeavesTheBucketAlone() {
given()
.when()
.delete("/" + BUCKET + "?accelerate")
.then()
.statusCode(405)
.body(containsString("MethodNotAllowed"));
given()
.when()
.get("/" + BUCKET + "?accelerate")
.then()
.statusCode(200)
.body(containsString("<AccelerateConfiguration"));
}
}