From d97574207be327fd5b115e138db76061f3fac959 Mon Sep 17 00:00:00 2001 From: Koushik Dutta Date: Tue, 10 Nov 2026 23:28:19 +0530 Subject: [PATCH] feat(s3vectors): support vector bucket policy operations (#7825) * feat(s3vectors): implement vector bucket policy management (create, get, delete) * fix(s3vectors): validate bucket name length and ARN account in policy operations * refactor(s3vectors): share bucket selector validation and use partitionForRegion --- docs/services/index.md | 2 +- docs/services/s3vectors.md | 14 +- .../provisioners/S3VectorsCfnProvisioner.java | 39 ++--- .../s3vectors/S3VectorsController.java | 61 ++++++++ .../services/s3vectors/S3VectorsService.java | 137 +++++++++++++++--- .../s3vectors/model/VectorBucket.java | 4 + .../s3vectors/S3VectorsIntegrationTest.java | 70 +++++++++ .../S3VectorsSdkIntegrationTest.java | 42 ++++++ .../s3vectors/S3VectorsServiceTest.java | 132 ++++++++++++++++- .../s3vectors/S3VectorsWriteLockTest.java | 28 ++++ 10 files changed, 473 insertions(+), 56 deletions(-) diff --git a/docs/services/index.md b/docs/services/index.md index d8763fecba..bb510843fe 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -14,7 +14,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [SQS](sqs.md) | `POST /` with `Action=` param | Query / JSON | 23 | | [SNS](sns.md) | `POST /` with `Action=` param | Query / JSON | 39 | | [S3](s3.md) | `/{bucket}/{key}` | REST XML | 58 | -| [S3 Vectors](s3vectors.md) | `POST /{OperationName}` | REST JSON | 12 | +| [S3 Vectors](s3vectors.md) | `POST /{OperationName}` | REST JSON | 16 | | [S3 Tables](s3tables.md) | `/buckets`, `/namespaces/*`, `/tables/*` | REST JSON | 25 | | [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 28 | | [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 | diff --git a/docs/services/s3vectors.md b/docs/services/s3vectors.md index 50ed73f9f3..7eae7cb095 100644 --- a/docs/services/s3vectors.md +++ b/docs/services/s3vectors.md @@ -11,9 +11,9 @@ shape, so the AWS SDK and CLI `s3vectors` clients work without modification. | Category | Operations | |---|---| -| **Vector buckets** | CreateVectorBucket, GetVectorBucket, ListVectorBuckets, DeleteVectorBucket | +| **Vector buckets** | CreateVectorBucket, GetVectorBucket, ListVectorBuckets, DeleteVectorBucket, PutVectorBucketPolicy, GetVectorBucketPolicy, DeleteVectorBucketPolicy | | **Indexes** | CreateIndex, GetIndex, ListIndexes, DeleteIndex | -| **Vectors** | PutVectors, GetVectors, DeleteVectors, QueryVectors | +| **Vectors** | PutVectors, GetVectors, ListVectors, DeleteVectors, QueryVectors | ## Example @@ -69,8 +69,14 @@ Index dimensions must be between 1 and 4096. Metadata configuration accepts up t 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. -Writes to the same bucket are serialized across tags, indexes, vectors, and bucket -deletion so concurrent changes do not overwrite each other or restore deleted data. +Writes to the same bucket are serialized across policies, tags, indexes, vectors, and +bucket deletion so concurrent changes do not overwrite each other or restore deleted data. + +Bucket policies can be attached, retrieved, and deleted by either `vectorBucketName` or +`vectorBucketArn`. `PutVectorBucketPolicy` validates that the policy is a JSON object and +stores it with the bucket; `GetVectorBucketPolicy` returns `NotFoundException` when no +policy is attached. Bucket policies are stored and returned, but Floci does not evaluate +or enforce them on requests. 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/cloudformation/provisioners/S3VectorsCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/S3VectorsCfnProvisioner.java index 1a5a071f21..27c6362719 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/S3VectorsCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/S3VectorsCfnProvisioner.java @@ -130,11 +130,7 @@ public class S3VectorsCfnProvisioner implements CfnResourceProvisioner { } private static String validateName(String name, String property, boolean index) { - 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.matches(pattern)) { - throw validation(property + " must be a valid lowercase name of 3 to 63 characters."); - } - return name; + return S3VectorsService.validateName(name, property, index, "ValidationError"); } private static void rejectSameNameReplacement(ProvisionContext ctx, boolean updatesEntity, String resourcePath) { @@ -144,36 +140,19 @@ public class S3VectorsCfnProvisioner implements CfnResourceProvisioner { } private static String bucketName(JsonNode props, ProvisionContext ctx) { - String name = ctx.resolveOptional(props, "VectorBucketName"); - String arn = ctx.resolveOptional(props, "VectorBucketArn"); - if ((name == null) == (arn == null)) { - throw validation("Specify exactly one of VectorBucketName or VectorBucketArn."); - } - if (arn == null) { - return validateName(name, "VectorBucketName", false); - } - String[] parts = arnParts(arn, false); - AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); - if (!ctx.region().equals(parsed.region()) || !ctx.accountId().equals(parsed.accountId()) - || !AwsRegions.partitionFor(ctx.region()).equals(parsed.partition())) { + S3VectorsService.ResolvedBucket resolved = S3VectorsService.resolveBucket( + ctx.resolveOptional(props, "VectorBucketName"), + ctx.resolveOptional(props, "VectorBucketArn"), + ctx.region(), AwsRegions::partitionFor, "ValidationError"); + if (resolved.accountId() != null + && (!ctx.region().equals(resolved.region()) || !ctx.accountId().equals(resolved.accountId()))) { throw validation("VectorBucketArn must belong to the stack's region and account."); } - return validateName(parts[1], "VectorBucketArn bucket name", false); + return resolved.bucketName(); } private static String[] arnParts(String arn, boolean index) { - try { - AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); - String[] parts = parsed.resource().split("/", -1); - if (!"s3vectors".equals(parsed.service()) || parts.length != (index ? 4 : 2) - || !"bucket".equals(parts[0]) || parts[1].isBlank() - || (index && (!"index".equals(parts[2]) || parts[3].isBlank()))) { - throw validation("Invalid S3 Vectors ARN: " + arn); - } - return parts; - } catch (IllegalArgumentException e) { - throw validation("Invalid S3 Vectors ARN: " + arn); - } + return S3VectorsService.arnParts(arn, index, "ValidationError"); } private static Object encryption(JsonNode props, ProvisionContext ctx, String defaultType) { 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 2ddf19eaf1..e6f43e8a0e 100644 --- a/src/main/java/io/floci/aws/services/s3vectors/S3VectorsController.java +++ b/src/main/java/io/floci/aws/services/s3vectors/S3VectorsController.java @@ -102,6 +102,30 @@ public class S3VectorsController { String vectorBucketArn ) {} + @RegisterForReflection + public record PutVectorBucketPolicyRequest( + String vectorBucketName, + String vectorBucketArn, + String policy + ) {} + + @RegisterForReflection + public record GetVectorBucketPolicyRequest( + String vectorBucketName, + String vectorBucketArn + ) {} + + @RegisterForReflection + public record GetVectorBucketPolicyResponse( + String policy + ) {} + + @RegisterForReflection + public record DeleteVectorBucketPolicyRequest( + String vectorBucketName, + String vectorBucketArn + ) {} + @RegisterForReflection public record CreateIndexRequest( String vectorBucketName, @@ -316,6 +340,43 @@ public class S3VectorsController { return Response.ok(objectMapper.createObjectNode()).build(); } + @POST + @Path("/PutVectorBucketPolicy") + public Response putVectorBucketPolicy(@Context HttpHeaders headers, PutVectorBucketPolicyRequest request) { + String region = regionResolver.resolveRegion(headers); + service.putVectorBucketPolicy( + request != null ? request.vectorBucketName() : null, + request != null ? request.vectorBucketArn() : null, + request != null ? request.policy() : null, + region + ); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @POST + @Path("/GetVectorBucketPolicy") + public Response getVectorBucketPolicy(@Context HttpHeaders headers, GetVectorBucketPolicyRequest request) { + String region = regionResolver.resolveRegion(headers); + String policy = service.getVectorBucketPolicy( + request != null ? request.vectorBucketName() : null, + request != null ? request.vectorBucketArn() : null, + region + ); + return Response.ok(new GetVectorBucketPolicyResponse(policy)).build(); + } + + @POST + @Path("/DeleteVectorBucketPolicy") + public Response deleteVectorBucketPolicy(@Context HttpHeaders headers, DeleteVectorBucketPolicyRequest request) { + String region = regionResolver.resolveRegion(headers); + service.deleteVectorBucketPolicy( + request != null ? request.vectorBucketName() : null, + request != null ? request.vectorBucketArn() : null, + region + ); + return Response.ok(objectMapper.createObjectNode()).build(); + } + @POST @Path("/CreateIndex") public Response createIndex(@Context HttpHeaders headers, CreateIndexRequest request) { 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 bf817f46b8..e239ed7958 100644 --- a/src/main/java/io/floci/aws/services/s3vectors/S3VectorsService.java +++ b/src/main/java/io/floci/aws/services/s3vectors/S3VectorsService.java @@ -1,6 +1,10 @@ package io.floci.aws.services.s3vectors; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; @@ -13,6 +17,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; @@ -24,11 +29,14 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; import java.util.stream.Collectors; @ApplicationScoped public class S3VectorsService { 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); private final AccountAwareStorageBackend store; private final RegionResolver regionResolver; @@ -61,7 +69,7 @@ public class S3VectorsService { } private String buildBucketArn(String region, String bucketName) { - return AwsArnUtils.Arn.of("s3vectors", region, regionResolver.getAccountId(), "bucket/" + bucketName).toString(); + return regionResolver.buildArn("s3vectors", region, "bucket/" + bucketName); } private String buildIndexArn(String region, String bucketName, String indexName) { @@ -153,6 +161,113 @@ public class S3VectorsService { } } + public void putVectorBucketPolicy(String bucketName, String bucketArn, String policy, String region) { + ResolvedBucket target = resolveBucket(bucketName, bucketArn, region); + validatePolicyDocument(policy); + synchronized (lockFor(target.bucketName(), target.region())) { + VectorBucket bucket = getVectorBucket(target.bucketName(), target.region()); + bucket.setPolicy(policy); + store.put(buildStorageKey(target.region(), target.bucketName()), bucket); + LOG.infov("Put policy on Vector Bucket: {0} in region {1}", target.bucketName(), target.region()); + } + } + + public String getVectorBucketPolicy(String bucketName, String bucketArn, String region) { + ResolvedBucket target = resolveBucket(bucketName, bucketArn, region); + synchronized (lockFor(target.bucketName(), target.region())) { + VectorBucket bucket = getVectorBucket(target.bucketName(), target.region()); + String policy = bucket.getPolicy(); + if (policy == null) { + throw new AwsException("NotFoundException", + "The vector bucket policy for " + target.bucketName() + " does not exist.", 404); + } + return policy; + } + } + + public void deleteVectorBucketPolicy(String bucketName, String bucketArn, String region) { + ResolvedBucket target = resolveBucket(bucketName, bucketArn, region); + synchronized (lockFor(target.bucketName(), target.region())) { + VectorBucket bucket = getVectorBucket(target.bucketName(), target.region()); + if (bucket.getPolicy() != null) { + bucket.setPolicy(null); + store.put(buildStorageKey(target.region(), target.bucketName()), bucket); + } + LOG.infov("Deleted policy from Vector Bucket: {0} in region {1}", target.bucketName(), target.region()); + } + } + + 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); + } + return resolved; + } + + public static ResolvedBucket resolveBucket(String bucketName, String bucketArn, + String defaultRegion, Function partitionForRegion, + String errorCode) { + if ((bucketName == null) == (bucketArn == null)) { + throw new AwsException(errorCode, + "Specify exactly one of VectorBucketName or VectorBucketArn.", 400); + } + if (bucketArn == null) { + return new ResolvedBucket(validateName(bucketName, "VectorBucketName", false, errorCode), + defaultRegion, null); + } + String[] parts = arnParts(bucketArn, false, errorCode); + AwsArnUtils.Arn parsed = AwsArnUtils.parse(bucketArn); + String name = validateName(parts[1], "VectorBucketArn bucket name", false, errorCode); + if (parsed.region().isEmpty() || parsed.accountId().isEmpty() + || !partitionForRegion.apply(parsed.region()).equals(parsed.partition())) { + throw new AwsException(errorCode, "Invalid S3 Vectors ARN: " + bucketArn, 400); + } + return new ResolvedBucket(name, 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)) { + throw new AwsException(errorCode, + property + " must be a valid lowercase name of 3 to 63 characters.", 400); + } + return name; + } + + public static String[] arnParts(String arn, boolean index, String errorCode) { + try { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String[] parts = parsed.resource().split("/", -1); + if (!"s3vectors".equals(parsed.service()) || parts.length != (index ? 4 : 2) + || !"bucket".equals(parts[0]) || parts[1].isBlank() + || (index && (!"index".equals(parts[2]) || parts[3].isBlank()))) { + throw new AwsException(errorCode, "Invalid S3 Vectors ARN: " + arn, 400); + } + return parts; + } catch (IllegalArgumentException e) { + throw new AwsException(errorCode, "Invalid S3 Vectors ARN: " + arn, 400); + } + } + + private static void validatePolicyDocument(String policy) { + if (policy == null || policy.isBlank()) { + throw new AwsException("ValidationException", "Policy must be a non-empty JSON object.", 400); + } + try { + JsonNode parsed = STRICT_JSON_READER.readTree(policy); + if (parsed == null || !parsed.isObject()) { + throw new AwsException("ValidationException", "Policy must be a valid JSON object.", 400); + } + } catch (IOException e) { + throw new AwsException("ValidationException", "Policy must be a valid JSON object.", 400); + } + } + + public record ResolvedBucket(String bucketName, String region, String accountId) {} + public VectorIndex createIndex(String bucketName, String indexName, int dimension, String dataType, String distanceMetric, List nonFilterableMetadataKeys, String region) { return createIndex(bucketName, indexName, dimension, dataType, distanceMetric, @@ -328,26 +443,12 @@ public class S3VectorsService { if (indexArn == null || indexArn.isBlank()) { throw new AwsException("ValidationException", "Either indexName or indexArn is required.", 400); } - AwsArnUtils.Arn parsed; - try { - parsed = AwsArnUtils.parse(indexArn); - } catch (IllegalArgumentException e) { - throw new AwsException("ValidationException", "Malformed indexArn: " + indexArn, 400); - } - if (!"s3vectors".equals(parsed.service())) { - throw new AwsException("ValidationException", "Not an S3 Vectors indexArn: " + indexArn, 400); - } - String resource = parsed.resource(); - int marker = resource.lastIndexOf("/index/"); - if (marker < 0 || !resource.startsWith("bucket/")) { - throw new AwsException("ValidationException", "Malformed indexArn: " + indexArn, 400); - } - String bucketNameFromArn = resource.substring("bucket/".length(), marker); - String indexNameFromArn = resource.substring(marker + "/index/".length()); + 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(bucketNameFromArn, indexNameFromArn, arnRegion); + return getIndex(parts[1], parts[3], arnRegion); } /** diff --git a/src/main/java/io/floci/aws/services/s3vectors/model/VectorBucket.java b/src/main/java/io/floci/aws/services/s3vectors/model/VectorBucket.java index 7036ab2160..3666cb5da8 100644 --- a/src/main/java/io/floci/aws/services/s3vectors/model/VectorBucket.java +++ b/src/main/java/io/floci/aws/services/s3vectors/model/VectorBucket.java @@ -13,6 +13,7 @@ public class VectorBucket { private String vectorBucketName; private String vectorBucketArn; private Object encryptionConfiguration; + private String policy; private Map indexes = new ConcurrentHashMap<>(); public VectorBucket() {} @@ -38,6 +39,9 @@ public class VectorBucket { public Object getEncryptionConfiguration() { return encryptionConfiguration; } public void setEncryptionConfiguration(Object encryptionConfiguration) { this.encryptionConfiguration = encryptionConfiguration; } + public String getPolicy() { return policy; } + public void setPolicy(String policy) { this.policy = policy; } + public Map getIndexes() { return indexes; } public void setIndexes(Map indexes) { this.indexes = indexes; } } 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 1508738a93..411317a683 100644 --- a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsIntegrationTest.java @@ -9,6 +9,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestMethodOrder; +import java.util.Map; + import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; @@ -718,4 +720,72 @@ class S3VectorsIntegrationTest { .body("vectors", hasSize(1)) .body("vectors[0].key", equalTo("only")); } + + @Test + @Order(19) + void vectorBucketPolicyLifecycleByNameAndArn() { + String bucketName = "policy-vector-bucket"; + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"s3vectors:*\",\"Resource\":\"*\"}]}"; + + String bucketArn = + given() + .contentType(JSON_CONTENT_TYPE) + .body(""" + { "vectorBucketName": "%s" } + """.formatted(bucketName)) + .when() + .post("/CreateVectorBucket") + .then() + .statusCode(200) + .extract().path("vectorBucketArn"); + + given() + .contentType(JSON_CONTENT_TYPE) + .body(Map.of("vectorBucketName", bucketName)) + .when() + .post("/GetVectorBucketPolicy") + .then() + .statusCode(404); + + given() + .contentType(JSON_CONTENT_TYPE) + .body(Map.of("vectorBucketName", bucketName, "policy", policy)) + .when() + .post("/PutVectorBucketPolicy") + .then() + .statusCode(200); + + given() + .contentType(JSON_CONTENT_TYPE) + .body(Map.of("vectorBucketArn", bucketArn)) + .when() + .post("/GetVectorBucketPolicy") + .then() + .statusCode(200) + .body("policy", equalTo(policy)); + + given() + .contentType(JSON_CONTENT_TYPE) + .body(Map.of("vectorBucketArn", bucketArn)) + .when() + .post("/DeleteVectorBucketPolicy") + .then() + .statusCode(200); + + given() + .contentType(JSON_CONTENT_TYPE) + .body(Map.of("vectorBucketName", bucketName)) + .when() + .post("/GetVectorBucketPolicy") + .then() + .statusCode(404); + + given() + .contentType(JSON_CONTENT_TYPE) + .body(Map.of("vectorBucketName", bucketName)) + .when() + .post("/DeleteVectorBucket") + .then() + .statusCode(200); + } } diff --git a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsSdkIntegrationTest.java b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsSdkIntegrationTest.java index 30b351832e..34749bad03 100644 --- a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsSdkIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsSdkIntegrationTest.java @@ -16,6 +16,7 @@ import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3vectors.S3VectorsClient; import software.amazon.awssdk.services.s3vectors.model.Index; +import software.amazon.awssdk.services.s3vectors.model.NotFoundException; import software.amazon.awssdk.services.s3vectors.model.PutInputVector; import software.amazon.awssdk.services.s3vectors.model.QueryVectorsResponse; import software.amazon.awssdk.services.s3vectors.model.ValidationException; @@ -240,6 +241,47 @@ class S3VectorsSdkIntegrationTest { } } + @Test + void vectorBucketPolicyLifecycleAndValidationThroughTheSdk() { + String name = "policy-vectors-" + UUID.randomUUID().toString().substring(0, 8); + String policyV1 = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Read\",\"Effect\":\"Allow\"}]}"; + String policyV2 = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Write\",\"Effect\":\"Deny\"}]}"; + try (S3VectorsClient vectors = vectors("us-east-1")) { + String bucketArn = vectors.createVectorBucket(request -> request.vectorBucketName(name)).vectorBucketArn(); + try { + NotFoundException initialMissing = assertThrows(NotFoundException.class, + () -> vectors.getVectorBucketPolicy(request -> request.vectorBucketName(name))); + assertEquals(404, initialMissing.statusCode()); + + vectors.putVectorBucketPolicy(request -> request.vectorBucketName(name).policy(policyV1)); + assertEquals(policyV1, + vectors.getVectorBucketPolicy(request -> request.vectorBucketName(name)).policy()); + assertEquals(policyV1, + vectors.getVectorBucketPolicy(request -> request.vectorBucketArn(bucketArn)).policy()); + + vectors.putVectorBucketPolicy(request -> request.vectorBucketArn(bucketArn).policy(policyV2)); + assertEquals(policyV2, + vectors.getVectorBucketPolicy(request -> request.vectorBucketName(name)).policy()); + + ValidationException invalidJson = assertThrows(ValidationException.class, + () -> vectors.putVectorBucketPolicy(request -> request.vectorBucketName(name).policy("not-json"))); + assertEquals(400, invalidJson.statusCode()); + + ValidationException bothIdentifiers = assertThrows(ValidationException.class, + () -> vectors.getVectorBucketPolicy(request -> request + .vectorBucketName(name).vectorBucketArn(bucketArn))); + assertEquals(400, bothIdentifiers.statusCode()); + + vectors.deleteVectorBucketPolicy(request -> request.vectorBucketArn(bucketArn)); + NotFoundException deletedMissing = assertThrows(NotFoundException.class, + () -> vectors.getVectorBucketPolicy(request -> request.vectorBucketName(name))); + assertEquals(404, deletedMissing.statusCode()); + } finally { + vectors.deleteVectorBucket(request -> request.vectorBucketName(name)); + } + } + } + private S3VectorsClient vectors(String region) { return S3VectorsClient.builder().endpointOverride(endpoint).region(Region.of(region)) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) 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 c08e94a45a..435b0471e5 100644 --- a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsServiceTest.java +++ b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsServiceTest.java @@ -14,6 +14,7 @@ import org.junit.jupiter.api.Test; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -28,15 +29,19 @@ class S3VectorsServiceTest { @BeforeEach void setUp() { - StorageFactory factory = new StorageFactory(null, null) { + StorageFactory factory = inMemoryFactory(); + service = new S3VectorsService(factory, new RegionResolver(REGION, "000000000000"), + Clock.fixed(CREATION_TIME, ZoneOffset.UTC)); + } + + private static StorageFactory inMemoryFactory() { + return new StorageFactory(null, null) { @Override public AccountAwareStorageBackend create(String serviceName, String fileName, TypeReference> typeReference) { return AccountAwareStorageBackend.inMemory("000000000000"); } }; - service = new S3VectorsService(factory, new RegionResolver(REGION, "000000000000"), - Clock.fixed(CREATION_TIME, ZoneOffset.UTC)); } @Test @@ -131,4 +136,125 @@ class S3VectorsServiceTest { VectorIndex index = service.createIndex("bucket", "index", 3, "float32", "euclidean", keys, REGION); assertEquals(keys, index.getNonFilterableMetadataKeys()); } + + @Test + void vectorBucketPolicyLifecycleAndPersistenceByNameAndArn() throws Exception { + VectorBucket bucket = service.createVectorBucket("bucket", null, REGION); + String policyV1 = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + String policyV2 = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}"; + + AwsException missingInitial = assertThrows(AwsException.class, + () -> service.getVectorBucketPolicy("bucket", null, REGION)); + assertEquals("NotFoundException", missingInitial.getErrorCode()); + + service.putVectorBucketPolicy("bucket", null, policyV1, REGION); + assertEquals(policyV1, service.getVectorBucketPolicy("bucket", null, REGION)); + assertEquals(policyV1, service.getVectorBucketPolicy(null, bucket.getVectorBucketArn(), REGION)); + + ObjectMapper mapper = new ObjectMapper().findAndRegisterModules(); + VectorBucket restored = mapper.readValue(mapper.writeValueAsString(bucket), VectorBucket.class); + assertEquals(policyV1, restored.getPolicy()); + + service.putVectorBucketPolicy(null, bucket.getVectorBucketArn(), policyV2, REGION); + assertEquals(policyV2, service.getVectorBucketPolicy("bucket", null, REGION)); + + service.deleteVectorBucketPolicy(null, bucket.getVectorBucketArn(), REGION); + AwsException afterDelete = assertThrows(AwsException.class, + () -> service.getVectorBucketPolicy("bucket", null, REGION)); + assertEquals("NotFoundException", afterDelete.getErrorCode()); + + // Deleting again when no policy is attached remains idempotent on an existing bucket. + service.deleteVectorBucketPolicy("bucket", null, REGION); + } + + @Test + void vectorBucketPolicyByArnResolvesTheArnsOwnRegion() { + VectorBucket westBucket = service.createVectorBucket("west-bucket", null, "us-west-2"); + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + + 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")); + + service.deleteVectorBucketPolicy(null, westBucket.getVectorBucketArn(), REGION); + AwsException notFound = assertThrows(AwsException.class, + () -> service.getVectorBucketPolicy("west-bucket", null, "us-west-2")); + assertEquals("NotFoundException", notFound.getErrorCode()); + + // Custom region in a non-commercial deployment stays in the deployment's 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"); + assertEquals(policy, chinaService.getVectorBucketPolicy("custom-bucket", null, "custom-region-1")); + } + + @Test + void vectorBucketPolicyRejectsInvalidInputsAndMissingBuckets() { + VectorBucket bucket = service.createVectorBucket("bucket", null, REGION); + VectorIndex index = service.createIndex("bucket", "index", 3, "float32", "cosine", List.of(), REGION); + 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"; + for (Runnable action : List.of( + () -> service.putVectorBucketPolicy("missing", null, validPolicy, REGION), + () -> service.getVectorBucketPolicy("missing", null, REGION), + () -> service.deleteVectorBucketPolicy("missing", null, REGION), + () -> service.putVectorBucketPolicy(null, foreignAccountArn, "{\"Statement\":[]}", REGION), + () -> service.getVectorBucketPolicy(null, foreignAccountArn, REGION), + () -> service.deleteVectorBucketPolicy(null, foreignAccountArn, REGION))) { + assertRejected("NotFoundException", 404, validPolicy, action); + } + + // Neither, both, or invalid bucket names return ValidationException (400). + String overlongName = "a".repeat(64); + for (Runnable action : List.of( + () -> service.putVectorBucketPolicy(null, null, validPolicy, REGION), + () -> service.putVectorBucketPolicy(" ", "", validPolicy, REGION), + () -> service.putVectorBucketPolicy("ab", null, validPolicy, REGION), + () -> service.putVectorBucketPolicy("Upper", null, validPolicy, REGION), + () -> service.putVectorBucketPolicy(overlongName, null, validPolicy, REGION), + () -> service.putVectorBucketPolicy("bucket", bucket.getVectorBucketArn(), validPolicy, REGION), + () -> service.getVectorBucketPolicy(null, null, REGION), + () -> service.getVectorBucketPolicy("ab", null, REGION), + () -> service.getVectorBucketPolicy(overlongName, null, REGION), + () -> service.getVectorBucketPolicy("bucket", bucket.getVectorBucketArn(), REGION), + () -> service.deleteVectorBucketPolicy(null, null, REGION), + () -> service.deleteVectorBucketPolicy("ab", null, REGION), + () -> service.deleteVectorBucketPolicy(overlongName, null, REGION), + () -> service.deleteVectorBucketPolicy("bucket", bucket.getVectorBucketArn(), REGION))) { + assertRejected("ValidationException", 400, validPolicy, action); + } + + // Malformed, regionless, wrong-resource, or partition-mismatched ARNs return ValidationException (400). + for (String invalidArn : List.of( + "not-an-arn", + "arn:aws:s3:::bucket", + "arn:aws:s3vectors:us-east-1:000000000000:bucket/", + "arn:aws:s3vectors:us-east-1:000000000000:bucket/ab", + "arn:aws:s3vectors::000000000000:bucket/bucket", + "arn:aws:s3vectors:us-east-1::bucket/bucket", + "arn:aws-cn:s3vectors:us-east-1:000000000000:bucket/bucket", + index.getIndexArn())) { + assertRejected("ValidationException", 400, validPolicy, + () -> service.putVectorBucketPolicy(null, invalidArn, validPolicy, REGION)); + } + + // Non-JSON or non-object policy documents return ValidationException (400) without mutating stored policy. + for (String invalidPolicy : Arrays.asList(null, "", " ", "not-json", "[]", "\"string\"", "{} trailing")) { + assertRejected("ValidationException", 400, validPolicy, + () -> service.putVectorBucketPolicy("bucket", null, invalidPolicy, REGION)); + } + } + + private void assertRejected(String errorCode, int status, String expectedPolicy, Runnable action) { + AwsException error = assertThrows(AwsException.class, action::run); + assertEquals(errorCode, error.getErrorCode()); + assertEquals(status, error.getHttpStatus()); + assertEquals(expectedPolicy, service.getVectorBucketPolicy("bucket", null, REGION)); + } } diff --git a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsWriteLockTest.java b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsWriteLockTest.java index f6e8dc31be..b13eb2fcd0 100644 --- a/src/test/java/io/floci/aws/services/s3vectors/S3VectorsWriteLockTest.java +++ b/src/test/java/io/floci/aws/services/s3vectors/S3VectorsWriteLockTest.java @@ -150,6 +150,34 @@ class S3VectorsWriteLockTest { assertEquals(Map.of("new", "tag"), service.getVectorBucket("bucket", REGION).getTags()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void bucketPolicyDoesNotOverwriteConcurrentIndexCreation(boolean copyOnAccess) throws Exception { + setUp(copyOnAccess); + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + overlap(() -> service.putVectorBucketPolicy("bucket", null, policy, REGION), this::createIndex); + assertEquals(policy, service.getVectorBucketPolicy("bucket", null, REGION)); + assertEquals("index", service.getIndex("bucket", "index", REGION).getIndexName()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void bucketPolicyUpdateCannotResurrectADeletedOrRecreatedBucket(boolean copyOnAccess) throws Exception { + setUp(copyOnAccess); + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + overlap(() -> service.putVectorBucketPolicy("bucket", null, policy, REGION), + () -> service.deleteVectorBucket("bucket", REGION)); + assertThrows(AwsException.class, () -> service.getVectorBucket("bucket", REGION)); + + service.createVectorBucket("bucket", null, REGION); + overlap(() -> service.putVectorBucketPolicy("bucket", null, policy, REGION), () -> { + service.deleteVectorBucket("bucket", REGION); + service.createVectorBucket("bucket", null, Map.of("new", "tag"), REGION); + }); + assertEquals(Map.of("new", "tag"), service.getVectorBucket("bucket", REGION).getTags()); + assertThrows(AwsException.class, () -> service.getVectorBucketPolicy("bucket", null, REGION)); + } + private void putVector(String key) { service.putVectors("bucket", "index", List.of(new VectorData(key, List.of(1.0f), Map.of())), REGION); }