From 7a57347fbb79c0667a2bcb34b29e7588002179b2 Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Sun, 29 Nov 2026 23:23:51 +0900 Subject: [PATCH] feat(s3tables): add TagResource, UntagResource and ListTagsForResource (#9724) S3 Tables accepted tags only at CreateTableBucket and CreateTable, so a client could not read them back or change them. The three operations are served on their modelled restJson1 routes, POST, DELETE and GET /tag/{resourceArn}, for a table bucket's ARN or a table's ARN. They read and change the tags the create operations store, the same ones IAM reads for aws:ResourceTag conditions, so a tag set with TagResource is what the next request's condition sees. The IAM route and action tables already mapped the routes to s3tables:TagResource, UntagResource and ListTagsForResource. Like S3 Tables' other routes, /tag is rewritten only for a request signed for s3tables, so a path-style S3 request for a bucket named tag still reaches S3. A table keeps its tags through a rename, as its ARN ends in a minted id, and tagging leaves its versionToken. An unknown table bucket answers NotFoundException "The specified bucket does not exist.", and a table ARN whose table or bucket is missing "The specified table does not exist.", as AWS does. TagResource refuses with BadRequestException a missing or non-object tags member, a value that is not a string, a key beginning with aws:, a key outside the tag character set, a key or value outside the modelled lengths (in Smithy's validation wording), or more than 50 tags on the resource counting the ones it already has. The aws:, character set, key length and 50-tag messages are the ones AWS answers. CreateTableBucket and CreateTable now apply the same rules to the tags they are given, and no longer store a null or non-string value as its text. TagResource and UntagResource build the new tags apart and restore the old ones if the save throws, so a failed WAL write leaves nothing visible to ListTagsForResource or IAM resource-tag conditions. Tag condition keys come from generated data, and that table covers only the IAM namespace, so S3 Tables' TagResource and UntagResource stay without aws:RequestTag and aws:TagKeys, as most services' tagging actions do. --- .../java/com/floci/test/S3TablesTest.java | 23 +++ docs/services/index.md | 2 +- docs/services/s3tables.md | 8 + .../services/s3tables/S3TablesController.java | 35 +++- .../s3tables/S3TablesRouteFilter.java | 3 +- .../services/s3tables/S3TablesService.java | 146 ++++++++++++++- .../s3tables/S3TablesIamIntegrationTest.java | 39 ++++ .../s3tables/S3TablesIntegrationTest.java | 124 +++++++++++++ .../S3TablesRouteIntegrationTest.java | 9 +- .../s3tables/S3TablesServiceTest.java | 166 ++++++++++++++++++ 10 files changed, 540 insertions(+), 15 deletions(-) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3TablesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3TablesTest.java index 624f1eb98d..c2d836686a 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3TablesTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3TablesTest.java @@ -212,6 +212,29 @@ class S3TablesTest { @Test @Order(8) + void tagsAndUntagsTheTableBucketAndTheTable() { + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder().resourceArn(bucketArn).build()) + .tags()).containsExactlyEntriesOf(Map.of("suite", "sdk-java")); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder().resourceArn(tableArn).build()) + .tags()).containsExactlyEntriesOf(Map.of("suite", "sdk-java")); + + client.tagResource(TagResourceRequest.builder().resourceArn(bucketArn).tags(Map.of("team", "data")).build()); + client.tagResource(TagResourceRequest.builder().resourceArn(tableArn).tags(Map.of("owner", "alice")).build()); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder().resourceArn(bucketArn).build()) + .tags()).containsOnly(Map.entry("suite", "sdk-java"), Map.entry("team", "data")); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder().resourceArn(tableArn).build()) + .tags()).containsOnly(Map.entry("suite", "sdk-java"), Map.entry("owner", "alice")); + + client.untagResource(UntagResourceRequest.builder().resourceArn(bucketArn).tagKeys("suite", "team").build()); + client.untagResource(UntagResourceRequest.builder().resourceArn(tableArn).tagKeys("suite").build()); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder().resourceArn(bucketArn).build()) + .tags()).isEmpty(); + assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder().resourceArn(tableArn).build()) + .tags()).containsOnly(Map.entry("owner", "alice")); + } + + @Test + @Order(9) void deletesPoliciesAndResourceHierarchy() { client.deleteTablePolicy(DeleteTablePolicyRequest.builder() .tableBucketARN(bucketArn).namespace(NAMESPACE).name(tableName).build()); diff --git a/docs/services/index.md b/docs/services/index.md index 8361e1287d..112d251852 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -30,7 +30,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [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 | 16 | -| [S3 Tables](s3tables.md) | `/buckets`, `/namespaces/*`, `/tables/*` | REST JSON | 27 | +| [S3 Tables](s3tables.md) | `/buckets`, `/namespaces/*`, `/tables/*`, `/tag/*` | REST JSON | 30 | | [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 54 | | [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 | | [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 69 | diff --git a/docs/services/s3tables.md b/docs/services/s3tables.md index 02322c029a..8d38dac6b7 100644 --- a/docs/services/s3tables.md +++ b/docs/services/s3tables.md @@ -44,6 +44,14 @@ was stored with, which ends in its name. | Metadata location | GetTableMetadataLocation, UpdateTableMetadataLocation | | Table policy | PutTablePolicy, GetTablePolicy, DeleteTablePolicy | | Table maintenance | PutTableMaintenanceConfiguration, GetTableMaintenanceConfiguration | +| Tags | TagResource, UntagResource, ListTagsForResource | + +The tag operations take a table bucket's ARN or a table's ARN. They read and +change the same tags `CreateTableBucket` and `CreateTable` store, which IAM +also reads for `aws:ResourceTag/` conditions. A table keeps its tags +through a rename, and tagging leaves its `versionToken` as it is. A resource +holds at most 50 tags, and keys beginning with `aws:` are refused, on create as +on `TagResource`. Tables must use `ICEBERG` format. `UpdateTableMetadataLocation` implements optimistic concurrency: supply the table's current `versionToken`; a stale diff --git a/src/main/java/io/floci/aws/services/s3tables/S3TablesController.java b/src/main/java/io/floci/aws/services/s3tables/S3TablesController.java index 943453f442..0c822c7ebd 100644 --- a/src/main/java/io/floci/aws/services/s3tables/S3TablesController.java +++ b/src/main/java/io/floci/aws/services/s3tables/S3TablesController.java @@ -9,6 +9,7 @@ import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.Encoded; import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; @@ -43,7 +44,7 @@ public class S3TablesController { @Path("/buckets") public Response createTableBucket(@Context HttpHeaders headers, Map request) { TableBucket bucket = service.createTableBucket(string(request, "name"), request.get("encryptionConfiguration"), - request.get("storageClassConfiguration"), stringMap(request.get("tags")), region(headers)); + request.get("storageClassConfiguration"), tags(request.get("tags")), region(headers)); return Response.ok(Map.of("arn", bucket.getArn())).build(); } @@ -164,7 +165,7 @@ public class S3TablesController { @PathParam("namespace") String namespace, Map request) { S3Table table = service.createTable(decode(tableBucketArn), namespace, string(request, "name"), string(request, "format"), request.get("metadata"), request.get("encryptionConfiguration"), request.get("storageClassConfiguration"), - stringMap(request.get("tags")), region(headers)); + tags(request.get("tags")), region(headers)); return Response.ok(Map.of("tableARN", table.getArn(), "versionToken", table.getVersionToken())).build(); } @@ -276,6 +277,29 @@ public class S3TablesController { "configuration", service.getTableMaintenanceConfigurations(arn, namespace, name, region(headers)))).build(); } + @POST + @Path("/tag/{resourceArn}") + public Response tagResource(@Context HttpHeaders headers, @Encoded @PathParam("resourceArn") String resourceArn, + Map request) { + service.tagResource(decode(resourceArn), request == null ? null : tags(request.get("tags")), region(headers)); + return Response.ok(Map.of()).build(); + } + + @DELETE + @Path("/tag/{resourceArn}") + public Response untagResource(@Context HttpHeaders headers, @Encoded @PathParam("resourceArn") String resourceArn, + @QueryParam("tagKeys") List tagKeys) { + service.untagResource(decode(resourceArn), tagKeys, region(headers)); + return Response.noContent().build(); + } + + @GET + @Path("/tag/{resourceArn}") + public Response listTagsForResource(@Context HttpHeaders headers, + @Encoded @PathParam("resourceArn") String resourceArn) { + return Response.ok(Map.of("tags", service.listTagsForResource(decode(resourceArn), region(headers)))).build(); + } + private Map bucketRepresentation(TableBucket bucket) { Map response = new LinkedHashMap<>(); response.put("arn", bucket.getArn()); @@ -331,13 +355,12 @@ public class S3TablesController { private String decode(String value) { return value == null ? null : URLDecoder.decode(value, StandardCharsets.UTF_8); } private String string(Map value, String key) { return value == null ? null : (String) value.get(key); } - @SuppressWarnings("unchecked") - private Map stringMap(Object value) { + private Map tags(Object value) { if (!(value instanceof Map map)) { - return Map.of(); + return null; } Map result = new LinkedHashMap<>(); - map.forEach((key, entry) -> result.put(String.valueOf(key), String.valueOf(entry))); + map.forEach((key, entry) -> result.put(String.valueOf(key), entry instanceof String text ? text : null)); return result; } diff --git a/src/main/java/io/floci/aws/services/s3tables/S3TablesRouteFilter.java b/src/main/java/io/floci/aws/services/s3tables/S3TablesRouteFilter.java index d201dab0d1..7c75b62ea8 100644 --- a/src/main/java/io/floci/aws/services/s3tables/S3TablesRouteFilter.java +++ b/src/main/java/io/floci/aws/services/s3tables/S3TablesRouteFilter.java @@ -27,7 +27,8 @@ public class S3TablesRouteFilter implements ContainerRequestFilter { private static final Predicate PUBLIC_PATHS = SignedServiceRoute.under("/buckets") .or(SignedServiceRoute.under("/get-table")) .or(SignedServiceRoute.under("/namespaces")) - .or(SignedServiceRoute.under("/tables")); + .or(SignedServiceRoute.under("/tables")) + .or(SignedServiceRoute.under("/tag")); private final SignedServiceRoute route; diff --git a/src/main/java/io/floci/aws/services/s3tables/S3TablesService.java b/src/main/java/io/floci/aws/services/s3tables/S3TablesService.java index 2331d2cbec..9cb168446c 100644 --- a/src/main/java/io/floci/aws/services/s3tables/S3TablesService.java +++ b/src/main/java/io/floci/aws/services/s3tables/S3TablesService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; 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.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -24,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.regex.Pattern; @ApplicationScoped public class S3TablesService { @@ -31,6 +33,15 @@ public class S3TablesService { private static final String BUCKET_PREFIX = "bucket/"; private static final String TABLE_INFIX = "/table/"; private static final int LIST_PAGE_SIZE = 1000; + private static final int MAX_TAGS = 50; + private static final int TAG_KEY_MAX = 128; + private static final int TAG_VALUE_MAX = 256; + private static final String RESERVED_TAG_PREFIX = "aws:"; + private static final List TAG_KEY_RULES = SmithyValidationErrors.constraintSet(1, TAG_KEY_MAX, null, null); + private static final List TAG_VALUE_RULES = SmithyValidationErrors.constraintSet(0, TAG_VALUE_MAX, null, null); + private static final Pattern TAG_KEY_CHARS = Pattern.compile("[\\p{L}\\p{N}\\p{Z}_.:/=+@-]*"); + private static final String TAGGED_BUCKET_NOT_FOUND = "The specified bucket does not exist."; + private static final String TAGGED_TABLE_NOT_FOUND = "The specified table does not exist."; private final StorageBackend store; private final RegionResolver regionResolver; @@ -46,6 +57,7 @@ public class S3TablesService { public synchronized TableBucket createTableBucket(String name, Object encryptionConfiguration, Object storageClassConfiguration, Map tags, String region) { validateBucketName(name); + validateCreateTags(tags); String key = storageKey(region, name); String arn = bucketArn(region, name); if (findTableBucket(key, arn).isPresent()) { @@ -134,6 +146,7 @@ public class S3TablesService { if (!"ICEBERG".equals(format)) { throw badRequest("format must be ICEBERG."); } + validateCreateTags(tags); TableBucket bucket = getTableBucket(tableBucketArn, region); Namespace namespace = getNamespace(bucket, namespaceName); if (namespace.getTables().containsKey(name)) { @@ -174,15 +187,50 @@ public class S3TablesService { throw notFound("The table does not exist."); } TableBucket bucket = getTableBucket(tableArn.substring(0, infix), region); - S3Table table = bucket.getNamespaces().values().stream() - .flatMap(namespace -> namespace.getTables().values().stream()) - .filter(candidate -> tableArn.equals(candidate.getArn())) - .findFirst() - .orElseThrow(() -> notFound("The table does not exist.")); + S3Table table = tableByArn(bucket, tableArn).orElseThrow(() -> notFound("The table does not exist.")); withWarehouses(bucket, List.of(table), region); return table; } + /** The tags of the table bucket or the table {@code resourceArn} names, as {@code ListTagsForResource} reads them. */ + public synchronized Map listTagsForResource(String resourceArn, String region) { + return new LinkedHashMap<>(resourceTags(taggedBucket(resourceArn, region), resourceArn)); + } + + /** + * Adds {@code tags} to the table bucket or the table {@code resourceArn} names, replacing the value of a key it + * already has. A table keeps its version token: tagging does not change the table's metadata. + */ + public synchronized void tagResource(String resourceArn, Map tags, String region) { + if (tags == null) { + throw SmithyValidationErrors.badRequest(SmithyValidationErrors.Violations.WITHOUT_VALUES.notNull("tags")); + } + validateTags(tags); + TableBucket bucket = taggedBucket(resourceArn, region); + Map current = resourceTags(bucket, resourceArn); + Map merged = new LinkedHashMap<>(current); + merged.putAll(tags); + requireTagCount(merged); + replaceTags(bucket, current, merged, region); + } + + /** Removes the {@code tagKeys} the table bucket or the table {@code resourceArn} names has; others are ignored. */ + public synchronized void untagResource(String resourceArn, List tagKeys, String region) { + if (tagKeys == null || tagKeys.isEmpty()) { + throw SmithyValidationErrors.badRequest( + SmithyValidationErrors.Violations.WITHOUT_VALUES.notNull("tagKeys")); + } + if (tagKeys.stream().anyMatch(key -> !tagKeyLengthValid(key))) { + throw SmithyValidationErrors.badRequest(SmithyValidationErrors.Violations.WITHOUT_VALUES.constraint( + "tagKeys", null, "Member must satisfy constraint: " + TAG_KEY_RULES)); + } + TableBucket bucket = taggedBucket(resourceArn, region); + Map current = resourceTags(bucket, resourceArn); + Map remaining = new LinkedHashMap<>(current); + tagKeys.forEach(remaining::remove); + replaceTags(bucket, current, remaining, region); + } + /** * The ARN of the table a request names by its table bucket's ARN, its namespace and its name, as IAM asks for it * before the handler runs; empty when there is no such table. Reads only: a table without a warehouse yet keeps @@ -481,6 +529,94 @@ public class S3TablesService { return table; } + private Optional tableByArn(TableBucket bucket, String tableArn) { + return bucket.getNamespaces().values().stream() + .flatMap(namespace -> namespace.getTables().values().stream()) + .filter(candidate -> tableArn.equals(candidate.getArn())) + .findFirst(); + } + + /** + * The table bucket that holds the resource {@code resourceArn} names: that bucket, or the bucket of that table. A + * table ARN whose bucket is missing is a missing table, as AWS answers it. + */ + private TableBucket taggedBucket(String resourceArn, String region) { + int infix = resourceArn == null ? -1 : resourceArn.lastIndexOf(TABLE_INFIX); + try { + return getTableBucket(infix < 0 ? resourceArn : resourceArn.substring(0, infix), region); + } catch (AwsException e) { + if (!"NotFoundException".equals(e.getErrorCode())) { + throw e; + } + throw notFound(infix < 0 ? TAGGED_BUCKET_NOT_FOUND : TAGGED_TABLE_NOT_FOUND); + } + } + + /** The stored, mutable tags of {@code bucket} or of its table {@code resourceArn} names. */ + private Map resourceTags(TableBucket bucket, String resourceArn) { + if (resourceArn.equals(bucket.getArn())) { + return bucket.getTags(); + } + return tableByArn(bucket, resourceArn).orElseThrow(() -> notFound(TAGGED_TABLE_NOT_FOUND)).getTags(); + } + + /** + * Gives {@code current} the {@code replacement} tags and saves the bucket, putting the old tags back if the save + * fails, so a caller told the change failed never reads it. + */ + private void replaceTags(TableBucket bucket, Map current, Map replacement, + String region) { + Map previous = new LinkedHashMap<>(current); + current.clear(); + current.putAll(replacement); + try { + persist(bucket, region); + } catch (RuntimeException e) { + current.clear(); + current.putAll(previous); + throw e; + } + } + + private void validateCreateTags(Map tags) { + if (tags != null) { + validateTags(tags); + requireTagCount(tags); + } + } + + private void validateTags(Map tags) { + List violations = new ArrayList<>(); + if (tags.keySet().stream().anyMatch(key -> !tagKeyLengthValid(key))) { + violations.add(SmithyValidationErrors.Violations.WITHOUT_VALUES.mapKeys("tags", null, TAG_KEY_RULES)); + } + if (tags.values().stream().anyMatch(value -> value == null || value.length() > TAG_VALUE_MAX)) { + violations.add(SmithyValidationErrors.Violations.WITHOUT_VALUES.mapValues("tags", null, TAG_VALUE_RULES)); + } + if (!violations.isEmpty()) { + throw SmithyValidationErrors.badRequest(violations); + } + for (String key : tags.keySet()) { + if (!TAG_KEY_CHARS.matcher(key).matches()) { + throw badRequest("The provided tags are invalid. Tag key can only contain alphanumeric characters, " + + "spaces, and _.:/=+@-"); + } + if (key.startsWith(RESERVED_TAG_PREFIX)) { + throw badRequest("Tags beginning with '" + RESERVED_TAG_PREFIX + "' are reserved for system use."); + } + } + } + + private boolean tagKeyLengthValid(String key) { + return key != null && !key.isEmpty() && key.length() <= TAG_KEY_MAX; + } + + private void requireTagCount(Map tags) { + if (tags.size() > MAX_TAGS) { + throw badRequest("The provided tags are invalid. Number of user tags must not exceed " + MAX_TAGS); + } + } + private String bucketArn(String region, String name) { return AwsArnUtils.Arn.of("s3tables", region, regionResolver.getAccountId(), BUCKET_PREFIX + name).toString(); } diff --git a/src/test/java/io/floci/aws/services/s3tables/S3TablesIamIntegrationTest.java b/src/test/java/io/floci/aws/services/s3tables/S3TablesIamIntegrationTest.java index 50b8b3130b..7dc91b9142 100644 --- a/src/test/java/io/floci/aws/services/s3tables/S3TablesIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3tables/S3TablesIamIntegrationTest.java @@ -200,6 +200,45 @@ class S3TablesIamIntegrationTest { } } + /** + * The tag operations are checked on the table bucket or the table their path names, and the tags + * {@code TagResource} sets are the ones a resource-tag condition then reads. + */ + @Test + void tagOperationsAreCheckedOnTheResourceTheirPathNames() throws Exception { + String bucket = createBucket(); + String events = createTable(bucket, "analytics", "events"); + String orders = createTable(bucket, "analytics", "orders"); + String tagging = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":" + + "[\"s3tables:TagResource\",\"s3tables:UntagResource\",\"s3tables:ListTagsForResource\"]," + + "\"Resource\":\"" + events + "\"},{\"Effect\":\"Allow\",\"Action\":\"s3tables:GetTable\"," + + "\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}]}"; + try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "s3t-iam-", "tagging", tagging)) { + String tags = "{\"tags\":{\"team\":\"data\"}}"; + send(user.signer("s3tables"), "POST", "/tag/" + encoded(events), tags).then().statusCode(200); + denied(send(user.signer("s3tables"), "POST", "/tag/" + encoded(orders), tags), "s3tables:TagResource"); + denied(send(user.signer("s3tables"), "POST", "/tag/" + encoded(bucket), tags), "s3tables:TagResource"); + send(user.signer("s3tables"), "GET", "/tag/" + encoded(events), null).then().statusCode(200) + .body("tags.team", equalTo("data")); + denied(send(user.signer("s3tables"), "GET", "/tag/" + encoded(bucket), null), + "s3tables:ListTagsForResource"); + + send(user.signer("s3tables"), "GET", "/get-table?tableArn=" + encoded(events), null).then() + .statusCode(200); + denied(send(user.signer("s3tables"), "GET", "/get-table?tableArn=" + encoded(orders), null), + "s3tables:GetTable"); + + denied(send(user.signer("s3tables"), "DELETE", "/tag/" + encoded(orders) + "?tagKeys=team", null), + "s3tables:UntagResource"); + send(user.signer("s3tables"), "DELETE", "/tag/" + encoded(events) + "?tagKeys=team", null).then() + .statusCode(204); + denied(send(user.signer("s3tables"), "GET", "/get-table?tableArn=" + encoded(events), null), + "s3tables:GetTable"); + } finally { + deleteBucket(bucket, "analytics"); + } + } + @Test void encryptionReadbackRequiresPermissionOnTheRequestedBucket() throws Exception { String bucket = createBucket(); diff --git a/src/test/java/io/floci/aws/services/s3tables/S3TablesIntegrationTest.java b/src/test/java/io/floci/aws/services/s3tables/S3TablesIntegrationTest.java index 750f794093..4bb2499cc7 100644 --- a/src/test/java/io/floci/aws/services/s3tables/S3TablesIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3tables/S3TablesIntegrationTest.java @@ -199,4 +199,128 @@ class S3TablesIntegrationTest { .statusCode(200) .body("configuration.icebergCompaction.status", equalTo("enabled")); } + + @Test + @Order(6) + void tagsTheTableBucketAndTheTableOnTheTagRoute() { + String tableArn = s3tables() + .urlEncodingEnabled(false) + .when() + .get("/get-table?tableBucketARN=" + ENCODED_BUCKET_ARN + "&namespace=" + NAMESPACE + "&name=" + TABLE_NAME) + .then() + .statusCode(200) + .extract().path("tableARN"); + String encodedTableArn = URLEncoder.encode(tableArn, StandardCharsets.UTF_8); + + s3tables() + .urlEncodingEnabled(false) + .contentType(JSON_CONTENT_TYPE) + .body("{ \"tags\": { \"team\": \"data\", \"env\": \"dev\" } }") + .when() + .post("/tag/" + ENCODED_BUCKET_ARN) + .then() + .statusCode(200) + .body(equalTo("{}")); + s3tables() + .urlEncodingEnabled(false) + .contentType(JSON_CONTENT_TYPE) + .body("{ \"tags\": { \"owner\": \"alice\" } }") + .when() + .post("/tag/" + encodedTableArn) + .then() + .statusCode(200); + + s3tables() + .urlEncodingEnabled(false) + .when() + .get("/tag/" + ENCODED_BUCKET_ARN) + .then() + .statusCode(200) + .contentType(containsString(JSON_CONTENT_TYPE)) + .body("tags.team", equalTo("data")) + .body("tags.env", equalTo("dev")); + s3tables() + .urlEncodingEnabled(false) + .when() + .get("/tag/" + encodedTableArn) + .then() + .statusCode(200) + .body("tags.owner", equalTo("alice")) + .body("tags", not(hasKey("team"))); + + s3tables() + .urlEncodingEnabled(false) + .when() + .delete("/tag/" + ENCODED_BUCKET_ARN + "?tagKeys=env&tagKeys=absent") + .then() + .statusCode(204); + s3tables() + .urlEncodingEnabled(false) + .when() + .get("/tag/" + ENCODED_BUCKET_ARN) + .then() + .statusCode(200) + .body("tags.team", equalTo("data")) + .body("tags", not(hasKey("env"))); + } + + @Test + @Order(7) + void refusesTagsOnAnUnknownResourceReservedKeysAndMalformedBodies() { + s3tables() + .urlEncodingEnabled(false) + .when() + .get("/tag/" + URLEncoder.encode(BUCKET_ARN + "/table/unknown", StandardCharsets.UTF_8)) + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", equalTo("The specified table does not exist.")); + s3tables() + .urlEncodingEnabled(false) + .when() + .get("/tag/" + URLEncoder.encode(BUCKET_ARN + "-missing", StandardCharsets.UTF_8)) + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", equalTo("The specified bucket does not exist.")); + + s3tables() + .urlEncodingEnabled(false) + .contentType(JSON_CONTENT_TYPE) + .body("{ \"tags\": { \"aws:team\": \"data\" } }") + .when() + .post("/tag/" + ENCODED_BUCKET_ARN) + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("Tags beginning with 'aws:' are reserved for system use.")); + + for (String body : new String[] {"{ \"tags\": { \"rejected\": null } }", "{ \"tags\": { \"rejected\": 1 } }", + "{ \"tags\": [\"rejected\"] }", "{ \"tags\": \"rejected\" }", "{}"}) { + s3tables() + .urlEncodingEnabled(false) + .contentType(JSON_CONTENT_TYPE) + .body(body) + .when() + .post("/tag/" + ENCODED_BUCKET_ARN) + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + s3tables() + .urlEncodingEnabled(false) + .when() + .get("/tag/" + ENCODED_BUCKET_ARN) + .then() + .statusCode(200) + .body("tags", not(hasKey("rejected"))); + + s3tables() + .urlEncodingEnabled(false) + .when() + .delete("/tag/" + ENCODED_BUCKET_ARN) + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } } diff --git a/src/test/java/io/floci/aws/services/s3tables/S3TablesRouteIntegrationTest.java b/src/test/java/io/floci/aws/services/s3tables/S3TablesRouteIntegrationTest.java index 80b7e5203e..dff9755ef6 100644 --- a/src/test/java/io/floci/aws/services/s3tables/S3TablesRouteIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3tables/S3TablesRouteIntegrationTest.java @@ -11,6 +11,8 @@ import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.services.s3tables.S3TablesClient; import software.amazon.awssdk.services.s3tables.model.CreateTableBucketResponse; +import java.util.Map; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -19,7 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class S3TablesRouteIntegrationTest { @ParameterizedTest - @ValueSource(strings = {"buckets", "get-table", "namespaces", "tables"}) + @ValueSource(strings = {"buckets", "get-table", "namespaces", "tables", "tag"}) void pathStyleS3RequestsForABucketNamedAfterAnS3TablesRouteReachS3(String bucket) { try (S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1)) { @@ -36,7 +38,7 @@ class S3TablesRouteIntegrationTest { } @ParameterizedTest - @ValueSource(strings = {"buckets", "tables"}) + @ValueSource(strings = {"buckets", "tables", "tag"}) void s3TablesRequestsStillReachS3TablesWhileAnS3BucketHasTheSameName(String name) { try (S3Client s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), "000000000000", Region.US_EAST_1); @@ -46,6 +48,9 @@ class S3TablesRouteIntegrationTest { CreateTableBucketResponse created = tables.createTableBucket(r -> r.name("route-" + name)); try { assertEquals(created.arn(), tables.getTableBucket(r -> r.tableBucketARN(created.arn())).arn()); + tables.tagResource(r -> r.resourceArn(created.arn()).tags(Map.of("env", "test"))); + assertEquals(Map.of("env", "test"), + tables.listTagsForResource(r -> r.resourceArn(created.arn())).tags()); assertTrue(tables.listTableBuckets(r -> { }).tableBuckets().stream() .anyMatch(b -> b.arn().equals(created.arn()))); s3.headBucket(r -> r.bucket(name)); diff --git a/src/test/java/io/floci/aws/services/s3tables/S3TablesServiceTest.java b/src/test/java/io/floci/aws/services/s3tables/S3TablesServiceTest.java index 8ef8c555bd..9e175d78ff 100644 --- a/src/test/java/io/floci/aws/services/s3tables/S3TablesServiceTest.java +++ b/src/test/java/io/floci/aws/services/s3tables/S3TablesServiceTest.java @@ -14,9 +14,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.mockito.Mockito; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -33,6 +36,14 @@ class S3TablesServiceTest { private static final String ACCOUNT_ID = "000000000000"; private static final String REGION = "us-east-1"; private static final String BUCKET = "unit-test-table-bucket"; + private static final String BUCKET_NOT_FOUND = "The specified bucket does not exist."; + private static final String TABLE_NOT_FOUND = "The specified table does not exist."; + private static final String TOO_MANY_TAGS = "The provided tags are invalid. Number of user tags must not exceed 50"; + private static final String KEY_LENGTH = "Value at 'tags' failed to satisfy constraint: Map keys must satisfy " + + "constraint: [Member must have length less than or equal to 128, Member must have length greater than " + + "or equal to 1]"; + private static final String VALUE_LENGTH = "Value at 'tags' failed to satisfy constraint: Map value must satisfy " + + "constraint: [Member must have length less than or equal to 256]"; private S3TablesService service; private S3Service s3Service; @@ -237,6 +248,161 @@ class S3TablesServiceTest { assertError("NotFoundException", () -> service.getTablePolicy(arn, "analytics", "events", REGION)); } + @Test + void tagResourceMergesIntoTheBucketsOrTheTablesTagsAndUntagResourceRemovesThem() { + TableBucket bucket = service.createTableBucket(BUCKET, null, null, Map.of("team", "data"), REGION); + service.createNamespace(bucket.getArn(), List.of("analytics"), REGION); + S3Table table = createTable(bucket.getArn(), "analytics", "events"); + String token = table.getVersionToken(); + + service.tagResource(bucket.getArn(), Map.of("team", "platform", "env", "dev"), REGION); + service.tagResource(table.getArn(), Map.of("owner", "alice"), REGION); + + assertEquals(Map.of("team", "platform", "env", "dev"), service.listTagsForResource(bucket.getArn(), REGION)); + assertEquals(Map.of("owner", "alice"), service.listTagsForResource(table.getArn(), REGION)); + assertEquals(Map.of("team", "platform", "env", "dev"), service.storedTags(bucket.getArn())); + assertEquals(token, service.getTable(bucket.getArn(), "analytics", "events", REGION).getVersionToken(), + "tagging a table leaves its version token"); + + service.untagResource(bucket.getArn(), List.of("env", "absent"), REGION); + service.untagResource(table.getArn(), List.of("owner"), REGION); + + assertEquals(Map.of("team", "platform"), service.listTagsForResource(bucket.getArn(), REGION)); + assertEquals(Map.of(), service.listTagsForResource(table.getArn(), REGION)); + assertEquals(Map.of(), service.storedTags(table.getArn())); + } + + @Test + void aFailedSaveLeavesTheTagsTagResourceAndUntagResourceWouldHaveChanged() { + TableBucket bucket = service.createTableBucket(BUCKET, null, null, Map.of("team", "data"), REGION); + service.createNamespace(bucket.getArn(), List.of("analytics"), REGION); + S3Table table = service.createTable(bucket.getArn(), "analytics", "events", "ICEBERG", null, null, null, + Map.of("owner", "alice"), REGION); + Mockito.doThrow(new IllegalStateException("disk full")).when(store).put(Mockito.anyString(), Mockito.any()); + + assertThrows(IllegalStateException.class, + () -> service.tagResource(bucket.getArn(), Map.of("team", "platform", "env", "dev"), REGION)); + assertThrows(IllegalStateException.class, + () -> service.untagResource(table.getArn(), List.of("owner"), REGION)); + + Mockito.doCallRealMethod().when(store).put(Mockito.anyString(), Mockito.any()); + assertEquals(Map.of("team", "data"), service.listTagsForResource(bucket.getArn(), REGION)); + assertEquals(Map.of("owner", "alice"), service.listTagsForResource(table.getArn(), REGION)); + assertEquals(Map.of("owner", "alice"), service.storedTags(table.getArn())); + } + + @Test + void aRenamedTableKeepsItsTagsUnderItsArn() { + String arn = createBucketWithNamespace("analytics"); + S3Table table = createTable(arn, "analytics", "events"); + service.tagResource(table.getArn(), Map.of("owner", "alice"), REGION); + + service.renameTable(arn, "analytics", "events", null, "daily_events", null, REGION); + + assertEquals(Map.of("owner", "alice"), service.listTagsForResource(table.getArn(), REGION)); + } + + @Test + void tagOperationsOnAResourceThatDoesNotExistAreNotFound() { + String arn = createBucketWithNamespace("analytics"); + S3Table table = createTable(arn, "analytics", "events"); + service.deleteTable(arn, "analytics", "events", REGION); + String otherBucket = arn.replace(BUCKET, "other-bucket"); + + assertNotFound(TABLE_NOT_FOUND, () -> service.listTagsForResource(table.getArn(), REGION)); + assertNotFound(TABLE_NOT_FOUND, () -> service.tagResource(table.getArn(), Map.of("k", "v"), REGION)); + assertNotFound(TABLE_NOT_FOUND, () -> service.untagResource(table.getArn(), List.of("k"), REGION)); + assertNotFound(TABLE_NOT_FOUND, () -> service.listTagsForResource(otherBucket + "/table/" + UUID.randomUUID(), + REGION)); + assertNotFound(BUCKET_NOT_FOUND, () -> service.listTagsForResource(otherBucket, REGION)); + assertNotFound(BUCKET_NOT_FOUND, () -> service.listTagsForResource(arn.replace(REGION, "eu-west-1"), REGION)); + assertNotFound(BUCKET_NOT_FOUND, () -> service.listTagsForResource(arn + "/namespace/analytics", REGION)); + assertNotFound(BUCKET_NOT_FOUND, () -> service.listTagsForResource("not-an-arn", REGION)); + } + + @Test + void tagResourceRefusesTagsAwsWouldNotStore() { + TableBucket bucket = createBucket(); + String arn = bucket.getArn(); + + assertBadRequest("Tags beginning with 'aws:' are reserved for system use.", + () -> service.tagResource(arn, Map.of("aws:team", "data"), REGION)); + assertBadRequest("The provided tags are invalid. Tag key can only contain alphanumeric characters, " + + "spaces, and _.:/=+@-", () -> service.tagResource(arn, Map.of("team#1", "data"), REGION)); + assertBadRequest(oneViolation("Value at 'tags' failed to satisfy constraint: Member must not be null"), + () -> service.tagResource(arn, null, REGION)); + assertBadRequest(oneViolation(KEY_LENGTH), () -> service.tagResource(arn, Map.of("", "data"), REGION)); + assertBadRequest(oneViolation(KEY_LENGTH), () -> service.tagResource(arn, Map.of("k".repeat(129), "v"), REGION)); + assertBadRequest(oneViolation(VALUE_LENGTH), + () -> service.tagResource(arn, Map.of("k", "v".repeat(257)), REGION)); + assertBadRequest("2 validation errors detected: " + KEY_LENGTH + "; " + VALUE_LENGTH, + () -> service.tagResource(arn, Map.of("k".repeat(129), "v".repeat(257)), REGION)); + Map nullValue = new HashMap<>(); + nullValue.put("k", null); + assertBadRequest(oneViolation(VALUE_LENGTH), () -> service.tagResource(arn, nullValue, REGION)); + assertBadRequest(oneViolation("Value at 'tagKeys' failed to satisfy constraint: Member must not be null"), + () -> service.untagResource(arn, List.of(), REGION)); + assertBadRequest(oneViolation("Value at 'tagKeys' failed to satisfy constraint: Member must satisfy " + + "constraint: [Member must have length less than or equal to 128, Member must have length greater " + + "than or equal to 1]"), () -> service.untagResource(arn, List.of("k".repeat(129)), REGION)); + assertEquals(Map.of(), service.listTagsForResource(arn, REGION)); + + service.tagResource(arn, Map.of("k".repeat(128), "v".repeat(256), "empty", ""), REGION); + assertEquals(2, service.listTagsForResource(arn, REGION).size()); + } + + @Test + void tagResourceCountsTheTagsTheResourceAlreadyHasAgainstTheLimitOfFifty() { + String arn = createBucket().getArn(); + service.tagResource(arn, numberedTags(0, 49), REGION); + service.tagResource(arn, Map.of("key-0", "replaced"), REGION); + + assertBadRequest(TOO_MANY_TAGS, + () -> service.tagResource(arn, numberedTags(49, 51), REGION)); + assertEquals(49, service.listTagsForResource(arn, REGION).size()); + service.tagResource(arn, numberedTags(49, 50), REGION); + assertEquals(50, service.listTagsForResource(arn, REGION).size()); + } + + @Test + void createRefusesTheTagsTagResourceRefuses() { + assertBadRequest("Tags beginning with 'aws:' are reserved for system use.", + () -> service.createTableBucket(BUCKET, null, null, Map.of("aws:team", "data"), REGION)); + assertBadRequest(TOO_MANY_TAGS, + () -> service.createTableBucket(BUCKET, null, null, numberedTags(0, 51), REGION)); + assertEquals(List.of(), service.listTableBuckets(null, REGION)); + String arn = createBucketWithNamespace("analytics"); + assertBadRequest("Tags beginning with 'aws:' are reserved for system use.", + () -> service.createTable(arn, "analytics", "events", "ICEBERG", null, null, null, + Map.of("aws:team", "data"), REGION)); + assertError("NotFoundException", () -> service.getTable(arn, "analytics", "events", REGION)); + } + + private static Map numberedTags(int from, int to) { + Map tags = new LinkedHashMap<>(); + for (int i = from; i < to; i++) { + tags.put("key-" + i, "value"); + } + return tags; + } + + private static String oneViolation(String violation) { + return "1 validation error detected: " + violation; + } + + private void assertNotFound(String expectedMessage, Executable action) { + AwsException exception = assertThrows(AwsException.class, action); + assertEquals("NotFoundException", exception.getErrorCode()); + assertEquals(expectedMessage, exception.getMessage()); + } + + private void assertBadRequest(String expectedMessage, Executable action) { + AwsException exception = assertThrows(AwsException.class, action); + assertEquals("BadRequestException", exception.getErrorCode()); + assertEquals(400, exception.getHttpStatus()); + assertEquals(expectedMessage, exception.getMessage()); + } + private TableBucket createBucket() { return service.createTableBucket(BUCKET, null, null, Map.of(), REGION); }