feat(logs): add vended log delivery sources, destinations and deliveries (#7411)

This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-11-03 13:20:11 -04:00
1 parent 8c252ef0de
commit 3308ea2f1c
27 files changed
+1709 -42

No files matched your search

@@ -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<String, String> tags;
@@ -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 <T> Response page(String member, PaginatedResult<T> page, Function<T, ObjectNode> 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<String, String> stringMap(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
}
Map<String, String> map = new LinkedHashMap<>();
node.properties().forEach(entry -> map.put(entry.getKey(), entry.getValue().asText()));
return map;
}
private static List<String> stringList(JsonNode node) {
if (node == null || !node.isArray()) {
return null;
}
List<String> list = new ArrayList<>();
node.forEach(value -> list.add(value.asText()));
return list;
}
}
@@ -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<String> 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<String> 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<String> 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;
}
}
@@ -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<String> 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<String> 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<String, DeliverySource> sources;
private final StorageBackend<String, DeliveryDestination> destinations;
private final StorageBackend<String, Delivery> deliveries;
private final RegionResolver regionResolver;
@Inject
public CloudWatchLogsDeliveryService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory.create("cloudwatchlogs", "cwlogs-delivery-sources.json",
new TypeReference<Map<String, DeliverySource>>() {}),
storageFactory.create("cloudwatchlogs", "cwlogs-delivery-destinations.json",
new TypeReference<Map<String, DeliveryDestination>>() {}),
storageFactory.create("cloudwatchlogs", "cwlogs-deliveries.json",
new TypeReference<Map<String, Delivery>>() {}),
regionResolver);
}
CloudWatchLogsDeliveryService(StorageBackend<String, DeliverySource> sources,
StorageBackend<String, DeliveryDestination> destinations,
StorageBackend<String, Delivery> 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<String, String> configuration,
Map<String, String> tags, String region) {
if (!AwsArnUtils.isArn(resourceArn)) {
throw validation("resourceArn must be the ARN of the resource that sends the logs.");
}
Optional<DeliverySource> 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<DeliverySource> describeDeliverySources(Integer limit, String nextToken,
List<String> resourceArns, String region) {
List<DeliverySource> 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<String, String> tags, String region) {
String resolvedType = destinationType(destinationResourceArn, type);
Optional<DeliveryDestination> 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<DeliveryDestination> describeDeliveryDestinations(Integer limit, String nextToken,
List<String> names, String region) {
List<DeliveryDestination> 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<String> recordFields,
String fieldDelimiter, Boolean enableHiveCompatiblePath,
String suffixPath, Map<String, String> 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<String> 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<Delivery> describeDeliveries(Integer limit, String nextToken,
List<String> deliverySourceNames, String region) {
List<Delivery> 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<String, String> 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<String, String> tags, String region) {
retag(arn, region, current -> {
Map<String, String> 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<String> keys, String region) {
retag(arn, region, current -> {
Map<String, String> remaining = new LinkedHashMap<>(current);
keys.forEach(remaining::remove);
return remaining;
});
}
private void retag(String arn, String region, UnaryOperator<Map<String, String>> 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 <T> PaginatedResult<T> page(List<T> all, Function<T, String> 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 + "::";
}
}
@@ -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<String, String> 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<String, String> 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<String> 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();
}
@@ -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());
}
@@ -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<String> recordFields = new ArrayList<>();
private String fieldDelimiter;
private Boolean enableHiveCompatiblePath;
private String suffixPath;
private Map<String, String> 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<String> getRecordFields() { return recordFields; }
public void setRecordFields(List<String> 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<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); }
}
@@ -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<String, String> 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<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); }
}
@@ -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<String> resourceArns = new ArrayList<>();
private String service;
private String logType;
private Map<String, String> deliverySourceConfiguration = new LinkedHashMap<>();
private Map<String, String> 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<String> getResourceArns() { return resourceArns; }
public void setResourceArns(List<String> 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<String, String> getDeliverySourceConfiguration() { return deliverySourceConfiguration; }
public void setDeliverySourceConfiguration(Map<String, String> configuration) {
this.deliverySourceConfiguration = configuration != null ? configuration : new LinkedHashMap<>();
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new LinkedHashMap<>(); }
}
@@ -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<String> 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