Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudwatchlogs): add cross-account policy operations (#3089)
Franklin G. Mendoza6a728f1b9fe5
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsCrossAccountPolicyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsCrossAccountPolicyTest.javanew file mode 100644index 0000000000..2c86ea56ae--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsCrossAccountPolicyTest.java@@ -0,0 +1,92 @@+package com.floci.test;++import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;+import software.amazon.awssdk.services.cloudwatchlogs.model.InvalidParameterException;+import software.amazon.awssdk.services.cloudwatchlogs.model.LimitExceededException;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.junit.jupiter.api.Assumptions.assumeFalse;++@DisplayName("CloudWatch Logs cross-account management APIs")+class CloudWatchLogsCrossAccountPolicyTest {+ private static final String DESTINATION_NAME = "floci-sdk-cross-account-destination";+ private static final String POLICY_NAME = "floci-sdk-cross-account-transformer";++ @Test+ @DisplayName("uses AWS SDK models for destination and account policy operations")+ void destinationAndAccountPolicyOperationsUseAwsSdk() {+ assumeFalse(TestFixtures.isRealAws(), "Uses emulator-only destination ARNs and persistent test resources");++ try (CloudWatchLogsClient logs = TestFixtures.cloudWatchLogsClient()) {+ var putDestination = logs.putDestination(request -> request+ .destinationName(DESTINATION_NAME)+ .targetArn("arn:aws:kinesis:us-east-1:000000000000:stream/floci-sdk-logs")+ .roleArn("arn:aws:iam::000000000000:role/floci-sdk-logs"));++ assertThat(putDestination.destination()).isNotNull();+ assertThat(putDestination.destination().destinationName()).isEqualTo(DESTINATION_NAME);+ assertThat(putDestination.destination().arn()).contains(":logs:us-east-1:");++ logs.putDestinationPolicy(request -> request+ .destinationName(DESTINATION_NAME)+ .accessPolicy("{\"Version\":\"2012-10-17\",\"Statement\":[]}"));++ var putPolicy = logs.putAccountPolicy(request -> request+ .policyName(POLICY_NAME)+ .policyType("TRANSFORMER_POLICY")+ .policyDocument("[{\"parseJSON\":{}}]")+ .selectionCriteria("LogGroupNamePrefix = \"/floci/sdk-cross-account/\"")+ .scope("ALL"));++ assertThat(putPolicy.accountPolicy()).isNotNull();+ assertThat(putPolicy.accountPolicy().policyName()).isEqualTo(POLICY_NAME);+ assertThat(putPolicy.accountPolicy().policyTypeAsString()).isEqualTo("TRANSFORMER_POLICY");++ var policies = logs.describeAccountPolicies(request -> request.policyType("TRANSFORMER_POLICY"));+ assertThat(policies.accountPolicies())+ .anySatisfy(policy -> {+ assertThat(policy.policyName()).isEqualTo(POLICY_NAME);+ assertThat(policy.selectionCriteria())+ .isEqualTo("LogGroupNamePrefix = \"/floci/sdk-cross-account/\"");+ });++ var fieldIndex = logs.putAccountPolicy(request -> request+ .policyName("floci-sdk-field-index-quoted-value")+ .policyType("FIELD_INDEX_POLICY")+ .policyDocument("{\"Fields\":[\"requestId\"]}")+ .selectionCriteria("LogGroupNamePrefix = \"/DataSourceName/DataSourceType/\"")+ .scope("ALL"));++ assertThat(fieldIndex.accountPolicy().selectionCriteria())+ .isEqualTo("LogGroupNamePrefix = \"/DataSourceName/DataSourceType/\"");++ assertThatThrownBy(() -> logs.putAccountPolicy(request -> request+ .policyName("floci-sdk-field-index-global")+ .policyType("FIELD_INDEX_POLICY")+ .policyDocument("{\"Fields\":[\"requestId\"]}")+ .scope("ALL")))+ .isInstanceOfSatisfying(LimitExceededException.class, error ->+ assertThat(error.awsErrorDetails().errorCode()).isEqualTo("LimitExceededException"));+ }+ }++ @Test+ @DisplayName("returns the modeled SDK error for mixed field-index selection criteria")+ void mixedFieldIndexCriteriaReturnsSdkInvalidParameterException() {+ assumeFalse(TestFixtures.isRealAws(), "Avoids mutating account-level policies in real AWS");++ try (CloudWatchLogsClient logs = TestFixtures.cloudWatchLogsClient()) {+ assertThatThrownBy(() -> logs.putAccountPolicy(request -> request+ .policyName("floci-sdk-invalid-mixed-index")+ .policyType("FIELD_INDEX_POLICY")+ .policyDocument("{\"Fields\":[\"requestId\"]}")+ .selectionCriteria("LogGroupNamePrefix = \"/floci/\" AND DataSourceName = \"amazon_vpc\" AND DataSourceType = \"flow\"")+ .scope("ALL")))+ .isInstanceOfSatisfying(InvalidParameterException.class, error ->+ assertThat(error.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterException"));+ }+ }+}diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.mdindex 65f051b5bb..6142fce2d0 100644--- a/docs/services/cloudwatch.md+++ b/docs/services/cloudwatch.md@@ -38,6 +38,10 @@ Floci supports both CloudWatch Logs and CloudWatch Metrics.| `DeleteSubscriptionFilter` | Delete a subscription filter || `PutResourcePolicy` | Create or update an account-level resource policy || `DescribeResourcePolicies` | List account-level resource policies |+| `PutDestination` | Create or update a cross-account subscription destination |+| `PutDestinationPolicy` | Create or update the access policy for a destination |+| `PutAccountPolicy` | Create or update an account-level Logs policy |+| `DescribeAccountPolicies` | List account-level Logs policies by type and optional name || `GetDataProtectionPolicy` | Return the resolved log group identifier (see note below) || `StartQuery` | Start a Logs Insights query (see [Logs Insights](#logs-insights)) || `GetQueryResults` | Get the status and results of a Logs Insights query |diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.javanew file mode 100644index 0000000000..f67cf24c0c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java@@ -0,0 +1,328 @@+package io.github.hectorvent.floci.services.cloudwatch.logs;++import com.fasterxml.jackson.core.type.TypeReference;+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.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.AccountPolicy;+import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogDestination;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.nio.charset.StandardCharsets;+import java.util.Comparator;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++@ApplicationScoped+public class CloudWatchLogsCrossAccountService {+ private static final Pattern DESTINATION_NAME = Pattern.compile("[^:*]{1,512}");+ private static final Pattern METRIC_SELECTION_CRITERIA = Pattern.compile(+ "\\s*(LogGroupName|LogGroupNamePrefix)\\s+(IN|NOT\\s+IN)\\s*(\\[.*])\\s*",+ Pattern.DOTALL);+ private static final Pattern QUOTED_SELECTION_VALUE = Pattern.compile(+ "'(?:\\\\.|[^'\\\\])*'|\"(?:\\\\.|[^\"\\\\])*\"");+ private static final Set<String> POLICY_TYPES = Set.of(+ "DATA_PROTECTION_POLICY", "SUBSCRIPTION_FILTER_POLICY", "FIELD_INDEX_POLICY",+ "TRANSFORMER_POLICY", "METRIC_EXTRACTION_POLICY");+ private static final int DESTINATION_POLICY_MAX_BYTES = 5120;+ private static final int ACCOUNT_POLICY_MAX_CHARS = 30_720;+ private static final int SELECTION_CRITERIA_MAX_BYTES = 25 * 1024;++ private final StorageBackend<String, LogDestination> destinations;+ private final StorageBackend<String, AccountPolicy> accountPolicies;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;++ @Inject+ public CloudWatchLogsCrossAccountService(StorageFactory storageFactory, RegionResolver regionResolver,+ ObjectMapper objectMapper) {+ this(+ storageFactory.create("cloudwatchlogs", "cwlogs-destinations.json",+ new TypeReference<Map<String, LogDestination>>() {}),+ storageFactory.create("cloudwatchlogs", "cwlogs-account-policies.json",+ new TypeReference<Map<String, AccountPolicy>>() {}),+ regionResolver, objectMapper);+ }++ CloudWatchLogsCrossAccountService(StorageBackend<String, LogDestination> destinations,+ StorageBackend<String, AccountPolicy> accountPolicies,+ RegionResolver regionResolver, ObjectMapper objectMapper) {+ this.destinations = destinations;+ this.accountPolicies = accountPolicies;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ }++ public synchronized LogDestination putDestination(String destinationName, String targetArn,+ String roleArn, String region) {+ validateDestinationName(destinationName);+ requireArn(targetArn, "targetArn");+ requireArn(roleArn, "roleArn");+ String key = destinationKey(region, destinationName);+ LogDestination destination = destinations.get(key).orElseGet(LogDestination::new);+ destination.setDestinationName(destinationName);+ destination.setTargetArn(targetArn);+ destination.setRoleArn(roleArn);+ destination.setArn("arn:aws:logs:" + region + ":" + regionResolver.getAccountId() + ":destination:" + destinationName);+ if (destination.getCreationTime() == 0) {+ destination.setCreationTime(System.currentTimeMillis());+ }+ destinations.put(key, destination);+ return destination;+ }++ public synchronized void putDestinationPolicy(String destinationName, String accessPolicy, String region) {+ validateDestinationName(destinationName);+ requireJsonObject(accessPolicy, "accessPolicy", DESTINATION_POLICY_MAX_BYTES);+ String key = destinationKey(region, destinationName);+ LogDestination destination = destinations.get(key)+ .orElseThrow(() -> invalid("The specified destination does not exist."));+ destination.setAccessPolicy(accessPolicy);+ destinations.put(key, destination);+ }++ public synchronized AccountPolicy putAccountPolicy(String policyName, String policyDocument,+ String policyType, String selectionCriteria, String scope,+ String region) {+ validatePolicyName(policyName);+ if (policyType == null || !POLICY_TYPES.contains(policyType)) {+ throw invalid("policyType is invalid.");+ }+ requirePolicyDocument(policyDocument, policyType);+ if (scope != null && !"ALL".equals(scope)) {+ throw invalid("scope must be ALL.");+ }+ validateSelectionCriteria(policyType, selectionCriteria);++ String key = policyKey(region, policyType, policyName);+ validatePolicyQuota(region, policyType, policyName, selectionCriteria);++ AccountPolicy policy = accountPolicies.get(key).orElseGet(AccountPolicy::new);+ policy.setAccountId(regionResolver.getAccountId());+ policy.setPolicyName(policyName);+ policy.setPolicyDocument(policyDocument);+ policy.setPolicyType(policyType);+ policy.setSelectionCriteria(selectionCriteria);+ policy.setScope(scope == null || scope.isBlank() ? "ALL" : scope);+ policy.setLastUpdatedTime(System.currentTimeMillis());+ accountPolicies.put(key, policy);+ return policy;+ }++ public List<AccountPolicy> describeAccountPolicies(String policyType, String policyName, String region) {+ if (policyType == null || !POLICY_TYPES.contains(policyType)) {+ throw invalid("policyType is required and must be valid.");+ }+ List<AccountPolicy> result = accountPolicies.scan(key -> key.startsWith(region + "::" + policyType + "::")).stream()+ .filter(policy -> policyName == null || policyName.equals(policy.getPolicyName()))+ .sorted(Comparator.comparing(AccountPolicy::getPolicyName))+ .toList();+ if (policyName != null && result.isEmpty()) {+ throw new AwsException("ResourceNotFoundException", "The specified account policy does not exist.", 400);+ }+ return result;+ }++ private void validatePolicyQuota(String region, String type, String policyName, String selectionCriteria) {+ List<AccountPolicy> others = accountPolicies.scan(key -> key.startsWith(region + "::" + type + "::")).stream()+ .filter(policy -> !policyName.equals(policy.getPolicyName()))+ .toList();+ boolean scoped = hasSelectionCriteria(selectionCriteria);++ switch (type) {+ case "DATA_PROTECTION_POLICY", "SUBSCRIPTION_FILTER_POLICY" -> {+ if (!others.isEmpty()) {+ throw quotaExceeded(type);+ }+ }+ case "TRANSFORMER_POLICY" -> validateExclusiveScopedQuota(type, scoped, 20, others);+ case "METRIC_EXTRACTION_POLICY" -> validateExclusiveScopedQuota(type, scoped, 5, others);+ case "FIELD_INDEX_POLICY" -> validateFieldIndexQuota(selectionCriteria, others);+ default -> {+ // policyType is validated before this method is called.+ }+ }+ }++ private static void validateExclusiveScopedQuota(String type, boolean scoped, int scopedLimit,+ List<AccountPolicy> others) {+ long scopedCount = others.stream()+ .filter(policy -> hasSelectionCriteria(policy.getSelectionCriteria()))+ .count();+ boolean hasUnscoped = others.stream()+ .anyMatch(policy -> !hasSelectionCriteria(policy.getSelectionCriteria()));+ if (scoped ? hasUnscoped || scopedCount >= scopedLimit : !others.isEmpty()) {+ throw quotaExceeded(type);+ }+ }++ private static void validateFieldIndexQuota(String selectionCriteria, List<AccountPolicy> others) {+ FieldIndexScope requestedScope = fieldIndexScope(selectionCriteria);+ long prefixCount = others.stream()+ .filter(policy -> fieldIndexScope(policy.getSelectionCriteria()) == FieldIndexScope.PREFIX)+ .count();+ long dataSourceCount = others.stream()+ .filter(policy -> fieldIndexScope(policy.getSelectionCriteria()) == FieldIndexScope.DATA_SOURCE)+ .count();+ boolean hasGlobal = others.stream()+ .anyMatch(policy -> fieldIndexScope(policy.getSelectionCriteria()) == FieldIndexScope.GLOBAL);++ boolean exceeded = switch (requestedScope) {+ case GLOBAL -> hasGlobal || prefixCount > 0;+ case PREFIX -> hasGlobal || prefixCount >= 20;+ case DATA_SOURCE -> dataSourceCount >= 20;+ };+ if (exceeded) {+ throw quotaExceeded("FIELD_INDEX_POLICY");+ }+ }++ private static boolean hasSelectionCriteria(String selectionCriteria) {+ return selectionCriteria != null && !selectionCriteria.isBlank();+ }++ private static FieldIndexScope fieldIndexScope(String selectionCriteria) {+ if (!hasSelectionCriteria(selectionCriteria)) {+ return FieldIndexScope.GLOBAL;+ }+ String operators = fieldIndexOperators(selectionCriteria);+ if (operators.contains("DataSourceName") && operators.contains("DataSourceType")) {+ return FieldIndexScope.DATA_SOURCE;+ }+ return FieldIndexScope.PREFIX;+ }++ private static String fieldIndexOperators(String selectionCriteria) {+ return QUOTED_SELECTION_VALUE.matcher(selectionCriteria).replaceAll("");+ }++ private static AwsException quotaExceeded(String policyType) {+ return new AwsException("LimitExceededException",+ "The account policy quota for " + policyType + " has been exceeded.", 400);+ }++ private void validateSelectionCriteria(String policyType, String selectionCriteria) {+ if (selectionCriteria == null || selectionCriteria.isBlank()) {+ return;+ }+ if (selectionCriteria.getBytes(StandardCharsets.UTF_8).length > SELECTION_CRITERIA_MAX_BYTES) {+ throw invalid("selectionCriteria exceeds 25 KB.");+ }+ switch (policyType) {+ case "DATA_PROTECTION_POLICY" ->+ throw invalid("selectionCriteria is not supported for data protection policies.");+ case "METRIC_EXTRACTION_POLICY" -> validateMetricSelectionCriteria(selectionCriteria);+ case "SUBSCRIPTION_FILTER_POLICY" -> {+ if (!selectionCriteria.matches("\\s*LogGroupName\\s+NOT\\s+IN\\s*\\[.*]\\s*")) {+ throw invalid("Subscription filter selectionCriteria must use LogGroupName NOT IN [...].");+ }+ }+ case "TRANSFORMER_POLICY" -> {+ if (!selectionCriteria.contains("LogGroupNamePrefix")) {+ throw invalid("Transformer selectionCriteria must use LogGroupNamePrefix.");+ }+ }+ case "FIELD_INDEX_POLICY" -> {+ String operators = fieldIndexOperators(selectionCriteria);+ boolean prefix = operators.contains("LogGroupNamePrefix");+ boolean dataSourceName = operators.contains("DataSourceName");+ boolean dataSourceType = operators.contains("DataSourceType");+ boolean prefixOnly = prefix && !dataSourceName && !dataSourceType;+ boolean dataSourcePairOnly = !prefix && dataSourceName && dataSourceType;+ if (!prefixOnly && !dataSourcePairOnly) {+ throw invalid("Field index selectionCriteria must use either LogGroupNamePrefix or DataSourceName and DataSourceType.");+ }+ }+ default -> throw invalid("policyType is invalid.");+ }+ }++ private void validateMetricSelectionCriteria(String selectionCriteria) {+ Matcher matcher = METRIC_SELECTION_CRITERIA.matcher(selectionCriteria);+ if (!matcher.matches()) {+ throw invalid("Metric extraction selectionCriteria must use LogGroupName or LogGroupNamePrefix with IN or NOT IN.");+ }+ try {+ JsonNode values = objectMapper.readTree(matcher.group(3));+ if (!values.isArray() || values.isEmpty() || values.size() > 50) {+ throw invalid("Metric extraction selectionCriteria must contain between 1 and 50 values.");+ }+ for (JsonNode value : values) {+ if (!value.isTextual() || value.textValue().isBlank()) {+ throw invalid("Metric extraction selectionCriteria values must be non-empty strings.");+ }+ }+ } catch (AwsException e) {+ throw e;+ } catch (Exception e) {+ throw invalid("Metric extraction selectionCriteria must contain a valid JSON string array.");+ }+ }++ private enum FieldIndexScope {+ GLOBAL,+ PREFIX,+ DATA_SOURCE+ }++ private void requireJsonObject(String value, String field, int maxBytes) {+ JsonNode document = parseJson(value, field, maxBytes, true);+ if (!document.isObject()) {+ throw invalid(field + " must contain a JSON object.");+ }+ }++ private void requirePolicyDocument(String value, String policyType) {+ JsonNode document = parseJson(value, "policyDocument", ACCOUNT_POLICY_MAX_CHARS, false);+ if ("TRANSFORMER_POLICY".equals(policyType)) {+ if (!document.isArray() && !document.isObject()) {+ throw invalid("policyDocument must contain a JSON object or processor array.");+ }+ return;+ }+ if (!document.isObject()) {+ throw invalid("policyDocument must contain a JSON object.");+ }+ }++ private JsonNode parseJson(String value, String field, int max, boolean countUtf8Bytes) {+ if (value == null || value.isBlank()) {+ throw invalid(field + " is required.");+ }+ int size = countUtf8Bytes ? value.getBytes(StandardCharsets.UTF_8).length : value.length();+ if (size > max) {+ throw invalid(field + " exceeds the maximum size.");+ }+ try {+ return objectMapper.readTree(value);+ } catch (Exception e) {+ throw invalid(field + " must contain valid JSON.");+ }+ }++ private static void validateDestinationName(String value) {+ if (value == null || !DESTINATION_NAME.matcher(value).matches()) {+ throw invalid("destinationName is invalid.");+ }+ }+ private static void validatePolicyName(String value) {+ if (value == null || value.isBlank() || value.startsWith("aws/") || value.length() > 256) {+ throw invalid("policyName is invalid.");+ }+ }+ private static void requireArn(String value, String field) {+ if (value == null || !value.startsWith("arn:") || value.length() < 10) {+ throw invalid(field + " must be a valid ARN.");+ }+ }+ private static String destinationKey(String region, String name) { return region + "::" + name; }+ private static String policyKey(String region, String type, String name) { return region + "::" + type + "::" + name; }+ private static AwsException invalid(String message) { return new AwsException("InvalidParameterException", message, 400); }+}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.javaindex b4806531b7..86fd3e679b 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@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.cloudwatch.logs;import io.github.hectorvent.floci.core.common.AwsErrorResponse;import io.github.hectorvent.floci.core.common.AwsException;+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;import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream;@@ -25,11 +27,15 @@ import java.util.Map;public class CloudWatchLogsHandler {private final CloudWatchLogsService logsService;+ private final CloudWatchLogsCrossAccountService crossAccountService;private final ObjectMapper objectMapper;@Inject- public CloudWatchLogsHandler(CloudWatchLogsService logsService, ObjectMapper objectMapper) {+ public CloudWatchLogsHandler(CloudWatchLogsService logsService,+ CloudWatchLogsCrossAccountService crossAccountService,+ ObjectMapper objectMapper) {this.logsService = logsService;+ this.crossAccountService = crossAccountService;this.objectMapper = objectMapper;}@@ -60,6 +66,10 @@ public class CloudWatchLogsHandler {case "DisassociateKmsKey" -> handleDisassociateKmsKey(request, region);case "PutResourcePolicy" -> handlePutResourcePolicy(request, region);case "DescribeResourcePolicies" -> handleDescribeResourcePolicies(region);+ case "PutDestination" -> handlePutDestination(request, region);+ case "PutDestinationPolicy" -> handlePutDestinationPolicy(request, region);+ case "PutAccountPolicy" -> handlePutAccountPolicy(request, region);+ case "DescribeAccountPolicies" -> handleDescribeAccountPolicies(request, region);case "GetDataProtectionPolicy" -> handleGetDataProtectionPolicy(request, region);case "StartQuery" -> handleStartQuery(request, region);case "GetQueryResults" -> handleGetQueryResults(request, region);@@ -160,6 +170,74 @@ public class CloudWatchLogsHandler {return node;}+ private Response handlePutDestination(JsonNode request, String region) {+ LogDestination destination = crossAccountService.putDestination(+ request.path("destinationName").asText(null),+ request.path("targetArn").asText(null),+ request.path("roleArn").asText(null),+ region);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("destination", buildDestination(destination));+ return Response.ok(response).build();+ }++ private Response handlePutDestinationPolicy(JsonNode request, String region) {+ crossAccountService.putDestinationPolicy(+ request.path("destinationName").asText(null),+ request.path("accessPolicy").asText(null), region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handlePutAccountPolicy(JsonNode request, String region) {+ AccountPolicy policy = crossAccountService.putAccountPolicy(+ request.path("policyName").asText(null),+ request.path("policyDocument").asText(null),+ request.path("policyType").asText(null),+ request.path("selectionCriteria").asText(null),+ request.path("scope").asText(null), region);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("accountPolicy", buildAccountPolicy(policy));+ return Response.ok(response).build();+ }++ private Response handleDescribeAccountPolicies(JsonNode request, String region) {+ String policyType = request.path("policyType").asText(null);+ String policyName = request.path("policyName").asText(null);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode policies = response.putArray("accountPolicies");+ for (AccountPolicy policy : crossAccountService.describeAccountPolicies(policyType, policyName, region)) {+ policies.add(buildAccountPolicy(policy));+ }+ return Response.ok(response).build();+ }++ private ObjectNode buildDestination(LogDestination destination) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("destinationName", destination.getDestinationName());+ node.put("targetArn", destination.getTargetArn());+ node.put("roleArn", destination.getRoleArn());+ node.put("arn", destination.getArn());+ node.put("creationTime", destination.getCreationTime());+ if (destination.getAccessPolicy() != null) {+ node.put("accessPolicy", destination.getAccessPolicy());+ }+ return node;+ }++ private ObjectNode buildAccountPolicy(AccountPolicy policy) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("accountId", policy.getAccountId());+ node.put("policyName", policy.getPolicyName());+ node.put("policyDocument", policy.getPolicyDocument());+ node.put("policyType", policy.getPolicyType());+ node.put("scope", policy.getScope());+ node.put("lastUpdatedTime", policy.getLastUpdatedTime());+ if (policy.getSelectionCriteria() != null) {+ node.put("selectionCriteria", policy.getSelectionCriteria());+ }+ return node;+ }+private Response handleCreateLogStream(JsonNode request, String region) {String groupName = request.path("logGroupName").asText();String streamName = request.path("logStreamName").asText();diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/AccountPolicy.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/AccountPolicy.javanew file mode 100644index 0000000000..ec409df672--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/AccountPolicy.java@@ -0,0 +1,31 @@+package io.github.hectorvent.floci.services.cloudwatch.logs.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class AccountPolicy {+ private String accountId;+ private String policyName;+ private String policyDocument;+ private String policyType;+ private String selectionCriteria;+ private String scope;+ private long lastUpdatedTime;++ public String getAccountId() { return accountId; }+ public void setAccountId(String accountId) { this.accountId = accountId; }+ public String getPolicyName() { return policyName; }+ public void setPolicyName(String policyName) { this.policyName = policyName; }+ public String getPolicyDocument() { return policyDocument; }+ public void setPolicyDocument(String policyDocument) { this.policyDocument = policyDocument; }+ public String getPolicyType() { return policyType; }+ public void setPolicyType(String policyType) { this.policyType = policyType; }+ public String getSelectionCriteria() { return selectionCriteria; }+ public void setSelectionCriteria(String selectionCriteria) { this.selectionCriteria = selectionCriteria; }+ public String getScope() { return scope; }+ public void setScope(String scope) { this.scope = scope; }+ public long getLastUpdatedTime() { return lastUpdatedTime; }+ public void setLastUpdatedTime(long lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/LogDestination.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/LogDestination.javanew file mode 100644index 0000000000..a3fdf4a17e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/model/LogDestination.java@@ -0,0 +1,28 @@+package io.github.hectorvent.floci.services.cloudwatch.logs.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class LogDestination {+ private String destinationName;+ private String targetArn;+ private String roleArn;+ private String accessPolicy;+ private String arn;+ private long creationTime;++ public String getDestinationName() { return destinationName; }+ public void setDestinationName(String destinationName) { this.destinationName = destinationName; }+ public String getTargetArn() { return targetArn; }+ public void setTargetArn(String targetArn) { this.targetArn = targetArn; }+ public String getRoleArn() { return roleArn; }+ public void setRoleArn(String roleArn) { this.roleArn = roleArn; }+ public String getAccessPolicy() { return accessPolicy; }+ public void setAccessPolicy(String accessPolicy) { this.accessPolicy = accessPolicy; }+ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }+ public long getCreationTime() { return creationTime; }+ public void setCreationTime(long creationTime) { this.creationTime = creationTime; }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountIntegrationTest.javanew file mode 100644index 0000000000..b0080fc84b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountIntegrationTest.java@@ -0,0 +1,59 @@+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 static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasSize;++@QuarkusTest+class CloudWatchLogsCrossAccountIntegrationTest {+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/logs/aws4_request";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void destinationAndAccountPolicyLifecycle() {+ json("Logs_20140328.PutDestination",+ "{\"destinationName\":\"cross-account\",\"targetArn\":\"arn:aws:kinesis:us-east-1:000000000000:stream/logs\",\"roleArn\":\"arn:aws:iam::000000000000:role/logs\"}")+ .then().statusCode(200).body("destination.destinationName", equalTo("cross-account"));+ json("Logs_20140328.PutDestinationPolicy",+ "{\"destinationName\":\"cross-account\",\"accessPolicy\":\"{}\"}")+ .then().statusCode(200);+ json("Logs_20140328.PutAccountPolicy",+ "{\"policyName\":\"central-subscription\",\"policyDocument\":\"{}\",\"policyType\":\"SUBSCRIPTION_FILTER_POLICY\",\"scope\":\"ALL\"}")+ .then().statusCode(200).body("accountPolicy.policyName", equalTo("central-subscription"));+ json("Logs_20140328.DescribeAccountPolicies",+ "{\"policyType\":\"SUBSCRIPTION_FILTER_POLICY\"}")+ .then().statusCode(200).body("accountPolicies", hasSize(1));+ }++ @Test+ void transformerPolicyAcceptsProcessorArrayDocument() {+ json("Logs_20140328.PutAccountPolicy",+ "{\"policyName\":\"account-transformer\",\"policyDocument\":\"[{\\\"parseJSON\\\":{}}]\","+ + "\"policyType\":\"TRANSFORMER_POLICY\",\"scope\":\"ALL\"}")+ .then().statusCode(200)+ .body("accountPolicy.policyType", equalTo("TRANSFORMER_POLICY"))+ .body("accountPolicy.policyDocument", equalTo("[{\"parseJSON\":{}}]"));+ }++ @Test+ void destinationPolicyRequiresExistingDestination() {+ json("Logs_20140328.PutDestinationPolicy",+ "{\"destinationName\":\"missing\",\"accessPolicy\":\"{}\"}")+ .then().statusCode(400).body("__type", equalTo("InvalidParameterException"));+ }++ private static io.restassured.response.Response json(String target, String body) {+ return given().contentType(CONTENT_TYPE).header("Authorization", AUTH).header("X-Amz-Target", target)+ .body(body).post("/");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountServiceTest.javanew file mode 100644index 0000000000..f3d230817d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsCrossAccountServiceTest.java@@ -0,0 +1,125 @@+package io.github.hectorvent.floci.services.cloudwatch.logs;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++class CloudWatchLogsCrossAccountServiceTest {+ private static final String REGION = "us-east-1";+ private static final String DOCUMENT = "{}";++ private final CloudWatchLogsCrossAccountService service = new CloudWatchLogsCrossAccountService(+ new InMemoryStorage<>(), new InMemoryStorage<>(),+ new RegionResolver(REGION, "000000000000"), new ObjectMapper());++ @Test+ void transformerGlobalAndScopedPoliciesCannotCoexist() {+ service.putAccountPolicy("global", "[{\"parseJSON\":{}}]", "TRANSFORMER_POLICY", null, "ALL", REGION);++ AwsException error = assertThrows(AwsException.class,+ () -> service.putAccountPolicy("scoped", "[{\"parseJSON\":{}}]", "TRANSFORMER_POLICY",+ "LogGroupNamePrefix = 'aws/'", "ALL", REGION));++ assertEquals("LimitExceededException", error.getErrorCode());+ }++ @Test+ void updatingScopedTransformerToGlobalRevalidatesQuota() {+ service.putAccountPolicy("first", "[{\"parseJSON\":{}}]", "TRANSFORMER_POLICY",+ "LogGroupNamePrefix = 'aws/'", "ALL", REGION);+ service.putAccountPolicy("second", "[{\"parseJSON\":{}}]", "TRANSFORMER_POLICY",+ "LogGroupNamePrefix = 'app/'", "ALL", REGION);++ AwsException error = assertThrows(AwsException.class,+ () -> service.putAccountPolicy("first", "[{\"parseJSON\":{}}]", "TRANSFORMER_POLICY",+ null, "ALL", REGION));++ assertEquals("LimitExceededException", error.getErrorCode());+ }++ @Test+ void metricExtractionRejectsMalformedSelectionCriteria() {+ AwsException error = assertThrows(AwsException.class,+ () -> service.putAccountPolicy("metrics", DOCUMENT, "METRIC_EXTRACTION_POLICY",+ "not a criterion", "ALL", REGION));++ assertEquals("InvalidParameterException", error.getErrorCode());+ }++ @Test+ void metricExtractionAcceptsDocumentedSelectionCriteria() {+ service.putAccountPolicy("metrics", DOCUMENT, "METRIC_EXTRACTION_POLICY",+ "LogGroupNamePrefix IN [\"/aws/lambda/\",\"/app/\"]", "ALL", REGION);++ assertEquals(1, service.describeAccountPolicies("METRIC_EXTRACTION_POLICY", null, REGION).size());+ }++ @Test+ void fieldIndexRejectsMixedScopeForms() {+ AwsException error = assertThrows(AwsException.class,+ () -> service.putAccountPolicy("mixed-index", DOCUMENT, "FIELD_INDEX_POLICY",+ "LogGroupNamePrefix = 'aws/' AND DataSourceName = 'amazon_vpc' AND DataSourceType = 'flow'",+ "ALL", REGION));++ assertEquals("InvalidParameterException", error.getErrorCode());+ }++ @Test+ void fieldIndexRequiresCompleteDataSourcePair() {+ AwsException error = assertThrows(AwsException.class,+ () -> service.putAccountPolicy("partial-index", DOCUMENT, "FIELD_INDEX_POLICY",+ "DataSourceName = 'amazon_vpc'", "ALL", REGION));++ assertEquals("InvalidParameterException", error.getErrorCode());+ }++ @Test+ void fieldIndexIgnoresReservedFieldNamesInsidePrefixValue() {+ service.putAccountPolicy("prefix-index", DOCUMENT, "FIELD_INDEX_POLICY",+ "LogGroupNamePrefix = \"/DataSourceName/DataSourceType/\"", "ALL", REGION);++ assertEquals(1, service.describeAccountPolicies("FIELD_INDEX_POLICY", null, REGION).size());+ }++ @Test+ void fieldIndexIgnoresReservedFieldNamesInsideDataSourceValues() {+ service.putAccountPolicy("data-source-index", DOCUMENT, "FIELD_INDEX_POLICY",+ "DataSourceName = \"LogGroupNamePrefix\" AND DataSourceType = \"flow\"", "ALL", REGION);++ assertEquals(1, service.describeAccountPolicies("FIELD_INDEX_POLICY", null, REGION).size());+ }++ @Test+ void quotedPrefixStillConflictsWithGlobalFieldIndexPolicy() {+ service.putAccountPolicy("global-index", DOCUMENT, "FIELD_INDEX_POLICY", null, "ALL", REGION);++ AwsException error = assertThrows(AwsException.class,+ () -> service.putAccountPolicy("prefix-index", DOCUMENT, "FIELD_INDEX_POLICY",+ "LogGroupNamePrefix = \"/DataSourceName/DataSourceType/\"", "ALL", REGION));++ assertEquals("LimitExceededException", error.getErrorCode());+ }++ @Test+ void metricExtractionRejectsMoreThanFiftySelectionValues() {+ StringBuilder criteria = new StringBuilder("LogGroupName IN [");+ for (int i = 0; i < 51; i++) {+ if (i > 0) {+ criteria.append(',');+ }+ criteria.append('"').append("group-").append(i).append('"');+ }+ criteria.append(']');++ AwsException error = assertThrows(AwsException.class,+ () -> service.putAccountPolicy("metrics", DOCUMENT, "METRIC_EXTRACTION_POLICY",+ criteria.toString(), "ALL", REGION));++ assertEquals("InvalidParameterException", error.getErrorCode());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.javaindex 43c79e627f..a93c52fba6 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandlerTest.java@@ -53,7 +53,12 @@ class CloudWatchLogsHandlerTest {10_000,new RegionResolver(REGION, ACCOUNT));- handler = new CloudWatchLogsHandler(service, MAPPER);+ handler = new CloudWatchLogsHandler(+ service,+ new CloudWatchLogsCrossAccountService(+ new InMemoryStorage<>(), new InMemoryStorage<>(),+ new RegionResolver(REGION, ACCOUNT), MAPPER),+ MAPPER);service.createLogGroup(GROUP, null, null, REGION);service.createLogStream(GROUP, STREAM, REGION);diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInputConstraintTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInputConstraintTest.javaindex 24e8fb2782..60f004f376 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInputConstraintTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsInputConstraintTest.java@@ -38,7 +38,12 @@ class CloudWatchLogsInputConstraintTest {10_000,new RegionResolver(REGION, ACCOUNT));- handler = new CloudWatchLogsHandler(service, MAPPER);+ handler = new CloudWatchLogsHandler(+ service,+ new CloudWatchLogsCrossAccountService(+ new InMemoryStorage<>(), new InMemoryStorage<>(),+ new RegionResolver(REGION, ACCOUNT), MAPPER),+ MAPPER);service.createLogGroup(GROUP, null, null, REGION);service.createLogStream(GROUP, "s1", REGION);}