From a609eb2824b90d4611b2989e327edda25802825c Mon Sep 17 00:00:00 2001 From: Jimmy Liu Jia <91264074+JimmyLiuJia@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:58:52 +0800 Subject: [PATCH] fix(logs): preserve and manage destination tags (#8030) --- docs/services/cloudwatch.md | 8 +- .../common/IamConditionContextResolver.java | 28 +++-- .../CloudWatchLogsCrossAccountService.java | 47 ++++++- .../logs/CloudWatchLogsHandler.java | 14 +++ .../cloudwatch/logs/model/LogDestination.java | 8 ++ .../aws/services/iam/ResourceArnBuilder.java | 6 +- .../resources/aws/iam-request-resources.json | 1 + .../IamConditionContextResolverTest.java | 12 +- .../common/RequestResourceMembersTest.java | 1 + ...dWatchLogsCrossAccountIntegrationTest.java | 109 ++++++++++++++++ ...CloudWatchLogsCrossAccountServiceTest.java | 35 ++++++ .../dynamodb/backend/DynamoDbFacadeTest.java | 3 +- ...ogsArnTagAuthorizationIntegrationTest.java | 116 ++++++++++++++++++ .../services/iam/ResourceArnBuilderTest.java | 28 +++++ tools/aws/regen_iam_request_resources.py | 3 + 15 files changed, 402 insertions(+), 17 deletions(-) diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index f23dec4919..98f98dda01 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, 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 | +| `TagResource` | Tag a log group, cross-account destination, delivery source, delivery destination or delivery by ARN | +| `UntagResource` | Remove tags from a log group, cross-account destination, delivery source, delivery destination or delivery by ARN | +| `ListTagsForResource` | List tags for a log group, cross-account destination, 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 | @@ -42,7 +42,7 @@ Floci supports both CloudWatch Logs and CloudWatch Metrics. | `TestMetricFilter` | Run a filter pattern over sample messages and return the matches with their extracted values | | `PutResourcePolicy` | Create or update an account-level resource policy | | `DescribeResourcePolicies` | List account-level resource policies | -| `PutDestination` | Create or update a cross-account subscription destination | +| `PutDestination` | Create or update a cross-account subscription destination, with optional tags on creation | | `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 | diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index 6de8ebb156..107355a2d2 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -3,6 +3,7 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService; import io.floci.aws.services.cloudwatch.logs.LogGroupTagTarget; @@ -99,6 +100,7 @@ public class IamConditionContextResolver { private final Instance ec2Service; private final Instance s3Service; private final Instance logsService; + private final Instance crossAccountService; private final Instance iamService; private final Instance lambdaWebService; private final RequestContext requestContext; @@ -116,13 +118,15 @@ public class IamConditionContextResolver { Instance ec2Service, Instance s3Service, Instance logsService, + Instance crossAccountService, Instance iamService, Instance lambdaWebService, RequestContext requestContext, EmulatorConfig config, CurrentVertxRequest currentVertxRequest, ResolvedServiceCatalog serviceCatalog) { - this(dynamoDbFacade, ec2Service, s3Service, logsService, iamService, lambdaWebService, requestContext, + this(dynamoDbFacade, ec2Service, s3Service, logsService, crossAccountService, iamService, + lambdaWebService, requestContext, config, currentVertxRequest, serviceCatalog, Clock.systemUTC()); } @@ -130,6 +134,7 @@ public class IamConditionContextResolver { Instance ec2Service, Instance s3Service, Instance logsService, + Instance crossAccountService, Instance iamService, Instance lambdaWebService, RequestContext requestContext, @@ -140,6 +145,7 @@ public class IamConditionContextResolver { this.ec2Service = ec2Service; this.s3Service = s3Service; this.logsService = logsService; + this.crossAccountService = crossAccountService; this.iamService = iamService; this.lambdaWebService = lambdaWebService; this.requestContext = requestContext; @@ -164,7 +170,7 @@ public class IamConditionContextResolver { }; } - /** Group mutations and stream access use the handler's group and request scope. */ + /** Logs tag operations and group mutations use the handler's resource and request scope. */ private Map> logsConditionContext(String action, ContainerRequestContext ctx) { if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action) || LogGroupTagTarget.supports(action) || "logs:CreateLogGroup".equals(action) || "logs:DeleteLogGroup".equals(action) @@ -189,12 +195,14 @@ public class IamConditionContextResolver { conditions.put("aws:TagKeys", keys); return conditions; } - if (!logsService.isResolvable()) { + boolean direct = LogGroupTagTarget.supports(action); + boolean destination = direct && CloudWatchLogsCrossAccountService.isCrossAccountDestinationArn( + body.path("resourceArn").asText()); + if (destination ? !crossAccountService.isResolvable() : !logsService.isResolvable()) { return null; } String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion(); Map> conditions = new LinkedHashMap<>(); - boolean direct = LogGroupTagTarget.supports(action); if ("logs:TagResource".equals(action) && body.path("tags").isObject()) { List keys = new ArrayList<>(); body.path("tags").fields().forEachRemaining(entry -> { @@ -215,16 +223,20 @@ public class IamConditionContextResolver { // 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; try { - tags = logsService.get().listTagsLogGroup(group, region); + if (destination) { + tags = crossAccountService.get().listDestinationTags(body.path("resourceArn").asText(), region); + } else { + String group = direct ? logsService.get().resolveTagTarget(body.path("resourceArn").asText(), region).name() + : body.path("logGroupName").asText(); + tags = logsService.get().listTagsLogGroup(group, region); + } } catch (AwsException e) { if (!"ResourceNotFoundException".equals(e.getErrorCode())) { throw e; } - // Leave the handler to report a missing group; unexpected lookup errors must not hide a deny. + // Leave the handler to report a missing resource; unexpected lookup errors must not hide a deny. return conditions.isEmpty() ? null : conditions; } if (tags == null || tags.isEmpty()) { diff --git a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java index 6ac59985b0..6c5c7e505f 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountService.java @@ -15,6 +15,7 @@ import jakarta.inject.Inject; import java.nio.charset.StandardCharsets; import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -62,7 +63,7 @@ public class CloudWatchLogsCrossAccountService { } public synchronized LogDestination putDestination(String destinationName, String targetArn, - String roleArn, String region) { + String roleArn, Map tags, String region) { validateDestinationName(destinationName); requireArn(targetArn, "targetArn"); requireArn(roleArn, "roleArn"); @@ -74,11 +75,55 @@ public class CloudWatchLogsCrossAccountService { destination.setArn(AwsArnUtils.Arn.of("logs", region, regionResolver.getAccountId(), "destination:" + destinationName).toString()); if (destination.getCreationTime() == 0) { destination.setCreationTime(System.currentTimeMillis()); + destination.setTags(tags); } destinations.put(key, destination); return destination; } + public static boolean isCrossAccountDestinationArn(String arn) { + if (!AwsArnUtils.isArn(arn)) { + return false; + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + return "logs".equals(parsed.service()) && parsed.resource().startsWith("destination:"); + } + + public synchronized Map listDestinationTags(String arn, String region) { + return new LinkedHashMap<>(destinationByArn(arn, region).getTags()); + } + + public synchronized void tagDestination(String arn, Map tags, String region) { + LogDestination destination = destinationByArn(arn, region); + destination.getTags().putAll(tags); + destinations.put(destinationKey(region, destination.getDestinationName()), destination); + } + + public synchronized void untagDestination(String arn, List tagKeys, String region) { + LogDestination destination = destinationByArn(arn, region); + tagKeys.forEach(destination.getTags()::remove); + destinations.put(destinationKey(region, destination.getDestinationName()), destination); + } + + private LogDestination destinationByArn(String arn, String region) { + if (!isCrossAccountDestinationArn(arn)) { + throw destinationNotFound(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + if (!region.equals(parsed.region()) || !regionResolver.getAccountId().equals(parsed.accountId()) + || !regionResolver.partitionForRegion(region).equals(parsed.partition())) { + throw destinationNotFound(); + } + String name = parsed.resource().substring("destination:".length()); + return destinations.get(destinationKey(region, name)) + .filter(destination -> arn.equals(destination.getArn())) + .orElseThrow(CloudWatchLogsCrossAccountService::destinationNotFound); + } + + private static AwsException destinationNotFound() { + return new AwsException("ResourceNotFoundException", "The specified destination does not exist.", 400); + } + public synchronized void putDestinationPolicy(String destinationName, String accessPolicy, String region) { validateDestinationName(destinationName); requireJsonObject(accessPolicy, "accessPolicy", DESTINATION_POLICY_MAX_BYTES); diff --git a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsHandler.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsHandler.java index fb9ad964a9..9889bdada4 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsHandler.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsHandler.java @@ -254,6 +254,7 @@ public class CloudWatchLogsHandler { request.path("destinationName").asText(null), request.path("targetArn").asText(null), request.path("roleArn").asText(null), + extractTags(request.path("tags")), region); ObjectNode response = objectMapper.createObjectNode(); response.set("destination", buildDestination(destination)); @@ -646,6 +647,11 @@ public class CloudWatchLogsHandler { response.set("tags", objectMapper.valueToTree(deliveryService.listTags(resourceArn, region))); return Response.ok(response).build(); } + if (CloudWatchLogsCrossAccountService.isCrossAccountDestinationArn(resourceArn)) { + ObjectNode response = objectMapper.createObjectNode(); + response.set("tags", objectMapper.valueToTree(crossAccountService.listDestinationTags(resourceArn, region))); + return Response.ok(response).build(); + } String groupName = logsService.resolveTagTarget(resourceArn, region).name(); Map tags = logsService.listTagsLogGroup(groupName, region); @@ -663,6 +669,10 @@ public class CloudWatchLogsHandler { deliveryService.tag(resourceArn, tags, region); return Response.ok(objectMapper.createObjectNode()).build(); } + if (CloudWatchLogsCrossAccountService.isCrossAccountDestinationArn(resourceArn)) { + crossAccountService.tagDestination(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(); @@ -676,6 +686,10 @@ public class CloudWatchLogsHandler { deliveryService.untag(resourceArn, tagKeys, region); return Response.ok(objectMapper.createObjectNode()).build(); } + if (CloudWatchLogsCrossAccountService.isCrossAccountDestinationArn(resourceArn)) { + crossAccountService.untagDestination(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/floci/aws/services/cloudwatch/logs/model/LogDestination.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/model/LogDestination.java index 9de2315283..d87468f734 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/model/LogDestination.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/model/LogDestination.java @@ -3,6 +3,9 @@ package io.floci.aws.services.cloudwatch.logs.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.LinkedHashMap; +import java.util.Map; + @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) public class LogDestination { @@ -12,6 +15,7 @@ public class LogDestination { private String accessPolicy; private String arn; private long creationTime; + private Map tags = new LinkedHashMap<>(); public String getDestinationName() { return destinationName; } public void setDestinationName(String destinationName) { this.destinationName = destinationName; } @@ -25,4 +29,8 @@ public class LogDestination { public void setArn(String arn) { this.arn = arn; } public long getCreationTime() { return creationTime; } public void setCreationTime(long creationTime) { this.creationTime = creationTime; } + public Map getTags() { return tags; } + public void setTags(Map tags) { + this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags); + } } diff --git a/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java b/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java index d11b465adb..5143f3da68 100644 --- a/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java @@ -12,6 +12,7 @@ import io.floci.aws.core.common.ServicePrincipals; import io.floci.aws.core.common.SigV4CredentialScope; import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.common.auth.SigV4Canonicalization; +import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService; import io.floci.aws.services.cloudwatch.logs.LogGroupTagTarget; import io.floci.aws.services.eks.EksController; @@ -304,7 +305,7 @@ 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. + // Operations the vendored table reads take their resources from it. if (RequestResources.reads(action)) { return namedResources("logs", action, ctx, region, accountId, partition); } @@ -327,6 +328,9 @@ public class ResourceArnBuilder { if (CloudWatchLogsDeliveryService.isDeliveryResourceArn(resourceArn)) { return List.of(resourceArn); } + if (CloudWatchLogsCrossAccountService.isCrossAccountDestinationArn(resourceArn)) { + return List.of(resourceArn); + } return List.of(LogGroupTagTarget.resolve(resourceArn, region, accountId, partition).arn()); } String name = body.path("logGroupName").asText(); diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json index 1371c657d7..858e16acb8 100644 --- a/src/main/resources/aws/iam-request-resources.json +++ b/src/main/resources/aws/iam-request-resources.json @@ -2205,6 +2205,7 @@ "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:PutDestination": {"action": "logs:PutDestination", "types": ["destination"], "resources": [{"types": ["destination"], "arn": "roleArn"}, {"types": ["destination"], "arn": "targetArn"}, {"type": "destination", "fill": {"DestinationName": "destinationName"}}]}, "logs:UpdateDeliveryConfiguration": {"action": "logs:UpdateDeliveryConfiguration", "types": ["delivery", "delivery-destination", "delivery-source"], "resources": [{"type": "delivery", "fill": {"DeliveryName": "id"}}]}, "macie2:AcceptInvitation": {"action": "macie2:AcceptInvitation", "types": [], "resources": []}, "macie2:BatchGetCustomDataIdentifiers": {"action": "macie2:BatchGetCustomDataIdentifiers", "types": ["CustomDataIdentifier"], "resources": [{"type": "CustomDataIdentifier", "fill": {"ResourceId": "ids[]"}}]}, diff --git a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java index 86a789f0fe..a8c4443cef 100644 --- a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java @@ -3,6 +3,7 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService; import io.floci.aws.services.dynamodb.DynamoDbFacade; import io.floci.aws.services.dynamodb.DynamoDbService; @@ -67,6 +68,7 @@ class IamConditionContextResolverTest { private Ec2Service ec2Service; private S3Service s3Service; private CloudWatchLogsService logsService; + private CloudWatchLogsCrossAccountService crossAccountService; private IamService iamService; private LambdaWebService lambdaWebService; private RequestContext requestContext; @@ -95,6 +97,10 @@ class IamConditionContextResolverTest { Instance logsServiceInstance = mock(Instance.class); when(logsServiceInstance.isResolvable()).thenReturn(true); when(logsServiceInstance.get()).thenReturn(logsService); + crossAccountService = mock(CloudWatchLogsCrossAccountService.class); + Instance crossAccountServiceInstance = mock(Instance.class); + when(crossAccountServiceInstance.isResolvable()).thenReturn(true); + when(crossAccountServiceInstance.get()).thenReturn(crossAccountService); iamService = mock(IamService.class); Instance iamServiceInstance = mock(Instance.class); when(iamServiceInstance.isResolvable()).thenReturn(true); @@ -116,7 +122,8 @@ class IamConditionContextResolverTest { ServiceCatalog catalog = new ServiceCatalog(List.of(dynamo)); when(serviceCatalog.matchTarget(any())).thenAnswer(call -> catalog.matchTarget(call.getArgument(0))); resolver = new IamConditionContextResolver( - dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, iamServiceInstance, + dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, + crossAccountServiceInstance, iamServiceInstance, lambdaWebServiceInstance, requestContext, config, null, serviceCatalog); @@ -710,7 +717,8 @@ class IamConditionContextResolverTest { @SuppressWarnings("unchecked") private IamConditionContextResolver resolverAt(Instant now) { return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class), - mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext, config, null, + mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class), + requestContext, config, null, serviceCatalog, Clock.fixed(now, ZoneOffset.UTC)); } diff --git a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java index b5519bb572..d30a28afe8 100644 --- a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java @@ -79,6 +79,7 @@ class RequestResourceMembersTest { .map(operation -> "logs:" + operation).collect(Collectors.toSet()); Set expected = new HashSet<>(logsDelivery); expected.add("dynamodb:ListTables"); + expected.add("logs:PutDestination"); assertEquals(expected, table.operations().keySet().stream() .filter(operation -> table.handBuilt().contains(operation.substring(0, operation.indexOf(':')))) .collect(Collectors.toSet()), diff --git a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountIntegrationTest.java index 7b36a17210..27d657d622 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountIntegrationTest.java @@ -1,19 +1,43 @@ package io.floci.aws.services.cloudwatch.logs; +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.cloudwatch.logs.model.LogDestination; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; + +import java.util.Map; +import java.util.UUID; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; @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"; + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Inject + StorageFactory storageFactory; @BeforeAll static void configureRestAssured() { @@ -53,6 +77,91 @@ class CloudWatchLogsCrossAccountIntegrationTest { .then().statusCode(400).body("__type", equalTo("InvalidParameterException")); } + @Test + void destinationCreationTagsCanBeListedByArn() { + String name = "tagged-" + UUID.randomUUID().toString().substring(0, 8); + String arn = putTaggedDestination(name); + + json("Logs_20140328.ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}") + .then().statusCode(200).body("tags.team", equalTo("red")); + } + + @Test + void destinationTagsCanBeUpdatedAndRemoved() { + String name = "updated-" + UUID.randomUUID().toString().substring(0, 8); + String arn = putTaggedDestination(name); + + json("Logs_20140328.TagResource", """ + {"resourceArn":"%s","tags":{"team":"blue","env":"dev"}} + """.formatted(arn)).then().statusCode(200); + json("Logs_20140328.ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}") + .then().statusCode(200).body("tags.team", equalTo("blue")).body("tags.env", equalTo("dev")); + + json("Logs_20140328.UntagResource", "{\"resourceArn\":\"" + arn + "\",\"tagKeys\":[\"team\"]}") + .then().statusCode(200); + json("Logs_20140328.ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}") + .then().statusCode(200).body("tags.team", nullValue()).body("tags.env", equalTo("dev")); + } + + @Test + void destinationTagsDoNotCrossAccountRegionOrPartition() { + String name = "isolated-" + UUID.randomUUID().toString().substring(0, 8); + String arn = putTaggedDestination(name); + + for (String foreignArn : new String[]{ + arn.replace(":000000000000:", ":111111111111:"), + arn.replace(":us-east-1:", ":eu-west-1:"), + arn.replace("arn:aws:", "arn:aws-cn:")}) { + json("Logs_20140328.ListTagsForResource", "{\"resourceArn\":\"" + foreignArn + "\"}") + .then().statusCode(400).body("__type", equalTo("ResourceNotFoundException")); + json("Logs_20140328.TagResource", """ + {"resourceArn":"%s","tags":{"team":"foreign"}} + """.formatted(foreignArn)).then().statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } + json("Logs_20140328.ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}") + .then().statusCode(200).body("tags.team", equalTo("red")); + } + + @Test + void destinationTagsRoundTripThroughAwsSdk() { + String name = "sdk-tagged-" + UUID.randomUUID().toString().substring(0, 8); + registerDestinationCleanup(name); + try (CloudWatchLogsClient client = AwsTestClients.create( + CloudWatchLogsClient.builder(), "AKID", Region.US_EAST_1)) { + String arn = client.putDestination(request -> request.destinationName(name) + .targetArn("arn:aws:kinesis:us-east-1:000000000000:stream/logs") + .roleArn("arn:aws:iam::000000000000:role/logs") + .tags(Map.of("team", "red"))).destination().arn(); + assertEquals(Map.of("team", "red"), + client.listTagsForResource(request -> request.resourceArn(arn)).tags()); + + client.tagResource(request -> request.resourceArn(arn).tags(Map.of("team", "blue"))); + assertEquals(Map.of("team", "blue"), + client.listTagsForResource(request -> request.resourceArn(arn)).tags()); + + client.untagResource(request -> request.resourceArn(arn).tagKeys("team")); + assertEquals(Map.of(), + client.listTagsForResource(request -> request.resourceArn(arn)).tags()); + } + } + + private String putTaggedDestination(String name) { + registerDestinationCleanup(name); + json("Logs_20140328.PutDestination", """ + {"destinationName":"%s","targetArn":"arn:aws:kinesis:us-east-1:000000000000:stream/logs", + "roleArn":"arn:aws:iam::000000000000:role/logs","tags":{"team":"red"}} + """.formatted(name)).then().statusCode(200); + return "arn:aws:logs:us-east-1:000000000000:destination:" + name; + } + + private void registerDestinationCleanup(String name) { + StorageBackend destinations = storageFactory.create("cloudwatchlogs", + "cwlogs-destinations.json", new TypeReference>() {}); + cleanup.register(() -> RequestScopes.runAs(ACCOUNT, REGION, + () -> destinations.delete(REGION + "::" + name))); + } + private static 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/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountServiceTest.java b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountServiceTest.java index 602d4f2d17..91db523b7d 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsCrossAccountServiceTest.java @@ -1,10 +1,18 @@ package io.floci.aws.services.cloudwatch.logs; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.PersistentStorage; +import io.floci.aws.services.cloudwatch.logs.model.LogDestination; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -17,6 +25,33 @@ class CloudWatchLogsCrossAccountServiceTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), new ObjectMapper()); + @Test + void destinationTagsSurvivePersistentStorageReload(@TempDir Path tempDir) { + Path file = tempDir.resolve("destinations.json"); + TypeReference> type = new TypeReference<>() {}; + RegionResolver regionResolver = new RegionResolver(REGION, "000000000000"); + PersistentStorage firstStore = new PersistentStorage<>(file, type); + CloudWatchLogsCrossAccountService first = new CloudWatchLogsCrossAccountService( + firstStore, new InMemoryStorage<>(), regionResolver, new ObjectMapper()); + LogDestination destination = first.putDestination("persisted-tags", + "arn:aws:kinesis:us-east-1:000000000000:stream/logs", + "arn:aws:iam::000000000000:role/logs", Map.of("team", "red"), REGION); + first.tagDestination(destination.getArn(), Map.of("env", "dev"), REGION); + + PersistentStorage secondStore = new PersistentStorage<>(file, type); + secondStore.load(); + CloudWatchLogsCrossAccountService second = new CloudWatchLogsCrossAccountService( + secondStore, new InMemoryStorage<>(), regionResolver, new ObjectMapper()); + assertEquals(Map.of("team", "red", "env", "dev"), second.listDestinationTags(destination.getArn(), REGION)); + second.untagDestination(destination.getArn(), List.of("team"), REGION); + + PersistentStorage thirdStore = new PersistentStorage<>(file, type); + thirdStore.load(); + CloudWatchLogsCrossAccountService third = new CloudWatchLogsCrossAccountService( + thirdStore, new InMemoryStorage<>(), regionResolver, new ObjectMapper()); + assertEquals(Map.of("env", "dev"), third.listDestinationTags(destination.getArn(), REGION)); + } + @Test void transformerGlobalAndScopedPoliciesCannotCoexist() { service.putAccountPolicy("global", "[{\"parseJSON\":{}}]", "TRANSFORMER_POLICY", null, "ALL", REGION); diff --git a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbFacadeTest.java b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbFacadeTest.java index 51c4b9ba2c..a2cc000112 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbFacadeTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbFacadeTest.java @@ -152,7 +152,8 @@ class DynamoDbFacadeTest { RequestContext requestContext = new RequestContext(); requestContext.setRegion(OTHER_REGION); IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb, - mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class), + mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class), + mock(Instance.class), mock(Instance.class), requestContext, mock(EmulatorConfig.class), null, mock(io.floci.aws.core.common.ResolvedServiceCatalog.class)); diff --git a/src/test/java/io/floci/aws/services/iam/LogsArnTagAuthorizationIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/LogsArnTagAuthorizationIntegrationTest.java index 98cff70037..248eee3219 100644 --- a/src/test/java/io/floci/aws/services/iam/LogsArnTagAuthorizationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/LogsArnTagAuthorizationIntegrationTest.java @@ -1,7 +1,11 @@ package io.floci.aws.services.iam; +import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService; +import io.floci.aws.services.cloudwatch.logs.model.LogDestination; import io.floci.aws.testing.IamEnforcementProfile; import io.floci.aws.testing.LogsAuthorizationFixtures; import io.floci.aws.testing.PartitionCleanup; @@ -46,6 +50,9 @@ class LogsArnTagAuthorizationIntegrationTest { @Inject CloudWatchLogsService logsService; + @Inject + StorageFactory storageFactory; + @BeforeAll static void configureContentTypes() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -202,6 +209,85 @@ class LogsArnTagAuthorizationIntegrationTest { assertTags(selected, Map.of("protected", "retained")); } + @Test + void destinationTagReadUsesItsExactArn() { + String selected = destination("blue"); + String other = destination("green"); + String caller = user(statement("Allow", "ListTagsForResource", selected)); + + invoke(caller, "ListTagsForResource", other).statusCode(400) + .body(containsString("AccessDeniedException")); + invoke(caller, "ListTagsForResource", selected).statusCode(200) + .body("tags.team", equalTo("blue")); + } + + @Test + void destinationResourceTagsControlConditionalAccess() { + String selected = destination("blue"); + String other = destination("green"); + String caller = user(statement("Allow", "ListTagsForResource", "*") + "," + + "{\"Effect\":\"Deny\",\"Action\":\"logs:ListTagsForResource\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}}"); + + invoke(caller, "ListTagsForResource", selected).statusCode(400) + .body(containsString("AccessDeniedException")); + invoke(caller, "ListTagsForResource", other).statusCode(200) + .body("tags.team", equalTo("green")); + } + + @Test + void destinationCreationChecksTheNamedResourceArn() { + String selected = "logs-destination-tag-" + UUID.randomUUID(); + String other = "logs-destination-tag-" + UUID.randomUUID(); + registerDestinationCleanup(selected); + registerDestinationCleanup(other); + String caller = user(statement("Allow", "PutDestination", destinationArn(selected)) + "," + + statement("Allow", "TagResource", "*") + "," + + "{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\",\"Resource\":\"*\"}"); + + putTaggedDestination(caller, other).statusCode(400).body(containsString("AccessDeniedException")); + invoke(ACCOUNT, "ListTagsForResource", destinationArn(other)).statusCode(400) + .body(containsString("ResourceNotFoundException")); + putTaggedDestination(caller, selected).statusCode(200); + invoke(ACCOUNT, "ListTagsForResource", destinationArn(selected)).statusCode(200) + .body("tags.team", equalTo("blue")); + } + + @Test + void taggedDestinationCreationAcceptsResourceScopedTagPermission() { + String selected = "logs-destination-tag-" + UUID.randomUUID(); + String other = "logs-destination-tag-" + UUID.randomUUID(); + registerDestinationCleanup(selected); + registerDestinationCleanup(other); + String caller = user(statement("Allow", "PutDestination", "*") + "," + + statement("Allow", "TagResource", destinationArn(selected)) + "," + + "{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\",\"Resource\":\"*\"}"); + + putTaggedDestination(caller, other).statusCode(400).body(containsString("AccessDeniedException")); + putTaggedDestination(caller, selected).statusCode(200); + invoke(ACCOUNT, "ListTagsForResource", destinationArn(selected)).statusCode(200) + .body("tags.team", equalTo("blue")); + } + + @Test + void taggedDestinationCreationHonorsResourceScopedExplicitDeny() { + String selected = "logs-destination-tag-" + UUID.randomUUID(); + String other = "logs-destination-tag-" + UUID.randomUUID(); + registerDestinationCleanup(selected); + registerDestinationCleanup(other); + String caller = user(statement("Allow", "PutDestination", "*") + "," + + statement("Allow", "TagResource", "*") + "," + + statement("Deny", "TagResource", destinationArn(selected)) + "," + + "{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\",\"Resource\":\"*\"}"); + + putTaggedDestination(caller, selected).statusCode(400).body(containsString("AccessDeniedException")); + invoke(ACCOUNT, "ListTagsForResource", destinationArn(selected)).statusCode(400) + .body(containsString("ResourceNotFoundException")); + putTaggedDestination(caller, other).statusCode(200); + invoke(ACCOUNT, "ListTagsForResource", destinationArn(other)).statusCode(200) + .body("tags.team", equalTo("blue")); + } + private void assertSuccess(ValidatableResponse response, String action) { response.statusCode(200); if (action.equals("ListTagsForResource")) { @@ -231,6 +317,36 @@ class LogsArnTagAuthorizationIntegrationTest { return name; } + private String destination(String team) { + String name = "logs-destination-tag-" + UUID.randomUUID(); + registerDestinationCleanup(name); + call(endpoint.getPort(), ACCOUNT, "PutDestination", Map.of( + "destinationName", name, + "targetArn", "arn:aws:kinesis:us-east-1:" + ACCOUNT + ":stream/logs", + "roleArn", "arn:aws:iam::" + ACCOUNT + ":role/logs", + "tags", Map.of("team", team))).statusCode(200); + return destinationArn(name); + } + + private void registerDestinationCleanup(String name) { + StorageBackend destinations = storageFactory.create("cloudwatchlogs", + "cwlogs-destinations.json", new TypeReference>() {}); + cleanup.register(() -> RequestScopes.runAs(ACCOUNT, REGION, + () -> destinations.delete(REGION + "::" + name))); + } + + private ValidatableResponse putTaggedDestination(String caller, String name) { + return call(endpoint.getPort(), caller, "PutDestination", Map.of( + "destinationName", name, + "targetArn", "arn:aws:kinesis:us-east-1:" + ACCOUNT + ":stream/logs", + "roleArn", "arn:aws:iam::" + ACCOUNT + ":role/logs", + "tags", Map.of("team", "blue"))); + } + + private static String destinationArn(String name) { + return "arn:aws:logs:" + REGION + ":" + ACCOUNT + ":destination:" + name; + } + private String user(String statements) { return LogsAuthorizationFixtures.user(cleanup, endpoint.getPort(), ACCOUNT, "logs-arn-tag-", "arn-tags", statements); diff --git a/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java index ce4cdf4838..008a269f10 100644 --- a/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java @@ -889,6 +889,34 @@ class ResourceArnBuilderTest { } } + @Test + void destinationTagTargetsUseDestinationArn() { + for (String action : List.of("logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource")) { + for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) { + String partition = AwsRegions.partitionFor(region); + String arn = "arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":destination:central"; + setJsonBody("{\"resourceArn\":\"" + arn + "\"}"); + assertEquals(List.of(arn), builder.buildLogResources(action, ctx, region, ACCOUNT, partition)); + } + } + } + + @ParameterizedTest + @CsvSource({"aws,us-east-1", "aws-cn,cn-north-1", "aws-us-gov,us-gov-west-1"}) + void putDestinationTargetsTheDestinationItNames(String partition, String region) { + setJsonBody("{\"destinationName\":\"central\"}"); + assertEquals(List.of("arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":destination:central"), + builder.buildLogResources("logs:PutDestination", ctx, region, ACCOUNT, partition)); + String targetArn = "arn:" + partition + ":kinesis:" + region + ":" + ACCOUNT + ":stream/central"; + String roleArn = "arn:" + partition + ":iam::" + ACCOUNT + ":role/logs-delivery"; + setJsonBody("{\"destinationName\":\"central\",\"targetArn\":\"" + targetArn + + "\",\"roleArn\":\"" + roleArn + "\"}"); + assertEquals(List.of("arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":destination:central"), + builder.buildLogResources("logs:PutDestination", ctx, region, ACCOUNT, partition)); + setJsonBody("{}"); + assertEquals(List.of("*"), builder.buildLogResources("logs:PutDestination", ctx, region, ACCOUNT, partition)); + } + @Test void deliveryActionsAreAuthorizedOnTheSourceDestinationOrDeliveryTheyName() { String prefix = "arn:aws:logs:us-east-1:" + ACCOUNT + ":"; diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index 1b4a2acc36..ef2bcfd26a 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -207,6 +207,9 @@ READ_IN_HAND_BUILT: dict[str, str] = { "DescribeDeliveryDestinations", "CreateDelivery", "GetDelivery", "UpdateDeliveryConfiguration", "DeleteDelivery", "DescribeDeliveries") } +READ_IN_HAND_BUILT["logs:PutDestination"] = ( + "CloudWatch Logs destination creation names the destination by destinationName, which ResourceArnBuilder " + "reads from the generated request-resource table") _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 reads from the route a request "