feat(s3vectors): support resource tagging (#9059)

S3 Vectors buckets and indexes now support TagResource, UntagResource and
ListTagsForResource through the shared tag routes. A tag call reads the
resource ARN in the request's Region, partition and account as the other
ARN operations do, merges tags by key, and holds the 50-tag limit under
the bucket lock. Create, replace and TagResource validate tags the same
way, with the service's not-found wording and modeled constraint errors.
Strict tag handlers reject trailing JSON before calling their service.

Adapted from AndreKurait/floci#815.

Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Jackson PriceandAndre Kurait authored and GitHub committed 2026-11-19 22:14:23 -04:00
1 parent 41aa3ba2eb
commit e50e7dac36
10 files changed
+647 -3

No files matched your search

+10 -2
View File
@@ -1,7 +1,7 @@
# S3 Vectors
**Protocol:** REST JSON
**Endpoint:** `POST /{OperationName}` (e.g. `POST /CreateVectorBucket`)
**Endpoint:** `POST /{OperationName}` (e.g. `POST /CreateVectorBucket`); tagging uses `GET`, `POST`, and `DELETE /tags/{resourceArn}`
Floci emulates the S3 Vectors API: vector buckets, vector indexes, and vector
storage with similarity queries. All operations use the AWS REST JSON wire
@@ -14,6 +14,7 @@ shape, so the AWS SDK and CLI `s3vectors` clients work without modification.
| **Vector buckets** | CreateVectorBucket, GetVectorBucket, ListVectorBuckets, DeleteVectorBucket, PutVectorBucketPolicy, GetVectorBucketPolicy, DeleteVectorBucketPolicy |
| **Indexes** | CreateIndex, GetIndex, ListIndexes, DeleteIndex |
| **Vectors** | PutVectors, GetVectors, ListVectors, DeleteVectors, QueryVectors |
| **Tags** | TagResource, UntagResource, ListTagsForResource |
## Example
@@ -91,7 +92,14 @@ Vectors requires: one of another partition or Region is refused with a `Validati
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.
`TagResource`, `UntagResource`, and `ListTagsForResource` work with vector bucket
and index ARNs. Tagging merges keys and replaces the values of existing keys;
untagging removes only the requested keys. Each resource can have up to 50 tags,
including tags supplied during creation. Invalid tags or updates that exceed that limit
leave its tags unchanged. A legacy resource above the limit can still be listed and
untagged until it is within the limit. Tag operations apply the ARN scope checks above
and reject malformed JSON, including trailing content, before changing tags.
Tag changes use the configured storage backend and survive restarts in persistent storage modes.
## CloudFormation
@@ -1,5 +1,6 @@
package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -83,7 +84,9 @@ public class TagDispatcher {
String region = regionResolver.resolveRegion(headers);
String effectiveBody = (body == null || body.isBlank()) ? "{}" : body;
try {
JsonNode node = objectMapper.readTree(effectiveBody);
JsonNode node = handler.strictTagValidation()
? objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(effectiveBody)
: objectMapper.readTree(effectiveBody);
Map<String, String> tags = parseTags(handler, node);
handler.tagResource(region, arn, tags);
return successResponse;
@@ -8,6 +8,7 @@ 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;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
@@ -53,6 +54,7 @@ public class S3VectorsService implements StoredResourceArns {
private static final String BUCKET_EXISTS = "A vector bucket with the specified name already exists";
private static final String INDEX_EXISTS = "An index with the specified name already exists";
private static final Logger LOG = Logger.getLogger(S3VectorsService.class);
private static final Pattern TAG_CHARACTERS = Pattern.compile("[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*");
private static final ObjectReader STRICT_JSON_READER =
new ObjectMapper().reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
/** What a vector bucket's ARN resource starts with, its name following. */
@@ -105,6 +107,7 @@ public class S3VectorsService implements StoredResourceArns {
public VectorBucket createVectorBucket(String bucketName, Object encryptionConfiguration,
Map<String, String> tags, String region) {
requireValidName(bucketName, "vectorBucketName", "Invalid vector bucket name");
validateTags(tags);
synchronized (lockFor(bucketName, region)) {
String key = buildStorageKey(region, bucketName);
if (store.get(key).isPresent()) {
@@ -404,6 +407,7 @@ public class S3VectorsService implements StoredResourceArns {
String distanceMetric, List<String> nonFilterableMetadataKeys,
Object encryptionConfiguration, Map<String, String> tags, String region) {
requireValidName(indexName, "indexName", "Invalid index name");
validateTags(tags);
if (dimension < 1 || dimension > 4096) {
throw new AwsException("ValidationException", "Dimension must be between 1 and 4096.", 400);
}
@@ -472,6 +476,7 @@ public class S3VectorsService implements StoredResourceArns {
}
public void replaceBucketTags(String bucketName, Map<String, String> tags, String region) {
validateTags(tags);
synchronized (lockFor(bucketName, region)) {
VectorBucket bucket = getVectorBucket(bucketName, region);
bucket.setTags(new ConcurrentHashMap<>(tags));
@@ -480,6 +485,7 @@ public class S3VectorsService implements StoredResourceArns {
}
public void replaceIndexTags(String bucketName, String indexName, Map<String, String> tags, String region) {
validateTags(tags);
synchronized (lockFor(bucketName, region)) {
VectorBucket bucket = getVectorBucket(bucketName, region);
VectorIndex index = getIndex(bucket, indexName);
@@ -529,6 +535,122 @@ public class S3VectorsService implements StoredResourceArns {
return new LinkedHashMap<>(tags);
}
public Map<String, String> listTagsForResource(String resourceArn, String region) {
TaggedResource resource = taggedResource(resourceArn, region);
synchronized (lockFor(resource.bucketName(), resource.region())) {
VectorBucket bucket = taggedBucket(resource, resourceArn);
return Map.copyOf(resourceTags(bucket, resource));
}
}
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
validateTags(tags);
TaggedResource resource = taggedResource(resourceArn, region);
synchronized (lockFor(resource.bucketName(), resource.region())) {
VectorBucket bucket = taggedBucket(resource, resourceArn);
Map<String, String> merged = new LinkedHashMap<>(resourceTags(bucket, resource));
merged.putAll(tags);
validateTagCount(merged);
setResourceTags(bucket, resource, merged);
store.put(buildStorageKey(resource.region(), resource.bucketName()), bucket);
}
}
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
if (tagKeys == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("tagKeys"));
}
tagKeys.forEach(key -> validateTagKey(key, "tagKeys"));
TaggedResource resource = taggedResource(resourceArn, region);
synchronized (lockFor(resource.bucketName(), resource.region())) {
VectorBucket bucket = taggedBucket(resource, resourceArn);
Map<String, String> remaining = new LinkedHashMap<>(resourceTags(bucket, resource));
tagKeys.forEach(remaining::remove);
setResourceTags(bucket, resource, remaining);
store.put(buildStorageKey(resource.region(), resource.bucketName()), bucket);
}
}
private void validateTags(Map<String, String> tags) {
if (tags == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("tags"));
}
validateTagCount(tags);
tags.forEach((key, value) -> {
validateTagKey(key, "tags.key");
validateTagString(value, "tags.value", 0, 256);
});
}
private void validateTagCount(Map<String, String> tags) {
String violation = SmithyValidationErrors.sizeOutOfRange("tags", tags.size(), 0, 50);
if (violation != null) {
throw SmithyValidationErrors.validationException(violation);
}
}
private void validateTagKey(String key, String path) {
validateTagString(key, path, 1, 128);
if (key.regionMatches(true, 0, "aws:", 0, 4)) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.Violations.QUOTED
.constraint(path, key, "Member must not start with aws:"));
}
}
private void validateTagString(String value, String path, int minLength, int maxLength) {
if (value == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull(path));
}
String violation = SmithyValidationErrors.lengthOutOfRange(path, value, minLength, maxLength);
if (violation != null) {
throw SmithyValidationErrors.validationException(violation);
}
if (!TAG_CHARACTERS.matcher(value).matches()) {
throw SmithyValidationErrors.validationException(
SmithyValidationErrors.pattern(path, value, TAG_CHARACTERS.pattern()));
}
}
private TaggedResource taggedResource(String resourceArn, String region) {
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(resourceArn);
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Invalid S3 Vectors resource ARN.", 400);
}
boolean index = arn.resource().contains(INDEX_SEGMENT);
String[] parts = arnParts(resourceArn, index, "ValidationException");
ResolvedBucket bucket = inRequestScope(bucketOfArn(resourceArn, parts,
regionResolver::partitionForRegion, "ValidationException"), region);
return new TaggedResource(bucket.region(), bucket.bucketName(), index ? parts[3] : null);
}
private VectorBucket taggedBucket(TaggedResource resource, String resourceArn) {
VectorBucket bucket = getVectorBucket(resource.bucketName(), resource.region());
String storedArn = resource.indexName() == null ? bucket.getVectorBucketArn()
: getIndex(bucket, resource.indexName()).getIndexArn();
if (!resourceArn.equals(storedArn)) {
throw new AwsException("NotFoundException", resource.indexName() == null ? NO_SUCH_BUCKET : NO_SUCH_INDEX, 404);
}
return bucket;
}
private Map<String, String> resourceTags(VectorBucket bucket, TaggedResource resource) {
Map<String, String> tags = resource.indexName() == null ? bucket.getTags()
: getIndex(bucket, resource.indexName()).getTags();
return tags == null ? Map.of() : tags;
}
private void setResourceTags(VectorBucket bucket, TaggedResource resource, Map<String, String> tags) {
if (resource.indexName() == null) {
bucket.setTags(new ConcurrentHashMap<>(tags));
} else {
getIndex(bucket, resource.indexName()).setTags(new ConcurrentHashMap<>(tags));
}
}
private record TaggedResource(String region, String bucketName, String indexName) {}
public void putVectors(String bucketName, String indexName, List<VectorData> vectors, String region) {
synchronized (lockFor(bucketName, region)) {
VectorBucket bucket = getVectorBucket(bucketName, region);
@@ -0,0 +1,54 @@
package io.floci.aws.services.s3vectors;
import io.floci.aws.core.common.TagHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
/** S3 Vectors uses the shared REST tag path for both buckets and indexes. */
@ApplicationScoped
public class S3VectorsTagHandler implements TagHandler {
private final S3VectorsService service;
@Inject
public S3VectorsTagHandler(S3VectorsService service) {
this.service = service;
}
@Override
public String serviceKey() {
return "s3vectors";
}
@Override
public boolean strictTagValidation() {
return true;
}
@Override
public int tagResourceSuccessStatus() {
return 200;
}
@Override
public int untagResourceSuccessStatus() {
return 200;
}
@Override
public Map<String, String> listTags(String region, String arn) {
return service.listTagsForResource(arn, region);
}
@Override
public void tagResource(String region, String arn, Map<String, String> tags) {
service.tagResource(arn, tags, region);
}
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
service.untagResource(arn, tagKeys, region);
}
}
@@ -1,17 +1,26 @@
package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class TagDispatcherTest {
@@ -51,6 +60,37 @@ class TagDispatcherTest {
assertSame(apiGateway, dispatcher.resolveHandler(REST_API, sent("/tags/" + REST_API)));
}
@ParameterizedTest
@ValueSource(strings = {"garbage", "{}", "null"})
void strictTaggingRejectsTrailingTokensBeforeCallingTheService(String trailing) {
when(scheduler.strictTagValidation()).thenReturn(true);
when(scheduler.tagsBodyKey()).thenReturn("tags");
when(scheduler.tagValidationErrorCode()).thenReturn("ValidationException");
HttpHeaders headers = mock(HttpHeaders.class);
try (Response success = Response.ok().build()) {
AwsException error = assertThrows(AwsException.class,
() -> dispatcher.tagResourcePost(headers, GROUP, "{\"tags\":{\"team\":\"ops\"}} " + trailing, success));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
verify(scheduler, never()).tagResource(any(), any(), anyMap());
}
}
@Test
void strictParsingDoesNotChangeTheInjectedMapperOrLenientHandlers() {
when(scheduler.strictTagValidation()).thenReturn(true);
when(scheduler.tagsBodyKey()).thenReturn("tags");
when(apiGateway.tagsBodyKey()).thenReturn("tags");
HttpHeaders headers = mock(HttpHeaders.class);
try (Response success = Response.ok().build()) {
String body = "{\"tags\":{\"team\":\"ops\"}}";
assertSame(success, dispatcher.tagResourcePost(headers, GROUP, body, success));
assertSame(success, dispatcher.tagResourcePost(headers, REST_API, body + " {}", success));
verify(scheduler).tagResource("us-east-1", GROUP, Map.of("team", "ops"));
verify(apiGateway).tagResource("us-east-1", REST_API, Map.of("team", "ops"));
}
}
private static TagHandler handler(String serviceKey) {
TagHandler handler = mock(TagHandler.class);
when(handler.serviceKey()).thenReturn(serviceKey);
@@ -9,14 +9,25 @@ import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
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.AccessDeniedException;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.SignedRestRequests.denied;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* S3 Vectors requests are checked against the caller's policies through its generated routes: a vector bucket call
@@ -32,6 +43,50 @@ class S3VectorsIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@ParameterizedTest
@ValueSource(booleans = {false, true})
void tagOperationsRequireTheirOwnPermissionsOnTheExactResource(boolean index) throws Exception {
String name = bucketName();
String bucketArn = createBucket(name, "{\"team\":\"data\"}");
try {
String indexArn = createIndex(name, "events", "{\"team\":\"web\"}");
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "s3v-tags-", "access",
allow("\"s3vectors:ListTagsForResource\"", index ? indexArn : bucketArn));
S3VectorsClient client = S3VectorsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey())))
.httpClientBuilder(UrlConnectionHttpClient.builder()).build()) {
String arn = index ? indexArn : bucketArn;
String otherArn = index ? bucketArn : indexArn;
Map<String, String> original = Map.of("team", index ? "web" : "data");
assertEquals(original, client.listTagsForResource(request -> request.resourceArn(arn)).tags());
assertThrows(AccessDeniedException.class, () -> client.tagResource(request -> request
.resourceArn(arn).tags(Map.of("team", "changed"))));
assertThrows(AccessDeniedException.class, () -> client.untagResource(request -> request
.resourceArn(arn).tagKeys("team")));
assertEquals(original, client.listTagsForResource(request -> request.resourceArn(arn)).tags());
SignedIamUsers.iam(endpoint, "PutUserPolicy", Map.of("UserName", user.name(), "PolicyName", "access",
"PolicyDocument", allow("[\"s3vectors:ListTagsForResource\",\"s3vectors:TagResource\","
+ "\"s3vectors:UntagResource\"]", arn))).then().statusCode(200);
client.tagResource(request -> request.resourceArn(arn).tags(Map.of("owner", "allowed")));
assertEquals("allowed", client.listTagsForResource(request -> request.resourceArn(arn)).tags().get("owner"));
client.untagResource(request -> request.resourceArn(arn).tagKeys("owner"));
assertEquals(original, client.listTagsForResource(request -> request.resourceArn(arn)).tags());
assertThrows(AccessDeniedException.class, () -> client.listTagsForResource(request -> request
.resourceArn(otherArn)));
assertThrows(AccessDeniedException.class, () -> client.tagResource(request -> request
.resourceArn(otherArn).tags(Map.of("team", "changed"))));
assertThrows(AccessDeniedException.class, () -> client.untagResource(request -> request
.resourceArn(otherArn).tagKeys("team")));
} finally {
send(admin, "/DeleteIndex", index(name, "events")).then().statusCode(200);
}
} finally {
deleteBucket(name);
}
}
@Test
void callerWithoutPermissionsIsRefusedBeforeAVectorBucketIsCreated() throws Exception {
String name = "iam-none-" + UUID.randomUUID().toString().substring(0, 8);
@@ -11,6 +11,7 @@ import io.floci.aws.testing.StorageTestBackends;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -31,6 +32,35 @@ class S3VectorsPersistenceTest {
private static final Instant KNOWN_TIME = Instant.parse("2026-01-01T00:00:00Z");
private static final Instant MIGRATION_TIME = Instant.parse("2026-02-01T00:00:00Z");
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void resourceTagChangesSurviveStorageReload(String mode, @TempDir Path directory) {
Path snapshot = directory.resolve("s3vectors.json");
String bucketArn;
String indexArn;
StorageBackend<String, VectorBucket> first = open(mode, snapshot);
try {
S3VectorsService service = service(first, Clock.fixed(KNOWN_TIME, ZoneOffset.UTC));
bucketArn = service.createVectorBucket("bucket", null, Map.of("remove", "old"), REGION).getVectorBucketArn();
indexArn = service.createIndex("bucket", "index", 2, "float32", "euclidean", List.of(),
null, Map.of("remove", "old"), REGION).getIndexArn();
for (String arn : List.of(bucketArn, indexArn)) {
service.tagResource(arn, Map.of("persisted", "value"), REGION);
service.untagResource(arn, List.of("remove"), REGION);
}
} finally {
StorageTestBackends.close(first);
}
StorageBackend<String, VectorBucket> second = open(mode, snapshot);
try {
S3VectorsService restarted = service(second, Clock.fixed(MIGRATION_TIME, ZoneOffset.UTC));
assertEquals(Map.of("persisted", "value"), restarted.listTagsForResource(bucketArn, REGION));
assertEquals(Map.of("persisted", "value"), restarted.listTagsForResource(indexArn, REGION));
} finally {
StorageTestBackends.close(second);
}
}
@ParameterizedTest
@CsvSource({"persistent,false", "persistent,true", "hybrid,false", "hybrid,true", "wal,false", "wal,true"})
void legacyMetadataIsSavedOnceAndSurvivesReload(String mode, boolean listFirst, @TempDir Path directory)
@@ -12,12 +12,15 @@ import io.floci.aws.services.s3vectors.model.VectorIndex;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -47,6 +50,71 @@ class S3VectorsServiceTest {
};
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void invalidTagsAreRejectedBeforeCreatingOrReplacingResources(boolean index) {
VectorBucket bucket = service.createVectorBucket("bucket", null, Map.of("original", "value"), REGION);
VectorIndex vectorIndex = service.createIndex("bucket", "index", 2, "float32", "euclidean", List.of(),
null, Map.of("original", "value"), REGION);
String arn = index ? vectorIndex.getIndexArn() : bucket.getVectorBucketArn();
for (Map<String, String> tags : List.of(
Map.of("", "value"), Map.of("invalid!", "value"), Map.of("aws:reserved", "value"),
Map.of("x".repeat(129), "value"), Map.of("key", "x".repeat(257)),
Map.of("key", "invalid!"), numberedTags(51))) {
AwsException createError = assertThrows(AwsException.class, () -> {
if (index) {
service.createIndex("bucket", "new-index", 2, "float32", "euclidean", List.of(), null, tags, REGION);
} else {
service.createVectorBucket("new-bucket", null, tags, REGION);
}
});
assertEquals("ValidationException", createError.getErrorCode());
assertEquals(1, service.listVectorBuckets(REGION).size());
assertEquals(1, service.listIndexes("bucket", REGION).size());
AwsException replaceError = assertThrows(AwsException.class, () -> {
if (index) {
service.replaceIndexTags("bucket", "index", tags, REGION);
} else {
service.replaceBucketTags("bucket", tags, REGION);
}
});
assertEquals("ValidationException", replaceError.getErrorCode());
assertEquals(Map.of("original", "value"), service.listTagsForResource(arn, REGION));
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void legacyOverLimitTagsCanBeRemovedBeforeFurtherUpdates(boolean index) {
VectorBucket bucket = service.createVectorBucket("bucket", null, REGION);
VectorIndex vectorIndex = service.createIndex("bucket", "index", 2, "float32", "euclidean", List.of(), REGION);
// Seed an old stored record that predates tag validation.
if (index) {
vectorIndex.setTags(numberedTags(52));
} else {
bucket.setTags(numberedTags(52));
}
String arn = index ? vectorIndex.getIndexArn() : bucket.getVectorBucketArn();
assertEquals(52, service.listTagsForResource(arn, REGION).size());
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> service.tagResource(arn, Map.of("key0", "changed"), REGION)).getErrorCode());
assertEquals("value", service.listTagsForResource(arn, REGION).get("key0"));
service.untagResource(arn, List.of("key51"), REGION);
assertEquals(51, service.listTagsForResource(arn, REGION).size());
service.untagResource(arn, List.of("key50"), REGION);
service.tagResource(arn, Map.of("key0", "changed"), REGION);
assertEquals(50, service.listTagsForResource(arn, REGION).size());
assertEquals("changed", service.listTagsForResource(arn, REGION).get("key0"));
}
private static Map<String, String> numberedTags(int count) {
Map<String, String> tags = new LinkedHashMap<>();
for (int i = 0; i < count; i++) {
tags.put("key" + i, "value");
}
return tags;
}
/**
* IAM's lookup reads the tags of the vector bucket or the index the ARN names, an index's own and not its bucket's,
* as a replace leaves them, and nothing for another account's, another Region's or an unknown one.
@@ -0,0 +1,250 @@
package io.floci.aws.services.s3vectors;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
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.AccessDeniedException;
import software.amazon.awssdk.services.s3vectors.model.NotFoundException;
import software.amazon.awssdk.services.s3vectors.model.ValidationException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class S3VectorsTaggingIntegrationTest {
@TestHTTPResource
URI endpoint;
@ParameterizedTest
@ValueSource(booleans = {false, true})
void sdkTagsMergeAndRemoveWithoutChangingTheOtherResource(boolean index) {
try (S3VectorsClient client = client("us-east-1"); Fixture fixture = fixture(client)) {
String arn = index ? fixture.indexArn() : fixture.bucketArn();
String otherArn = index ? fixture.bucketArn() : fixture.indexArn();
assertEquals(Map.of("created", "original", "keep", "value"),
client.listTagsForResource(request -> request.resourceArn(arn)).tags());
assertEquals(200, client.tagResource(request -> request.resourceArn(arn)
.tags(Map.of("created", "updated", "remove", "yes", "empty", ""))).sdkHttpResponse().statusCode());
assertEquals(Map.of("created", "updated", "keep", "value", "remove", "yes", "empty", ""),
client.listTagsForResource(request -> request.resourceArn(arn)).tags());
assertEquals(200, client.untagResource(request -> request.resourceArn(arn)
.tagKeys("remove", "absent")).sdkHttpResponse().statusCode());
assertEquals(Map.of("created", "updated", "keep", "value", "empty", ""),
client.listTagsForResource(request -> request.resourceArn(arn)).tags());
assertEquals(Map.of("created", "original", "keep", "value"),
client.listTagsForResource(request -> request.resourceArn(otherArn)).tags());
client.untagResource(request -> request.resourceArn(arn).tagKeys("created", "keep", "empty"));
assertEquals(Map.of(), client.listTagsForResource(request -> request.resourceArn(arn)).tags());
client.tagResource(request -> request.resourceArn(arn).tags(Map.of()));
assertThrows(ValidationException.class,
() -> client.untagResource(request -> request.resourceArn(arn).tagKeys(List.of())));
assertTrue(client.listTagsForResource(request -> request.resourceArn(arn)).tags().isEmpty());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void quotaCountsMergedKeysAndFailedUpdatesAreAtomic(boolean index) {
try (S3VectorsClient client = client("us-east-1"); Fixture fixture = fixture(client)) {
String arn = index ? fixture.indexArn() : fixture.bucketArn();
Map<String, String> tags = new LinkedHashMap<>();
for (int i = 0; i < 48; i++) {
tags.put("key" + i, "value");
}
client.tagResource(request -> request.resourceArn(arn).tags(tags));
Map<String, String> before = client.listTagsForResource(request -> request.resourceArn(arn)).tags();
assertEquals(50, before.size());
ValidationException overLimit = assertThrows(ValidationException.class,
() -> client.tagResource(request -> request.resourceArn(arn)
.tags(Map.of("overflow", "value", "created", "should-not-change"))));
assertEquals("1 validation error detected: Value at 'tags' failed to satisfy constraint: "
+ "Member must have length less than or equal to 50", overLimit.awsErrorDetails().errorMessage());
assertEquals(before, client.listTagsForResource(request -> request.resourceArn(arn)).tags());
client.tagResource(request -> request.resourceArn(arn).tags(Map.of("created", "replaced")));
assertEquals("replaced", client.listTagsForResource(request -> request.resourceArn(arn)).tags().get("created"));
client.untagResource(request -> request.resourceArn(arn).tagKeys("key0"));
client.tagResource(request -> request.resourceArn(arn).tags(Map.of("new", "value")));
assertEquals(50, client.listTagsForResource(request -> request.resourceArn(arn)).tags().size());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void invalidTagsAndMissingResourcesReturnModeledErrors(boolean index) {
try (S3VectorsClient client = client("us-east-1"); Fixture fixture = fixture(client)) {
String arn = index ? fixture.indexArn() : fixture.bucketArn();
for (Map<String, String> tags : List.of(
Map.of("", "value"), Map.of("x".repeat(129), "value"), Map.of("invalid!", "value"),
Map.of("aws:reserved", "value"), Map.of("valid", "x".repeat(257)), Map.of("valid", "invalid!"))) {
ValidationException invalid = assertThrows(ValidationException.class,
() -> client.tagResource(request -> request.resourceArn(arn).tags(tags)));
assertTrue(invalid.awsErrorDetails().errorMessage().startsWith("1 validation error detected: "));
assertTrue(invalid.awsErrorDetails().errorMessage().contains("'tags."));
}
ValidationException invalidKey = assertThrows(ValidationException.class,
() -> client.untagResource(request -> request.resourceArn(arn).tagKeys("")));
assertTrue(invalidKey.awsErrorDetails().errorMessage().startsWith("1 validation error detected: "));
assertTrue(invalidKey.awsErrorDetails().errorMessage().contains("'tagKeys'"));
assertEquals(Map.of("created", "original", "keep", "value"),
client.listTagsForResource(request -> request.resourceArn(arn)).tags());
String missing = index ? fixture.bucketArn() + "/index/missing" : fixture.bucketArn() + "-missing";
String missingMessage = index ? "The specified index could not be found"
: "The specified vector bucket could not be found";
NotFoundException missingList = assertThrows(NotFoundException.class,
() -> client.listTagsForResource(request -> request.resourceArn(missing)));
NotFoundException missingTag = assertThrows(NotFoundException.class,
() -> client.tagResource(request -> request.resourceArn(missing).tags(Map.of("key", "value"))));
NotFoundException missingUntag = assertThrows(NotFoundException.class,
() -> client.untagResource(request -> request.resourceArn(missing).tagKeys("key")));
assertEquals(missingMessage, missingList.awsErrorDetails().errorMessage());
assertEquals(missingMessage, missingTag.awsErrorDetails().errorMessage());
assertEquals(missingMessage, missingUntag.awsErrorDetails().errorMessage());
}
}
@ParameterizedTest
@ValueSource(strings = {"us-gov-west-1", "cn-north-1"})
void taggingUsesTheResourceArnInOtherPartitions(String region) {
try (S3VectorsClient client = client(region); Fixture fixture = fixture(client)) {
for (String arn : List.of(fixture.bucketArn(), fixture.indexArn())) {
client.tagResource(request -> request.resourceArn(arn).tags(Map.of("partition", region)));
assertEquals(region, client.listTagsForResource(request -> request.resourceArn(arn)).tags().get("partition"));
client.untagResource(request -> request.resourceArn(arn).tagKeys("partition"));
assertFalse(client.listTagsForResource(request -> request.resourceArn(arn)).tags().containsKey("partition"));
}
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void identicalResourceNamesInDifferentAccountsKeepTheirOwnTags(boolean index) {
String name = "tag-accounts-" + UUID.randomUUID().toString().substring(0, 8);
try (S3VectorsClient firstClient = client("us-east-1", "111111111111");
S3VectorsClient secondClient = client("us-east-1", "222222222222");
Fixture first = fixture(firstClient, name);
Fixture second = fixture(secondClient, name)) {
String firstArn = index ? first.indexArn() : first.bucketArn();
String secondArn = index ? second.indexArn() : second.bucketArn();
firstClient.tagResource(request -> request.resourceArn(firstArn).tags(Map.of("owner", "first")));
secondClient.tagResource(request -> request.resourceArn(secondArn).tags(Map.of("owner", "second")));
Map<String, String> firstTags = firstClient.listTagsForResource(request -> request.resourceArn(firstArn)).tags();
Map<String, String> secondTags = secondClient.listTagsForResource(request -> request.resourceArn(secondArn)).tags();
assertEquals("first", firstTags.get("owner"));
assertEquals("second", secondTags.get("owner"));
assertThrows(AccessDeniedException.class, () -> firstClient.listTagsForResource(request -> request.resourceArn(secondArn)));
assertThrows(AccessDeniedException.class, () -> firstClient.tagResource(request -> request
.resourceArn(secondArn).tags(Map.of("owner", "changed"))));
assertThrows(AccessDeniedException.class, () -> firstClient.untagResource(request -> request
.resourceArn(secondArn).tagKeys("owner")));
assertEquals(firstTags, firstClient.listTagsForResource(request -> request.resourceArn(firstArn)).tags());
assertEquals(secondTags, secondClient.listTagsForResource(request -> request.resourceArn(secondArn)).tags());
}
}
@ParameterizedTest
@ValueSource(strings = {"us-west-2", "us-gov-west-1", "cn-north-1"})
void tagOperationsRejectResourcesOutsideTheRequestRegion(String resourceRegion) {
try (S3VectorsClient eastClient = client("us-east-1");
S3VectorsClient owner = client(resourceRegion);
Fixture fixture = fixture(owner)) {
for (String arn : List.of(fixture.bucketArn(), fixture.indexArn())) {
Map<String, String> before = owner.listTagsForResource(request -> request.resourceArn(arn)).tags();
assertThrows(ValidationException.class, () -> eastClient.listTagsForResource(request -> request.resourceArn(arn)));
assertThrows(ValidationException.class, () -> eastClient.tagResource(request -> request
.resourceArn(arn).tags(Map.of("created", "changed"))));
assertThrows(ValidationException.class, () -> eastClient.untagResource(request -> request
.resourceArn(arn).tagKeys("created")));
assertEquals(before, owner.listTagsForResource(request -> request.resourceArn(arn)).tags());
}
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void tagOperationsRejectAnArnWithTheWrongPartition(boolean index) {
try (S3VectorsClient client = client("us-east-1"); Fixture fixture = fixture(client)) {
String arn = index ? fixture.indexArn() : fixture.bucketArn();
String invalid = arn.replace("arn:aws:", "arn:aws-cn:");
assertThrows(ValidationException.class, () -> client.listTagsForResource(request -> request.resourceArn(invalid)));
assertThrows(ValidationException.class, () -> client.tagResource(request -> request
.resourceArn(invalid).tags(Map.of("created", "changed"))));
assertThrows(ValidationException.class, () -> client.untagResource(request -> request
.resourceArn(invalid).tagKeys("created")));
assertEquals(Map.of("created", "original", "keep", "value"),
client.listTagsForResource(request -> request.resourceArn(arn)).tags());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void malformedJsonDoesNotChangeTags(boolean index) {
try (S3VectorsClient client = client("us-east-1"); Fixture fixture = fixture(client)) {
String arn = index ? fixture.indexArn() : fixture.bucketArn();
String path = "tags/" + URLEncoder.encode(arn, StandardCharsets.UTF_8);
Map<String, String> before = client.listTagsForResource(request -> request.resourceArn(arn)).tags();
for (String trailing : List.of("garbage", "{}", "null")) {
given().urlEncodingEnabled(false).contentType("application/json")
.body("{\"tags\":{\"created\":\"changed\"}} " + trailing)
.when().post(endpoint.resolve(path))
.then().statusCode(400).body(containsString("ValidationException"));
assertEquals(before, client.listTagsForResource(request -> request.resourceArn(arn)).tags());
}
}
}
private Fixture fixture(S3VectorsClient client) {
String name = "tag-vectors-" + UUID.randomUUID().toString().substring(0, 8);
return fixture(client, name);
}
private Fixture fixture(S3VectorsClient client, String name) {
Map<String, String> tags = Map.of("created", "original", "keep", "value");
String bucketArn = client.createVectorBucket(request -> request.vectorBucketName(name).tags(tags)).vectorBucketArn();
try {
String indexArn = client.createIndex(request -> request.vectorBucketName(name).indexName("index")
.dimension(2).dataType("float32").distanceMetric("euclidean").tags(tags)).indexArn();
return new Fixture(client, name, bucketArn, indexArn);
} catch (RuntimeException | Error failure) {
try {
client.deleteVectorBucket(request -> request.vectorBucketName(name));
} catch (RuntimeException | Error cleanup) {
failure.addSuppressed(cleanup);
}
throw failure;
}
}
private S3VectorsClient client(String region) {
return client(region, "test");
}
private S3VectorsClient client(String region, String account) {
return S3VectorsClient.builder().endpointOverride(endpoint).region(Region.of(region))
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test")))
.httpClientBuilder(UrlConnectionHttpClient.builder()).build();
}
private record Fixture(S3VectorsClient client, String name, String bucketArn, String indexArn) implements AutoCloseable {
@Override
public void close() {
client.deleteIndex(request -> request.vectorBucketName(name).indexName("index"));
client.deleteVectorBucket(request -> request.vectorBucketName(name));
}
}
}
@@ -178,6 +178,20 @@ class S3VectorsWriteLockTest {
assertThrows(AwsException.class, () -> service.getVectorBucketPolicy("bucket", null, REGION));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void resourceTagMergesPreserveConcurrentTagsAndVectors(boolean copyOnAccess) throws Exception {
setUp(copyOnAccess);
createIndex();
String arn = service.getIndex("bucket", "index", REGION).getIndexArn();
overlap(() -> service.tagResource(arn, Map.of("first", "value"), REGION),
() -> service.tagResource(arn, Map.of("second", "value"), REGION));
assertEquals(Map.of("first", "value", "second", "value"), service.listTagsForResource(arn, REGION));
overlap(() -> service.untagResource(arn, List.of("first"), REGION), () -> putVector("stored"));
assertEquals(Map.of("second", "value"), service.listTagsForResource(arn, REGION));
assertEquals(1, service.getVectors("bucket", "index", List.of("stored"), REGION).size());
}
private void putVector(String key) {
service.putVectors("bucket", "index", List.of(new VectorData(key, List.of(1.0f), Map.of())), REGION);
}