diff --git a/docs/services/s3vectors.md b/docs/services/s3vectors.md index 7eae7cb095..26bc9f87fd 100644 --- a/docs/services/s3vectors.md +++ b/docs/services/s3vectors.md @@ -78,6 +78,11 @@ stores it with the bucket; `GetVectorBucketPolicy` returns `NotFoundException` w policy is attached. Bucket policies are stored and returned, but Floci does not evaluate or enforce them on requests. +A bucket ARN or an index ARN must be of the request's partition, Region and account, as S3 +Vectors requires: one of another partition or Region is refused with a `ValidationException` +("Unexpected value for ARN partition component" or "Unexpected value for ARN region +component"), and one of another account with an `AccessDeniedException`. + Encryption settings are stored and returned; Floci does not perform KMS encryption. Standalone S3 Vectors tagging APIs are not implemented. diff --git a/src/main/java/io/floci/aws/services/s3vectors/S3VectorsController.java b/src/main/java/io/floci/aws/services/s3vectors/S3VectorsController.java index e6f43e8a0e..a9f365640f 100644 --- a/src/main/java/io/floci/aws/services/s3vectors/S3VectorsController.java +++ b/src/main/java/io/floci/aws/services/s3vectors/S3VectorsController.java @@ -313,8 +313,9 @@ public class S3VectorsController { @POST @Path("/GetVectorBucket") public Response getVectorBucket(@Context HttpHeaders headers, GetVectorBucketRequest request) { - String region = regionResolver.resolveRegion(headers); - VectorBucket bucket = service.getVectorBucket(request.vectorBucketName(), region); + S3VectorsService.ResolvedBucket target = bucketOf(headers, request.vectorBucketName(), + request.vectorBucketArn()); + VectorBucket bucket = service.getVectorBucket(target.bucketName(), target.region()); VectorBucketRepresentation rep = new VectorBucketRepresentation(bucket.getVectorBucketName(), bucket.getVectorBucketArn(), EpochSeconds.fromInstant(bucket.getCreationTime()), bucket.getEncryptionConfiguration()); return Response.ok(new GetVectorBucketResponse(rep)).build(); @@ -335,8 +336,9 @@ public class S3VectorsController { @POST @Path("/DeleteVectorBucket") public Response deleteVectorBucket(@Context HttpHeaders headers, DeleteVectorBucketRequest request) { - String region = regionResolver.resolveRegion(headers); - service.deleteVectorBucket(request.vectorBucketName(), region); + S3VectorsService.ResolvedBucket target = bucketOf(headers, request.vectorBucketName(), + request.vectorBucketArn()); + service.deleteVectorBucket(target.bucketName(), target.region()); return Response.ok(objectMapper.createObjectNode()).build(); } @@ -380,9 +382,10 @@ public class S3VectorsController { @POST @Path("/CreateIndex") public Response createIndex(@Context HttpHeaders headers, CreateIndexRequest request) { - String region = regionResolver.resolveRegion(headers); + S3VectorsService.ResolvedBucket target = bucketOf(headers, request.vectorBucketName(), + request.vectorBucketArn()); VectorIndex index = service.createIndex( - request.vectorBucketName(), + target.bucketName(), request.indexName(), request.dimension(), request.dataType() != null ? request.dataType() : "float32", @@ -391,7 +394,7 @@ public class S3VectorsController { ? request.metadataConfiguration().nonFilterableMetadataKeys() : List.of(), request.encryptionConfiguration(), request.tags() != null ? request.tags() : Map.of(), - region + target.region() ); return Response.ok(new CreateIndexResponse(index.getIndexArn())).build(); } @@ -399,8 +402,9 @@ public class S3VectorsController { @POST @Path("/GetIndex") public Response getIndex(@Context HttpHeaders headers, GetIndexRequest request) { - String region = regionResolver.resolveRegion(headers); - VectorIndex index = service.getIndex(request.vectorBucketName(), request.indexName(), region); + S3VectorsService.ResolvedIndex target = indexOf(headers, request.vectorBucketName(), request.indexName(), + request.indexArn()); + VectorIndex index = service.getIndex(target.bucketName(), target.indexName(), target.region()); IndexRepresentation rep = new IndexRepresentation( EpochSeconds.fromInstant(index.getCreationTime()), index.getVectorBucketName(), @@ -419,8 +423,9 @@ public class S3VectorsController { @POST @Path("/ListIndexes") public Response listIndexes(@Context HttpHeaders headers, ListIndexesRequest request) { - String region = regionResolver.resolveRegion(headers); - List indexes = service.listIndexes(request.vectorBucketName(), region); + S3VectorsService.ResolvedBucket target = bucketOf(headers, request.vectorBucketName(), + request.vectorBucketArn()); + List indexes = service.listIndexes(target.bucketName(), target.region()); List reps = indexes.stream() .map(i -> new IndexSummary( EpochSeconds.fromInstant(i.getCreationTime()), @@ -435,15 +440,17 @@ public class S3VectorsController { @POST @Path("/DeleteIndex") public Response deleteIndex(@Context HttpHeaders headers, DeleteIndexRequest request) { - String region = regionResolver.resolveRegion(headers); - service.deleteIndex(request.vectorBucketName(), request.indexName(), region); + S3VectorsService.ResolvedIndex target = indexOf(headers, request.vectorBucketName(), request.indexName(), + request.indexArn()); + service.deleteIndex(target.bucketName(), target.indexName(), target.region()); return Response.ok(objectMapper.createObjectNode()).build(); } @POST @Path("/PutVectors") public Response putVectors(@Context HttpHeaders headers, PutVectorsRequest request) { - String region = regionResolver.resolveRegion(headers); + S3VectorsService.ResolvedIndex target = indexOf(headers, request.vectorBucketName(), request.indexName(), + request.indexArn()); List vectors = new ArrayList<>(); if (request.vectors() != null) { for (VectorRepresentation vRep : request.vectors()) { @@ -454,15 +461,17 @@ public class S3VectorsController { vectors.add(new VectorData(vRep.key(), floatList, metadata)); } } - service.putVectors(request.vectorBucketName(), request.indexName(), vectors, region); + service.putVectors(target.bucketName(), target.indexName(), vectors, target.region()); return Response.ok(objectMapper.createObjectNode()).build(); } @POST @Path("/GetVectors") public Response getVectors(@Context HttpHeaders headers, GetVectorsRequest request) { - String region = regionResolver.resolveRegion(headers); - List vectors = service.getVectors(request.vectorBucketName(), request.indexName(), request.keys(), region); + S3VectorsService.ResolvedIndex target = indexOf(headers, request.vectorBucketName(), request.indexName(), + request.indexArn()); + List vectors = service.getVectors(target.bucketName(), target.indexName(), request.keys(), + target.region()); boolean returnData = request.returnData() != null && request.returnData(); boolean returnMetadata = request.returnMetadata() != null && request.returnMetadata(); @@ -503,25 +512,27 @@ public class S3VectorsController { @POST @Path("/DeleteVectors") public Response deleteVectors(@Context HttpHeaders headers, DeleteVectorsRequest request) { - String region = regionResolver.resolveRegion(headers); - service.deleteVectors(request.vectorBucketName(), request.indexName(), request.keys(), region); + S3VectorsService.ResolvedIndex target = indexOf(headers, request.vectorBucketName(), request.indexName(), + request.indexArn()); + service.deleteVectors(target.bucketName(), target.indexName(), request.keys(), target.region()); return Response.ok(objectMapper.createObjectNode()).build(); } @POST @Path("/QueryVectors") public Response queryVectors(@Context HttpHeaders headers, QueryVectorsRequest request) { - String region = regionResolver.resolveRegion(headers); List queryVector = (request.queryVector() != null && request.queryVector().float32() != null) ? request.queryVector().float32() : List.of(); + S3VectorsService.ResolvedIndex target = indexOf(headers, request.vectorBucketName(), request.indexName(), + request.indexArn()); List results = service.queryVectors( - request.vectorBucketName(), - request.indexName(), + target.bucketName(), + target.indexName(), queryVector, request.filter(), request.topK() > 0 ? request.topK() : 10, - region + target.region() ); boolean returnMetadata = request.returnMetadata() != null && request.returnMetadata(); @@ -535,7 +546,18 @@ public class S3VectorsController { }) .toList(); - VectorIndex index = service.getIndex(request.vectorBucketName(), request.indexName(), region); + VectorIndex index = service.getIndex(target.bucketName(), target.indexName(), target.region()); return Response.ok(new QueryVectorsResponse(reps, index.getDistanceMetric())).build(); } + + /** The vector bucket a request names by its name or by its ARN. */ + private S3VectorsService.ResolvedBucket bucketOf(HttpHeaders headers, String bucketName, String bucketArn) { + return service.bucketTarget(bucketName, bucketArn, regionResolver.resolveRegion(headers)); + } + + /** The index a request names by its bucket's name and its own, or by its ARN. */ + private S3VectorsService.ResolvedIndex indexOf(HttpHeaders headers, String bucketName, String indexName, + String indexArn) { + return service.resolveIndexTarget(bucketName, indexName, indexArn, regionResolver.resolveRegion(headers)); + } } diff --git a/src/main/java/io/floci/aws/services/s3vectors/S3VectorsService.java b/src/main/java/io/floci/aws/services/s3vectors/S3VectorsService.java index e239ed7958..52ec71022b 100644 --- a/src/main/java/io/floci/aws/services/s3vectors/S3VectorsService.java +++ b/src/main/java/io/floci/aws/services/s3vectors/S3VectorsService.java @@ -82,6 +82,7 @@ public class S3VectorsService { public VectorBucket createVectorBucket(String bucketName, Object encryptionConfiguration, Map tags, String region) { + requireAddressableName(bucketName, "vectorBucketName", "Invalid vector bucket name"); synchronized (lockFor(bucketName, region)) { String key = buildStorageKey(region, bucketName); if (store.get(key).isPresent()) { @@ -162,7 +163,7 @@ public class S3VectorsService { } public void putVectorBucketPolicy(String bucketName, String bucketArn, String policy, String region) { - ResolvedBucket target = resolveBucket(bucketName, bucketArn, region); + ResolvedBucket target = resolvePolicyBucket(bucketName, bucketArn, region); validatePolicyDocument(policy); synchronized (lockFor(target.bucketName(), target.region())) { VectorBucket bucket = getVectorBucket(target.bucketName(), target.region()); @@ -173,7 +174,7 @@ public class S3VectorsService { } public String getVectorBucketPolicy(String bucketName, String bucketArn, String region) { - ResolvedBucket target = resolveBucket(bucketName, bucketArn, region); + ResolvedBucket target = resolvePolicyBucket(bucketName, bucketArn, region); synchronized (lockFor(target.bucketName(), target.region())) { VectorBucket bucket = getVectorBucket(target.bucketName(), target.region()); String policy = bucket.getPolicy(); @@ -186,7 +187,7 @@ public class S3VectorsService { } public void deleteVectorBucketPolicy(String bucketName, String bucketArn, String region) { - ResolvedBucket target = resolveBucket(bucketName, bucketArn, region); + ResolvedBucket target = resolvePolicyBucket(bucketName, bucketArn, region); synchronized (lockFor(target.bucketName(), target.region())) { VectorBucket bucket = getVectorBucket(target.bucketName(), target.region()); if (bucket.getPolicy() != null) { @@ -197,16 +198,87 @@ public class S3VectorsService { } } - private ResolvedBucket resolveBucket(String bucketName, String bucketArn, String region) { - ResolvedBucket resolved = resolveBucket(bucketName, bucketArn, region, - regionResolver::partitionForRegion, "ValidationException"); - if (resolved.accountId() != null && !store.accountId().equals(resolved.accountId())) { - throw new AwsException("NotFoundException", - "The vector bucket " + resolved.bucketName() + " does not exist.", 404); + /** + * As {@link #bucketTarget}, for the policy calls, which have always checked the bucket's name, first: by name or + * in its ARN. + */ + private ResolvedBucket resolvePolicyBucket(String bucketName, String bucketArn, String region) { + String name = given(bucketName); + String arn = given(bucketArn); + requireBucketChoice(name, arn); + return inRequestScope(resolveBucket(name, arn, region, regionResolver::partitionForRegion, "ValidationException"), + region); + } + + /** + * The vector bucket a request names, by {@code vectorBucketName} or by {@code vectorBucketArn}, refused as S3 + * Vectors refuses a request that gives neither or both. The name is read as given, as CreateVectorBucket takes + * it, so a bucket it made stays reachable by its name and by the ARN it was given. An ARN outside the request's + * partition, Region or account is refused ({@link #inRequestScope}). + */ + public ResolvedBucket bucketTarget(String bucketName, String bucketArn, String region) { + String name = given(bucketName); + String arn = given(bucketArn); + requireBucketChoice(name, arn); + if (arn == null) { + return new ResolvedBucket(name, region, null); + } + return inRequestScope(bucketOfArn(arn, arnParts(arn, false, "ValidationException"), + regionResolver::partitionForRegion, "ValidationException"), region); + } + + /** S3 Vectors' refusal of a request that names a bucket by neither its name nor its ARN, or by both. */ + private static void requireBucketChoice(String name, String arn) { + if ((name == null) == (arn == null)) { + throw new AwsException("ValidationException", + "Must specify either vectorBucketName or vectorBucketArn but not both", 400); + } + } + + /** + * Refuses, as S3 Vectors does (measured on AWS), a bucket an ARN names outside the request's partition, Region or + * account: another partition or Region with a ValidationException, the partition first, and another account with + * an AccessDeniedException that carries no message. A bucket named by its name is the request's own. + */ + private ResolvedBucket inRequestScope(ResolvedBucket resolved, String region) { + if (resolved.accountId() == null) { + return resolved; + } + if (!regionResolver.partitionForRegion(resolved.region()).equals(regionResolver.partitionForRegion(region))) { + throw new AwsException("ValidationException", "Unexpected value for ARN partition component", 400); + } + if (!region.equals(resolved.region())) { + throw new AwsException("ValidationException", "Unexpected value for ARN region component", 400); + } + if (!store.accountId().equals(resolved.accountId())) { + throw new AwsException("AccessDeniedException", "", 403); } return resolved; } + /** + * 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. + */ + private static void requireAddressableName(String name, String member, String invalidMessage) { + if (name == null || !(name.isBlank() || name.indexOf('/') >= 0)) { + return; + } + if (name.length() < 3 || name.length() > 63) { + 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); + } + + /** A member's value, or null when the request left it out or empty. */ + private static String given(String member) { + return member == null || member.isBlank() ? null : member; + } + public static ResolvedBucket resolveBucket(String bucketName, String bucketArn, String defaultRegion, Function partitionForRegion, String errorCode) { @@ -219,13 +291,22 @@ public class S3VectorsService { defaultRegion, null); } String[] parts = arnParts(bucketArn, false, errorCode); - AwsArnUtils.Arn parsed = AwsArnUtils.parse(bucketArn); - String name = validateName(parts[1], "VectorBucketArn bucket name", false, errorCode); + validateName(parts[1], "VectorBucketArn bucket name", false, errorCode); + return bucketOfArn(bucketArn, parts, partitionForRegion, errorCode); + } + + /** + * The bucket an S3 Vectors ARN names, a bucket's or an index's, given its {@link #arnParts}: the ARN must name a + * Region and an account, in the Region's partition. + */ + private static ResolvedBucket bucketOfArn(String arn, String[] parts, Function partitionForRegion, + String errorCode) { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); if (parsed.region().isEmpty() || parsed.accountId().isEmpty() || !partitionForRegion.apply(parsed.region()).equals(parsed.partition())) { - throw new AwsException(errorCode, "Invalid S3 Vectors ARN: " + bucketArn, 400); + throw new AwsException(errorCode, "Invalid S3 Vectors ARN: " + arn, 400); } - return new ResolvedBucket(name, parsed.region(), parsed.accountId()); + return new ResolvedBucket(parts[1], parsed.region(), parsed.accountId()); } public static String validateName(String name, String property, boolean index, String errorCode) { @@ -268,6 +349,9 @@ public class S3VectorsService { public record ResolvedBucket(String bucketName, String region, String accountId) {} + /** An index a request names: its bucket's name, its own name and the Region it is in. */ + public record ResolvedIndex(String bucketName, String indexName, String region) {} + public VectorIndex createIndex(String bucketName, String indexName, int dimension, String dataType, String distanceMetric, List nonFilterableMetadataKeys, String region) { return createIndex(bucketName, indexName, dimension, dataType, distanceMetric, @@ -277,6 +361,7 @@ public class S3VectorsService { public VectorIndex createIndex(String bucketName, String indexName, int dimension, String dataType, String distanceMetric, List nonFilterableMetadataKeys, Object encryptionConfiguration, Map tags, String region) { + requireAddressableName(indexName, "indexName", "Invalid index name"); if (dimension < 1 || dimension > 4096) { throw new AwsException("ValidationException", "Dimension must be between 1 and 4096.", 400); } @@ -437,18 +522,32 @@ public class S3VectorsService { * ListVectors' "vectorBucketName + indexName, or indexArn alone" input contract. */ private VectorIndex resolveIndex(String bucketName, String indexName, String indexArn, String region) { - if (indexName != null && !indexName.isBlank()) { - return getIndex(bucketName, indexName, region); + ResolvedIndex target = resolveIndexTarget(bucketName, indexName, indexArn, region); + return getIndex(target.bucketName(), target.indexName(), target.region()); + } + + /** + * The index a request names, by its {@code vectorBucketName} and {@code indexName} or by its {@code indexArn}, + * refused as S3 Vectors refuses a request that gives neither or mixes them. The ARN's bucket is checked as a bucket + * ARN is ({@link #inRequestScope}). + */ + public ResolvedIndex resolveIndexTarget(String bucketName, String indexName, String indexArn, String region) { + String bucket = given(bucketName); + String index = given(indexName); + String arn = given(indexArn); + boolean byArn = arn != null && bucket == null && index == null; + boolean byName = arn == null && bucket != null && index != null; + if (!byArn && !byName) { + throw new AwsException("ValidationException", + "Must specify either indexArn or both vectorBucketName and indexName", 400); } - if (indexArn == null || indexArn.isBlank()) { - throw new AwsException("ValidationException", "Either indexName or indexArn is required.", 400); + if (byName) { + return new ResolvedIndex(bucket, index, region); } - String[] parts = arnParts(indexArn, true, "ValidationException"); - AwsArnUtils.Arn parsed = AwsArnUtils.parse(indexArn); - // The ARN carries its own region — an index in one region must resolve there regardless - // of which region the ListVectors request itself was signed for. - String arnRegion = parsed.region().isEmpty() ? region : parsed.region(); - return getIndex(parts[1], parts[3], arnRegion); + String[] parts = arnParts(arn, true, "ValidationException"); + ResolvedBucket owner = inRequestScope(bucketOfArn(arn, parts, regionResolver::partitionForRegion, + "ValidationException"), region); + return new ResolvedIndex(owner.bucketName(), parts[3], owner.region()); } /** diff --git a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsArnAddressingIntegrationTest.java b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsArnAddressingIntegrationTest.java new file mode 100644 index 0000000000..0ee8c54357 --- /dev/null +++ b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsArnAddressingIntegrationTest.java @@ -0,0 +1,247 @@ +package io.floci.aws.services.s3vectors; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; + +/** + * Every S3 Vectors call that names a vector bucket takes its {@code vectorBucketName} or its {@code vectorBucketArn}, + * and every call that names an index takes its bucket's name and its {@code indexName}, or its {@code indexArn}, as + * AWS does. A request that gives neither, or mixes them, is refused with the message AWS gives (measured on AWS). + */ +@QuarkusTest +class S3VectorsArnAddressingIntegrationTest { + + private static final String BUCKET_CHOICE = "Must specify either vectorBucketName or vectorBucketArn but not both"; + private static final String INDEX_CHOICE = "Must specify either indexArn or both vectorBucketName and indexName"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aVectorBucketIsReadListedAndDeletedByItsArn() { + String bucket = bucketName(); + String arn = post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200) + .extract().path("vectorBucketArn"); + + post("/GetVectorBucket", byBucketArn(arn)).statusCode(200) + .body("vectorBucket.vectorBucketName", equalTo(bucket)) + .body("vectorBucket.vectorBucketArn", equalTo(arn)); + post("/CreateIndex", "{\"vectorBucketArn\":\"" + arn + "\",\"indexName\":\"events\",\"dataType\":\"float32\"," + + "\"dimension\":2,\"distanceMetric\":\"cosine\"}").statusCode(200) + .body("indexArn", equalTo(arn + "/index/events")); + post("/ListIndexes", byBucketArn(arn)).statusCode(200) + .body("indexes.indexName", equalTo(List.of("events"))); + post("/DeleteIndex", "{\"indexArn\":\"" + arn + "/index/events\"}").statusCode(200); + post("/DeleteVectorBucket", byBucketArn(arn)).statusCode(200); + + post("/GetVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(404) + .body("__type", equalTo("NotFoundException")); + } + + @Test + void anIndexIsReadAndItsVectorsWrittenQueriedAndDeletedByItsArn() { + String bucket = bucketName(); + post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200); + String index = post("/CreateIndex", "{\"vectorBucketName\":\"" + bucket + "\",\"indexName\":\"events\"," + + "\"dataType\":\"float32\",\"dimension\":2,\"distanceMetric\":\"cosine\"}").statusCode(200) + .extract().path("indexArn"); + try { + post("/GetIndex", byIndexArn(index)).statusCode(200) + .body("index.indexName", equalTo("events")) + .body("index.vectorBucketName", equalTo(bucket)); + post("/PutVectors", "{\"indexArn\":\"" + index + "\",\"vectors\":[{\"key\":\"v1\"," + + "\"data\":{\"float32\":[1.0,0.0]}}]}").statusCode(200); + post("/GetVectors", "{\"indexArn\":\"" + index + "\",\"keys\":[\"v1\"]}").statusCode(200) + .body("vectors.key", equalTo(List.of("v1"))); + post("/QueryVectors", "{\"indexArn\":\"" + index + "\",\"topK\":1," + + "\"queryVector\":{\"float32\":[1.0,0.0]}}").statusCode(200) + .body("vectors", hasSize(1)) + .body("distanceMetric", equalTo("cosine")); + post("/DeleteVectors", "{\"indexArn\":\"" + index + "\",\"keys\":[\"v1\"]}").statusCode(200); + post("/GetVectors", "{\"indexArn\":\"" + index + "\",\"keys\":[\"v1\"]}").statusCode(200) + .body("vectors", hasSize(0)); + } finally { + post("/DeleteIndex", "{\"vectorBucketName\":\"" + bucket + "\",\"indexName\":\"events\"}").statusCode(200); + post("/DeleteVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200); + } + } + + @ParameterizedTest + @ValueSource(strings = {"/GetVectorBucket", "/DeleteVectorBucket", "/ListIndexes", "/CreateIndex"}) + void aBucketCallGivingNeitherOrBothIsRefused(String path) { + String bucket = bucketName(); + String arn = "arn:aws:s3vectors:us-east-1:000000000000:bucket/" + bucket; + + refused(post(path, "{}"), BUCKET_CHOICE); + refused(post(path, "{\"vectorBucketName\":\"" + bucket + "\",\"vectorBucketArn\":\"" + arn + "\"}"), + BUCKET_CHOICE); + } + + @ParameterizedTest + @ValueSource(strings = {"/GetIndex", "/DeleteIndex", "/PutVectors", "/GetVectors", "/DeleteVectors", "/QueryVectors", + "/ListVectors"}) + void anIndexCallGivingNeitherOrMixingThemIsRefused(String path) { + String bucket = bucketName(); + String index = "arn:aws:s3vectors:us-east-1:000000000000:bucket/" + bucket + "/index/events"; + + refused(post(path, "{\"keys\":[\"v1\"]}"), INDEX_CHOICE); + refused(post(path, "{\"vectorBucketName\":\"" + bucket + "\",\"keys\":[\"v1\"]}"), INDEX_CHOICE); + refused(post(path, "{\"indexName\":\"events\",\"indexArn\":\"" + index + "\",\"keys\":[\"v1\"]}"), + INDEX_CHOICE); + } + + /** An index ARN is checked as a bucket ARN is: it names a Region and an account, of the Region's partition. */ + @ParameterizedTest + @ValueSource(strings = {"arn:aws:s3vectors:us-east-1::bucket/vectors/index/events", + "arn:aws-cn:s3vectors:us-east-1:000000000000:bucket/vectors/index/events"}) + void aMalformedIndexArnIsRefused(String arn) { + refused(post("/GetIndex", byIndexArn(arn)), "Invalid S3 Vectors ARN: " + arn); + refused(post("/ListVectors", byIndexArn(arn)), "Invalid S3 Vectors ARN: " + arn); + } + + /** + * 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. + */ + @Test + void aBucketAndAnIndexAreReachedByTheNamesAndArnsTheyWereGiven() { + String bucket = "Arn_" + UUID.randomUUID().toString().substring(0, 8); + String arn = post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200) + .extract().path("vectorBucketArn"); + 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); + } finally { + post("/DeleteIndex", "{\"vectorBucketName\":\"" + bucket + "\",\"indexName\":\"My_Index\"}"); + post("/DeleteVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200); + } + } + + /** + * An ARN of another account is refused with an AccessDeniedException that carries no message, as S3 Vectors does + * (measured on AWS), even when the caller has a bucket and an index of those names. + */ + @Test + void anArnOfAnotherAccountIsRefused() { + String bucket = bucketName(); + post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200); + post("/CreateIndex", "{\"vectorBucketName\":\"" + bucket + "\",\"indexName\":\"events\"," + + "\"dataType\":\"float32\",\"dimension\":2,\"distanceMetric\":\"cosine\"}").statusCode(200); + String other = "arn:aws:s3vectors:us-east-1:111122223333:bucket/" + bucket; + try { + for (ValidatableResponse response : List.of(post("/GetVectorBucket", byBucketArn(other)), + post("/ListIndexes", byBucketArn(other)), post("/GetIndex", byIndexArn(other + "/index/events")))) { + response.statusCode(403).body("__type", equalTo("AccessDeniedException")).body("message", equalTo("")); + } + } finally { + post("/DeleteIndex", "{\"vectorBucketName\":\"" + bucket + "\",\"indexName\":\"events\"}").statusCode(200); + post("/DeleteVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200); + } + } + + /** + * 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. + */ + @Test + void aBucketNameNoCallCouldReachIsRefusedOnCreate() { + refused(post("/CreateVectorBucket", "{\"vectorBucketName\":\"\"}"), "1 validation error detected. " + + "Value with length 0 at '/vectorBucketName' failed to satisfy constraint: " + + "Member must have length between 3 and 63, inclusive"); + for (String name : List.of("a/b", " ", bucketName() + "/index/events")) { + refused(post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + name + "\"}"), "Invalid vector bucket name"); + post("/ListVectorBuckets", "{}").statusCode(200).body("vectorBuckets.vectorBucketName", not(hasItem(name))); + } + } + + /** + * An index name no call could reach the index by is refused before the bucket is looked for, as S3 Vectors does + * (measured on AWS for a slash), and nothing is left that would keep its bucket from being deleted. + */ + @Test + void anIndexNameNoCallCouldReachIsRefusedOnCreate() { + refused(post("/CreateIndex", index(bucketName(), "a/b")), "Invalid index name"); + String bucket = bucketName(); + post("/CreateVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200); + try { + refused(post("/CreateIndex", index(bucket, "a/b")), "Invalid index name"); + refused(post("/CreateIndex", index(bucket, " ")), "Invalid index name"); + refused(post("/CreateIndex", index(bucket, "")), "1 validation error detected. " + + "Value with length 0 at '/indexName' failed to satisfy constraint: " + + "Member must have length between 3 and 63, inclusive"); + post("/ListIndexes", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200) + .body("indexes", hasSize(0)); + } finally { + post("/DeleteVectorBucket", "{\"vectorBucketName\":\"" + bucket + "\"}").statusCode(200); + } + } + + /** + * An ARN of another Region than the request's, or of another partition, is refused as S3 Vectors refuses it + * (measured on AWS), by calls of each kind that take one (bucket, index, ListVectors and policy), the partition + * checked first. + */ + @ParameterizedTest + @ValueSource(strings = {"/GetVectorBucket", "/DeleteVectorBucket", "/ListIndexes", "/GetIndex", "/DeleteIndex", + "/ListVectors", "/GetVectorBucketPolicy"}) + void anArnOfAnotherRegionOrPartitionIsRefused(String path) { + boolean byIndex = List.of("/GetIndex", "/DeleteIndex", "/ListVectors").contains(path); + String bucket = bucketName(); + String west = "arn:aws:s3vectors:us-west-2:000000000000:bucket/" + bucket; + String china = "arn:aws-cn:s3vectors:cn-north-1:000000000000:bucket/" + bucket; + refused(post(path, byIndex ? byIndexArn(west + "/index/events") : byBucketArn(west)), + "Unexpected value for ARN region component"); + refused(post(path, byIndex ? byIndexArn(china + "/index/events") : byBucketArn(china)), + "Unexpected value for ARN partition component"); + } + + private static String index(String bucket, String index) { + return "{\"vectorBucketName\":\"" + bucket + "\",\"indexName\":\"" + index + "\",\"dataType\":\"float32\"," + + "\"dimension\":2,\"distanceMetric\":\"cosine\"}"; + } + + private static String bucketName() { + return "arn-" + UUID.randomUUID().toString().substring(0, 8); + } + + private static String byBucketArn(String arn) { + return "{\"vectorBucketArn\":\"" + arn + "\"}"; + } + + private static String byIndexArn(String arn) { + return "{\"indexArn\":\"" + arn + "\"}"; + } + + private static ValidatableResponse post(String path, String body) { + return given().contentType("application/json").body(body).when().post(path).then(); + } + + private static void refused(ValidatableResponse response, String message) { + response.statusCode(400).body("__type", equalTo("ValidationException")).body("message", equalTo(message)); + } +} diff --git a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsIntegrationTest.java b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsIntegrationTest.java index 411317a683..44c182a2db 100644 --- a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsIntegrationTest.java @@ -653,7 +653,7 @@ class S3VectorsIntegrationTest { @Test @Order(18) - void listVectorsByIndexArnResolvesTheArnsOwnRegionNotTheRequestRegion() { + void listVectorsByIndexArnIsRefusedOutsideTheRequestsRegion() { String bucketName = "cross-region-vector-bucket"; String indexName = "cross-region-idx"; String otherRegionAuth = "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/s3vectors/aws4_request"; @@ -705,9 +705,8 @@ class S3VectorsIntegrationTest { .then() .statusCode(200); - // No Authorization header here, so this request resolves to the default region — not - // us-west-2. The lookup must still succeed because it honors the region encoded in the - // ARN itself, not the region the ListVectors request happens to be signed for. + // No Authorization header here, so this request resolves to the default region, not us-west-2. S3 Vectors + // refuses an ARN of another Region than the request's (measured on AWS). given() .contentType(JSON_CONTENT_TYPE) .body(""" @@ -715,6 +714,20 @@ class S3VectorsIntegrationTest { """.formatted(indexArn)) .when() .post("/ListVectors") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("Unexpected value for ARN region component")); + + // Signed for the ARN's Region, it lists the index's vectors. + given() + .contentType(JSON_CONTENT_TYPE) + .header("Authorization", otherRegionAuth) + .body(""" + { "indexArn": "%s" } + """.formatted(indexArn)) + .when() + .post("/ListVectors") .then() .statusCode(200) .body("vectors", hasSize(1)) diff --git a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsServiceTest.java b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsServiceTest.java index 435b0471e5..936f4d94e6 100644 --- a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsServiceTest.java +++ b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsServiceTest.java @@ -167,28 +167,40 @@ class S3VectorsServiceTest { service.deleteVectorBucketPolicy("bucket", null, REGION); } + /** + * The policy calls take a bucket ARN of the request's Region and refuse one of another Region or partition, as S3 + * Vectors does (measured on AWS), leaving that bucket's policy alone. + */ @Test - void vectorBucketPolicyByArnResolvesTheArnsOwnRegion() { + void vectorBucketPolicyByArnIsTakenOnlyInTheRequestsRegion() { VectorBucket westBucket = service.createVectorBucket("west-bucket", null, "us-west-2"); String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + String westArn = westBucket.getVectorBucketArn(); - service.putVectorBucketPolicy(null, westBucket.getVectorBucketArn(), policy, REGION); - assertEquals(policy, service.getVectorBucketPolicy(null, westBucket.getVectorBucketArn(), REGION)); - assertEquals(policy, service.getVectorBucketPolicy("west-bucket", null, "us-west-2")); + for (Runnable call : List.of(() -> service.putVectorBucketPolicy(null, westArn, policy, REGION), + () -> service.getVectorBucketPolicy(null, westArn, REGION), + () -> service.deleteVectorBucketPolicy(null, westArn, REGION))) { + AwsException refused = assertThrows(AwsException.class, call::run); + assertEquals("ValidationException", refused.getErrorCode()); + assertEquals("Unexpected value for ARN region component", refused.getMessage()); + } + assertEquals("NotFoundException", assertThrows(AwsException.class, + () -> service.getVectorBucketPolicy("west-bucket", null, "us-west-2")).getErrorCode()); - service.deleteVectorBucketPolicy(null, westBucket.getVectorBucketArn(), REGION); - AwsException notFound = assertThrows(AwsException.class, - () -> service.getVectorBucketPolicy("west-bucket", null, "us-west-2")); - assertEquals("NotFoundException", notFound.getErrorCode()); + service.putVectorBucketPolicy(null, westArn, policy, "us-west-2"); + assertEquals(policy, service.getVectorBucketPolicy(null, westArn, "us-west-2")); - // Custom region in a non-commercial deployment stays in the deployment's partition. + // A custom Region of a non-commercial deployment is in the deployment's partition: its ARN is taken in that + // Region, and a commercial Region's ARN is of another partition. S3VectorsService chinaService = new S3VectorsService(inMemoryFactory(), new RegionResolver("cn-north-1", "000000000000"), Clock.fixed(CREATION_TIME, ZoneOffset.UTC)); VectorBucket customRegionBucket = chinaService.createVectorBucket("custom-bucket", null, "custom-region-1"); assertTrue(customRegionBucket.getVectorBucketArn().startsWith("arn:aws-cn:s3vectors:custom-region-1:")); - chinaService.putVectorBucketPolicy(null, customRegionBucket.getVectorBucketArn(), policy, "cn-north-1"); + chinaService.putVectorBucketPolicy(null, customRegionBucket.getVectorBucketArn(), policy, "custom-region-1"); assertEquals(policy, chinaService.getVectorBucketPolicy("custom-bucket", null, "custom-region-1")); + assertEquals("Unexpected value for ARN partition component", assertThrows(AwsException.class, + () -> chinaService.getVectorBucketPolicy(null, westArn, "cn-north-1")).getMessage()); } @Test @@ -198,16 +210,20 @@ class S3VectorsServiceTest { String validPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; service.putVectorBucketPolicy("bucket", null, validPolicy, REGION); - // Missing bucket or foreign-account ARN returns NotFoundException (404) and leaves local bucket untouched. - String foreignAccountArn = "arn:aws:s3vectors:us-east-1:111122223333:bucket/bucket"; + // A missing bucket returns NotFoundException (404), and another account's ARN AccessDeniedException (403), as + // S3 Vectors answers it (measured on AWS); either leaves the local bucket untouched. for (Runnable action : List.of( () -> service.putVectorBucketPolicy("missing", null, validPolicy, REGION), () -> service.getVectorBucketPolicy("missing", null, REGION), - () -> service.deleteVectorBucketPolicy("missing", null, REGION), + () -> service.deleteVectorBucketPolicy("missing", null, REGION))) { + assertRejected("NotFoundException", 404, validPolicy, action); + } + String foreignAccountArn = "arn:aws:s3vectors:us-east-1:111122223333:bucket/bucket"; + for (Runnable action : List.of( () -> service.putVectorBucketPolicy(null, foreignAccountArn, "{\"Statement\":[]}", REGION), () -> service.getVectorBucketPolicy(null, foreignAccountArn, REGION), () -> service.deleteVectorBucketPolicy(null, foreignAccountArn, REGION))) { - assertRejected("NotFoundException", 404, validPolicy, action); + assertRejected("AccessDeniedException", 403, validPolicy, action); } // Neither, both, or invalid bucket names return ValidationException (400).