fix(s3vectors): check create names by S3 Vectors' naming rules and answer its not-found messages (#8966)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-19 07:25:11 -04:00
1 parent 5f38401fdd
commit 3316d46df3
7 files changed
+190 -51

No files matched your search

+7
View File
@@ -65,6 +65,13 @@ bucket default, or `AES256` when the bucket has no setting. Missing creation tim
are set to the migration time and saved through the configured storage backend;
the original creation time is unavailable. Later reads and restarts retain that value.
Bucket and index names follow the same rules, as S3 Vectors applies them: 3 to 63
characters, labels of lowercase letters, numbers and hyphens that begin and end with a
letter or number, joined by single dots, not an IPv4 address, and without the prefix
`sthree-` or the suffixes `-s3alias` and `--x-s3`. `CreateVectorBucket` and
`CreateIndex` refuse any other name with a `ValidationException`, CloudFormation with a
`ValidationError`.
Index dimensions must be between 1 and 4096. Metadata configuration accepts up to
10 unique non-filterable keys, each a non-blank string of 1 to 63 characters.
Queries reject filters on these keys, including filters nested in logical expressions.
@@ -73,7 +73,7 @@ public class S3VectorsCfnProvisioner implements CfnResourceProvisioner {
snapshotTags(resource, bucket.getTags());
service.replaceBucketTags(name, tags, ctx.region());
} else {
String name = physicalName(props, "VectorBucketName", resource, ctx, false);
String name = physicalName(props, "VectorBucketName", resource, ctx);
rejectSameNameReplacement(ctx, updatesEntity, "bucket/" + name);
bucket = service.createVectorBucket(name, encryption(props, ctx, "AES256"), tags, ctx.region());
}
@@ -100,7 +100,7 @@ public class S3VectorsCfnProvisioner implements CfnResourceProvisioner {
snapshotTags(resource, index.getTags());
service.replaceIndexTags(bucketName, name, tags, ctx.region());
} else {
String name = physicalName(props, "IndexName", resource, ctx, true);
String name = physicalName(props, "IndexName", resource, ctx);
rejectSameNameReplacement(ctx, updatesEntity, "bucket/" + bucketName + "/index/" + name);
JsonNode metadataKeys = props.path("MetadataConfiguration").path("NonFilterableMetadataKeys");
List<String> keys = new ArrayList<>();
@@ -121,16 +121,16 @@ public class S3VectorsCfnProvisioner implements CfnResourceProvisioner {
}
private static String physicalName(JsonNode props, String property, StackResource resource,
ProvisionContext ctx, boolean index) {
ProvisionContext ctx) {
String name = ctx.resolveOptional(props, property);
if (name == null) {
return ctx.generatePhysicalName(resource.getLogicalId(), 63, true);
}
return validateName(name, property, index);
return validateName(name, property);
}
private static String validateName(String name, String property, boolean index) {
return S3VectorsService.validateName(name, property, index, "ValidationError");
private static String validateName(String name, String property) {
return S3VectorsService.validateName(name, property, "ValidationError");
}
private static void rejectSameNameReplacement(ProvisionContext ctx, boolean updatesEntity, String resourcePath) {
@@ -32,10 +32,23 @@ import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ApplicationScoped
public class S3VectorsService implements StoredResourceArns {
/**
* S3 Vectors' naming rules, the same for a bucket and an index (measured on AWS): labels of lowercase letters,
* numbers and hyphens that begin and end with a letter or number, joined by single dots; not an IPv4 address, and
* without S3's reserved prefix {@code sthree-} or suffixes {@code -s3alias} and {@code --x-s3}.
*/
private static final Pattern NAME =
Pattern.compile("[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*");
private static final Pattern IPV4_ADDRESS = Pattern.compile("[0-9]{1,3}(\\.[0-9]{1,3}){3}");
/** S3 Vectors' not-found messages (measured on AWS). */
private static final String NO_SUCH_BUCKET = "The specified vector bucket could not be found";
private static final String NO_SUCH_INDEX = "The specified index could not be found";
private static final Logger LOG = Logger.getLogger(S3VectorsService.class);
private static final ObjectReader STRICT_JSON_READER =
new ObjectMapper().reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
@@ -88,7 +101,7 @@ public class S3VectorsService implements StoredResourceArns {
public VectorBucket createVectorBucket(String bucketName, Object encryptionConfiguration,
Map<String, String> tags, String region) {
requireAddressableName(bucketName, "vectorBucketName", "Invalid vector bucket name");
requireValidName(bucketName, "vectorBucketName", "Invalid vector bucket name");
synchronized (lockFor(bucketName, region)) {
String key = buildStorageKey(region, bucketName);
if (store.get(key).isPresent()) {
@@ -107,7 +120,7 @@ public class S3VectorsService implements StoredResourceArns {
public VectorBucket getVectorBucket(String bucketName, String region) {
return findVectorBucket(bucketName, region).orElseThrow(() ->
new AwsException("NotFoundException", "The vector bucket " + bucketName + " does not exist.", 404));
new AwsException("NotFoundException", NO_SUCH_BUCKET, 404));
}
public List<VectorBucket> listVectorBuckets(String region) {
@@ -158,7 +171,7 @@ public class S3VectorsService implements StoredResourceArns {
synchronized (lockFor(bucketName, region)) {
String key = buildStorageKey(region, bucketName);
VectorBucket bucket = store.get(key).orElseThrow(() ->
new AwsException("NotFoundException", "The vector bucket " + bucketName + " does not exist.", 404));
new AwsException("NotFoundException", NO_SUCH_BUCKET, 404));
if (!bucket.getIndexes().isEmpty()) {
throw new AwsException("ConflictException", "The vector bucket " + bucketName + " is not empty.", 409);
@@ -263,21 +276,31 @@ public class S3VectorsService implements StoredResourceArns {
}
/**
* Refuses, on create, a name no call could reach what it made by: a blank one, which every call reads as left
* out, or one with a slash, which splits the ARN it would get. S3 Vectors refuses both, checking the length first
* (measured on AWS: an empty bucket name, and a bucket and an index name with a slash). Its other naming rules
* aren't checked here, so a name it would refuse otherwise is still taken as given.
* Refuses, on create, a name S3 Vectors refuses (measured on AWS): one of fewer than 3 or more than 63 characters
* with its length message, any other outside its naming rules with {@code invalidMessage}, "Invalid vector bucket
* name" or "Invalid index name". A name left out is taken as before.
*/
private static void requireAddressableName(String name, String member, String invalidMessage) {
if (name == null || !(name.isBlank() || name.indexOf('/') >= 0)) {
private static void requireValidName(String name, String member, String invalidMessage) {
if (name == null) {
return;
}
if (name.length() < 3 || name.length() > 63) {
if (!hasValidLength(name)) {
throw new AwsException("ValidationException", "1 validation error detected. Value with length "
+ name.length() + " at '/" + member
+ "' failed to satisfy constraint: Member must have length between 3 and 63, inclusive", 400);
}
throw new AwsException("ValidationException", invalidMessage, 400);
if (!followsNamingRules(name)) {
throw new AwsException("ValidationException", invalidMessage, 400);
}
}
private static boolean hasValidLength(String name) {
return name.length() >= 3 && name.length() <= 63;
}
private static boolean followsNamingRules(String name) {
return NAME.matcher(name).matches() && !IPV4_ADDRESS.matcher(name).matches() && !name.startsWith("sthree-")
&& !name.endsWith("-s3alias") && !name.endsWith("--x-s3");
}
/** A member's value, or null when the request left it out or empty. */
@@ -293,11 +316,11 @@ public class S3VectorsService implements StoredResourceArns {
"Specify exactly one of VectorBucketName or VectorBucketArn.", 400);
}
if (bucketArn == null) {
return new ResolvedBucket(validateName(bucketName, "VectorBucketName", false, errorCode),
return new ResolvedBucket(checkName(bucketName, "VectorBucketName", errorCode, false),
defaultRegion, null);
}
String[] parts = arnParts(bucketArn, false, errorCode);
validateName(parts[1], "VectorBucketArn bucket name", false, errorCode);
checkName(parts[1], "VectorBucketArn bucket name", errorCode, false);
return bucketOfArn(bucketArn, parts, partitionForRegion, errorCode);
}
@@ -315,9 +338,19 @@ public class S3VectorsService implements StoredResourceArns {
return new ResolvedBucket(parts[1], parsed.region(), parsed.accountId());
}
public static String validateName(String name, String property, boolean index, String errorCode) {
String pattern = index ? "[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]" : "[a-z0-9][a-z0-9-]{1,61}[a-z0-9]";
if (name == null || !name.matches(pattern)) {
/** A name a CloudFormation resource creates its bucket or index under, checked by the naming rules. */
public static String validateName(String name, String property, String errorCode) {
return checkName(name, property, errorCode, true);
}
/**
* A name of 3 to 63 characters made of dot-joined labels. One that names a new bucket or index must also follow the
* rest of the naming rules ({@code creates}); one that refers to a bucket need not, so a bucket an older Floci took
* under a reserved name, such as {@code sthree-logs}, stays reachable.
*/
private static String checkName(String name, String property, String errorCode, boolean creates) {
if (name == null || !hasValidLength(name)
|| !(creates ? followsNamingRules(name) : NAME.matcher(name).matches())) {
throw new AwsException(errorCode,
property + " must be a valid lowercase name of 3 to 63 characters.", 400);
}
@@ -367,7 +400,7 @@ public class S3VectorsService implements StoredResourceArns {
public VectorIndex createIndex(String bucketName, String indexName, int dimension, String dataType,
String distanceMetric, List<String> nonFilterableMetadataKeys,
Object encryptionConfiguration, Map<String, String> tags, String region) {
requireAddressableName(indexName, "indexName", "Invalid index name");
requireValidName(indexName, "indexName", "Invalid index name");
if (dimension < 1 || dimension > 4096) {
throw new AwsException("ValidationException", "Dimension must be between 1 and 4096.", 400);
}
@@ -411,8 +444,7 @@ public class S3VectorsService implements StoredResourceArns {
private VectorIndex getIndex(VectorBucket bucket, String indexName) {
VectorIndex index = bucket.getIndexes().get(indexName);
if (index == null) {
throw new AwsException("NotFoundException",
"The index " + indexName + " does not exist in bucket " + bucket.getVectorBucketName() + ".", 404);
throw new AwsException("NotFoundException", NO_SUCH_INDEX, 404);
}
return index;
}
@@ -428,7 +460,7 @@ public class S3VectorsService implements StoredResourceArns {
synchronized (lockFor(bucketName, region)) {
VectorBucket bucket = getVectorBucket(bucketName, region);
if (!bucket.getIndexes().containsKey(indexName)) {
throw new AwsException("NotFoundException", "The index " + indexName + " does not exist.", 404);
throw new AwsException("NotFoundException", NO_SUCH_INDEX, 404);
}
bucket.getIndexes().remove(indexName);
store.put(buildStorageKey(region, bucketName), bucket);
@@ -220,7 +220,7 @@ class S3VectorsCfnProvisionerTest {
}
@ParameterizedTest
@ValueSource(strings = {"", " ", "\t", "Uppercase", "under_score", "dot.name", "ab", "-bucket", "bucket-",
@ValueSource(strings = {"", " ", "\t", "Uppercase", "under_score", "dot..name", "ab", "-bucket", "bucket-",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl"})
void invalidBucketNamesAreRejectedForBothSelectors(String name) throws Exception {
for (String selector : List.of("VectorBucketName", "VectorBucketArn")) {
@@ -234,6 +234,28 @@ class S3VectorsCfnProvisionerTest {
verifyNoInteractions(service);
}
/**
* An index may name, by name or by ARN, a bucket an older Floci took under a name the create rules now reserve;
* a bucket the stack creates under such a name is refused.
*/
@Test
void anIndexReachesABucketStoredUnderAReservedName() throws Exception {
stubCreates();
for (String selector : List.of("VectorBucketName", "VectorBucketArn")) {
ObjectNode props = indexProps();
props.remove("VectorBucketArn");
props.put(selector, "VectorBucketName".equals(selector) ? "sthree-logs"
: BUCKET_ARN.replace("my-bucket", "sthree-logs"));
provisioner.provision(resource("Index"), props, context(null));
}
verify(service, times(2)).createIndex(eq("sthree-logs"), eq("my-index"), eq(3), eq("float32"), eq("cosine"),
anyList(), any(), anyMap(), eq(REGION));
AwsException refused = assertThrows(AwsException.class, () -> provisioner.provision(resource("VectorBucket"),
props("{\"VectorBucketName\":\"sthree-logs\"}"), context(null)));
assertEquals("ValidationError", refused.getErrorCode());
}
@Test
void blankExplicitResourceNamesAreRejected() throws Exception {
for (String name : List.of("", " ")) {
@@ -116,29 +116,52 @@ class S3VectorsArnAddressingIntegrationTest {
}
/**
* CreateVectorBucket and CreateIndex take a name without checking it, so what they make stays reachable by that
* name and by the ARN they gave it.
* CreateVectorBucket and CreateIndex refuse a name outside S3 Vectors' naming rules, which are the same for both,
* with "Invalid vector bucket name" or "Invalid index name", as it does (measured on AWS). The index name is
* checked before its bucket is looked for.
*/
@ParameterizedTest
@ValueSource(strings = {"Arn-name", "arn_name", "-arn-name", "arn-name-", ".arn-name", "arn-name.", "arn..name",
"arn.-name", "arn-.name", "192.168.5.4", "sthree-arn-name", "arn-name-s3alias", "arn-name--x-s3"})
void aNameOutsideTheNamingRulesIsRefusedOnCreate(String name) {
refused(post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + name + "\"}"), "Invalid vector bucket name");
refused(post("/CreateIndex", index(bucketName(), name)), "Invalid index name");
post("/ListVectorBuckets", "{}").statusCode(200).body("vectorBuckets.vectorBucketName", not(hasItem(name)));
}
/** A name of fewer than 3 or more than 63 characters gets the length message first (measured on AWS). */
@ParameterizedTest
@ValueSource(ints = {2, 64})
void aNameOfAnotherLengthIsRefusedOnCreate(int length) {
String name = "a".repeat(length);
String limit = " failed to satisfy constraint: Member must have length between 3 and 63, inclusive";
refused(post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + name + "\"}"),
"1 validation error detected. Value with length " + length + " at '/vectorBucketName'" + limit);
refused(post("/CreateIndex", index(bucketName(), name)),
"1 validation error detected. Value with length " + length + " at '/indexName'" + limit);
}
/**
* Names the rules take, though their documentation lists only letters, numbers and hyphens for a bucket: dots
* between labels, hyphens running together, labels of numbers only, and S3's reserved prefix {@code xn--}
* (measured on AWS).
*/
@Test
void aBucketAndAnIndexAreReachedByTheNamesAndArnsTheyWereGiven() {
String bucket = "Arn_" + UUID.randomUUID().toString().substring(0, 8);
String arn = post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200)
.extract().path("vectorBucketArn");
void aNameOfDottedLabelsIsTakenOnCreate() {
String id = UUID.randomUUID().toString().substring(0, 8);
List<String> names = List.of("arn." + id + ".v2", "ar--n-" + id, "123." + id, "xn--arn-" + id);
try {
String index = post("/CreateIndex", "{\"vectorBucketName\":\"" + bucket + "\",\"indexName\":\"My_Index\","
+ "\"dataType\":\"float32\",\"dimension\":2,\"distanceMetric\":\"cosine\"}").statusCode(200)
.extract().path("indexArn");
post("/GetVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200)
.body("vectorBucket.vectorBucketName", equalTo(bucket));
post("/ListIndexes", byBucketArn(arn)).statusCode(200)
.body("indexes.indexName", equalTo(List.of("My_Index")));
post("/GetIndex", byIndexArn(index)).statusCode(200)
.body("index.indexName", equalTo("My_Index"));
post("/DeleteIndex", byIndexArn(index)).statusCode(200);
for (String name : names) {
post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + name + "\"}").statusCode(200);
}
post("/CreateIndex", index(names.getFirst(), "1.2.3")).statusCode(200);
post("/ListIndexes", "{\"vectorBucketName\":\"" + names.getFirst() + "\"}").statusCode(200)
.body("indexes.indexName", equalTo(List.of("1.2.3")));
} finally {
post("/DeleteIndex", "{\"vectorBucketName\":\"" + bucket + "\",\"indexName\":\"My_Index\"}");
post("/DeleteVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200);
post("/DeleteIndex", "{\"vectorBucketName\":\"" + names.getFirst() + "\",\"indexName\":\"1.2.3\"}");
for (String name : names) {
post("/DeleteVectorBucket", "{\"vectorBucketName\":\"" + name + "\"}");
}
}
}
@@ -166,7 +189,7 @@ class S3VectorsArnAddressingIntegrationTest {
/**
* A name no call could reach the bucket by, blank or with a slash, is refused on create, as S3 Vectors refuses it
* (measured on AWS), the length first. A bucket of a name AWS refuses otherwise is still made: see above.
* (measured on AWS), the length first.
*/
@Test
void aBucketNameNoCallCouldReachIsRefusedOnCreate() {
@@ -452,7 +452,7 @@ class S3VectorsIntegrationTest {
.then()
.statusCode(200);
// Verify index is gone
// Verify index is gone, with S3 Vectors' message (measured on AWS)
given()
.contentType(JSON_CONTENT_TYPE)
.body("""
@@ -464,7 +464,9 @@ class S3VectorsIntegrationTest {
.when()
.post("/GetIndex")
.then()
.statusCode(404);
.statusCode(404)
.body("__type", equalTo("NotFoundException"))
.body("message", equalTo("The specified index could not be found"));
}
@Test
@@ -482,7 +484,7 @@ class S3VectorsIntegrationTest {
.then()
.statusCode(200);
// Verify bucket is gone
// Verify bucket is gone, with S3 Vectors' message (measured on AWS)
given()
.contentType(JSON_CONTENT_TYPE)
.body("""
@@ -493,7 +495,9 @@ class S3VectorsIntegrationTest {
.when()
.post("/GetVectorBucket")
.then()
.statusCode(404);
.statusCode(404)
.body("__type", equalTo("NotFoundException"))
.body("message", equalTo("The specified vector bucket could not be found"));
}
// Self-contained: each test below creates its own bucket/index so it doesn't depend on the
@@ -86,6 +86,57 @@ class S3VectorsServiceTest {
assertEquals(Set.of(REGION + "::legacy"), raw.keys());
}
/**
* A bucket and an index an older Floci stored under names S3 Vectors' rules refuse, which the create calls now
* refuse too, stay reachable by those names and by their ARNs in the calls that read a name as given.
*/
@Test
void aBucketAndAnIndexStoredUnderNamesTheRulesRefuseStayReachable() {
String bucketArn = "arn:aws:s3vectors:us-east-1:000000000000:bucket/Legacy_Bucket";
VectorBucket legacy = new VectorBucket("Legacy_Bucket", bucketArn, Map.of("sseType", "AES256"));
legacy.setCreationTime(CREATION_TIME);
legacy.getIndexes().put("My_Index",
new VectorIndex("My_Index", bucketArn + "/index/My_Index", "Legacy_Bucket", 2, "float32", "cosine"));
S3VectorsService upgraded = storing(legacy);
assertEquals(new S3VectorsService.ResolvedBucket("Legacy_Bucket", REGION, null),
upgraded.bucketTarget("Legacy_Bucket", null, REGION));
assertEquals(new S3VectorsService.ResolvedBucket("Legacy_Bucket", REGION, "000000000000"),
upgraded.bucketTarget(null, bucketArn, REGION));
assertEquals(new S3VectorsService.ResolvedIndex("Legacy_Bucket", "My_Index", REGION),
upgraded.resolveIndexTarget(null, null, bucketArn + "/index/My_Index", REGION));
assertEquals("My_Index", upgraded.getIndex("Legacy_Bucket", "My_Index", REGION).getIndexName());
assertEquals(List.of("My_Index"), upgraded.listIndexes("Legacy_Bucket", REGION).stream()
.map(VectorIndex::getIndexName).toList());
}
/**
* A bucket an older Floci took under a name the create rules now reserve keeps its policy calls, by name and by
* ARN: they check only that the bucket's name is one of dot-joined labels, as before.
*/
@Test
void aBucketStoredUnderAReservedNameKeepsItsPolicyCalls() {
String bucketArn = "arn:aws:s3vectors:us-east-1:000000000000:bucket/sthree-logs";
VectorBucket legacy = new VectorBucket("sthree-logs", bucketArn, Map.of("sseType", "AES256"));
legacy.setCreationTime(CREATION_TIME);
S3VectorsService upgraded = storing(legacy);
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Read\",\"Effect\":\"Allow\"}]}";
upgraded.putVectorBucketPolicy("sthree-logs", null, policy, REGION);
assertEquals(policy, upgraded.getVectorBucketPolicy(null, bucketArn, REGION));
upgraded.deleteVectorBucketPolicy(null, bucketArn, REGION);
assertEquals("NotFoundException", assertThrows(AwsException.class,
() -> upgraded.getVectorBucketPolicy("sthree-logs", null, REGION)).getErrorCode());
}
/** A service over a store holding {@code bucket}, as an older Floci stored it. */
private static S3VectorsService storing(VectorBucket bucket) {
AccountAwareStorageBackend<VectorBucket> stored = AccountAwareStorageBackend.inMemory("000000000000");
stored.put(REGION + "::" + bucket.getVectorBucketName(), bucket);
return new S3VectorsService(new InMemoryStorageFactory("000000000000").withStore("s3vectors.json", stored),
new RegionResolver(REGION, "000000000000"), Clock.fixed(CREATION_TIME, ZoneOffset.UTC));
}
@Test
void persistsCreationTimesConfigurationAndCreationTags() throws Exception {
Map<String, String> encryption = Map.of("sseType", "aws:kms", "kmsKeyArn", "key");