fix(s3): ListBuckets filters the buckets by prefix and bucket-region (#9887)

ListBuckets read prefix and bucket-region only to decide whether to
render each bucket's BucketRegion, so the list was never narrowed. Both
parameters now filter the listed buckets before the page is cut, so a
continuation token resumes the filtered list, and a sent prefix, empty
included, comes back as the response's Prefix. A bucket-region outside
the Regions AWS publishes, or other than the Region the request reached
(for a presigned request, the one its credential names), is refused
with InvalidArgument as AWS answers it.

Closes #9858
This commit is contained in:
XuJian authored and GitHub committed 2026-12-02 11:57:42 -04:00
1 parent 253e988b63
commit 35b760918c
6 files changed
+305 -9

No files matched your search

+7 -2
View File
@@ -46,8 +46,13 @@ the S3 Control `TagResource` and `UntagResource` change them, and `GetBucketTagg
configured default region. Bare requests omit the field. Buckets are listed in name order and
paged by `max-buckets` (1 to 10000), with a `ContinuationToken` on every page but the last; a
`max-buckets` out of range or a token that is unreadable or was issued to another account is
refused with `InvalidArgument`. Without `max-buckets`, every bucket comes back on one page. Filtering by `prefix` and `bucket-region` is not implemented;
those parameters do not limit the returned bucket list.
refused with `InvalidArgument`. Without `max-buckets`, every bucket comes back on one page. `prefix`
limits the list to buckets whose name begins with it and `bucket-region` to buckets in that region,
where a bucket with no stored region belongs to the configured default region; both filters apply
before paging, so a continuation token resumes the filtered list. A request that sends a `prefix`
gets it back as the response's `Prefix`. A `bucket-region` outside the regions AWS publishes, or one
naming a region other than the endpoint the request was signed for, is refused with `InvalidArgument`
before the list is filtered.
## Event Notifications
@@ -272,9 +272,15 @@ public class S3Controller {
try {
boolean includeRegion = List.of("bucket-region", "continuation-token", "max-buckets", "prefix")
.stream().anyMatch(queryParams::containsKey);
String prefix = queryParams.getFirst("prefix");
String bucketRegion = queryParams.getFirst("bucket-region");
if (bucketRegion != null && !bucketRegion.isBlank()) {
requireBucketRegion(bucketRegion, regionResolver.getRegion());
}
PaginatedResult<Bucket> page = s3Service.listBuckets(
Pagination.parseMaxResults(queryParams.getFirst("max-buckets"), "InvalidArgument"),
queryParams.getFirst("continuation-token"));
queryParams.getFirst("continuation-token"),
prefix, bucketRegion);
XmlBuilder xml = new XmlBuilder()
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.start("ListAllMyBucketsResult", AwsNamespaces.S3)
@@ -288,8 +294,7 @@ public class S3Controller {
.elem("Name", b.getName())
.elem("CreationDate", ISO_FORMAT.format(b.getCreationDate()));
if (includeRegion) {
String region = b.getRegion();
xml.elem("BucketRegion", region == null || region.isBlank() ? regionResolver.getDefaultRegion() : region);
xml.elem("BucketRegion", s3Service.listedBucketRegion(b));
}
xml.end("Bucket");
}
@@ -297,6 +302,9 @@ public class S3Controller {
if (page.nextToken() != null) {
xml.elem("ContinuationToken", page.nextToken());
}
if (prefix != null) {
xml.elem("Prefix", prefix);
}
xml.end("ListAllMyBucketsResult");
return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build();
} catch (AwsException e) {
@@ -304,6 +312,25 @@ public class S3Controller {
}
}
/**
* AWS answers a {@code bucket-region} outside the Regions it publishes, and one naming a Region other
* than the endpoint the request reached, with {@code InvalidArgument} before it lists anything. The
* filter can only narrow what this endpoint's account has, so a mismatch is a caller mistake rather than
* an empty page. {@code requestRegion} is the Region {@code AccountContextFilter} resolved for the
* request, which for a presigned URL comes from its {@code X-Amz-Credential} because it sends no
* {@code Authorization} header. An empty value stays the no-filter the request without it sends.
*/
private void requireBucketRegion(String bucketRegion, String requestRegion) {
if (!RegionResolver.isKnownRegion(bucketRegion) && !config.partitions().allowUnknownRegions()) {
throw new AwsException("InvalidArgument",
"Argument value " + bucketRegion + " is not a valid AWS Region", 400);
}
if (!bucketRegion.equals(requestRegion)) {
throw new AwsException("InvalidArgument", "Requests with bucket-region specified must be made to"
+ " the corresponding regional endpoint", 400);
}
}
@HEAD
@Path("/{bucket}")
public Response headBucket(@PathParam("bucket") String bucket,
@@ -775,17 +775,37 @@ public class S3Service implements Resettable, ResourceProvider {
.toList();
}
public PaginatedResult<Bucket> listBuckets(Integer maxBuckets, String continuationToken) {
public PaginatedResult<Bucket> listBuckets(Integer maxBuckets, String continuationToken,
String prefix, String bucketRegion) {
if (maxBuckets != null && (maxBuckets < 1 || maxBuckets > MAX_LIST_BUCKETS)) {
throw new AwsException("InvalidArgument",
"max-buckets must be between 1 and " + MAX_LIST_BUCKETS + ".", 400);
}
return Pagination.paginate(listBuckets(), Bucket::getName,
List<Bucket> buckets = listBuckets().stream()
.filter(bucket -> prefix == null || bucket.getName().startsWith(prefix))
.filter(bucket -> bucketRegion == null || bucketRegion.isBlank()
|| bucketRegion.equals(listedBucketRegion(bucket)))
.toList();
return Pagination.paginate(buckets, Bucket::getName,
maxBuckets == null ? Integer.MAX_VALUE : maxBuckets, continuationToken,
"buckets:" + ownerId(),
token -> new AwsException("InvalidArgument", "The continuation token provided is incorrect.", 400));
}
/**
* The Region {@code ListBuckets} reports for a bucket, and the one its {@code bucket-region} filter
* matches against: the Region the bucket records, or the configured default for a bucket stored before
* buckets recorded their Region. Reporting and filtering have to agree, or a filtered page lists a
* bucket under a Region the caller did not ask for.
*/
String listedBucketRegion(Bucket bucket) {
String region = bucket.getRegion();
if (region != null && !region.isBlank()) {
return region;
}
return regionResolver == null ? null : regionResolver.getDefaultRegion();
}
private static boolean isScratchBucket(Bucket bucket) {
return Arrays.stream(S3ScratchSpace.values()).anyMatch(space -> space.matchesBucket(bucket));
}
@@ -0,0 +1,239 @@
package io.floci.aws.services.s3;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
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 software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Bucket;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* {@code ListBuckets} treats {@code prefix} and {@code bucket-region} as the filters AWS documents them as,
* instead of reading them only to decide whether to report each bucket's region. The filters are applied
* before {@code max-buckets} cuts the page, so a caller paging an account full of buckets can ask for one
* family of them rather than walk every page of the whole list, and AWS's two refusals of a
* {@code bucket-region} come before the filtering too.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class S3ListBucketsFilterIntegrationTest {
@Inject
S3Service service;
// Buckets are listed per account, so an account no other test uses holds exactly these buckets.
private static final String ACCOUNT = "444455558888";
/** The account a request with no credential is read against, which is where {@code S3Service} writes. */
private static final String DEFAULT_ACCOUNT = "000000000000";
/** Signatures are not validated in the default test profile; the account it names selects the list. */
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261116/us-east-1/s3/aws4_request";
private static final String PREFIX = "s3-filter-" + UUID.randomUUID().toString().substring(0, 8);
/** All three start with {@link #PREFIX} and none records a region, so they are listed in this order. */
private static final String MATCHED_B = PREFIX + "-bz-matched";
private static final String MATCHED_EU = PREFIX + "-eu-central-1";
private static final String MATCHED_M = PREFIX + "-matched";
private static final String UNMATCHED = "s3-unfiltered-" + UUID.randomUUID().toString().substring(0, 8);
private static S3Client client(Region region) {
return client(ACCOUNT, region);
}
private static S3Client client(String account, Region region) {
return AwsTestClients.create(S3Client.builder().forcePathStyle(true), account, region);
}
/** The bucket names a response lists, in the order it lists them. */
private static List<String> names(ListBucketsResponse response) {
return response.buckets().stream().map(Bucket::name).toList();
}
@Test
@Order(1)
void createBuckets() {
try (S3Client s3 = client(Region.US_EAST_1)) {
s3.createBucket(r -> r.bucket(UNMATCHED));
s3.createBucket(r -> r.bucket(MATCHED_M));
s3.createBucket(r -> r.bucket(MATCHED_B));
s3.createBucket(r -> r.bucket(MATCHED_EU)
.createBucketConfiguration(c -> c.locationConstraint("eu-central-1")));
}
}
@Test
@Order(2)
void prefixLimitsTheListToBucketsWhoseNameBeginsWithIt() {
try (S3Client s3 = client(Region.US_EAST_1)) {
ListBucketsResponse matched = s3.listBuckets(r -> r.prefix(PREFIX));
assertEquals(List.of(MATCHED_B, MATCHED_EU, MATCHED_M), names(matched));
assertEquals(PREFIX, matched.prefix(), "AWS echoes the prefix a request sent");
assertEquals(List.of(MATCHED_B, MATCHED_EU, MATCHED_M, UNMATCHED),
names(s3.listBuckets(r -> r.prefix("s3-"))));
ListBucketsResponse none = s3.listBuckets(r -> r.prefix("no-such-bucket-prefix"));
assertEquals(List.of(), names(none));
assertEquals("no-such-bucket-prefix", none.prefix());
assertNull(none.continuationToken());
}
}
@Test
@Order(3)
void bucketRegionLimitsTheListToBucketsOfThatRegion() {
// The us-east-1 buckets recorded no region, and ListBuckets reports them in the default one.
try (S3Client s3 = client(Region.US_EAST_1)) {
ListBucketsResponse us = s3.listBuckets(r -> r.bucketRegion("us-east-1"));
assertEquals(List.of(MATCHED_B, MATCHED_M, UNMATCHED), names(us));
assertNull(us.prefix(), "a request without a prefix has none to echo");
}
try (S3Client eu = client(Region.EU_CENTRAL_1)) {
assertEquals(List.of(MATCHED_EU), names(eu.listBuckets(r -> r.bucketRegion("eu-central-1"))));
}
}
@Test
@Order(4)
void filtersApplyBeforePagingSoATokenResumesTheFilteredList() {
try (S3Client s3 = client(Region.US_EAST_1)) {
List<String> seen = new ArrayList<>();
List<Boolean> tokens = new ArrayList<>();
String token = null;
do {
String next = token;
ListBucketsResponse page = s3.listBuckets(
r -> r.prefix(PREFIX).maxBuckets(1).continuationToken(next));
assertEquals(1, page.buckets().size());
seen.addAll(names(page));
token = page.continuationToken();
tokens.add(token != null);
} while (token != null && seen.size() < 10);
assertEquals(List.of(MATCHED_B, MATCHED_EU, MATCHED_M), seen);
assertEquals(List.of(true, true, false), tokens);
}
}
/**
* A prefix sent empty is still a prefix the caller sent: AWS echoes it back, and every name begins with
* an empty prefix, so the list is the whole one.
*/
@Test
@Order(5)
void anEmptyPrefixListsEveryBucketAndIsStillEchoed() {
List<String> listed = given().header("Authorization", AUTH).queryParam("prefix", "")
.when().get("/").then().statusCode(200)
.body(containsString("<Prefix></Prefix>"))
.extract().xmlPath().getList("ListAllMyBucketsResult.Buckets.Bucket.Name", String.class);
assertEquals(List.of(MATCHED_B, MATCHED_EU, MATCHED_M, UNMATCHED), listed);
}
/**
* A bucket stored before buckets recorded their Region has no Region of its own, and {@code bucket-region}
* puts it in the Region ListBuckets reports for it. Without that fallback the filter would drop it from
* every Region's list while the same request still named the default Region beside it.
*/
@Test
@Order(6)
void bucketRegionFilterCountsABucketWithoutAStoredRegionAsTheDefaultRegion() {
String legacyPrefix = "s3-filter-legacy-" + UUID.randomUUID().toString().substring(0, 8);
String absentRegion = legacyPrefix + "-null";
String blankRegion = legacyPrefix + "-blank";
service.createBucket(absentRegion, null);
service.createBucket(blankRegion, " ");
try (S3Client us = client(DEFAULT_ACCOUNT, Region.US_EAST_1);
S3Client eu = client(DEFAULT_ACCOUNT, Region.EU_CENTRAL_1)) {
assertEquals(List.of(blankRegion, absentRegion),
names(us.listBuckets(r -> r.prefix(legacyPrefix).bucketRegion("us-east-1"))));
assertEquals(List.of(), names(eu.listBuckets(r -> r.prefix(legacyPrefix).bucketRegion("eu-central-1"))));
} finally {
service.deleteBucket(absentRegion);
service.deleteBucket(blankRegion);
}
}
/**
* AWS answers both a region it does not publish and one that is not the region the request was signed for
* with {@code InvalidArgument}, rather than with the list that filter would have narrowed the account to.
*/
@Test
@Order(7)
void bucketRegionIsRefusedWhenItIsNoRegionOrNotTheEndpoints() {
try (S3Client s3 = client(Region.US_EAST_1)) {
assertRefused(s3, "not-a-region", "Argument value not-a-region is not a valid AWS Region");
assertRefused(s3, "ap-southeast-2",
"Requests with bucket-region specified must be made to the corresponding regional endpoint");
given().header("Authorization", AUTH).queryParam("bucket-region", "not-a-region")
.when().get("/").then().statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"))
.body(containsString("Argument value not-a-region is not a valid AWS Region"))
.body(not(containsString("<Name>" + MATCHED_B + "</Name>")));
}
try (S3Client eu = client(Region.EU_CENTRAL_1)) {
assertRefused(eu, "us-east-1",
"Requests with bucket-region specified must be made to the corresponding regional endpoint");
}
}
private static void assertRefused(S3Client s3, String bucketRegion, String message) {
S3Exception refused = assertThrows(S3Exception.class,
() -> s3.listBuckets(r -> r.bucketRegion(bucketRegion)));
assertEquals(400, refused.statusCode());
assertEquals("InvalidArgument", refused.awsErrorDetails().errorCode());
assertEquals(message, refused.awsErrorDetails().errorMessage());
}
/**
* A presigned request names its Region in {@code X-Amz-Credential} and sends no {@code Authorization}
* header, so that credential, not the header, says which endpoint it was signed for. A
* {@code bucket-region} agreeing with it lists, and one naming another Region is refused the way the
* header form is.
*/
@Test
@Order(8)
void presignedBucketRegionIsCheckedAgainstTheRegionItsCredentialNames() {
String presigned = "/?" + EnforcementFixtures.presignedQuery(ACCOUNT, "s3", "eu-central-1");
List<String> listed = given().urlEncodingEnabled(false)
.when().get(presigned + "&bucket-region=eu-central-1")
.then().statusCode(200)
.extract().xmlPath().getList("ListAllMyBucketsResult.Buckets.Bucket.Name", String.class);
assertEquals(List.of(MATCHED_EU), listed);
given().urlEncodingEnabled(false)
.when().get(presigned + "&bucket-region=us-east-1")
.then().statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"))
.body(containsString("Requests with bucket-region specified must be made to"
+ " the corresponding regional endpoint"))
.body(not(containsString("<Name>" + MATCHED_B + "</Name>")));
}
@Test
@Order(9)
void deleteBuckets() {
try (S3Client eu = client(Region.EU_CENTRAL_1)) {
eu.deleteBucket(r -> r.bucket(MATCHED_EU));
}
try (S3Client s3 = client(Region.US_EAST_1)) {
for (String bucket : List.of(MATCHED_B, MATCHED_M, UNMATCHED)) {
s3.deleteBucket(r -> r.bucket(bucket));
}
}
}
}
@@ -513,7 +513,7 @@ class S3ServiceTest {
bucketStore.put(name, new Bucket(name));
}
PaginatedResult<Bucket> page = service.listBuckets(null, null);
PaginatedResult<Bucket> page = service.listBuckets(null, null, null, null);
assertEquals(10001, page.items().size());
assertNull(page.nextToken());
@@ -252,9 +252,14 @@ public final class EnforcementFixtures {
* as {@link #auth}'s is.
*/
public static String presignedQuery(String accessKeyId, String service) {
return presignedQuery(accessKeyId, service, "us-east-1");
}
/** A presigned query scoped to the named Region, for a request signed for a regional endpoint. */
public static String presignedQuery(String accessKeyId, String service, String region) {
String amzDate = AMZ_DATE.format(Instant.now());
String credential = URLEncoder.encode(
accessKeyId + "/" + amzDate.substring(0, 8) + "/us-east-1/" + service + "/aws4_request",
accessKeyId + "/" + amzDate.substring(0, 8) + "/" + region + "/" + service + "/aws4_request",
StandardCharsets.UTF_8);
return "X-Amz-Algorithm=AWS4-HMAC-SHA256"
+ "&X-Amz-Credential=" + credential