From 3308ea2f1c3485393677873dda92b5099f02c472 Mon Sep 17 00:00:00 2001 From: "Ovidiu (Ovi)" <163712869+ovi-fabric@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:20:11 +0200 Subject: [PATCH] feat(logs): add vended log delivery sources, destinations and deliveries (#7411) --- Makefile | 5 + docs/services/cloudwatch.md | 55 ++- .../common/IamConditionContextResolver.java | 5 + .../logs/CloudWatchLogsDeliveryHandler.java | 224 +++++++++ .../CloudWatchLogsDeliveryRequestShapes.java | 97 ++++ .../logs/CloudWatchLogsDeliveryService.java | 446 ++++++++++++++++++ .../logs/CloudWatchLogsHandler.java | 36 +- .../logs/CloudWatchLogsService.java | 5 + .../cloudwatch/logs/model/Delivery.java | 48 ++ .../logs/model/DeliveryDestination.java | 32 ++ .../cloudwatch/logs/model/DeliverySource.java | 41 ++ .../services/iam/ResourceArnBuilder.java | 12 +- .../resources/aws/iam-request-resources.json | 17 +- .../aws/logs-delivery-request-shapes.json | 303 ++++++++++++ .../common/RequestResourceMembersTest.java | 15 +- ...CloudWatchLogsDeliveryIntegrationTest.java | 205 ++++++++ ...tchLogsGroupPaginationIntegrationTest.java | 6 +- ...dWatchLogsMetricFilterIntegrationTest.java | 8 +- ...hLogsMetricFilterRetryIntegrationTest.java | 25 +- .../services/iam/ResourceArnBuilderTest.java | 31 ++ .../floci/testing/LogsRequests.java | 31 ++ tools/aws/regen_iam_request_resources.py | 40 +- tools/aws/regen_logs_delivery_shapes.py | 35 ++ tools/aws/request_shapes.py | 2 +- tools/aws/test_regen_iam_request_resources.py | 23 + tools/aws/test_request_shapes.py | 3 +- tools/docs/services.yaml | 1 + 27 files changed, 1709 insertions(+), 42 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryHandler.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryRequestShapes.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/Delivery.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/DeliveryDestination.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/DeliverySource.java create mode 100644 src/main/resources/aws/logs-delivery-request-shapes.json create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/testing/LogsRequests.java create mode 100644 tools/aws/regen_logs_delivery_shapes.py diff --git a/Makefile b/Makefile index edda17b514..31bcade954 100644 --- a/Makefile +++ b/Makefile @@ -261,6 +261,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s $(PYTHON) tools/aws/regen_dynamodb_shapes.py $(PYTHON) tools/aws/regen_redshift_serverless_shapes.py $(PYTHON) tools/aws/regen_resource_groups_shapes.py + $(PYTHON) tools/aws/regen_logs_delivery_shapes.py $(PYTHON) tools/aws/regen_ecr_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_shapes.py $(PYTHON) tools/aws/regen_iam_shapes.py @@ -341,6 +342,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres echo "error: Resource Groups request shapes are out of date; run 'make aws-data-sync'."; \ exit 1; \ } + @$(PYTHON) tools/aws/regen_logs_delivery_shapes.py --check || { \ + echo "error: Logs delivery request shapes are out of date; run 'make aws-data-sync'."; \ + exit 1; \ + } @$(PYTHON) tools/aws/regen_ecr_shapes.py --check || { \ echo ""; \ echo "error: src/main/resources/aws/ecr-request-shapes.json is out of date."; \ diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index cf34032aa6..8795e928bf 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -30,9 +30,9 @@ Floci supports both CloudWatch Logs and CloudWatch Metrics. | `TagLogGroup` | Tag a log group | | `UntagLogGroup` | Remove tags | | `ListTagsLogGroup` | List tags | -| `TagResource` | Tag a log group by ARN | -| `UntagResource` | Remove tags from a log group by ARN | -| `ListTagsForResource` | List tags for a log group ARN | +| `TagResource` | Tag a log group, delivery source, delivery destination or delivery by ARN | +| `UntagResource` | Remove tags from a log group, delivery source, delivery destination or delivery by ARN | +| `ListTagsForResource` | List tags for a log group, delivery source, delivery destination or delivery ARN | | `PutSubscriptionFilter` | Create or update a subscription filter (see [Subscription filters](#subscription-filters)) | | `DescribeSubscriptionFilters` | List subscription filters on a log group | | `DeleteSubscriptionFilter` | Delete a subscription filter | @@ -50,6 +50,19 @@ Floci supports both CloudWatch Logs and CloudWatch Metrics. | `StartQuery` | Start a Logs Insights query (see [Logs Insights](#logs-insights)) | | `GetQueryResults` | Get the status and results of a Logs Insights query | | `StopQuery` | Stop a query that has not completed yet | +| `PutDeliverySource` | Create or replace a vended-log delivery source (see [Vended log delivery](#vended-log-delivery)) | +| `GetDeliverySource` | Return a delivery source | +| `DeleteDeliverySource` | Delete a delivery source no delivery uses | +| `DescribeDeliverySources` | List delivery sources, optionally only those for given resource ARNs | +| `PutDeliveryDestination` | Create or replace a delivery destination: a log group, S3 bucket, Firehose stream or X-Ray | +| `GetDeliveryDestination` | Return a delivery destination | +| `DeleteDeliveryDestination` | Delete a delivery destination no delivery uses | +| `DescribeDeliveryDestinations` | List delivery destinations, optionally only those with given names | +| `CreateDelivery` | Pair a delivery source with a delivery destination | +| `GetDelivery` | Return a delivery, with its record fields and S3 configuration | +| `UpdateDeliveryConfiguration` | Change a delivery's record fields, delimiter or S3 configuration | +| `DeleteDelivery` | Delete a delivery | +| `DescribeDeliveries` | List deliveries, optionally only those from given delivery sources | `DescribeLogGroups` returns names in ASCII order, with up to 50 groups per page by default. Set `limit` to an integer from 1 to 50 and pass the returned `nextToken` with the same region @@ -77,6 +90,42 @@ exclusions, JSON and space-delimited patterns. An invalid pattern is refused wit `InvalidParameterException`, and so is a request that names no log group by `logGroupName` or `logGroupIdentifier`. +### Vended log delivery {#vended-log-delivery} + +Delivery sources, delivery destinations and the deliveries that pair them, which Terraform's +`aws_cloudwatch_log_delivery_source`, `aws_cloudwatch_log_delivery_destination` and +`aws_cloudwatch_log_delivery` manage, for example for an EventBridge bus's logs. Floci stores the +configuration and does not deliver the source's logs. + +- `PutDeliverySource` and `PutDeliveryDestination` create the resource or replace every parameter + of an existing one. A source reports the service of its resource's ARN (`events` for an event + bus) and the `logType` it was given. +- A destination's `deliveryDestinationType` follows from its resource's ARN: `CWL` for a log group, + `S3` for a bucket, `FH` for a Firehose stream. Only an X-Ray destination, which has no resource, + names its type. +- `CreateDelivery` needs an existing source and destination, and one delivery per pair; a second is + `ConflictException`. Its id is 16 letters and digits. For an EventBridge event bus source, + `recordFields` defaults to the bus's ten template fields and `s3DeliveryConfiguration` to the + `{region}/{yyyy}/{MM}/{dd}/{HH}/` suffix path, as AWS reports them. `GetDelivery` returns those; + `DescribeDeliveries` leaves them out, as AWS does. +- A source or destination a delivery uses cannot be deleted (`ConflictException`). +- Tags are set on create and through `TagResource`, `UntagResource` and `ListTagsForResource` on the + resource's ARN; the Get and Describe responses carry none, as on AWS. +- `DescribeDeliverySources` narrows to `resourceArns`, `DescribeDeliveryDestinations` to `names` and + `DescribeDeliveries` to `deliverySourceNames`; a name that matches nothing is left out, not an error. +- Requests are checked against the Logs API model's lengths, patterns, enums and required members, + with AWS's `ValidationException` wording, for example "1 validation error detected: Value at + 'limit' failed to satisfy constraint: Member must have value less than or equal to 50". +- An unknown name or id is `ResourceNotFoundException`, "Requested Delivery Source does not exist in + this account." (likewise for a Delivery Destination and a Delivery). +- With IAM enforcement on, each action is authorized on the resources the AWS Service Authorization + Reference lists for it: the source, destination or delivery it names, and for `CreateDelivery` the + source, the destination and the new delivery; `DeleteDeliverySource` on the source it deletes. The + Describe actions are authorized on `*`, as the reference lists no resource for them. + +Not modelled: delivery destination policies (`PutDeliveryDestinationPolicy` and its siblings), and +record field defaults for sources other than an EventBridge event bus. + ### Subscription filters {#subscription-filters} Subscription filters deliver newly ingested log events to a downstream destination. Floci delivers diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java index 2d0ee35418..b285773ab3 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsDeliveryService; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget; import io.github.hectorvent.floci.services.dynamodb.DynamoDbConditionKeys; @@ -206,6 +207,10 @@ public class IamConditionContextResolver { conditions.put("aws:TagKeys", keys); } } + if (direct && CloudWatchLogsDeliveryService.isDeliveryResourceArn(body.path("resourceArn").asText())) { + // A delivery source, destination or delivery: its request tags apply, its own tags are not read. + return conditions.isEmpty() ? null : conditions; + } String group = direct ? logsService.get().resolveTagTarget(body.path("resourceArn").asText(), region).name() : body.path("logGroupName").asText(); Map tags; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryHandler.java new file mode 100644 index 0000000000..f57ba3c307 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryHandler.java @@ -0,0 +1,224 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.Delivery; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.DeliveryDestination; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.DeliverySource; +import jakarta.ws.rs.core.Response; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +/** + * The wire shapes of the vended-log delivery operations, reached through + * {@link CloudWatchLogsHandler}: request members in the JSON 1.1 form the Logs API takes, + * responses as the API reference lists them. + */ +class CloudWatchLogsDeliveryHandler { + + private final CloudWatchLogsDeliveryService deliveries; + private final ObjectMapper objectMapper; + + CloudWatchLogsDeliveryHandler(CloudWatchLogsDeliveryService deliveries, ObjectMapper objectMapper) { + this.deliveries = deliveries; + this.objectMapper = objectMapper; + } + + Response handle(String action, JsonNode request, String region) { + CloudWatchLogsDeliveryRequestShapes.check(action, request); + return switch (action) { + case "PutDeliverySource" -> putDeliverySource(request, region); + case "GetDeliverySource" -> wrapped("deliverySource", + source(deliveries.getDeliverySource(text(request, "name"), region))); + case "DeleteDeliverySource" -> { + deliveries.deleteDeliverySource(text(request, "name"), region); + yield empty(); + } + case "DescribeDeliverySources" -> page("deliverySources", + deliveries.describeDeliverySources(limit(request), text(request, "nextToken"), + stringList(request.get("resourceArns")), region), + this::source); + case "PutDeliveryDestination" -> putDeliveryDestination(request, region); + case "GetDeliveryDestination" -> wrapped("deliveryDestination", + destination(deliveries.getDeliveryDestination(text(request, "name"), region))); + case "DeleteDeliveryDestination" -> { + deliveries.deleteDeliveryDestination(text(request, "name"), region); + yield empty(); + } + case "DescribeDeliveryDestinations" -> page("deliveryDestinations", + deliveries.describeDeliveryDestinations(limit(request), text(request, "nextToken"), + stringList(request.get("names")), region), + this::destination); + case "CreateDelivery" -> createDelivery(request, region); + case "GetDelivery" -> wrapped("delivery", delivery(deliveries.getDelivery(text(request, "id"), region))); + case "UpdateDeliveryConfiguration" -> updateDeliveryConfiguration(request, region); + case "DeleteDelivery" -> { + deliveries.deleteDelivery(text(request, "id"), region); + yield empty(); + } + case "DescribeDeliveries" -> page("deliveries", + deliveries.describeDeliveries(limit(request), text(request, "nextToken"), + stringList(request.get("deliverySourceNames")), region), + this::deliverySummary); + default -> throw new IllegalStateException("not a delivery action: " + action); + }; + } + + private Response putDeliverySource(JsonNode request, String region) { + DeliverySource source = deliveries.putDeliverySource(text(request, "name"), text(request, "resourceArn"), + text(request, "logType"), stringMap(request.get("deliverySourceConfiguration")), + stringMap(request.get("tags")), region); + return wrapped("deliverySource", source(source)); + } + + private Response putDeliveryDestination(JsonNode request, String region) { + JsonNode configuration = request.path("deliveryDestinationConfiguration"); + DeliveryDestination destination = deliveries.putDeliveryDestination(text(request, "name"), + text(request, "outputFormat"), text(configuration, "destinationResourceArn"), + text(request, "deliveryDestinationType"), stringMap(request.get("tags")), region); + return wrapped("deliveryDestination", destination(destination)); + } + + private Response createDelivery(JsonNode request, String region) { + JsonNode s3 = request.path("s3DeliveryConfiguration"); + Delivery delivery = deliveries.createDelivery(text(request, "deliverySourceName"), + text(request, "deliveryDestinationArn"), stringList(request.get("recordFields")), + text(request, "fieldDelimiter"), bool(s3, "enableHiveCompatiblePath"), text(s3, "suffixPath"), + stringMap(request.get("tags")), region); + return wrapped("delivery", delivery(delivery)); + } + + private Response updateDeliveryConfiguration(JsonNode request, String region) { + JsonNode s3 = request.path("s3DeliveryConfiguration"); + deliveries.updateDeliveryConfiguration(text(request, "id"), stringList(request.get("recordFields")), + text(request, "fieldDelimiter"), bool(s3, "enableHiveCompatiblePath"), text(s3, "suffixPath"), + region); + return empty(); + } + + private ObjectNode source(DeliverySource source) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("name", source.getName()); + node.put("arn", source.getArn()); + ArrayNode resourceArns = node.putArray("resourceArns"); + source.getResourceArns().forEach(resourceArns::add); + node.put("service", source.getService()); + node.put("logType", source.getLogType()); + if (!source.getDeliverySourceConfiguration().isEmpty()) { + node.set("deliverySourceConfiguration", objectMapper.valueToTree(source.getDeliverySourceConfiguration())); + } + return node; + } + + private ObjectNode destination(DeliveryDestination destination) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("name", destination.getName()); + node.put("arn", destination.getArn()); + node.put("deliveryDestinationType", destination.getDeliveryDestinationType()); + if (destination.getOutputFormat() != null) { + node.put("outputFormat", destination.getOutputFormat()); + } + if (destination.getDestinationResourceArn() != null) { + node.putObject("deliveryDestinationConfiguration") + .put("destinationResourceArn", destination.getDestinationResourceArn()); + } + return node; + } + + private ObjectNode delivery(Delivery delivery) { + ObjectNode node = deliverySummary(delivery); + if (!delivery.getRecordFields().isEmpty()) { + ArrayNode fields = node.putArray("recordFields"); + delivery.getRecordFields().forEach(fields::add); + } + // An empty delimiter, the default, is left out, as AWS leaves it out. + if (delivery.getFieldDelimiter() != null && !delivery.getFieldDelimiter().isEmpty()) { + node.put("fieldDelimiter", delivery.getFieldDelimiter()); + } + if (delivery.getEnableHiveCompatiblePath() != null || delivery.getSuffixPath() != null) { + ObjectNode s3 = node.putObject("s3DeliveryConfiguration"); + if (delivery.getEnableHiveCompatiblePath() != null) { + s3.put("enableHiveCompatiblePath", delivery.getEnableHiveCompatiblePath()); + } + if (delivery.getSuffixPath() != null) { + s3.put("suffixPath", delivery.getSuffixPath()); + } + } + return node; + } + + /** + * A delivery as DescribeDeliveries lists it: without the record fields, delimiter and S3 + * configuration GetDelivery adds. Tags are read through ListTagsForResource only, as on AWS. + */ + private ObjectNode deliverySummary(Delivery delivery) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("id", delivery.getId()); + node.put("arn", delivery.getArn()); + node.put("deliverySourceName", delivery.getDeliverySourceName()); + node.put("deliveryDestinationArn", delivery.getDeliveryDestinationArn()); + node.put("deliveryDestinationType", delivery.getDeliveryDestinationType()); + return node; + } + + private Response wrapped(String member, ObjectNode value) { + ObjectNode out = objectMapper.createObjectNode(); + out.set(member, value); + return Response.ok(out).build(); + } + + private Response page(String member, PaginatedResult page, Function render) { + ObjectNode out = objectMapper.createObjectNode(); + ArrayNode items = out.putArray(member); + page.items().forEach(item -> items.add(render.apply(item))); + if (page.nextToken() != null) { + out.put("nextToken", page.nextToken()); + } + return Response.ok(out).build(); + } + + private Response empty() { + return Response.ok(objectMapper.createObjectNode()).build(); + } + + /** The page size; the vendored constraints have already checked it is an integer from 1 to 50. */ + private static Integer limit(JsonNode request) { + JsonNode limit = request.get("limit"); + return limit == null || limit.isNull() ? null : limit.asInt(); + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + return value == null || value.isNull() ? null : value.asText(); + } + + private static Boolean bool(JsonNode node, String field) { + JsonNode value = node.get(field); + return value == null || value.isNull() ? null : value.asBoolean(); + } + + private static Map stringMap(JsonNode node) { + if (node == null || !node.isObject()) { + return null; + } + Map map = new LinkedHashMap<>(); + node.properties().forEach(entry -> map.put(entry.getKey(), entry.getValue().asText())); + return map; + } + + private static List stringList(JsonNode node) { + if (node == null || !node.isArray()) { + return null; + } + List list = new ArrayList<>(); + node.forEach(value -> list.add(value.asText())); + return list; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryRequestShapes.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryRequestShapes.java new file mode 100644 index 0000000000..8c41550546 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryRequestShapes.java @@ -0,0 +1,97 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RequestConstraintCheck; +import io.github.hectorvent.floci.core.common.VendoredPatterns; +import io.github.hectorvent.floci.core.common.VendoredResources; + +import java.util.ArrayList; +import java.util.List; + +/** + * Checks a vended-log delivery request against the constraints vendored in + * {@code aws/logs-delivery-request-shapes.json} by {@code tools/aws/regen_logs_delivery_shapes.py}, + * answering {@code ValidationException} in the form AWS words it: + * {@code 1 validation error detected: Value at 'limit' failed to satisfy constraint: Member must have + * value less than or equal to 50}. An element of a list is reported at the list, with every + * constraint on its elements: {@code Value at 'deliverySourceNames' failed to satisfy constraint: + * Member must satisfy constraint: [Member must have length less than or equal to 60, ...]}. + */ +final class CloudWatchLogsDeliveryRequestShapes { + + private static final JsonNode MODEL = VendoredResources.read("aws/logs-delivery-request-shapes.json", + "Logs delivery request shapes", input -> new ObjectMapper().readTree(input)); + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.of(MODEL, + new RequestConstraintCheck.Messages() { + @Override + public AwsException type(String path, String type) { + return violation(path, "Member must be a " + type); + } + + @Override + public AwsException bounds(String path, String type, Long min, Long max, long size) { + String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length"; + return max != null && size > max + ? violation(path, "Member must have " + measure + " less than or equal to " + max) + : violation(path, "Member must have " + measure + " greater than or equal to " + min); + } + + @Override + public AwsException pattern(String path, String pattern) { + return violation(path, "Member must satisfy regular expression pattern: " + pattern); + } + + @Override + public AwsException enumValue(String path, List values) { + return violation(path, "Member must satisfy enum value set: " + values); + } + + @Override + public AwsException required(String path) { + return violation(path, "Member must not be null"); + } + }); + + private CloudWatchLogsDeliveryRequestShapes() { + } + + static void check(String operation, JsonNode request) { + CHECK.check(operation, request); + } + + /** The member's path without the operation name the check starts it with. */ + private static AwsException violation(String path, String constraint) { + String member = path.contains(".") ? path.substring(path.indexOf('.') + 1) : path; + if (member.endsWith("[]")) { + member = member.substring(0, member.length() - 2); + constraint = "Member must satisfy constraint: " + elementConstraints(path); + } + return new AwsException("ValidationException", "1 validation error detected: Value at '" + member + + "' failed to satisfy constraint: " + constraint, 400); + } + + /** Every constraint on the elements of the top-level list at {@code path}, in the order AWS lists them. */ + private static List elementConstraints(String path) { + String operation = path.substring(0, path.indexOf('.')); + String list = path.substring(path.indexOf('.') + 1, path.length() - 2); + JsonNode shapes = MODEL.path("shapes"); + String input = MODEL.path("operations").path(operation).asText(); + String listShape = shapes.path(input).path("members").path(list).asText(); + JsonNode element = shapes.path(shapes.path(listShape).path("member").asText()); + String measure = "integer".equals(element.path("type").asText()) ? "value" : "length"; + List constraints = new ArrayList<>(); + if (element.has("max")) { + constraints.add("Member must have " + measure + " less than or equal to " + element.get("max").asLong()); + } + if (element.has("min")) { + constraints.add("Member must have " + measure + " greater than or equal to " + element.get("min").asLong()); + } + if (element.has("pattern")) { + constraints.add("Member must satisfy regular expression pattern: " + VendoredPatterns.quoted(element)); + } + return constraints; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryService.java new file mode 100644 index 0000000000..6add9d5145 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryService.java @@ -0,0 +1,446 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.Delivery; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.DeliveryDestination; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.DeliverySource; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * CloudWatch Logs vended-log delivery: delivery sources, delivery destinations and the + * deliveries that pair them. A configuration registry: Floci stores and returns them, and does + * not send the source's logs anywhere. + */ +@ApplicationScoped +public class CloudWatchLogsDeliveryService { + + /** What a delivery, source or destination ARN's resource starts with, in AWS's form. */ + static final String SOURCE_RESOURCE = "delivery-source:"; + static final String DESTINATION_RESOURCE = "delivery-destination:"; + static final String DELIVERY_RESOURCE = "delivery:"; + + private static final String ID_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int ID_LENGTH = 16; + private static final int MAX_TAGS = 50; + private static final int MAX_PAGE = 50; + + /** + * What AWS fills in for a delivery from an EventBridge event bus when the request names no + * record fields: the defaults of the bus's configuration templates (one per log type), and the + * S3 suffix path GetDelivery reports even for a log group destination. + */ + private static final List EVENT_BUS_RECORD_FIELDS = List.of("resource_arn", "message_timestamp_ms", + "event_bus_name", "request_id", "event_id", "invocation_id", "message_type", "log_level", "details", + "error"); + private static final Set EVENT_BUS_LOG_TYPES = Set.of("ERROR_LOGS", "INFO_LOGS", "TRACE_LOGS"); + private static final String DEFAULT_SUFFIX_PATH = "{region}/{yyyy}/{MM}/{dd}/{HH}/"; + + private final StorageBackend sources; + private final StorageBackend destinations; + private final StorageBackend deliveries; + private final RegionResolver regionResolver; + + @Inject + public CloudWatchLogsDeliveryService(StorageFactory storageFactory, RegionResolver regionResolver) { + this(storageFactory.create("cloudwatchlogs", "cwlogs-delivery-sources.json", + new TypeReference>() {}), + storageFactory.create("cloudwatchlogs", "cwlogs-delivery-destinations.json", + new TypeReference>() {}), + storageFactory.create("cloudwatchlogs", "cwlogs-deliveries.json", + new TypeReference>() {}), + regionResolver); + } + + CloudWatchLogsDeliveryService(StorageBackend sources, + StorageBackend destinations, + StorageBackend deliveries, RegionResolver regionResolver) { + this.sources = sources; + this.destinations = destinations; + this.deliveries = deliveries; + this.regionResolver = regionResolver; + } + + // ── Delivery sources ── + + /** Creates a delivery source or replaces every parameter of an existing one. */ + public synchronized DeliverySource putDeliverySource(String name, String resourceArn, String logType, + Map configuration, + Map tags, String region) { + if (!AwsArnUtils.isArn(resourceArn)) { + throw validation("resourceArn must be the ARN of the resource that sends the logs."); + } + Optional existing = sources.get(key(region, name)); + DeliverySource source = new DeliverySource(); + source.setName(name); + source.setArn(arn(region, SOURCE_RESOURCE + name)); + source.setResourceArns(new ArrayList<>(List.of(resourceArn))); + source.setService(AwsArnUtils.parse(resourceArn).service()); + source.setLogType(logType); + source.setDeliverySourceConfiguration(configuration == null ? null : new LinkedHashMap<>(configuration)); + source.setTags(new LinkedHashMap<>(tags == null ? existing.map(DeliverySource::getTags).orElse(Map.of()) : tags)); + sources.put(key(region, name), source); + return source; + } + + public DeliverySource getDeliverySource(String name, String region) { + return sources.get(key(region, name)).orElseThrow(() -> notFound("Delivery Source")); + } + + /** Refused while a delivery uses the source, as AWS does. */ + public synchronized void deleteDeliverySource(String name, String region) { + DeliverySource source = getDeliverySource(name, region); + if (inUse(source, region)) { + throw conflict("Delivery source " + name + " is used by a delivery; delete the delivery first."); + } + sources.delete(key(region, name)); + } + + /** Every source, or those sending from one of {@code resourceArns}. */ + public PaginatedResult describeDeliverySources(Integer limit, String nextToken, + List resourceArns, String region) { + List all = sources.scan(k -> k.startsWith(prefix(region))).stream() + .filter(source -> resourceArns == null + || source.getResourceArns().stream().anyMatch(resourceArns::contains)) + .toList(); + return page(all, DeliverySource::getName, limit, nextToken, "delivery-sources"); + } + + // ── Delivery destinations ── + + /** + * Creates a delivery destination or replaces every parameter of an existing one. The type + * follows from the destination resource's ARN; only X-Ray, which has no resource, names it. + */ + public synchronized DeliveryDestination putDeliveryDestination(String name, String outputFormat, + String destinationResourceArn, String type, + Map tags, String region) { + String resolvedType = destinationType(destinationResourceArn, type); + Optional existing = destinations.get(key(region, name)); + DeliveryDestination destination = new DeliveryDestination(); + destination.setName(name); + destination.setArn(arn(region, DESTINATION_RESOURCE + name)); + destination.setDeliveryDestinationType(resolvedType); + destination.setOutputFormat(outputFormat); + destination.setDestinationResourceArn(destinationResourceArn); + destination.setTags(new LinkedHashMap<>(tags == null + ? existing.map(DeliveryDestination::getTags).orElse(Map.of()) : tags)); + destinations.put(key(region, name), destination); + return destination; + } + + public DeliveryDestination getDeliveryDestination(String name, String region) { + return destinations.get(key(region, name)).orElseThrow(() -> notFound("Delivery Destination")); + } + + /** Refused while a delivery uses the destination, as AWS does. */ + public synchronized void deleteDeliveryDestination(String name, String region) { + DeliveryDestination destination = getDeliveryDestination(name, region); + if (inUse(destination, region)) { + throw conflict("Delivery destination " + name + " is used by a delivery; delete the delivery first."); + } + destinations.delete(key(region, name)); + } + + /** Every destination, or those {@code names} names. */ + public PaginatedResult describeDeliveryDestinations(Integer limit, String nextToken, + List names, String region) { + List all = destinations.scan(k -> k.startsWith(prefix(region))).stream() + .filter(destination -> names == null || names.contains(destination.getName())) + .toList(); + return page(all, DeliveryDestination::getName, limit, nextToken, "delivery-destinations"); + } + + // ── Deliveries ── + + /** Pairs a delivery source with a delivery destination; one delivery per pair. */ + public synchronized Delivery createDelivery(String sourceName, String destinationArn, List recordFields, + String fieldDelimiter, Boolean enableHiveCompatiblePath, + String suffixPath, Map tags, String region) { + DeliverySource source = getDeliverySource(sourceName, region); + DeliveryDestination destination = destinationByArn(destinationArn, region); + boolean taken = deliveries.scan(k -> k.startsWith(prefix(region))).stream() + .anyMatch(d -> sourceName.equals(d.getDeliverySourceName()) + && destination.getArn().equals(d.getDeliveryDestinationArn())); + if (taken) { + throw conflict("A delivery from " + sourceName + " to " + destination.getName() + " already exists."); + } + Delivery delivery = new Delivery(); + delivery.setId(newId(region)); + delivery.setArn(arn(region, DELIVERY_RESOURCE + delivery.getId())); + delivery.setDeliverySourceName(sourceName); + delivery.setDeliveryDestinationArn(destination.getArn()); + delivery.setDeliveryDestinationType(destination.getDeliveryDestinationType()); + boolean eventBus = isEventBus(source); + delivery.setRecordFields(new ArrayList<>(recordFields != null ? recordFields + : eventBus ? EVENT_BUS_RECORD_FIELDS : List.of())); + delivery.setFieldDelimiter(fieldDelimiter); + delivery.setEnableHiveCompatiblePath(enableHiveCompatiblePath != null ? enableHiveCompatiblePath + : eventBus ? Boolean.FALSE : null); + delivery.setSuffixPath(suffixPath != null ? suffixPath : eventBus ? DEFAULT_SUFFIX_PATH : null); + delivery.setTags(new LinkedHashMap<>(tags == null ? Map.of() : tags)); + deliveries.put(key(region, delivery.getId()), delivery); + return delivery; + } + + public Delivery getDelivery(String id, String region) { + return deliveries.get(key(region, id)).orElseThrow(() -> notFound("Delivery")); + } + + /** Replaces the record fields, delimiter and S3 options a request gives; the rest stay. */ + public synchronized void updateDeliveryConfiguration(String id, List recordFields, String fieldDelimiter, + Boolean enableHiveCompatiblePath, String suffixPath, + String region) { + Delivery delivery = getDelivery(id, region); + if (recordFields != null) { + delivery.setRecordFields(new ArrayList<>(recordFields)); + } + if (fieldDelimiter != null) { + delivery.setFieldDelimiter(fieldDelimiter); + } + if (enableHiveCompatiblePath != null) { + delivery.setEnableHiveCompatiblePath(enableHiveCompatiblePath); + } + if (suffixPath != null) { + delivery.setSuffixPath(suffixPath); + } + deliveries.put(key(region, id), delivery); + } + + public synchronized void deleteDelivery(String id, String region) { + getDelivery(id, region); + deliveries.delete(key(region, id)); + } + + /** Every delivery, or those from one of {@code deliverySourceNames}. */ + public PaginatedResult describeDeliveries(Integer limit, String nextToken, + List deliverySourceNames, String region) { + List all = deliveries.scan(k -> k.startsWith(prefix(region))).stream() + .filter(delivery -> deliverySourceNames == null + || deliverySourceNames.contains(delivery.getDeliverySourceName())) + .toList(); + return page(all, Delivery::getId, limit, nextToken, "deliveries"); + } + + // ── Tags ── + + /** + * True when the ARN names a delivery source, destination or delivery, in any account or Region: + * how IAM tells these ARNs on the shared tag operations apart from a log group's. + */ + public static boolean isDeliveryResourceArn(String arn) { + if (arn == null || !AwsArnUtils.isArn(arn)) { + return false; + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String resource = parsed.resource(); + return "logs".equals(parsed.service()) && (resource.startsWith(SOURCE_RESOURCE) + || resource.startsWith(DESTINATION_RESOURCE) || resource.startsWith(DELIVERY_RESOURCE)); + } + + /** True when the ARN names a delivery source, destination or delivery of this account and Region. */ + public boolean isDeliveryArn(String arn, String region) { + return resourceOf(arn, region) != null; + } + + public Map listTags(String arn, String region) { + return switch (kindOf(arn, region)) { + case SOURCE -> new LinkedHashMap<>(getDeliverySource(nameOf(arn, region), region).getTags()); + case DESTINATION -> new LinkedHashMap<>(getDeliveryDestination(nameOf(arn, region), region).getTags()); + case DELIVERY -> new LinkedHashMap<>(getDelivery(nameOf(arn, region), region).getTags()); + }; + } + + public synchronized void tag(String arn, Map tags, String region) { + retag(arn, region, current -> { + Map merged = new LinkedHashMap<>(current); + merged.putAll(tags); + if (merged.size() > MAX_TAGS) { + throw validation("A resource can have at most " + MAX_TAGS + " tags."); + } + return merged; + }); + } + + public synchronized void untag(String arn, List keys, String region) { + retag(arn, region, current -> { + Map remaining = new LinkedHashMap<>(current); + keys.forEach(remaining::remove); + return remaining; + }); + } + + private void retag(String arn, String region, UnaryOperator> change) { + String name = nameOf(arn, region); + switch (kindOf(arn, region)) { + case SOURCE -> { + DeliverySource source = getDeliverySource(name, region); + source.setTags(change.apply(source.getTags())); + sources.put(key(region, name), source); + } + case DESTINATION -> { + DeliveryDestination destination = getDeliveryDestination(name, region); + destination.setTags(change.apply(destination.getTags())); + destinations.put(key(region, name), destination); + } + case DELIVERY -> { + Delivery delivery = getDelivery(name, region); + delivery.setTags(change.apply(delivery.getTags())); + deliveries.put(key(region, name), delivery); + } + } + } + + // ── Helpers ── + + private enum Kind { SOURCE, DESTINATION, DELIVERY } + + private Kind kindOf(String arn, String region) { + String resource = resourceOf(arn, region); + if (resource == null) { + throw validation("Invalid resourceArn"); + } + if (resource.startsWith(SOURCE_RESOURCE)) { + return Kind.SOURCE; + } + return resource.startsWith(DESTINATION_RESOURCE) ? Kind.DESTINATION : Kind.DELIVERY; + } + + private String nameOf(String arn, String region) { + String resource = resourceOf(arn, region); + return resource.substring(resource.indexOf(':') + 1); + } + + /** The resource part of a delivery-family ARN of this account and Region, or null. */ + private String resourceOf(String arn, String region) { + if (arn == null || !AwsArnUtils.isArn(arn)) { + return null; + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + // The partition too: an ARN of another partition is not the caller's resource, even with the same + // Region, account and name. + if (!"logs".equals(parsed.service()) || !region.equals(parsed.region()) + || !regionResolver.getAccountId().equals(parsed.accountId()) + || !regionResolver.partitionForRegion(region).equals(parsed.partition())) { + return null; + } + String resource = parsed.resource(); + boolean delivery = resource.startsWith(SOURCE_RESOURCE) || resource.startsWith(DESTINATION_RESOURCE) + || resource.startsWith(DELIVERY_RESOURCE); + return delivery ? resource : null; + } + + private DeliveryDestination destinationByArn(String destinationArn, String region) { + String resource = resourceOf(destinationArn, region); + if (resource == null || !resource.startsWith(DESTINATION_RESOURCE)) { + throw notFound("Delivery Destination"); + } + return getDeliveryDestination(resource.substring(DESTINATION_RESOURCE.length()), region); + } + + /** An EventBridge event bus sending one of the log types its templates define. */ + private static boolean isEventBus(DeliverySource source) { + return "events".equals(source.getService()) && EVENT_BUS_LOG_TYPES.contains(source.getLogType()) + && source.getResourceArns().stream() + .anyMatch(arn -> AwsArnUtils.parse(arn).resource().startsWith("event-bus/")); + } + + private boolean inUse(DeliverySource source, String region) { + return deliveries.scan(k -> k.startsWith(prefix(region))).stream() + .anyMatch(d -> source.getName().equals(d.getDeliverySourceName())); + } + + private boolean inUse(DeliveryDestination destination, String region) { + return deliveries.scan(k -> k.startsWith(prefix(region))).stream() + .anyMatch(d -> destination.getArn().equals(d.getDeliveryDestinationArn())); + } + + /** The destination type an ARN's service names: Logs, S3 or Firehose; X-Ray has no resource. */ + private static String destinationType(String destinationResourceArn, String requestedType) { + if (destinationResourceArn == null || destinationResourceArn.isBlank()) { + if ("XRAY".equals(requestedType)) { + return requestedType; + } + throw validation("deliveryDestinationConfiguration is required unless deliveryDestinationType is XRAY."); + } + if (!AwsArnUtils.isArn(destinationResourceArn)) { + throw validation("destinationResourceArn must be an ARN."); + } + String type = switch (AwsArnUtils.parse(destinationResourceArn).service()) { + case "logs" -> "CWL"; + case "s3" -> "S3"; + case "firehose" -> "FH"; + default -> throw validation("destinationResourceArn must be a log group, an S3 bucket or a " + + "Firehose delivery stream."); + }; + if (requestedType != null && !requestedType.equals(type)) { + throw validation("deliveryDestinationType " + requestedType + " does not match the destination resource."); + } + return type; + } + + /** A page of up to {@code limit} (default 50) items, with AWS's wording for a bad token. */ + private static PaginatedResult page(List all, Function cursorOf, Integer limit, + String nextToken, String namespace) { + return Pagination.paginate(all, cursorOf, limit != null ? limit : MAX_PAGE, nextToken, namespace, + token -> validation("Invalid Next Token.")); + } + + private String newId(String region) { + String id; + do { + StringBuilder sb = new StringBuilder(ID_LENGTH); + for (int i = 0; i < ID_LENGTH; i++) { + sb.append(ID_CHARACTERS.charAt(ThreadLocalRandom.current().nextInt(ID_CHARACTERS.length()))); + } + id = sb.toString(); + } while (deliveries.get(key(region, id)).isPresent()); + return id; + } + + private String arn(String region, String resource) { + return regionResolver.buildArn("logs", region, resource); + } + + + + + private static AwsException validation(String message) { + return new AwsException("ValidationException", message, 400); + } + + private static AwsException conflict(String message) { + return new AwsException("ConflictException", message, 400); + } + + /** AWS's message: "Requested Delivery Source does not exist in this account." and its siblings. */ + private static AwsException notFound(String what) { + return new AwsException("ResourceNotFoundException", "Requested " + what + " does not exist in this account.", + 400); + } + + private static String key(String region, String name) { + return prefix(region) + name; + } + + private static String prefix(String region) { + return region + "::"; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java index 9476b8f008..40e157fe9c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java @@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsErrorResponse; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.cloudwatch.logs.model.AccountPolicy; import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogDestination; import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent; @@ -37,19 +38,33 @@ public class CloudWatchLogsHandler { private final CloudWatchLogsService logsService; private final CloudWatchLogsCrossAccountService crossAccountService; private final CloudWatchLogsMetricFilterHandler metricFilterHandler; + private final CloudWatchLogsDeliveryService deliveryService; + private final CloudWatchLogsDeliveryHandler deliveryHandler; private final ObjectMapper objectMapper; @Inject public CloudWatchLogsHandler(CloudWatchLogsService logsService, CloudWatchLogsCrossAccountService crossAccountService, CloudWatchLogsMetricFilterService metricFilterService, + CloudWatchLogsDeliveryService deliveryService, ObjectMapper objectMapper) { this.logsService = logsService; this.crossAccountService = crossAccountService; this.metricFilterHandler = new CloudWatchLogsMetricFilterHandler(metricFilterService, objectMapper); + this.deliveryService = deliveryService; + this.deliveryHandler = new CloudWatchLogsDeliveryHandler(deliveryService, objectMapper); this.objectMapper = objectMapper; } + /** For unit tests that exercise log groups only: deliveries live in memory. */ + CloudWatchLogsHandler(CloudWatchLogsService logsService, CloudWatchLogsCrossAccountService crossAccountService, + CloudWatchLogsMetricFilterService metricFilterService, ObjectMapper objectMapper) { + this(logsService, crossAccountService, metricFilterService, + new CloudWatchLogsDeliveryService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), logsService.regionResolver()), + objectMapper); + } + public Response handle(String action, JsonNode request, String region) { return switch (action) { case "CreateLogGroup" -> handleCreateLogGroup(request, region); @@ -75,6 +90,10 @@ public class CloudWatchLogsHandler { case "DeleteSubscriptionFilter" -> handleDeleteSubscriptionFilter(request, region); case "PutMetricFilter", "DescribeMetricFilters", "DeleteMetricFilter", "TestMetricFilter" -> metricFilterHandler.handle(action, request, region); + case "PutDeliverySource", "GetDeliverySource", "DeleteDeliverySource", "DescribeDeliverySources", + "PutDeliveryDestination", "GetDeliveryDestination", "DeleteDeliveryDestination", + "DescribeDeliveryDestinations", "CreateDelivery", "GetDelivery", "UpdateDeliveryConfiguration", + "DeleteDelivery", "DescribeDeliveries" -> deliveryHandler.handle(action, request, region); case "AssociateKmsKey" -> handleAssociateKmsKey(request, region); case "DisassociateKmsKey" -> handleDisassociateKmsKey(request, region); case "PutResourcePolicy" -> handlePutResourcePolicy(request, region); @@ -607,6 +626,11 @@ public class CloudWatchLogsHandler { private Response handleListTagsForResource(JsonNode request, String region) { String resourceArn = request.path("resourceArn").asText(); + if (deliveryService.isDeliveryArn(resourceArn, region)) { + ObjectNode response = objectMapper.createObjectNode(); + response.set("tags", objectMapper.valueToTree(deliveryService.listTags(resourceArn, region))); + return Response.ok(response).build(); + } String groupName = logsService.resolveTagTarget(resourceArn, region).name(); Map tags = logsService.listTagsLogGroup(groupName, region); @@ -619,17 +643,25 @@ public class CloudWatchLogsHandler { private Response handleTagResource(JsonNode request, String region) { String resourceArn = request.path("resourceArn").asText(); - String groupName = logsService.resolveTagTarget(resourceArn, region).name(); Map tags = extractTags(request.path("tags")); + if (deliveryService.isDeliveryArn(resourceArn, region)) { + deliveryService.tag(resourceArn, tags, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + String groupName = logsService.resolveTagTarget(resourceArn, region).name(); logsService.tagLogGroup(groupName, tags, region); return Response.ok(objectMapper.createObjectNode()).build(); } private Response handleUntagResource(JsonNode request, String region) { String resourceArn = request.path("resourceArn").asText(); - String groupName = logsService.resolveTagTarget(resourceArn, region).name(); List tagKeys = new ArrayList<>(); request.path("tagKeys").forEach(k -> tagKeys.add(k.asText())); + if (deliveryService.isDeliveryArn(resourceArn, region)) { + deliveryService.untag(resourceArn, tagKeys, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + String groupName = logsService.resolveTagTarget(resourceArn, region).name(); logsService.untagLogGroup(groupName, tagKeys, region); return Response.ok(objectMapper.createObjectNode()).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java index 1eb53bb8e4..5bb4981626 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java @@ -451,6 +451,11 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable { groupStore.put(key, group); } + /** The account and partition this service mints its ARNs in. */ + RegionResolver regionResolver() { + return regionResolver; + } + public LogGroupTagTarget resolveTagTarget(String resourceArn, String region) { return LogGroupTagTarget.resolve(resourceArn, region, regionResolver.getAccountId(), regionResolver.getPartition()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/Delivery.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/Delivery.java new file mode 100644 index 0000000000..c9623b6019 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/Delivery.java @@ -0,0 +1,48 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** A vended-logs delivery: one delivery source paired with one delivery destination. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class Delivery { + private String id; + private String arn; + private String deliverySourceName; + private String deliveryDestinationArn; + private String deliveryDestinationType; + private List recordFields = new ArrayList<>(); + private String fieldDelimiter; + private Boolean enableHiveCompatiblePath; + private String suffixPath; + private Map tags = new LinkedHashMap<>(); + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + public String getDeliverySourceName() { return deliverySourceName; } + public void setDeliverySourceName(String name) { this.deliverySourceName = name; } + public String getDeliveryDestinationArn() { return deliveryDestinationArn; } + public void setDeliveryDestinationArn(String arn) { this.deliveryDestinationArn = arn; } + public String getDeliveryDestinationType() { return deliveryDestinationType; } + public void setDeliveryDestinationType(String type) { this.deliveryDestinationType = type; } + public List getRecordFields() { return recordFields; } + public void setRecordFields(List recordFields) { + this.recordFields = recordFields != null ? recordFields : new ArrayList<>(); + } + public String getFieldDelimiter() { return fieldDelimiter; } + public void setFieldDelimiter(String fieldDelimiter) { this.fieldDelimiter = fieldDelimiter; } + public Boolean getEnableHiveCompatiblePath() { return enableHiveCompatiblePath; } + public void setEnableHiveCompatiblePath(Boolean enable) { this.enableHiveCompatiblePath = enable; } + public String getSuffixPath() { return suffixPath; } + public void setSuffixPath(String suffixPath) { this.suffixPath = suffixPath; } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/DeliveryDestination.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/DeliveryDestination.java new file mode 100644 index 0000000000..1f8d804f33 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/DeliveryDestination.java @@ -0,0 +1,32 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** A vended-logs delivery destination: a log group, bucket, Firehose stream or X-Ray. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeliveryDestination { + private String name; + private String arn; + private String deliveryDestinationType; + private String outputFormat; + private String destinationResourceArn; + private Map tags = new LinkedHashMap<>(); + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + public String getDeliveryDestinationType() { return deliveryDestinationType; } + public void setDeliveryDestinationType(String type) { this.deliveryDestinationType = type; } + public String getOutputFormat() { return outputFormat; } + public void setOutputFormat(String outputFormat) { this.outputFormat = outputFormat; } + public String getDestinationResourceArn() { return destinationResourceArn; } + public void setDestinationResourceArn(String arn) { this.destinationResourceArn = arn; } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/DeliverySource.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/DeliverySource.java new file mode 100644 index 0000000000..58247ee988 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/DeliverySource.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** A vended-logs delivery source: an AWS resource that sends one type of log. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeliverySource { + private String name; + private String arn; + private List resourceArns = new ArrayList<>(); + private String service; + private String logType; + private Map deliverySourceConfiguration = new LinkedHashMap<>(); + private Map tags = new LinkedHashMap<>(); + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getArn() { return arn; } + public void setArn(String arn) { this.arn = arn; } + public List getResourceArns() { return resourceArns; } + public void setResourceArns(List resourceArns) { + this.resourceArns = resourceArns != null ? resourceArns : new ArrayList<>(); + } + public String getService() { return service; } + public void setService(String service) { this.service = service; } + public String getLogType() { return logType; } + public void setLogType(String logType) { this.logType = logType; } + public Map getDeliverySourceConfiguration() { return deliverySourceConfiguration; } + public void setDeliverySourceConfiguration(Map configuration) { + this.deliverySourceConfiguration = configuration != null ? configuration : new LinkedHashMap<>(); + } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index c498407296..11dee5f360 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.common.SigV4CredentialScope; import io.github.hectorvent.floci.core.common.StoredResourceArns; import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization; +import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsDeliveryService; import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget; import io.github.hectorvent.floci.services.eks.EksController; import io.github.hectorvent.floci.services.eks.EksService; @@ -275,6 +276,10 @@ public class ResourceArnBuilder { /** Uses the serving operation and the same raw names as the handler. */ public List buildLogResources(String action, ContainerRequestContext ctx, String region, String accountId, String partition) { + // Operations the vendored table reads (the vended-log delivery family) take their resources from it. + if (RequestResources.reads(action)) { + return namedResources("logs", action, ctx, region, accountId, partition); + } boolean stream = "logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action); boolean group = switch (action) { case "logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy", @@ -289,7 +294,12 @@ public class ResourceArnBuilder { return List.of("*"); } if (LogGroupTagTarget.supports(action)) { - return List.of(LogGroupTagTarget.resolve(body.path("resourceArn").asText(), region, accountId, partition).arn()); + String resourceArn = body.path("resourceArn").asText(); + // A delivery source, destination or delivery is tagged through the same operations. + if (CloudWatchLogsDeliveryService.isDeliveryResourceArn(resourceArn)) { + return List.of(resourceArn); + } + return List.of(LogGroupTagTarget.resolve(resourceArn, region, accountId, partition).arn()); } String name = body.path("logGroupName").asText(); String resource = "log-group:" + name + (stream diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json index 0cab90ad65..a5f1f9ef4c 100644 --- a/src/main/resources/aws/iam-request-resources.json +++ b/src/main/resources/aws/iam-request-resources.json @@ -1,11 +1,11 @@ { "_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-03", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."}, - "namespaces": {"acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "dynamodb": ["dynamodb"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "redshift-data": ["redshift-data"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]}, + "namespaces": {"acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "dynamodb": ["dynamodb"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "logs": ["logs"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "redshift-data": ["redshift-data"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]}, "clientsNotRead": {"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members"}, "handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts"], "notCovered": {"access-analyzer": "REST: its requests name their resources in the path, which RequestResources does not read yet", "account": "REST: its requests name their resources in the path, which RequestResources does not read yet", "airflow": "REST: its requests name their resources in the path, which RequestResources does not read yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources does not read yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources does not read yet", "appsync": "REST: its requests name their resources in the path, which RequestResources does not read yet", "aps": "REST: its requests name their resources in the path, which RequestResources does not read yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup::autoScalingGroupName/`, while Floci mints `autoScalingGroup:`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources does not read yet", "batch": "REST: its requests name their resources in the path, which RequestResources does not read yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources does not read yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources does not read yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources does not read yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/_, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources does not read yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources does not read yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources does not read yet", "controltower": "REST: its requests name their resources in the path, which RequestResources does not read yet", "datasync": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "detective": "REST: its requests name their resources in the path, which RequestResources does not read yet", "dlm": "REST: its requests name their resources in the path, which RequestResources does not read yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ecs": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticache": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticbeanstalk": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticfilesystem": "REST: its requests name their resources in the path, which RequestResources does not read yet", "elasticmapreduce": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "emr-serverless": "REST: its requests name their resources in the path, which RequestResources does not read yet", "es": "REST: its requests name their resources in the path, which RequestResources does not read yet", "execute-api": "REST: its requests name their resources in the path, which RequestResources does not read yet", "fis": "REST: its requests name their resources in the path, which RequestResources does not read yet", "glue": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "guardduty": "REST: its requests name their resources in the path, which RequestResources does not read yet", "identitystore": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "inspector2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "iot": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "kafka": "REST: its requests name their resources in the path, which RequestResources does not read yet", "lightsail": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "macie2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "memorydb": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "mq": "REST: its requests name their resources in the path, which RequestResources does not read yet", "network-firewall": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "oam": "REST: its requests name their resources in the path, which RequestResources does not read yet", "organizations": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ram": "REST: its requests name their resources in the path, which RequestResources does not read yet", "rds": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rds-data": "REST: its requests name their resources in the path, which RequestResources does not read yet", "redshift": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "redshift-serverless": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rekognition": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "resource-explorer-2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "route53": "REST: its requests name their resources in the path, which RequestResources does not read yet", "route53resolver": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rum": "REST: its requests name their resources in the path, which RequestResources does not read yet", "s3tables": "REST: its requests name their resources in the path, which RequestResources does not read yet", "s3vectors": "REST: its requests name their resources in the path, which RequestResources does not read yet", "sagemaker": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "securityhub": "REST: its requests name their resources in the path, which RequestResources does not read yet", "servicecatalog": "not read yet: CreatePortfolioShare, UpdatePortfolioShare and DeletePortfolioShare give in AccountId the account a portfolio is shared with, which the rule reads as the portfolio's; a portfolio or product imported from another account keeps its owner's account in its ARN while requests name it by its id alone; and AppRegistry's applications and attribute groups are named in the path", "ses": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "signin": "REST: its requests name their resources in the path, which RequestResources does not read yet", "sso": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "sso-oauth": "REST: its requests name their resources in the path, which RequestResources does not read yet", "swf": "not read yet: the Service Reference gives a domain's ARN no Region, `swf:::/domain/`, while the SWF Developer Guide gives it as arn:aws:swf:Region:AccountID:/domain/DomainName, as Floci mints it; reading it needs that format corrected", "transcribe": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "transfer": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "verifiedpermissions": "not read yet: a policyStoreId may name its store by an alias, `policy-store-alias/`, which AWS authorizes as the action on the store the alias points to and GetPolicyStoreAlias on the alias, and an aliasName carries the `policy-store-alias/` its format already gives; reading it needs both", "wafv2": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint"}, "otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ec2-instance-connect", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "quicksight", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "signer", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web", "xray"], - "arnFormats": {"acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "dynamodb": {"backup": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/backup/${BackupName}", "export": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/export/${ExportName}", "global-table": "arn:${Partition}:dynamodb::${Account}:global-table/${GlobalTableName}", "import": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/import/${ImportName}", "index": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/index/${IndexName}", "stream": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/stream/${StreamLabel}", "table": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}"}, "ecr": {"repository": "arn:${Partition}:ecr:${Region}:${Account}:repository/${RepositoryName}"}, "elasticloadbalancing": {"listener-rule/app": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener-rule/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${ListenerRuleId}", "listener-rule/net": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener-rule/net/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${ListenerRuleId}", "listener/app": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "listener/gwy": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/gwy/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "listener/net": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/net/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "loadbalancer": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/${LoadBalancerName}", "loadbalancer/app/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/app/${LoadBalancerName}/${LoadBalancerId}", "loadbalancer/gwy/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/gwy/${LoadBalancerName}/${LoadBalancerId}", "loadbalancer/net/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/net/${LoadBalancerName}/${LoadBalancerId}", "targetgroup": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:targetgroup/${TargetGroupName}/${TargetGroupId}", "truststore": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:truststore/${TrustStoreName}/${TrustStoreId}"}, "events": {"alias": "arn:${Partition}:kms:${Region}:${Account}:alias/${Alias}", "api-destination": "arn:${Partition}:events:${Region}:${Account}:api-destination/${ApiDestinationName}", "archive": "arn:${Partition}:events:${Region}:${Account}:archive/${ArchiveName}", "connection": "arn:${Partition}:events:${Region}:${Account}:connection/${ConnectionName}", "create-snapshot": "arn:${Partition}:events:${Region}:${Account}:target/create-snapshot", "endpoint": "arn:${Partition}:events:${Region}:${Account}:endpoint/${EndpointName}", "event-bus": "arn:${Partition}:events:${Region}:${Account}:event-bus/${EventBusName}", "event-busv2": "arn:${Partition}:events:${Region}:${Account}:event-busv2/${EventBusName}/${OpaqueId}", "event-source": "arn:${Partition}:events:${Region}::event-source/${EventSourceName}", "event-sourcev2": "arn:${Partition}:events:${Region}:${Account}:event-sourcev2/${SourceType}/${EventSourceName}/${OpaqueId}", "key": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}", "reboot-instance": "arn:${Partition}:events:${Region}:${Account}:target/reboot-instance", "replay": "arn:${Partition}:events:${Region}:${Account}:replay/${ReplayName}", "rule-on-custom-event-bus": "arn:${Partition}:events:${Region}:${Account}:rule/${EventBusName}/${RuleName}", "rule-on-default-event-bus": "arn:${Partition}:events:${Region}:${Account}:rule/${RuleName}", "stop-instance": "arn:${Partition}:events:${Region}:${Account}:target/stop-instance", "subscriber": "arn:${Partition}:events:${Region}:${Account}:subscriber/${SubscriberName}/${OpaqueId}", "terminate-instance": "arn:${Partition}:events:${Region}:${Account}:target/terminate-instance"}, "firehose": {"deliverystream": "arn:${Partition}:firehose:${Region}:${Account}:deliverystream/${DeliveryStreamName}"}, "globalaccelerator": {"accelerator": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}", "attachment": "arn:${Partition}:globalaccelerator::${Account}:attachment/${ResourceId}", "endpointgroup": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}/listener/${ListenerId}/endpoint-group/${EndpointGroupId}", "listener": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}/listener/${ListenerId}"}, "kinesisanalytics": {"application": "arn:${Partition}:kinesisanalytics:${Region}:${Account}:application/${ApplicationName}"}, "payment-cryptography": {"alias": "arn:${Partition}:payment-cryptography:${Region}:${Account}:alias/${Alias}", "approval-team": "arn:${Partition}:mpa:${Region}:${Account}:approval-team/${ApprovalTeamId}", "key": "arn:${Partition}:payment-cryptography:${Region}:${Account}:key/${KeyId}"}, "redshift-data": {"cluster": "arn:${Partition}:redshift:${Region}:${Account}:cluster:${ClusterName}", "managed-workgroup": "arn:${Partition}:redshift-serverless:${Region}:${Account}:managed-workgroup/${ManagedWorkgroupId}", "workgroup": "arn:${Partition}:redshift-serverless:${Region}:${Account}:workgroup/${WorkgroupId}"}, "servicediscovery": {"namespace": "arn:${Partition}:servicediscovery:${Region}:${Account}:namespace/${NamespaceId}", "service": "arn:${Partition}:servicediscovery:${Region}:${Account}:service/${ServiceId}"}, "servicequotas": {"quota": "arn:${Partition}:servicequotas:${Region}:${Account}:${ServiceCode}/${QuotaCode}"}, "states": {"activity": "arn:${Partition}:states:${Region}:${Account}:activity:${ActivityName}", "execution": "arn:${Partition}:states:${Region}:${Account}:execution:${StateMachineName}:${ExecutionId}", "express": "arn:${Partition}:states:${Region}:${Account}:express:${StateMachineName}:${ExecutionId}:${ExpressId}", "labelled execution": "arn:${Partition}:states:${Region}:${Account}:execution:${StateMachineName}/${MapRunLabel}:${ExecutionId}", "labelled express": "arn:${Partition}:states:${Region}:${Account}:express:${StateMachineName}/${MapRunLabel}:${ExecutionId}:${ExpressId}", "maprun": "arn:${Partition}:states:${Region}:${Account}:mapRun:${StateMachineName}/${MapRunLabel}:${MapRunId}", "statemachine": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}", "statemachinealias": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}:${StateMachineAliasName}", "statemachineversion": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}:${StateMachineVersionId}"}, "textract": {"adapter": "arn:${Partition}:textract:${Region}:${Account}:/adapters/${AdapterId}", "adapterversion": "arn:${Partition}:textract:${Region}:${Account}:/adapters/${AdapterId}/versions/${AdapterVersion}"}, "timestream-influxdb": {"db-backup": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-backup/${DbBackupId}", "db-cluster": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-cluster/${DbClusterId}", "db-instance": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-instance/${DbInstanceIdentifier}", "db-parameter-group": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-parameter-group/${DbParameterGroupIdentifier}"}, "translate": {"parallel-data": "arn:${Partition}:translate:${Region}:${Account}:parallel-data/${ResourceName}", "terminology": "arn:${Partition}:translate:${Region}:${Account}:terminology/${ResourceName}"}}, + "arnFormats": {"acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "dynamodb": {"backup": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/backup/${BackupName}", "export": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/export/${ExportName}", "global-table": "arn:${Partition}:dynamodb::${Account}:global-table/${GlobalTableName}", "import": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/import/${ImportName}", "index": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/index/${IndexName}", "stream": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/stream/${StreamLabel}", "table": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}"}, "ecr": {"repository": "arn:${Partition}:ecr:${Region}:${Account}:repository/${RepositoryName}"}, "elasticloadbalancing": {"listener-rule/app": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener-rule/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${ListenerRuleId}", "listener-rule/net": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener-rule/net/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${ListenerRuleId}", "listener/app": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "listener/gwy": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/gwy/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "listener/net": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/net/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "loadbalancer": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/${LoadBalancerName}", "loadbalancer/app/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/app/${LoadBalancerName}/${LoadBalancerId}", "loadbalancer/gwy/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/gwy/${LoadBalancerName}/${LoadBalancerId}", "loadbalancer/net/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/net/${LoadBalancerName}/${LoadBalancerId}", "targetgroup": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:targetgroup/${TargetGroupName}/${TargetGroupId}", "truststore": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:truststore/${TrustStoreName}/${TrustStoreId}"}, "events": {"alias": "arn:${Partition}:kms:${Region}:${Account}:alias/${Alias}", "api-destination": "arn:${Partition}:events:${Region}:${Account}:api-destination/${ApiDestinationName}", "archive": "arn:${Partition}:events:${Region}:${Account}:archive/${ArchiveName}", "connection": "arn:${Partition}:events:${Region}:${Account}:connection/${ConnectionName}", "create-snapshot": "arn:${Partition}:events:${Region}:${Account}:target/create-snapshot", "endpoint": "arn:${Partition}:events:${Region}:${Account}:endpoint/${EndpointName}", "event-bus": "arn:${Partition}:events:${Region}:${Account}:event-bus/${EventBusName}", "event-busv2": "arn:${Partition}:events:${Region}:${Account}:event-busv2/${EventBusName}/${OpaqueId}", "event-source": "arn:${Partition}:events:${Region}::event-source/${EventSourceName}", "event-sourcev2": "arn:${Partition}:events:${Region}:${Account}:event-sourcev2/${SourceType}/${EventSourceName}/${OpaqueId}", "key": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}", "reboot-instance": "arn:${Partition}:events:${Region}:${Account}:target/reboot-instance", "replay": "arn:${Partition}:events:${Region}:${Account}:replay/${ReplayName}", "rule-on-custom-event-bus": "arn:${Partition}:events:${Region}:${Account}:rule/${EventBusName}/${RuleName}", "rule-on-default-event-bus": "arn:${Partition}:events:${Region}:${Account}:rule/${RuleName}", "stop-instance": "arn:${Partition}:events:${Region}:${Account}:target/stop-instance", "subscriber": "arn:${Partition}:events:${Region}:${Account}:subscriber/${SubscriberName}/${OpaqueId}", "terminate-instance": "arn:${Partition}:events:${Region}:${Account}:target/terminate-instance"}, "firehose": {"deliverystream": "arn:${Partition}:firehose:${Region}:${Account}:deliverystream/${DeliveryStreamName}"}, "globalaccelerator": {"accelerator": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}", "attachment": "arn:${Partition}:globalaccelerator::${Account}:attachment/${ResourceId}", "endpointgroup": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}/listener/${ListenerId}/endpoint-group/${EndpointGroupId}", "listener": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}/listener/${ListenerId}"}, "kinesisanalytics": {"application": "arn:${Partition}:kinesisanalytics:${Region}:${Account}:application/${ApplicationName}"}, "logs": {"anomaly-detector": "arn:${Partition}:logs:${Region}:${Account}:anomaly-detector:${DetectorId}", "delivery": "arn:${Partition}:logs:${Region}:${Account}:delivery:${DeliveryName}", "delivery-destination": "arn:${Partition}:logs:${Region}:${Account}:delivery-destination:${DeliveryDestinationName}", "delivery-source": "arn:${Partition}:logs:${Region}:${Account}:delivery-source:${DeliverySourceName}", "destination": "arn:${Partition}:logs:${Region}:${Account}:destination:${DestinationName}", "log-group": "arn:${Partition}:logs:${Region}:${Account}:log-group:${LogGroupName}", "log-stream": "arn:${Partition}:logs:${Region}:${Account}:log-group:${LogGroupName}:log-stream:${LogStreamName}", "lookup-table": "arn:${Partition}:logs:${Region}:${Account}:lookup-table:${LookupTableName}", "scheduled-query": "arn:${Partition}:logs:${Region}:${Account}:scheduled-query:${ScheduledQueryId}"}, "payment-cryptography": {"alias": "arn:${Partition}:payment-cryptography:${Region}:${Account}:alias/${Alias}", "approval-team": "arn:${Partition}:mpa:${Region}:${Account}:approval-team/${ApprovalTeamId}", "key": "arn:${Partition}:payment-cryptography:${Region}:${Account}:key/${KeyId}"}, "redshift-data": {"cluster": "arn:${Partition}:redshift:${Region}:${Account}:cluster:${ClusterName}", "managed-workgroup": "arn:${Partition}:redshift-serverless:${Region}:${Account}:managed-workgroup/${ManagedWorkgroupId}", "workgroup": "arn:${Partition}:redshift-serverless:${Region}:${Account}:workgroup/${WorkgroupId}"}, "servicediscovery": {"namespace": "arn:${Partition}:servicediscovery:${Region}:${Account}:namespace/${NamespaceId}", "service": "arn:${Partition}:servicediscovery:${Region}:${Account}:service/${ServiceId}"}, "servicequotas": {"quota": "arn:${Partition}:servicequotas:${Region}:${Account}:${ServiceCode}/${QuotaCode}"}, "states": {"activity": "arn:${Partition}:states:${Region}:${Account}:activity:${ActivityName}", "execution": "arn:${Partition}:states:${Region}:${Account}:execution:${StateMachineName}:${ExecutionId}", "express": "arn:${Partition}:states:${Region}:${Account}:express:${StateMachineName}:${ExecutionId}:${ExpressId}", "labelled execution": "arn:${Partition}:states:${Region}:${Account}:execution:${StateMachineName}/${MapRunLabel}:${ExecutionId}", "labelled express": "arn:${Partition}:states:${Region}:${Account}:express:${StateMachineName}/${MapRunLabel}:${ExecutionId}:${ExpressId}", "maprun": "arn:${Partition}:states:${Region}:${Account}:mapRun:${StateMachineName}/${MapRunLabel}:${MapRunId}", "statemachine": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}", "statemachinealias": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}:${StateMachineAliasName}", "statemachineversion": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}:${StateMachineVersionId}"}, "textract": {"adapter": "arn:${Partition}:textract:${Region}:${Account}:/adapters/${AdapterId}", "adapterversion": "arn:${Partition}:textract:${Region}:${Account}:/adapters/${AdapterId}/versions/${AdapterVersion}"}, "timestream-influxdb": {"db-backup": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-backup/${DbBackupId}", "db-cluster": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-cluster/${DbClusterId}", "db-instance": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-instance/${DbInstanceIdentifier}", "db-parameter-group": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-parameter-group/${DbParameterGroupIdentifier}"}, "translate": {"parallel-data": "arn:${Partition}:translate:${Region}:${Account}:parallel-data/${ResourceName}", "terminology": "arn:${Partition}:translate:${Region}:${Account}:terminology/${ResourceName}"}}, "unqualified": {"states": ["statemachine"]}, "mintedIds": {"events": ["api-destination", "connection"]}, "operations": { @@ -885,6 +885,19 @@ "kinesisanalytics:UntagResource": {"action": "kinesisanalytics:UntagResource", "types": ["application"], "resources": [{"types": ["application"], "arn": "ResourceARN"}]}, "kinesisanalytics:UpdateApplication": {"action": "kinesisanalytics:UpdateApplication", "types": ["application"], "resources": [{"type": "application", "fill": {"ApplicationName": "ApplicationName"}}]}, "kinesisanalytics:UpdateApplicationMaintenanceConfiguration": {"action": "kinesisanalytics:UpdateApplicationMaintenanceConfiguration", "types": ["application"], "resources": [{"type": "application", "fill": {"ApplicationName": "ApplicationName"}}]}, + "logs:CreateDelivery": {"action": "logs:CreateDelivery", "types": ["delivery", "delivery-destination", "delivery-source"], "resources": [{"types": ["delivery", "delivery-destination", "delivery-source"], "arn": "deliveryDestinationArn"}, {"type": "delivery", "fill": {}, "made": true}, {"type": "delivery-source", "fill": {"DeliverySourceName": "deliverySourceName"}}]}, + "logs:DeleteDelivery": {"action": "logs:DeleteDelivery", "types": ["delivery"], "resources": [{"type": "delivery", "fill": {"DeliveryName": "id"}}]}, + "logs:DeleteDeliveryDestination": {"action": "logs:DeleteDeliveryDestination", "types": ["delivery-destination"], "resources": [{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "name"}}]}, + "logs:DeleteDeliverySource": {"action": "logs:DeleteDeliverySource", "types": ["delivery-destination"], "resources": [{"type": "delivery-source", "fill": {"DeliverySourceName": "name"}}]}, + "logs:DescribeDeliveries": {"action": "logs:DescribeDeliveries", "types": [], "resources": []}, + "logs:DescribeDeliveryDestinations": {"action": "logs:DescribeDeliveryDestinations", "types": [], "resources": []}, + "logs:DescribeDeliverySources": {"action": "logs:DescribeDeliverySources", "types": [], "resources": []}, + "logs:GetDelivery": {"action": "logs:GetDelivery", "types": ["delivery"], "resources": [{"type": "delivery", "fill": {"DeliveryName": "id"}}]}, + "logs:GetDeliveryDestination": {"action": "logs:GetDeliveryDestination", "types": ["delivery-destination"], "resources": [{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "name"}}]}, + "logs:GetDeliverySource": {"action": "logs:GetDeliverySource", "types": ["delivery-source"], "resources": [{"type": "delivery-source", "fill": {"DeliverySourceName": "name"}}]}, + "logs:PutDeliveryDestination": {"action": "logs:PutDeliveryDestination", "types": ["delivery-destination"], "resources": [{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "name"}}]}, + "logs:PutDeliverySource": {"action": "logs:PutDeliverySource", "types": ["delivery-source"], "resources": [{"type": "delivery-source", "fill": {"DeliverySourceName": "name"}}]}, + "logs:UpdateDeliveryConfiguration": {"action": "logs:UpdateDeliveryConfiguration", "types": ["delivery", "delivery-destination", "delivery-source"], "resources": [{"type": "delivery", "fill": {"DeliveryName": "id"}}]}, "payment-cryptography:AddKeyReplicationRegions": {"action": "payment-cryptography:AddKeyReplicationRegions", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]}, "payment-cryptography:AssociateMpaTeam": {"action": "payment-cryptography:AssociateMpaTeam", "types": ["approval-team"], "resources": [{"types": ["approval-team"], "arn": "MpaTeamArn"}]}, "payment-cryptography:CreateAlias": {"action": "payment-cryptography:CreateAlias", "types": ["alias", "key"], "resources": [{"types": ["alias", "key"], "arn": "KeyArn"}, {"type": "alias", "fill": {"Alias": "AliasName"}, "made": true}]}, diff --git a/src/main/resources/aws/logs-delivery-request-shapes.json b/src/main/resources/aws/logs-delivery-request-shapes.json new file mode 100644 index 0000000000..6055f2a720 --- /dev/null +++ b/src/main/resources/aws/logs-delivery-request-shapes.json @@ -0,0 +1,303 @@ +{ + "_source": { + "generator": "tools/aws/regen_logs_delivery_shapes.py", + "botocore": "botocore 1.43.118 (installed package)" + }, + "operations": { + "PutDeliverySource": "PutDeliverySourceRequest", + "GetDeliverySource": "GetDeliverySourceRequest", + "DeleteDeliverySource": "DeleteDeliverySourceRequest", + "DescribeDeliverySources": "DescribeDeliverySourcesRequest", + "PutDeliveryDestination": "PutDeliveryDestinationRequest", + "GetDeliveryDestination": "GetDeliveryDestinationRequest", + "DeleteDeliveryDestination": "DeleteDeliveryDestinationRequest", + "DescribeDeliveryDestinations": "DescribeDeliveryDestinationsRequest", + "CreateDelivery": "CreateDeliveryRequest", + "GetDelivery": "GetDeliveryRequest", + "UpdateDeliveryConfiguration": "UpdateDeliveryConfigurationRequest", + "DeleteDelivery": "DeleteDeliveryRequest", + "DescribeDeliveries": "DescribeDeliveriesRequest" + }, + "shapes": { + "Arn": { + "type": "string" + }, + "Boolean": { + "type": "boolean" + }, + "CreateDeliveryRequest": { + "type": "structure", + "required": [ + "deliverySourceName", + "deliveryDestinationArn" + ], + "members": { + "deliverySourceName": "DeliverySourceName", + "deliveryDestinationArn": "Arn", + "recordFields": "RecordFields", + "fieldDelimiter": "FieldDelimiter", + "s3DeliveryConfiguration": "S3DeliveryConfiguration", + "tags": "Tags" + } + }, + "DeleteDeliveryDestinationRequest": { + "type": "structure", + "required": [ + "name" + ], + "members": { + "name": "DeliveryDestinationName" + } + }, + "DeleteDeliveryRequest": { + "type": "structure", + "required": [ + "id" + ], + "members": { + "id": "DeliveryId" + } + }, + "DeleteDeliverySourceRequest": { + "type": "structure", + "required": [ + "name" + ], + "members": { + "name": "DeliverySourceName" + } + }, + "DeliveryDestinationConfiguration": { + "type": "structure", + "required": [ + "destinationResourceArn" + ], + "members": { + "destinationResourceArn": "Arn" + } + }, + "DeliveryDestinationName": { + "type": "string", + "min": 1, + "max": 60, + "pattern": "[\\w-]*" + }, + "DeliveryDestinationNames": { + "type": "list", + "min": 1, + "max": 20, + "member": "DeliveryDestinationName" + }, + "DeliveryDestinationType": { + "type": "string", + "enum": [ + "S3", + "CWL", + "FH", + "XRAY" + ] + }, + "DeliveryId": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "^[0-9A-Za-z]+$" + }, + "DeliverySourceConfiguration": { + "type": "map", + "key": "DeliverySourceConfigurationKey", + "value": "DeliverySourceConfigurationValue" + }, + "DeliverySourceConfigurationKey": { + "type": "string", + "min": 1, + "max": 255 + }, + "DeliverySourceConfigurationValue": { + "type": "string", + "min": 1, + "max": 255 + }, + "DeliverySourceName": { + "type": "string", + "min": 1, + "max": 60, + "pattern": "[\\w-]*" + }, + "DeliverySourceNames": { + "type": "list", + "min": 1, + "max": 20, + "member": "DeliverySourceName" + }, + "DeliverySuffixPath": { + "type": "string", + "min": 1, + "max": 256 + }, + "DescribeDeliveriesRequest": { + "type": "structure", + "members": { + "nextToken": "NextToken", + "limit": "DescribeLimit", + "deliverySourceNames": "DeliverySourceNames" + } + }, + "DescribeDeliveryDestinationsRequest": { + "type": "structure", + "members": { + "nextToken": "NextToken", + "limit": "DescribeLimit", + "names": "DeliveryDestinationNames" + } + }, + "DescribeDeliverySourcesRequest": { + "type": "structure", + "members": { + "nextToken": "NextToken", + "limit": "DescribeLimit", + "resourceArns": "FilterResourceArns" + } + }, + "DescribeLimit": { + "type": "integer", + "min": 1, + "max": 50 + }, + "FieldDelimiter": { + "type": "string", + "min": 0, + "max": 5 + }, + "FieldHeader": { + "type": "string", + "min": 1, + "max": 64 + }, + "FilterResourceArns": { + "type": "list", + "min": 1, + "max": 20, + "member": "Arn" + }, + "GetDeliveryDestinationRequest": { + "type": "structure", + "required": [ + "name" + ], + "members": { + "name": "DeliveryDestinationName" + } + }, + "GetDeliveryRequest": { + "type": "structure", + "required": [ + "id" + ], + "members": { + "id": "DeliveryId" + } + }, + "GetDeliverySourceRequest": { + "type": "structure", + "required": [ + "name" + ], + "members": { + "name": "DeliverySourceName" + } + }, + "LogType": { + "type": "string", + "min": 1, + "max": 255, + "pattern": "[\\w]*" + }, + "NextToken": { + "type": "string", + "min": 1 + }, + "OutputFormat": { + "type": "string", + "enum": [ + "json", + "plain", + "w3c", + "raw", + "parquet" + ] + }, + "PutDeliveryDestinationRequest": { + "type": "structure", + "required": [ + "name" + ], + "members": { + "name": "DeliveryDestinationName", + "outputFormat": "OutputFormat", + "deliveryDestinationConfiguration": "DeliveryDestinationConfiguration", + "deliveryDestinationType": "DeliveryDestinationType", + "roleArn": "Arn", + "tags": "Tags" + } + }, + "PutDeliverySourceRequest": { + "type": "structure", + "required": [ + "name", + "resourceArn", + "logType" + ], + "members": { + "name": "DeliverySourceName", + "resourceArn": "Arn", + "logType": "LogType", + "tags": "Tags", + "deliverySourceConfiguration": "DeliverySourceConfiguration" + } + }, + "RecordFields": { + "type": "list", + "min": 0, + "max": 128, + "member": "FieldHeader" + }, + "S3DeliveryConfiguration": { + "type": "structure", + "members": { + "suffixPath": "DeliverySuffixPath", + "enableHiveCompatiblePath": "Boolean" + } + }, + "TagKey": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+)$" + }, + "TagValue": { + "type": "string", + "max": 256, + "pattern": "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$" + }, + "Tags": { + "type": "map", + "min": 1, + "max": 50, + "key": "TagKey", + "value": "TagValue" + }, + "UpdateDeliveryConfigurationRequest": { + "type": "structure", + "required": [ + "id" + ], + "members": { + "id": "DeliveryId", + "recordFields": "RecordFields", + "fieldDelimiter": "FieldDelimiter", + "s3DeliveryConfiguration": "S3DeliveryConfiguration" + } + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java index 514610eaca..a6c5a95047 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java @@ -14,6 +14,7 @@ import org.junit.jupiter.api.TestFactory; import java.io.ByteArrayInputStream; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -42,11 +43,19 @@ class RequestResourceMembersTest { RequestResourceMembers.Table table = RequestResourceMembers.table(); assertTrue(table.namespaces().containsAll(List.of("cognito-idp", "ecr", "elasticloadbalancing", "states"))); assertTrue(table.handBuilt().contains("lambda")); - assertEquals(Set.of("dynamodb"), table.namespaces().stream().filter(table.handBuilt()::contains) + assertEquals(Set.of("dynamodb", "logs"), table.namespaces().stream().filter(table.handBuilt()::contains) .collect(Collectors.toSet())); - assertEquals(Set.of("dynamodb:ListTables"), table.operations().keySet().stream() + Set logsDelivery = Stream.of("PutDeliverySource", "GetDeliverySource", "DeleteDeliverySource", + "DescribeDeliverySources", "PutDeliveryDestination", "GetDeliveryDestination", + "DeleteDeliveryDestination", "DescribeDeliveryDestinations", "CreateDelivery", "GetDelivery", + "UpdateDeliveryConfiguration", "DeleteDelivery", "DescribeDeliveries") + .map(operation -> "logs:" + operation).collect(Collectors.toSet()); + Set expected = new HashSet<>(logsDelivery); + expected.add("dynamodb:ListTables"); + assertEquals(expected, table.operations().keySet().stream() .filter(operation -> table.handBuilt().contains(operation.substring(0, operation.indexOf(':')))) - .collect(Collectors.toSet()), "only explicit corrections override hand-built operations"); + .collect(Collectors.toSet()), + "only explicit corrections and the operations listed to read override hand-built operations"); assertTrue(table.namespaces().stream().noneMatch(table.notCovered()::contains)); assertTrue(table.otherNamespaces().stream().noneMatch(table.notCovered()::contains)); table.operations().forEach((operation, resources) -> { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryIntegrationTest.java new file mode 100644 index 0000000000..a215557e95 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsDeliveryIntegrationTest.java @@ -0,0 +1,205 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.LogsRequests.logs; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +/** + * Vended-log delivery over the Logs JSON 1.1 API: an EventBridge bus as delivery source, a log + * group as delivery destination, and the delivery that pairs them, as + * {@code terraform-aws-modules/eventbridge}'s {@code log_delivery} creates them. + */ +@QuarkusTest +class CloudWatchLogsDeliveryIntegrationTest { + + private static final String PREFIX = "arn:aws:logs:us-east-1:000000000000:"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void anEventBusDeliversToALogGroup() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String bus = "arn:aws:events:us-east-1:000000000000:event-bus/orders-" + suffix; + String logGroup = PREFIX + "log-group:/aws/events/orders-" + suffix; + + logs("PutDeliverySource", """ + {"name": "orders-%s", "resourceArn": "%s", "logType": "ERROR_LOGS", "tags": {"team": "data"}} + """.formatted(suffix, bus)).then().statusCode(200) + .body("deliverySource.name", equalTo("orders-" + suffix)) + .body("deliverySource.arn", equalTo(PREFIX + "delivery-source:orders-" + suffix)) + .body("deliverySource.resourceArns", contains(bus)) + .body("deliverySource.service", equalTo("events")) + .body("deliverySource.logType", equalTo("ERROR_LOGS")) + .body("deliverySource.tags", nullValue()); + String destinationArn = logs("PutDeliveryDestination", """ + {"name": "orders-logs-%s", "outputFormat": "json", + "deliveryDestinationConfiguration": {"destinationResourceArn": "%s"}} + """.formatted(suffix, logGroup)).then().statusCode(200) + .body("deliveryDestination.arn", equalTo(PREFIX + "delivery-destination:orders-logs-" + suffix)) + .body("deliveryDestination.deliveryDestinationType", equalTo("CWL")) + .body("deliveryDestination.outputFormat", equalTo("json")) + .body("deliveryDestination.deliveryDestinationConfiguration.destinationResourceArn", + equalTo(logGroup)) + .extract().path("deliveryDestination.arn"); + + String id = logs("CreateDelivery", """ + {"deliverySourceName": "orders-%s", "deliveryDestinationArn": "%s", "tags": {"team": "data"}} + """.formatted(suffix, destinationArn)).then().statusCode(200) + .body("delivery.id", matchesPattern("[0-9A-Za-z]{16}")) + .body("delivery.deliveryDestinationType", equalTo("CWL")) + .extract().path("delivery.id"); + String deliveryArn = PREFIX + "delivery:" + id; + + // GetDelivery reports the event bus template's record fields and the S3 suffix path. + logs("GetDelivery", "{\"id\": \"" + id + "\"}").then().statusCode(200) + .body("delivery.arn", equalTo(deliveryArn)) + .body("delivery.deliverySourceName", equalTo("orders-" + suffix)) + .body("delivery.deliveryDestinationArn", equalTo(destinationArn)) + .body("delivery.recordFields", contains("resource_arn", "message_timestamp_ms", "event_bus_name", + "request_id", "event_id", "invocation_id", "message_type", "log_level", "details", "error")) + .body("delivery.s3DeliveryConfiguration.suffixPath", equalTo("{region}/{yyyy}/{MM}/{dd}/{HH}/")) + .body("delivery.s3DeliveryConfiguration.enableHiveCompatiblePath", equalTo(false)) + .body("delivery.fieldDelimiter", nullValue()) + .body("delivery.tags", nullValue()); + logs("DescribeDeliveries", "{}").then().statusCode(200) + .body("deliveries.id", hasItem(id)) + .body("deliveries.find { it.id == '" + id + "' }.recordFields", nullValue()); + + logs("UpdateDeliveryConfiguration", "{\"id\": \"" + id + "\", \"recordFields\": [\"event_id\", \"error\"]}") + .then().statusCode(200); + logs("GetDelivery", "{\"id\": \"" + id + "\"}").then() + .body("delivery.recordFields", contains("event_id", "error")); + + logs("ListTagsForResource", "{\"resourceArn\": \"" + deliveryArn + "\"}").then().statusCode(200) + .body("tags.team", equalTo("data")); + logs("TagResource", "{\"resourceArn\": \"" + PREFIX + "delivery-source:orders-" + suffix + + "\", \"tags\": {\"env\": \"local\"}}").then().statusCode(200); + logs("ListTagsForResource", "{\"resourceArn\": \"" + PREFIX + "delivery-source:orders-" + suffix + "\"}") + .then().body("tags.team", equalTo("data")).body("tags.env", equalTo("local")); + // The same name in another partition is not the caller's source. + logs("TagResource", "{\"resourceArn\": \"" + PREFIX.replace("arn:aws:", "arn:aws-cn:") + + "delivery-source:orders-" + suffix + "\", \"tags\": {\"env\": \"foreign\"}}").then().statusCode(400); + logs("ListTagsForResource", "{\"resourceArn\": \"" + PREFIX + "delivery-source:orders-" + suffix + "\"}") + .then().body("tags.env", equalTo("local")); + + // In use: neither end can go while the delivery pairs them, and a second delivery is refused. + logs("CreateDelivery", """ + {"deliverySourceName": "orders-%s", "deliveryDestinationArn": "%s"} + """.formatted(suffix, destinationArn)).then().statusCode(400) + .body("__type", equalTo("ConflictException")); + logs("DeleteDeliverySource", "{\"name\": \"orders-" + suffix + "\"}").then().statusCode(400) + .body("__type", equalTo("ConflictException")); + logs("DeleteDeliveryDestination", "{\"name\": \"orders-logs-" + suffix + "\"}").then().statusCode(400) + .body("__type", equalTo("ConflictException")); + + logs("DeleteDelivery", "{\"id\": \"" + id + "\"}").then().statusCode(200); + logs("DeleteDeliverySource", "{\"name\": \"orders-" + suffix + "\"}").then().statusCode(200); + logs("DeleteDeliveryDestination", "{\"name\": \"orders-logs-" + suffix + "\"}").then().statusCode(200); + logs("DescribeDeliverySources", "{}").then().statusCode(200) + .body("deliverySources.name", not(hasItem("orders-" + suffix))); + } + + @Test + void describeCallsNarrowToTheNamedSourcesDestinationsAndDeliveries() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String[] ids = new String[2]; + for (int i = 0; i < 2; i++) { + String bus = "arn:aws:events:us-east-1:000000000000:event-bus/filter-" + i + "-" + suffix; + logs("PutDeliverySource", """ + {"name": "filter-%d-%s", "resourceArn": "%s", "logType": "ERROR_LOGS"} + """.formatted(i, suffix, bus)).then().statusCode(200); + String destination = logs("PutDeliveryDestination", """ + {"name": "filter-%d-%s", "deliveryDestinationConfiguration": + {"destinationResourceArn": "%slog-group:/aws/events/filter-%d-%s"}} + """.formatted(i, suffix, PREFIX, i, suffix)).then().statusCode(200) + .extract().path("deliveryDestination.arn"); + ids[i] = logs("CreateDelivery", """ + {"deliverySourceName": "filter-%d-%s", "deliveryDestinationArn": "%s"} + """.formatted(i, suffix, destination)).then().statusCode(200).extract().path("delivery.id"); + } + + logs("DescribeDeliverySources", "{\"resourceArns\": [\"arn:aws:events:us-east-1:000000000000:event-bus/filter-1-" + + suffix + "\"]}").then().statusCode(200) + .body("deliverySources.name", contains("filter-1-" + suffix)); + logs("DescribeDeliveryDestinations", "{\"names\": [\"filter-0-" + suffix + "\", \"missing-" + suffix + "\"]}") + .then().statusCode(200) + .body("deliveryDestinations.name", contains("filter-0-" + suffix)); + logs("DescribeDeliveries", "{\"deliverySourceNames\": [\"filter-1-" + suffix + "\"]}").then().statusCode(200) + .body("deliveries.id", contains(ids[1])); + logs("DescribeDeliveries", "{\"deliverySourceNames\": [\"missing-" + suffix + "\"]}").then().statusCode(200) + .body("deliveries", empty()); + + for (int i = 0; i < 2; i++) { + logs("DeleteDelivery", "{\"id\": \"" + ids[i] + "\"}").then().statusCode(200); + logs("DeleteDeliverySource", "{\"name\": \"filter-" + i + "-" + suffix + "\"}").then().statusCode(200); + logs("DeleteDeliveryDestination", "{\"name\": \"filter-" + i + "-" + suffix + "\"}").then().statusCode(200); + } + } + + @Test + void unknownResourcesAndInvalidRequestsAreRefusedWithAwsMessages() { + refused("GetDeliverySource", "{\"name\": \"no-such-source\"}", "ResourceNotFoundException", + "Requested Delivery Source does not exist in this account."); + refused("GetDeliveryDestination", "{\"name\": \"no-such-destination\"}", "ResourceNotFoundException", + "Requested Delivery Destination does not exist in this account."); + refused("GetDelivery", "{\"id\": \"AAAAAAAAAAAAAAAA\"}", "ResourceNotFoundException", + "Requested Delivery does not exist in this account."); + refused("DeleteDelivery", "{\"id\": \"AAAAAAAAAAAAAAAA\"}", "ResourceNotFoundException", + "Requested Delivery does not exist in this account."); + refused("ListTagsForResource", "{\"resourceArn\": \"" + PREFIX + "delivery:AAAAAAAAAAAAAAAA\"}", + "ResourceNotFoundException", "Requested Delivery does not exist in this account."); + refused("DescribeDeliverySources", "{\"limit\": 51}", "ValidationException", + "1 validation error detected: Value at 'limit' failed to satisfy constraint: Member must have value " + + "less than or equal to 50"); + refused("DescribeDeliverySources", "{\"nextToken\": \"bogus\"}", "ValidationException", + "Invalid Next Token."); + + logs("PutDeliveryDestination", """ + {"name": "bad-destination", "deliveryDestinationConfiguration": + {"destinationResourceArn": "arn:aws:sqs:us-east-1:000000000000:queue"}} + """).then().statusCode(400).body("__type", equalTo("ValidationException")); + logs("PutDeliveryDestination", "{\"name\": \"traces\", \"deliveryDestinationType\": \"XRAY\"}") + .then().statusCode(200) + .body("deliveryDestination.deliveryDestinationType", equalTo("XRAY")) + .body("deliveryDestination.deliveryDestinationConfiguration", nullValue()); + logs("DeleteDeliveryDestination", "{\"name\": \"traces\"}").then().statusCode(200); + refused("PutDeliverySource", "{\"name\": \"bad name\", \"resourceArn\": \"x\", \"logType\": \"ERROR_LOGS\"}", + "ValidationException", "1 validation error detected: Value at 'name' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: [\\w-]*"); + refused("PutDeliverySource", "{\"name\": \"source\", \"logType\": \"ERROR_LOGS\"}", "ValidationException", + "1 validation error detected: Value at 'resourceArn' failed to satisfy constraint: " + + "Member must not be null"); + refused("GetDelivery", "{\"id\": \"a-b\"}", "ValidationException", + "1 validation error detected: Value at 'id' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: ^[0-9A-Za-z]+$"); + refused("DescribeDeliveries", "{\"deliverySourceNames\": [\"bad name\"]}", "ValidationException", + "1 validation error detected: Value at 'deliverySourceNames' failed to satisfy constraint: " + + "Member must satisfy constraint: [Member must have length less than or equal to 60, " + + "Member must have length greater than or equal to 1, " + + "Member must satisfy regular expression pattern: [\\w-]*]"); + logs("CreateDelivery", "{\"deliverySourceName\": \"no-such-source\", \"deliveryDestinationArn\": \"" + + PREFIX + "delivery-destination:no-such-destination\"}").then().statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")) + .body("message", notNullValue()); + } + + private static void refused(String action, String body, String type, String message) { + logs(action, body).then().statusCode(400).body("__type", equalTo(type)).body("message", equalTo(message)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPaginationIntegrationTest.java index eda0f47131..2eeffee676 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPaginationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupPaginationIntegrationTest.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import static io.github.hectorvent.floci.testing.LogsRequests.logs; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -148,9 +149,4 @@ class CloudWatchLogsGroupPaginationIntegrationTest { groups.add(group); } } - - private Response logs(String action, Map body) { - return given().contentType("application/x-amz-json-1.1") - .header("X-Amz-Target", "Logs_20140328." + action).body(body).post("/"); - } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterIntegrationTest.java index abb7419dda..6a20163c01 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterIntegrationTest.java @@ -12,6 +12,7 @@ import java.time.Instant; import java.util.List; import java.util.Map; +import static io.github.hectorvent.floci.testing.LogsRequests.logs; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.equalTo; @@ -30,8 +31,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @QuarkusTest class CloudWatchLogsMetricFilterIntegrationTest { - private static final String LOGS_CONTENT_TYPE = "application/x-amz-json-1.1"; - private static final String LOGS_AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260908/us-east-1/logs/aws4_request"; private static final String CW_CONTENT_TYPE = "application/x-amz-json-1.0"; private static final String CW_AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260908/us-east-1/monitoring/aws4_request"; @@ -40,11 +39,6 @@ class CloudWatchLogsMetricFilterIntegrationTest { RestAssuredJsonUtils.configureAwsContentTypes(); } - private static Response logs(String action, String body) { - return given().contentType(LOGS_CONTENT_TYPE).header("Authorization", LOGS_AUTH) - .header("X-Amz-Target", "Logs_20140328." + action).body(body).post("/"); - } - private static Response cloudWatch(String action, String body) { return given().contentType(CW_CONTENT_TYPE).header("Authorization", CW_AUTH) .header("X-Amz-Target", "GraniteServiceVersion20100801." + action).body(body).post("/"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterRetryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterRetryIntegrationTest.java index 44126e06c2..89f58f46bb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterRetryIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterRetryIntegrationTest.java @@ -17,6 +17,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static io.github.hectorvent.floci.testing.LogsRequests.logs; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.*; @@ -32,7 +33,8 @@ class CloudWatchLogsMetricFilterRetryIntegrationTest { @InjectSpy CloudWatchMetricsService metrics; @Inject CloudWatchLogsMetricFilterService publications; - private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260916/eu-west-1/logs/aws4_request"; + private static final String REGION = "eu-west-1"; + private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260916/" + REGION + "/monitoring/aws4_request"; private static final long TIME = 1_700_000_040_000L; @BeforeAll @@ -60,7 +62,7 @@ class CloudWatchLogsMetricFilterRetryIntegrationTest { .body("Datapoints[0].Sum", equalTo(7.0f)).body("Datapoints[0].SampleCount", equalTo(1.0f)); publications.retryPending(); statistics(group).then().body("Datapoints[0].SampleCount", equalTo(1.0f)); - logs("DeleteLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200); + logs(REGION, "DeleteLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200); } @Test @@ -80,33 +82,28 @@ class CloudWatchLogsMetricFilterRetryIntegrationTest { ingest(group); await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> statistics(group).then().statusCode(200) .body("Datapoints[0].Sum", equalTo(7.0f)).body("Datapoints[0].SampleCount", equalTo(1.0f))); - logs("DeleteLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200); + logs(REGION, "DeleteLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200); } private static void create(String group) { - logs("CreateLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200); - logs("CreateLogStream", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"s\"}").then().statusCode(200); - logs("PutMetricFilter", """ + logs(REGION, "CreateLogGroup", "{\"logGroupName\":\"" + group + "\"}").then().statusCode(200); + logs(REGION, "CreateLogStream", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"s\"}").then().statusCode(200); + logs(REGION, "PutMetricFilter", """ {"logGroupName":"%s","filterName":"retry","filterPattern":"ERROR", "metricTransformations":[{"metricName":"Value","metricNamespace":"%s","metricValue":"3","defaultValue":7}]} """.formatted(group, group)).then().statusCode(200); } private static void ingest(String group) { - logs("PutLogEvents", """ + logs(REGION, "PutLogEvents", """ {"logGroupName":"%s","logStreamName":"s","logEvents":[{"timestamp":%d,"message":"INFO"}]} """.formatted(group, TIME)).then().statusCode(200); - logs("GetLogEvents", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"s\"}") + logs(REGION, "GetLogEvents", "{\"logGroupName\":\"" + group + "\",\"logStreamName\":\"s\"}") .then().statusCode(200).body("events", hasSize(1)); } - private static Response logs(String action, String body) { - return given().contentType("application/x-amz-json-1.1").header("Authorization", AUTH) - .header("X-Amz-Target", "Logs_20140328." + action).body(body).post("/"); - } - private static Response statistics(String namespace) { - return given().contentType("application/x-amz-json-1.0").header("Authorization", AUTH.replace("/logs/", "/monitoring/")) + return given().contentType("application/x-amz-json-1.0").header("Authorization", AUTH) .header("X-Amz-Target", "GraniteServiceVersion20100801.GetMetricStatistics").body(""" {"Namespace":"%s","MetricName":"Value","Period":60,"StartTime":%d,"EndTime":%d, "Statistics":["Sum","SampleCount"]} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index 952753b0e7..8d3b2fafd8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -785,6 +785,37 @@ class ResourceArnBuilderTest { } } + @Test + void deliveryActionsAreAuthorizedOnTheSourceDestinationOrDeliveryTheyName() { + String prefix = "arn:aws:logs:us-east-1:" + ACCOUNT + ":"; + for (String action : List.of("logs:PutDeliverySource", "logs:GetDeliverySource", "logs:DeleteDeliverySource")) { + setJsonBody("{\"name\":\"bus-source\"}"); + assertEquals(List.of(prefix + "delivery-source:bus-source"), + builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws")); + } + for (String action : List.of("logs:PutDeliveryDestination", "logs:GetDeliveryDestination", + "logs:DeleteDeliveryDestination")) { + setJsonBody("{\"name\":\"bus-logs\"}"); + assertEquals(List.of(prefix + "delivery-destination:bus-logs"), + builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws")); + } + for (String action : List.of("logs:GetDelivery", "logs:DeleteDelivery", "logs:UpdateDeliveryConfiguration")) { + setJsonBody("{\"id\":\"AbCdEfGh12345678\"}"); + assertEquals(List.of(prefix + "delivery:AbCdEfGh12345678"), + builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws")); + } + setJsonBody("{\"deliverySourceName\":\"bus-source\",\"deliveryDestinationArn\":\"" + + prefix + "delivery-destination:bus-logs\"}"); + assertEquals(List.of(prefix + "delivery-destination:bus-logs", prefix + "delivery:*", + prefix + "delivery-source:bus-source"), + builder.buildLogResources("logs:CreateDelivery", ctx, "us-east-1", ACCOUNT, "aws")); + for (String action : List.of("logs:DescribeDeliverySources", "logs:DescribeDeliveryDestinations", + "logs:DescribeDeliveries")) { + setJsonBody("{}"); + assertEquals(List.of("*"), builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws")); + } + } + @Test void excludedLogsActionsKeepWildcardResources() { for (String action : List.of("logs:PutLogEvents")) { diff --git a/src/test/java/io/github/hectorvent/floci/testing/LogsRequests.java b/src/test/java/io/github/hectorvent/floci/testing/LogsRequests.java new file mode 100644 index 0000000000..b4d65166e4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/LogsRequests.java @@ -0,0 +1,31 @@ +package io.github.hectorvent.floci.testing; + +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +import java.util.Map; + +import static io.restassured.RestAssured.given; + +/** Sends CloudWatch Logs JSON 1.1 requests, signed for {@code us-east-1} unless a Region is given. */ +public final class LogsRequests { + private LogsRequests() {} + + public static Response logs(String action, String body) { + return logs("us-east-1", action, body); + } + + public static Response logs(String action, Map body) { + return request("us-east-1", action).body(body).post("/"); + } + + public static Response logs(String region, String action, String body) { + return request(region, action).body(body).post("/"); + } + + private static RequestSpecification request(String region, String action) { + return given().contentType("application/x-amz-json-1.1") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20261103/" + region + "/logs/aws4_request") + .header("X-Amz-Target", "Logs_20140328." + action); + } +} diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index 19d6815487..ee27933ffd 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -61,7 +61,9 @@ names none, is checked on `*`, as AWS checks it. Every operation in `NAMESPACES` is read, whether Floci serves it or not. Explicit `CORRECTIONS` in `HAND_BUILT` are also read, overriding only those operations while the remaining operations -keep their existing resource builders. `HAND_BUILT` are the namespaces `ResourceArnBuilder` builds resources for itself, and +keep their existing resource builders, and so are the operations `READ_IN_HAND_BUILT` lists, which +follow the rule unchanged: a family of a hand-built namespace whose requests name their resources the +way the rule reads them. `HAND_BUILT` are the namespaces `ResourceArnBuilder` builds resources for itself, and `NOT_COVERED` the ones Floci serves that are not read yet, each with its reason; `RequestResourceNamespacesIntegrationTest` fails for a served namespace in none of the three. `CORRECTIONS` gives an operation's resources where the rule gets them wrong, each with its reason; a @@ -157,6 +159,17 @@ CLIENTS_NOT_READ: dict[str, str] = { HAND_BUILT = ("apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts") +# Operations of a namespace in `HAND_BUILT` read from the reference all the same, each with its reason. +_LOGS_DELIVERY = ("CloudWatch Logs vended-log delivery: its requests name a delivery source, destination or delivery " + "by the member the rule reads, while ResourceArnBuilder keeps building the log group and stream ARNs") +READ_IN_HAND_BUILT: dict[str, str] = { + f"logs:{operation}": _LOGS_DELIVERY + for operation in ("PutDeliverySource", "GetDeliverySource", "DeleteDeliverySource", "DescribeDeliverySources", + "PutDeliveryDestination", "GetDeliveryDestination", "DeleteDeliveryDestination", + "DescribeDeliveryDestinations", "CreateDelivery", "GetDelivery", "UpdateDeliveryConfiguration", + "DeleteDelivery", "DescribeDeliveries") +} + _LATER = "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint" _REST = "REST: its requests name their resources in the path, which RequestResources does not read yet" @@ -262,6 +275,21 @@ NOT_COVERED: dict[str, str] = { # them apart (EventBridge's `events` and EventBridge V2's `eventsv2`): Floci applies it only to a request the service # of that endpoint serves, never by a member a caller could add to a request of the other. CORRECTIONS: dict[str, tuple[list[dict], str]] = { + "logs:PutDeliverySource": ([{"type": "delivery-source", "fill": {"DeliverySourceName": "name"}}], + "resourceArn is the ARN of the resource that sends the logs (an event bus, a load " + "balancer), never the delivery source's, which the request names by name"), + "logs:DeleteDeliverySource": ([{"type": "delivery-source", "fill": {"DeliverySourceName": "name"}}], + "the reference lists only delivery-destination, which nothing in the request names, " + "so the rule would authorize it on * and a deny on the source it deletes would not " + "apply; the request names that source by name"), + "logs:PutDeliveryDestination": ([{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "name"}}], + "deliveryDestinationConfiguration.destinationResourceArn is the log group, bucket " + "or stream the logs go to and roleArn a role, neither the delivery destination, " + "which the request names by name"), + **{f"logs:{operation}": ([{"type": "delivery", "fill": {"DeliveryName": "id"}}], + "the delivery format ends in ${DeliveryName}, while a delivery is named by the id " + "CreateDelivery mints, which the request gives in id") + for operation in ("GetDelivery", "DeleteDelivery", "UpdateDeliveryConfiguration")}, "dynamodb:ListTables": ([{"type": "table", "fill": {}}], "AWS policy probes accepted by review #7336 authorize the literal regional table/*: " "table/? matches while table/ does not, despite the Service Reference listing no " @@ -970,15 +998,21 @@ def _with_resource_types(documents: list[dict]) -> set[str]: def reads(operation: str) -> bool: - """Read whole namespaces, or explicit corrections in a namespace otherwise built by hand.""" + """Read whole namespaces, and in a namespace otherwise built by hand its explicit corrections and the + operations `READ_IN_HAND_BUILT` lists.""" namespace = namespace_of(operation) - return namespace in NAMESPACES or namespace in HAND_BUILT and operation in CORRECTIONS + return namespace in NAMESPACES or namespace in HAND_BUILT and (operation in CORRECTIONS + or operation in READ_IN_HAND_BUILT) def _check_overrides(covered: dict[str, dict]) -> None: """Every correction names an operation the file reads, and no namespace is in two places.""" stale = [f"CORRECTIONS names {operation}, which the file does not read" for operation in CORRECTIONS if operation not in covered] + stale += [f"READ_IN_HAND_BUILT names {operation}, which the reference does not give" for operation in READ_IN_HAND_BUILT + if operation not in covered] + stale += [f"READ_IN_HAND_BUILT names {operation}, outside HAND_BUILT" for operation in READ_IN_HAND_BUILT + if namespace_of(operation) not in HAND_BUILT] for left, right in (("NAMESPACES", "HAND_BUILT"), ("NAMESPACES", "NOT_COVERED"), ("HAND_BUILT", "NOT_COVERED")): stale += [f"{namespace} is in both {left} and {right}" for namespace in sorted(set(globals()[left]) & set(globals()[right]))] diff --git a/tools/aws/regen_logs_delivery_shapes.py b/tools/aws/regen_logs_delivery_shapes.py new file mode 100644 index 0000000000..6652b711d9 --- /dev/null +++ b/tools/aws/regen_logs_delivery_shapes.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Vendor CloudWatch Logs vended-log delivery request constraints from botocore's Apache-2.0 service model.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from regen_partitions import resolve_botocore_data, strip_source +from request_shapes import REPO_ROOT, build_constraints, load_model + +OUTPUT = REPO_ROOT / "src/main/resources/aws/logs-delivery-request-shapes.json" +MODEL = Path("logs/2014-03-28") +OPERATIONS = ("PutDeliverySource", "GetDeliverySource", "DeleteDeliverySource", "DescribeDeliverySources", + "PutDeliveryDestination", "GetDeliveryDestination", "DeleteDeliveryDestination", + "DescribeDeliveryDestinations", "CreateDelivery", "GetDelivery", "UpdateDeliveryConfiguration", + "DeleteDelivery", "DescribeDeliveries") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + parser.add_argument("--botocore-data", type=Path) + args = parser.parse_args() + data, provenance = resolve_botocore_data(args.botocore_data) + doc = build_constraints(load_model(data, MODEL), OPERATIONS, provenance, "tools/aws/regen_logs_delivery_shapes.py") + fresh = json.dumps(doc, indent=2) + "\n" + if args.check: + return int(not OUTPUT.exists() or strip_source(OUTPUT.read_text()) != strip_source(fresh)) + OUTPUT.write_text(fresh) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.py index ea196ced4f..3c5716c09c 100644 --- a/tools/aws/request_shapes.py +++ b/tools/aws/request_shapes.py @@ -2,7 +2,7 @@ `regen_dynamodb_shapes.py`, `regen_sesv2_shapes.py`, `regen_apigateway_shapes.py` and `regen_ecs_shapes.py` each name a botocore model and an output file and hand the rest to -`main()`. `regen_resource_groups_shapes.py` and +`main()`. `regen_resource_groups_shapes.py`, `regen_logs_delivery_shapes.py` and `regen_ecr_shapes.py` vendor constraints as well, through `build_constraints()`. The output keeps only what `RequestShapeModel` reads: the input shape of every operation, reduced to the members carried in the JSON body, and for every shape reachable from one, its type and the shapes of its members, list elements or map values. diff --git a/tools/aws/test_regen_iam_request_resources.py b/tools/aws/test_regen_iam_request_resources.py index 6e99dda51f..bd5486e368 100644 --- a/tools/aws/test_regen_iam_request_resources.py +++ b/tools/aws/test_regen_iam_request_resources.py @@ -181,6 +181,7 @@ def corrections(monkeypatch): monkeypatch.setattr(r, "HAND_BUILT", ("hand",)) monkeypatch.setattr(r, "NOT_COVERED", {"later": "a later batch"}) monkeypatch.setattr(r, "CORRECTIONS", {}) + monkeypatch.setattr(r, "READ_IN_HAND_BUILT", {}) monkeypatch.setattr(r, "UNQUALIFIED", {}) monkeypatch.setattr(r, "MINTED_IDS", {}) monkeypatch.setattr(r, "FOUND_BY", {}) @@ -693,6 +694,28 @@ def test_hand_built_correction_is_generated_without_claiming_other_operations(co assert r.verify_against(document, r.checked_actions(documents), document["arnFormats"]) == ([], []) +def test_hand_built_operations_listed_to_read_follow_the_rule(corrections, tmp_path): + corrections.setattr(r, "READ_IN_HAND_BUILT", {"hand:GetThing": "a family the rule reads"}) + documents = DOCUMENTS + [reference("hand", {"GetThing": ["thing"], "PutThing": ["thing"]}, + {"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"})] + hand = model({"GetThing": {"ThingName": "String"}, "PutThing": {"ThingName": "String"}}) + hand["metadata"]["endpointPrefix"] = "hand" + write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}), "hand": hand}) + document = r.build(documents, "test", tmp_path, "botocore test") + assert document["operations"]["hand:GetThing"] == { + "action": "hand:GetThing", "types": ["thing"], "resources": [{"type": "thing", "fill": {"ThingName": "ThingName"}}]} + assert "hand:PutThing" not in document["operations"] + assert r.reads("hand:GetThing") and not r.reads("hand:PutThing") + assert r.validate(document) == [] + + +def test_operations_listed_to_read_must_exist_and_be_hand_built(corrections, tmp_path): + write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})}) + corrections.setattr(r, "READ_IN_HAND_BUILT", {"hand:Gone": "no longer there"}) + with pytest.raises(ValueError, match="READ_IN_HAND_BUILT names hand:Gone, which the reference does not give"): + r.build(DOCUMENTS, "test", tmp_path, "botocore test") + + def test_measured_callback_correction_retains_action_metadata_and_rejects_unlisted_resources(): formats = {"activity": "arn:${Partition}:states:${Region}:${Account}:activity:${ActivityName}", "statemachine": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}"} diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index e48ae383d9..96fa3313d5 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -23,6 +23,7 @@ import regen_ecs_shapes import regen_emr_serverless_shapes import regen_iam_shapes import regen_payment_cryptography_shapes +import regen_logs_delivery_shapes import regen_resource_groups_shapes import regen_sesv2_shapes import regen_sts_shapes @@ -354,7 +355,7 @@ def vendored(script) -> tuple[str, ...]: @pytest.mark.parametrize("script", [ - regen_ecr_shapes, regen_iam_shapes, regen_payment_cryptography_shapes, + regen_ecr_shapes, regen_iam_shapes, regen_logs_delivery_shapes, regen_payment_cryptography_shapes, regen_resource_groups_shapes, regen_sts_shapes, ]) def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script): diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 2c712bba0b..267dbd3472 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -452,6 +452,7 @@ deferred_handlers: - { path: services/cloudmap/CloudMapHandler.java } # non-tabular doc (grouped/inline) - { path: services/cloudwatch/logs/CloudWatchLogsHandler.java } # multi-table doc (nested handler) - { path: services/cloudwatch/logs/CloudWatchLogsMetricFilterHandler.java } # multi-table doc (nested handler, reached through CloudWatchLogsHandler) + - { path: services/cloudwatch/logs/CloudWatchLogsDeliveryHandler.java } # multi-table doc (nested handler, reached through CloudWatchLogsHandler) - { path: services/cloudwatch/metrics/CloudWatchMetricsJsonHandler.java } # multi-table doc (nested handler) - { path: services/cloudwatch/metrics/CloudWatchMetricsQueryHandler.java } # multi-table doc (nested handler) - { path: services/codebuild/CodeBuildJsonHandler.java } # non-tabular doc (grouped/inline)