fix(logs): preserve and manage destination tags (#8030)

This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-11 15:58:52 -04:00
1 parent a6da82af8a
commit a609eb2824
15 files changed
+402 -17

No files matched your search

@@ -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<CloudWatchLogsService> logsServiceInstance = mock(Instance.class);
when(logsServiceInstance.isResolvable()).thenReturn(true);
when(logsServiceInstance.get()).thenReturn(logsService);
crossAccountService = mock(CloudWatchLogsCrossAccountService.class);
Instance<CloudWatchLogsCrossAccountService> crossAccountServiceInstance = mock(Instance.class);
when(crossAccountServiceInstance.isResolvable()).thenReturn(true);
when(crossAccountServiceInstance.get()).thenReturn(crossAccountService);
iamService = mock(IamService.class);
Instance<IamService> 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));
}
@@ -79,6 +79,7 @@ class RequestResourceMembersTest {
.map(operation -> "logs:" + operation).collect(Collectors.toSet());
Set<String> 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()),
@@ -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<String, LogDestination> destinations = storageFactory.create("cloudwatchlogs",
"cwlogs-destinations.json", new TypeReference<Map<String, LogDestination>>() {});
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("/");
@@ -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<Map<String, LogDestination>> type = new TypeReference<>() {};
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
PersistentStorage<String, LogDestination> 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<String, LogDestination> 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<String, LogDestination> 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);
@@ -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));
@@ -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<String, LogDestination> destinations = storageFactory.create("cloudwatchlogs",
"cwlogs-destinations.json", new TypeReference<Map<String, LogDestination>>() {});
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);
@@ -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 + ":";