From efd897124162322738eec749f3bb5260070e0ae4 Mon Sep 17 00:00:00 2001 From: Niels Kootstra <545768+nkootstra@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:23:21 +0100 Subject: [PATCH] fix(cur): keep report definition tags and serve the tag operations (#8095) PutReportDefinition now stores its Tags on the report definition, and TagResource, UntagResource and ListTagsForResource read and change them by ReportName instead of answering empty stubs. ModifyReportDefinition keeps the tags, a missing report answers ResourceNotFoundException, and the TagList and TagKeyList constraints from the model are checked. Closes #7952 PutReportDefinition and TagResource now fail with ValidationException when the report would hold more than 50 tags, when Tags is not a list, or when a tag key, value or TagKeys entry is not a string. tools/aws/regen_cur_shapes.py vendors the TagResource, UntagResource and ListTagsForResource input constraints from botocore, and CurRequestShapes checks them, and the Tags of PutReportDefinition, through RequestConstraintCheck in place of the hand-written limits. --- Makefile | 7 + docs/services/cur.md | 13 +- pom.xml | 6 + .../aws/services/cur/CurJsonHandler.java | 47 +++- .../aws/services/cur/CurRequestShapes.java | 31 +++ .../io/floci/aws/services/cur/CurService.java | 53 ++++- .../services/cur/model/ReportDefinition.java | 7 + .../resources/aws/cur-request-shapes.json | 84 +++++++ ...urReportDefinitionTagsIntegrationTest.java | 208 ++++++++++++++++++ tools/aws/regen_cur_shapes.py | 29 +++ tools/aws/test_request_shapes.py | 2 + 11 files changed, 470 insertions(+), 17 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/cur/CurRequestShapes.java create mode 100644 src/main/resources/aws/cur-request-shapes.json create mode 100644 src/test/java/io/floci/aws/services/cur/CurReportDefinitionTagsIntegrationTest.java create mode 100644 tools/aws/regen_cur_shapes.py diff --git a/Makefile b/Makefile index 234e252f36..7106b9abf4 100644 --- a/Makefile +++ b/Makefile @@ -27,6 +27,8 @@ # from botocore's ECR model by tools/aws/regen_ecr_shapes.py. # Athena request constraints for every operation are generated from botocore's Athena model # by tools/aws/regen_athena_shapes.py. +# src/main/resources/aws/cur-request-shapes.json, the Cost and Usage Reports tag operations' +# request constraints, is generated from botocore's CUR model by tools/aws/regen_cur_shapes.py. # src/main/resources/aws/payment-cryptography-request-shapes.json, the Payment Cryptography # request constraints, is generated from botocore's model by # tools/aws/regen_payment_cryptography_shapes.py. @@ -283,6 +285,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s $(PYTHON) tools/aws/regen_logs_delivery_shapes.py $(PYTHON) tools/aws/regen_ecr_shapes.py $(PYTHON) tools/aws/regen_athena_shapes.py + $(PYTHON) tools/aws/regen_cur_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_data_shapes.py $(PYTHON) tools/aws/regen_securityhub_shapes.py @@ -380,6 +383,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres echo "error: Athena request shapes are out of date; run 'make aws-data-sync'."; \ exit 1; \ } + @$(PYTHON) tools/aws/regen_cur_shapes.py --check || { \ + echo "error: CUR request shapes are out of date; run 'make aws-data-sync'."; \ + exit 1; \ + } @$(PYTHON) tools/aws/regen_payment_cryptography_shapes.py --check || { \ echo ""; \ echo "error: src/main/resources/aws/payment-cryptography-request-shapes.json is out of date."; \ diff --git a/docs/services/cur.md b/docs/services/cur.md index 338a839e6b..2dc7075d9a 100644 --- a/docs/services/cur.md +++ b/docs/services/cur.md @@ -12,15 +12,22 @@ real Parquet artifacts in Floci's S3 service via the `floci-duck` sidecar. | Operation | Notes | |-----------|-------| -| `PutReportDefinition` | Creates a new report; rejects duplicates with `DuplicateReportNameException`; enforces a 5-report-per-account limit | -| `ModifyReportDefinition` | Replaces an existing report's mutable fields | +| `PutReportDefinition` | Creates a new report with its `Tags`; rejects duplicates with `DuplicateReportNameException`; enforces a 5-report-per-account limit | +| `ModifyReportDefinition` | Replaces an existing report's mutable fields; its tags are kept | | `DescribeReportDefinitions` | Returns every report owned by the calling account | | `DeleteReportDefinition` | Idempotent; removing a missing report returns 200 | -| `TagResource` / `UntagResource` / `ListTagsForResource` | Stub responses (empty bodies) so SDK clients that probe for them succeed | +| `TagResource` / `UntagResource` / `ListTagsForResource` | Tag a report definition by `ReportName`. `TagResource` replaces the value of a key the report already has, and `UntagResource` ignores a key it does not have. A missing report answers `ResourceNotFoundException` | ## Validation rules - `ReportName`: alphanumerics + `-_`, max 256 chars +- `Tags`: up to 200 in one request, each a `Key` of 1 to 128 characters and a `Value` of up to 256. A report holds at most 50 tags, so a `PutReportDefinition` or `TagResource` that would leave it with more fails with `ValidationException` + +The tag operations, and the `Tags` of `PutReportDefinition`, are checked by `RequestConstraintCheck` +against the types, required members and bounds generated from botocore's CUR service model. +`tools/aws/regen_cur_shapes.py` vendors them; `make aws-data-sync` regenerates them and +`make aws-data-check` checks for drift. The 50-tag limit is documented in the model's prose only, +so Floci enforces it separately. - `TimeUnit`: `HOURLY` / `DAILY` / `MONTHLY` - `Format`: `Parquet` (CSV emission not yet implemented; `textORcsv` returns `ValidationException`) - `Compression`: `Parquet` (`ZIP` / `GZIP` not yet implemented) diff --git a/pom.xml b/pom.xml index 824dcb2df1..1529b12176 100644 --- a/pom.xml +++ b/pom.xml @@ -488,6 +488,12 @@ ${aws.sdk.version} test + + software.amazon.awssdk + costandusagereport + ${aws.sdk.version} + test + software.amazon.awssdk servicediscovery diff --git a/src/main/java/io/floci/aws/services/cur/CurJsonHandler.java b/src/main/java/io/floci/aws/services/cur/CurJsonHandler.java index 5d9ab5d2db..46c582fb60 100644 --- a/src/main/java/io/floci/aws/services/cur/CurJsonHandler.java +++ b/src/main/java/io/floci/aws/services/cur/CurJsonHandler.java @@ -13,7 +13,9 @@ import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * JSON 1.1 handler for AWS CUR operations. @@ -38,19 +40,15 @@ public class CurJsonHandler { public Response handle(String action, JsonNode request, String region) { LOG.debugv("CUR action: {0}", action); + CurRequestShapes.check(action, request); return switch (action) { case "PutReportDefinition" -> handlePutReportDefinition(request, region); case "ModifyReportDefinition" -> handleModifyReportDefinition(request, region); case "DescribeReportDefinitions" -> handleDescribeReportDefinitions(); case "DeleteReportDefinition" -> handleDeleteReportDefinition(request, region); - // Tag endpoints are not yet emulated; respond with empty bodies so SDK - // clients that probe for them don't trip on UnknownOperationException. - case "TagResource", "UntagResource" -> Response.ok(objectMapper.createObjectNode()).build(); - case "ListTagsForResource" -> { - ObjectNode body = objectMapper.createObjectNode(); - body.putArray("Tags"); - yield Response.ok(body).build(); - } + case "TagResource" -> handleTagResource(request, region); + case "UntagResource" -> handleUntagResource(request, region); + case "ListTagsForResource" -> handleListTagsForResource(request, region); default -> Response.status(400) .entity(new AwsErrorResponse("UnknownOperationException", "Unknown operation: AWSOrigamiServiceGatewayService." + action)) @@ -59,7 +57,9 @@ public class CurJsonHandler { } private Response handlePutReportDefinition(JsonNode request, String region) { + CurRequestShapes.checkTags(request.get("Tags")); ReportDefinition def = parseReportDefinition(request.path("ReportDefinition")); + def.setTags(parseTags(request.path("Tags"))); ReportDefinition created = service.putReportDefinition(def, region); // Emission failures must not roll back the management mutation — match AWS // semantics where the definition is created even if the first run errors. @@ -104,6 +104,37 @@ public class CurJsonHandler { return Response.ok(response).build(); } + private Response handleTagResource(JsonNode request, String region) { + service.tagResource(stringOrNull(request, "ReportName"), parseTags(request.path("Tags")), region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleUntagResource(JsonNode request, String region) { + service.untagResource(stringOrNull(request, "ReportName"), parseTagKeys(request.path("TagKeys")), region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleListTagsForResource(JsonNode request, String region) { + Map tags = service.listTags(stringOrNull(request, "ReportName"), region); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode list = response.putArray("Tags"); + tags.forEach((key, value) -> list.addObject().put("Key", key).put("Value", value)); + return Response.ok(response).build(); + } + + /** The tags of a request checked by {@link CurRequestShapes}; none when it has no {@code Tags}. */ + private static Map parseTags(JsonNode node) { + Map tags = new LinkedHashMap<>(); + node.forEach(tag -> tags.put(tag.get("Key").textValue(), tag.get("Value").textValue())); + return tags; + } + + private static List parseTagKeys(JsonNode node) { + List keys = new ArrayList<>(); + node.forEach(key -> keys.add(key.textValue())); + return keys; + } + private ReportDefinition parseReportDefinition(JsonNode node) { if (node == null || !node.isObject() || node.isEmpty()) { throw new AwsException("ValidationException", diff --git a/src/main/java/io/floci/aws/services/cur/CurRequestShapes.java b/src/main/java/io/floci/aws/services/cur/CurRequestShapes.java new file mode 100644 index 0000000000..7130001b42 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cur/CurRequestShapes.java @@ -0,0 +1,31 @@ +package io.floci.aws.services.cur; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.RequestConstraintCheck; + +/** + * Checks the Cost and Usage Reports tag operations, and the {@code Tags} of {@code PutReportDefinition}, + * against the constraints generated by {@code tools/aws/regen_cur_shapes.py}. + */ +final class CurRequestShapes { + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( + "aws/cur-request-shapes.json", "CUR request shapes", + RequestConstraintCheck.standardMessages("ValidationException")); + + private CurRequestShapes() { + } + + static void check(String operation, JsonNode request) { + if (CHECK.hasOperation(operation)) { + CHECK.check(operation, request); + } + } + + /** Checks a request's {@code Tags} member, when it has one, as a {@code TagList}. */ + static void checkTags(JsonNode tags) { + if (tags != null && !tags.isNull()) { + CHECK.checkShape("TagList", tags); + } + } +} diff --git a/src/main/java/io/floci/aws/services/cur/CurService.java b/src/main/java/io/floci/aws/services/cur/CurService.java index 65462b458c..ec2950d617 100644 --- a/src/main/java/io/floci/aws/services/cur/CurService.java +++ b/src/main/java/io/floci/aws/services/cur/CurService.java @@ -42,6 +42,7 @@ public class CurService { /** AWS hard limit per account: 5 report definitions. */ private static final int MAX_REPORTS_PER_ACCOUNT = 5; + private static final int MAX_TAGS_PER_REPORT = 50; /** AWS allows the report name to contain alphanumerics, hyphens, and underscores. */ private static final Pattern REPORT_NAME_PATTERN = Pattern.compile("[A-Za-z0-9_-]+"); @@ -76,8 +77,9 @@ public class CurService { } /** {@code PutReportDefinition} — creates a new report. Fails if one already exists. */ - public ReportDefinition putReportDefinition(ReportDefinition definition, String region) { + public synchronized ReportDefinition putReportDefinition(ReportDefinition definition, String region) { validateReportDefinition(definition); + requireTagLimit(definition.getTags()); String key = compositeKey(region, definition.getReportName()); if (store.get(key).isPresent()) { @@ -101,8 +103,8 @@ public class CurService { return definition; } - /** {@code ModifyReportDefinition} — replaces an existing report's definition. */ - public ReportDefinition modifyReportDefinition(String reportName, ReportDefinition incoming, String region) { + /** {@code ModifyReportDefinition}: replaces an existing report's definition, keeping its tags. */ + public synchronized ReportDefinition modifyReportDefinition(String reportName, ReportDefinition incoming, String region) { requireNonEmpty(reportName, "ReportName"); if (!reportName.equals(incoming.getReportName())) { throw new AwsException("ValidationException", @@ -116,6 +118,7 @@ public class CurService { "Report " + reportName + " not found.", 400)); incoming.setCreatedDate(existing.getCreatedDate()); + incoming.setTags(existing.getTags()); incoming.setLastUpdatedDate(Instant.now()); incoming.setReportStatus(existing.getReportStatus() == null ? "PENDING" : existing.getReportStatus()); incoming.setOwnerAccountId(existing.getOwnerAccountId() != null @@ -179,7 +182,7 @@ public class CurService { * success/error to {@code DescribeReportDefinitions} consumers. Silent * no-op if the report has been deleted in the meantime. */ - public void markReportStatus(String reportName, String region, String status) { + public synchronized void markReportStatus(String reportName, String region, String status) { if (reportName == null || region == null || status == null) { return; } @@ -197,7 +200,7 @@ public class CurService { * directly under {@code accountId} rather than relying on the request * context. */ - public void markReportStatusForAccount(String accountId, String reportName, String region, String status) { + public synchronized void markReportStatusForAccount(String accountId, String reportName, String region, String status) { if (accountId == null || reportName == null || region == null || status == null) { return; } @@ -216,8 +219,46 @@ public class CurService { }); } + /** {@code ListTagsForResource}: the tags of the named report definition. */ + public Map listTags(String reportName, String region) { + return existingReport(reportName, region).getTags(); + } + + /** {@code TagResource}: adds the tags, replacing the value of a key the report already has. */ + public synchronized void tagResource(String reportName, Map tags, String region) { + ReportDefinition report = existingReport(reportName, region); + Map merged = new LinkedHashMap<>(report.getTags()); + merged.putAll(tags); + requireTagLimit(merged); + report.setTags(merged); + store.put(compositeKey(region, reportName), report); + } + + /** {@code UntagResource}: removes the keys; a key the report does not have is ignored. */ + public synchronized void untagResource(String reportName, List tagKeys, String region) { + ReportDefinition report = existingReport(reportName, region); + Map remaining = new LinkedHashMap<>(report.getTags()); + tagKeys.forEach(remaining::remove); + report.setTags(remaining); + store.put(compositeKey(region, reportName), report); + } + + private static void requireTagLimit(Map tags) { + if (tags.size() > MAX_TAGS_PER_REPORT) { + throw new AwsException("ValidationException", + "A report definition can have up to " + MAX_TAGS_PER_REPORT + " tags.", 400); + } + } + + private ReportDefinition existingReport(String reportName, String region) { + requireNonEmpty(reportName, "ReportName"); + return store.get(compositeKey(region, reportName)).orElseThrow(() -> new AwsException( + "ResourceNotFoundException", + "The specified report (" + reportName + ") in the request doesn't exist.", 400)); + } + /** {@code DeleteReportDefinition} — removes a report; idempotent (returns null when absent). */ - public ReportDefinition deleteReportDefinition(String reportName, String region) { + public synchronized ReportDefinition deleteReportDefinition(String reportName, String region) { requireNonEmpty(reportName, "ReportName"); String key = compositeKey(region, reportName); ReportDefinition existing = store.get(key).orElse(null); diff --git a/src/main/java/io/floci/aws/services/cur/model/ReportDefinition.java b/src/main/java/io/floci/aws/services/cur/model/ReportDefinition.java index 9438813aeb..53def69c97 100644 --- a/src/main/java/io/floci/aws/services/cur/model/ReportDefinition.java +++ b/src/main/java/io/floci/aws/services/cur/model/ReportDefinition.java @@ -5,7 +5,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * AWS CUR (Cost and Usage Report) {@code ReportDefinition} record. @@ -31,6 +33,8 @@ public class ReportDefinition { private Instant createdDate; private Instant lastUpdatedDate; private String reportStatus; // SUCCESS | ERROR | PENDING + /** The report definition resource's tags. Not part of the {@code ReportDefinition} wire shape. */ + private Map tags = new LinkedHashMap<>(); /** * Snapshot of the account that owned the request that created this report. * Used by the background emission scheduler to locate the report under the @@ -87,6 +91,9 @@ public class ReportDefinition { public String getReportStatus() { return reportStatus; } public void setReportStatus(String v) { this.reportStatus = v; } + public Map getTags() { return tags; } + public void setTags(Map v) { this.tags = v; } + public String getOwnerAccountId() { return ownerAccountId; } public void setOwnerAccountId(String v) { this.ownerAccountId = v; } } diff --git a/src/main/resources/aws/cur-request-shapes.json b/src/main/resources/aws/cur-request-shapes.json new file mode 100644 index 0000000000..83c4c6f37f --- /dev/null +++ b/src/main/resources/aws/cur-request-shapes.json @@ -0,0 +1,84 @@ +{ + "_source": { + "generator": "tools/aws/regen_cur_shapes.py", + "botocore": "botocore 1.43.118 (installed package)" + }, + "operations": { + "ListTagsForResource": "ListTagsForResourceRequest", + "TagResource": "TagResourceRequest", + "UntagResource": "UntagResourceRequest" + }, + "shapes": { + "ListTagsForResourceRequest": { + "type": "structure", + "required": [ + "ReportName" + ], + "members": { + "ReportName": "ReportName" + } + }, + "ReportName": { + "type": "string", + "max": 256, + "pattern": "[0-9A-Za-z!\\-_.*\\'()]+" + }, + "Tag": { + "type": "structure", + "required": [ + "Key", + "Value" + ], + "members": { + "Key": "TagKey", + "Value": "TagValue" + } + }, + "TagKey": { + "type": "string", + "min": 1, + "max": 128, + "pattern": ".*" + }, + "TagKeyList": { + "type": "list", + "min": 0, + "max": 200, + "member": "TagKey" + }, + "TagList": { + "type": "list", + "min": 0, + "max": 200, + "member": "Tag" + }, + "TagResourceRequest": { + "type": "structure", + "required": [ + "ReportName", + "Tags" + ], + "members": { + "ReportName": "ReportName", + "Tags": "TagList" + } + }, + "TagValue": { + "type": "string", + "min": 0, + "max": 256, + "pattern": ".*" + }, + "UntagResourceRequest": { + "type": "structure", + "required": [ + "ReportName", + "TagKeys" + ], + "members": { + "ReportName": "ReportName", + "TagKeys": "TagKeyList" + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/cur/CurReportDefinitionTagsIntegrationTest.java b/src/test/java/io/floci/aws/services/cur/CurReportDefinitionTagsIntegrationTest.java new file mode 100644 index 0000000000..94a646b11e --- /dev/null +++ b/src/test/java/io/floci/aws/services/cur/CurReportDefinitionTagsIntegrationTest.java @@ -0,0 +1,208 @@ +package io.floci.aws.services.cur; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.costandusagereport.CostAndUsageReportClient; +import software.amazon.awssdk.services.costandusagereport.model.AdditionalArtifact; +import software.amazon.awssdk.services.costandusagereport.model.CompressionFormat; +import software.amazon.awssdk.services.costandusagereport.model.ReportDefinition; +import software.amazon.awssdk.services.costandusagereport.model.ReportFormat; +import software.amazon.awssdk.services.costandusagereport.model.ReportVersioning; +import software.amazon.awssdk.services.costandusagereport.model.ResourceNotFoundException; +import software.amazon.awssdk.services.costandusagereport.model.SchemaElement; +import software.amazon.awssdk.services.costandusagereport.model.Tag; +import software.amazon.awssdk.services.costandusagereport.model.TimeUnit; +import software.amazon.awssdk.services.costandusagereport.model.ValidationException; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.stream.IntStream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class CurReportDefinitionTagsIntegrationTest { + + private static final String ACCOUNT = "100000007952"; + + private CostAndUsageReportClient cur; + private String reportName; + + @BeforeEach + void createClient() { + cur = AwsTestClients.create(CostAndUsageReportClient.builder(), ACCOUNT, Region.US_EAST_1); + reportName = "tags-" + UUID.randomUUID().toString().substring(0, 8); + } + + @AfterEach + void deleteReportAndCloseClient() { + try { + cur.deleteReportDefinition(r -> r.reportName(reportName)); + } finally { + cur.close(); + } + } + + @Test + void tagsGivenToPutReportDefinitionAreListed() { + putReport(List.of(tag("team", "red"))); + + assertEquals(List.of(tag("team", "red")), listTags()); + } + + @Test + void tagResourceAddsAndOverwritesTagsAndUntagResourceRemovesThem() { + putReport(List.of(tag("team", "red"), tag("stage", "test"))); + + cur.tagResource(r -> r.reportName(reportName).tags(tag("env", "dev"), tag("team", "blue"))); + assertEquals(List.of(tag("team", "blue"), tag("stage", "test"), tag("env", "dev")), listTags()); + + cur.untagResource(r -> r.reportName(reportName).tagKeys("stage", "absent")); + assertEquals(List.of(tag("team", "blue"), tag("env", "dev")), listTags()); + } + + @Test + void modifyReportDefinitionKeepsTheReportsTags() { + putReport(List.of(tag("team", "red"))); + + cur.modifyReportDefinition(r -> r.reportName(reportName) + .reportDefinition(definition().toBuilder().s3Prefix("moved").build())); + + assertEquals(List.of(tag("team", "red")), listTags()); + } + + @Test + void aReportWithoutTagsListsNone() { + putReport(List.of()); + + assertTrue(listTags().isEmpty()); + } + + @Test + void tagOperationsOnAMissingReportAnswerResourceNotFound() { + String missing = reportName + "-missing"; + + assertThrows(ResourceNotFoundException.class, () -> cur.listTagsForResource(r -> r.reportName(missing))); + assertThrows(ResourceNotFoundException.class, + () -> cur.tagResource(r -> r.reportName(missing).tags(tag("team", "red")))); + assertThrows(ResourceNotFoundException.class, + () -> cur.untagResource(r -> r.reportName(missing).tagKeys("team"))); + } + + @Test + void aTagKeyLongerThan128CharactersIsRejected() { + putReport(List.of()); + + ValidationException error = assertThrows(ValidationException.class, + () -> cur.tagResource(r -> r.reportName(reportName).tags(tag("k".repeat(129), "v")))); + + assertTrue(error.getMessage().contains("'Tags.Key'"), error.getMessage()); + assertTrue(listTags().isEmpty()); + } + + @Test + void tagResourceWithoutTagsAndUntagResourceWithoutKeysAreRejected() { + putReport(List.of()); + + ValidationException noTags = assertThrows(ValidationException.class, + () -> cur.tagResource(r -> r.reportName(reportName))); + ValidationException noKeys = assertThrows(ValidationException.class, + () -> cur.untagResource(r -> r.reportName(reportName))); + + assertTrue(noTags.getMessage().contains("'Tags'"), noTags.getMessage()); + assertTrue(noKeys.getMessage().contains("'TagKeys'"), noKeys.getMessage()); + } + + @Test + void aReportCannotHoldMoreThan50Tags() { + assertThrows(ValidationException.class, () -> putReport(tags(51))); + + putReport(tags(50)); + assertThrows(ValidationException.class, + () -> cur.tagResource(r -> r.reportName(reportName).tags(tag("one-more", "v")))); + assertEquals(50, listTags().size()); + + cur.tagResource(r -> r.reportName(reportName).tags(tag("key-1", "replaced"))); + assertEquals(50, listTags().size()); + } + + @Test + void tagsThatAreNotAListAreRejectedOnCreate() { + String definition = "{\"ReportName\":\"" + reportName + "\",\"TimeUnit\":\"DAILY\"," + + "\"Format\":\"Parquet\",\"Compression\":\"Parquet\",\"AdditionalSchemaElements\":[\"RESOURCES\"]," + + "\"S3Bucket\":\"tag-report-bucket\",\"S3Prefix\":\"reports\",\"S3Region\":\"us-east-1\"," + + "\"AdditionalArtifacts\":[\"ATHENA\"],\"RefreshClosedReports\":true," + + "\"ReportVersioning\":\"OVERWRITE_REPORT\"}"; + + call("PutReportDefinition", "{\"ReportDefinition\":" + definition + + ",\"Tags\":{\"Key\":\"team\",\"Value\":\"red\"}}", 400); + call("PutReportDefinition", "{\"ReportDefinition\":" + definition + "}", 200); + } + + @Test + void tagKeysAndValuesThatAreNotStringsAreRejected() { + putReport(List.of(tag("1", "kept"))); + + call("TagResource", "{\"ReportName\":\"" + reportName + "\",\"Tags\":[{\"Key\":2,\"Value\":\"v\"}]}", 400); + call("TagResource", "{\"ReportName\":\"" + reportName + "\",\"Tags\":[{\"Key\":\"k\",\"Value\":3}]}", 400); + call("UntagResource", "{\"ReportName\":\"" + reportName + "\",\"TagKeys\":[1]}", 400); + + assertEquals(List.of(tag("1", "kept")), listTags()); + } + + private static void call(String action, String body, int status) { + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSOrigamiServiceGatewayService." + action) + .header("Authorization", + "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20260101/us-east-1/cur/aws4_request") + .body(body.getBytes(StandardCharsets.UTF_8)) + .when() + .post("/") + .then() + .statusCode(status) + .body(status == 200 ? not(containsString("__type")) : containsString("ValidationException")); + } + + private static List tags(int count) { + return IntStream.rangeClosed(1, count).mapToObj(i -> tag("key-" + i, "v")).toList(); + } + + private void putReport(List tags) { + cur.putReportDefinition(r -> r.reportDefinition(definition()).tags(tags)); + } + + private List listTags() { + return cur.listTagsForResource(r -> r.reportName(reportName)).tags(); + } + + private ReportDefinition definition() { + return ReportDefinition.builder() + .reportName(reportName) + .timeUnit(TimeUnit.DAILY) + .format(ReportFormat.PARQUET) + .compression(CompressionFormat.PARQUET) + .additionalSchemaElements(SchemaElement.RESOURCES) + .s3Bucket("tag-report-bucket") + .s3Prefix("reports") + .s3Region("us-east-1") + .additionalArtifacts(AdditionalArtifact.ATHENA) + .refreshClosedReports(true) + .reportVersioning(ReportVersioning.OVERWRITE_REPORT) + .build(); + } + + private static Tag tag(String key, String value) { + return Tag.builder().key(key).value(value).build(); + } +} diff --git a/tools/aws/regen_cur_shapes.py b/tools/aws/regen_cur_shapes.py new file mode 100644 index 0000000000..ac5c34ccbc --- /dev/null +++ b/tools/aws/regen_cur_shapes.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Vendor the Cost and Usage Reports tag operations' request constraints from botocore's Apache-2.0 service model. + +CurRequestShapes checks TagResource, UntagResource and ListTagsForResource, and the Tags of +PutReportDefinition, through RequestConstraintCheck using the model's types, required members and bounds. + +Run from anywhere in the repo: + python3 tools/aws/regen_cur_shapes.py + python3 tools/aws/regen_cur_shapes.py --check +""" +from __future__ import annotations + +import sys +from pathlib import Path + +import request_shapes + +OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/cur-request-shapes.json" +MODEL = Path("cur/2017-01-06") +OPERATIONS = ("ListTagsForResource", "TagResource", "UntagResource") + + +def main(argv: list[str] | None = None) -> int: + return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, + description=__doc__, operations=OPERATIONS) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index 4f1f7d937c..751d7bf3a7 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -21,6 +21,7 @@ import pytest import regen_apigateway_documentation_shapes import regen_apigateway_shapes import regen_athena_shapes +import regen_cur_shapes import regen_dynamodb_shapes import regen_ecr_shapes import regen_ecs_shapes @@ -436,6 +437,7 @@ def vendored(script) -> tuple[str, ...]: regen_securityhub_shapes, regen_rekognition_shapes, regen_athena_shapes, + regen_cur_shapes, ]) def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script): doc = json.loads(script.OUTPUT.read_text(encoding="utf-8"))