mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(logs): preserve and manage destination tags (#8030)
This commit is contained in:
1 parent
a6da82af8a
commit
a609eb2824
15 files changed
+402
-17
No files matched your search
@@ -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 |
|
||||
|
||||
@@ -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> ec2Service;
|
||||
private final Instance<S3Service> s3Service;
|
||||
private final Instance<CloudWatchLogsService> logsService;
|
||||
private final Instance<CloudWatchLogsCrossAccountService> crossAccountService;
|
||||
private final Instance<IamService> iamService;
|
||||
private final Instance<LambdaWebService> lambdaWebService;
|
||||
private final RequestContext requestContext;
|
||||
@@ -116,13 +118,15 @@ public class IamConditionContextResolver {
|
||||
Instance<Ec2Service> ec2Service,
|
||||
Instance<S3Service> s3Service,
|
||||
Instance<CloudWatchLogsService> logsService,
|
||||
Instance<CloudWatchLogsCrossAccountService> crossAccountService,
|
||||
Instance<IamService> iamService,
|
||||
Instance<LambdaWebService> 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> ec2Service,
|
||||
Instance<S3Service> s3Service,
|
||||
Instance<CloudWatchLogsService> logsService,
|
||||
Instance<CloudWatchLogsCrossAccountService> crossAccountService,
|
||||
Instance<IamService> iamService,
|
||||
Instance<LambdaWebService> 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<String, List<String>> 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<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
boolean direct = LogGroupTagTarget.supports(action);
|
||||
if ("logs:TagResource".equals(action) && body.path("tags").isObject()) {
|
||||
List<String> 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<String, String> 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()) {
|
||||
|
||||
+46
-1
@@ -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<String, String> 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<String, String> listDestinationTags(String arn, String region) {
|
||||
return new LinkedHashMap<>(destinationByArn(arn, region).getTags());
|
||||
}
|
||||
|
||||
public synchronized void tagDestination(String arn, Map<String, String> 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<String> 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);
|
||||
|
||||
@@ -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<String, String> 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();
|
||||
|
||||
@@ -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<String, String> 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<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags);
|
||||
}
|
||||
}
|
||||
@@ -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<String> buildLogResources(String action, ContainerRequestContext ctx,
|
||||
String region, String accountId, String partition) {
|
||||
// Operations the vendored table reads (the vended-log delivery family) take their resources from it.
|
||||
// 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();
|
||||
|
||||
@@ -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[]"}}]},
|
||||
|
||||
@@ -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()),
|
||||
|
||||
+109
@@ -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("/");
|
||||
|
||||
+35
@@ -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 + ":";
|
||||
|
||||
@@ -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 "
|
||||
|
||||
Reference in new issue
Block a user