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

@@ -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);
}