diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsArnTagAuthorizationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsArnTagAuthorizationTest.java new file mode 100644 index 0000000000..d75700e3a1 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsArnTagAuthorizationTest.java @@ -0,0 +1,113 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudWatch Logs ARN tag resource permissions") +class CloudWatchLogsArnTagAuthorizationTest extends CloudWatchLogsAuthorizationFixture { + + CloudWatchLogsArnTagAuthorizationTest() { + super("logs-arn-tag-permissions", "arn-tags"); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void exactBareArnGrant(String action) { + policy(statement("Allow", action, arn(protectedGroup))); + assertThatThrownBy(() -> invoke(action, otherGroup)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertTags(otherGroup, Map.of("protected", "false")); + Map response = invoke(action, protectedGroup); + assertResult(action, protectedGroup, "true", response); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void exactBareArnDenyOverridesWildcard(String action) { + policy(statement("Allow", action, "*") + "," + statement("Deny", action, arn(protectedGroup))); + assertThatThrownBy(() -> invoke(action, protectedGroup)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertTags(protectedGroup, Map.of("protected", "true")); + Map response = invoke(action, otherGroup); + assertResult(action, otherGroup, "false", response); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void incompleteArnPrefixIsALiteralName(String action) { + String name = "arn:" + TestFixtures.uniqueName("archive"); + createGroup(name, Map.of("protected", "true")); + policy(statement("Allow", action, arn(name))); + Map response = invokeResource(caller, action, name); + assertResult(action, name, "true", response); + assertTags(protectedGroup, Map.of("protected", "true")); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void rootCannotResolveNoncanonicalMarkersIntoLocalNames(String action) { + String foreign = TestFixtures.arn("logs", "999999999999", "log-group:" + protectedGroup); + for (String input : new String[]{"ARN:" + foreign.substring(4), " " + foreign, + "x:log-group:" + protectedGroup}) { + assertThatThrownBy(() -> invokeResource(root, action, input)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, error -> { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ResourceNotFoundException"); + }); + assertTags(protectedGroup, Map.of("protected", "true")); + } + Map response = invokeResource(root, action, arn(protectedGroup)); + assertResult(action, protectedGroup, "true", response); + assertTags(otherGroup, Map.of("protected", "false")); + } + + private void assertResult(String action, String group, String original, Map response) { + Map expected = switch (action) { + case "TagResource" -> Map.of("protected", original, "team", "red"); + case "UntagResource" -> Map.of(); + case "ListTagsForResource" -> Map.of("protected", original); + default -> throw new IllegalArgumentException(action); + }; + if (action.equals("ListTagsForResource")) { + assertThat(response).isEqualTo(expected); + } + assertTags(group, expected); + } + + private Map invoke(String action, String group) { + return invokeResource(caller, action, arn(group)); + } + + private Map invokeResource(CloudWatchLogsClient client, String action, String resource) { + switch (action) { + case "TagResource" -> client.tagResource(r -> r.resourceArn(resource).tags(Map.of("team", "red"))); + case "UntagResource" -> client.untagResource(r -> r.resourceArn(resource).tagKeys("protected")); + case "ListTagsForResource" -> { + return client.listTagsForResource(r -> r.resourceArn(resource)).tags(); + } + default -> throw new IllegalArgumentException(action); + } + return Map.of(); + } + + private String arn(String group) { + return TestFixtures.arn("logs", "000000000000", "log-group:" + group); + } + + private void assertTags(String group, Map expected) { + assertThat(root.listTagsLogGroup(r -> r.logGroupName(group)).tags()).isEqualTo(expected); + } + + private String statement(String effect, String action, String resource) { + return "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + action + + "\",\"Resource\":\"" + resource + "\"}"; + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsAuthorizationFixture.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsAuthorizationFixture.java new file mode 100644 index 0000000000..fdf5ef18c1 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsAuthorizationFixture.java @@ -0,0 +1,123 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.function.Executable; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; +import software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.AccessKey; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertAll; + +/** Shared emulator-only IAM lifecycle for Logs authorization SDK tests. */ +abstract class CloudWatchLogsAuthorizationFixture { + + private IamClient iam; + CloudWatchLogsClient root; + CloudWatchLogsClient caller; + private String user; + private AccessKey key; + String protectedGroup; + String otherGroup; + private boolean policyCreated; + + private final String prefix; + private final String policyName; + private final List groups = new ArrayList<>(); + + CloudWatchLogsAuthorizationFixture(String prefix, String policyName) { + this.prefix = prefix; + this.policyName = policyName; + } + + @BeforeEach + void setUp() { + Assumptions.assumeFalse(TestFixtures.isRealAws(), "Uses emulator account-root credentials"); + iam = TestFixtures.iamClient("000000000000"); + root = client("000000000000", "test"); + String name = TestFixtures.uniqueName(prefix); + iam.createUser(r -> r.userName(name)); + user = name; + key = iam.createAccessKey(r -> r.userName(user)).accessKey(); + caller = client(key.accessKeyId(), key.secretAccessKey()); + boolean enforced = false; + try { + caller.describeLogGroups(); + } catch (CloudWatchLogsException error) { + assertDenied(error); + enforced = true; + } + Assumptions.assumeTrue(enforced, "Requires floci.services.iam.enforcement-enabled=true"); + protectedGroup = createGroup(name + "-protected", Map.of("protected", "true")); + otherGroup = createGroup(name + "-other", Map.of("protected", "false")); + } + + @AfterEach + void cleanUp() { + List tasks = new ArrayList<>(groups); + tasks.addAll(List.of( + () -> { + if (policyCreated) { + iam.deleteUserPolicy(r -> r.userName(user).policyName(policyName)); + } + }, + () -> { + if (key != null) { + iam.deleteAccessKey(r -> r.userName(user).accessKeyId(key.accessKeyId())); + } + }, + () -> { + if (user != null) { + iam.deleteUser(r -> r.userName(user)); + } + }, + () -> { + if (caller != null) { + caller.close(); + } + }, + () -> { + if (root != null) { + root.close(); + } + }, + () -> { + if (iam != null) { + iam.close(); + } + })); + assertAll("remove Logs and IAM fixtures and close every client", tasks.stream()); + } + + final String createGroup(String name, Map tags) { + root.createLogGroup(r -> r.logGroupName(name).tags(tags)); + groups.add(() -> root.deleteLogGroup(r -> r.logGroupName(name))); + return name; + } + + final void policy(String statements) { + iam.putUserPolicy(r -> r.userName(user).policyName(policyName) + .policyDocument("{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}")); + policyCreated = true; + } + + final void assertDenied(CloudWatchLogsException error) { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().errorCode()).contains("AccessDenied"); + } + + private static CloudWatchLogsClient client(String accessKey, String secret) { + return CloudWatchLogsClient.builder().endpointOverride(TestFixtures.endpoint()).region(TestFixtures.region()) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secret))) + .build(); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsStreamAuthorizationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsStreamAuthorizationTest.java index b6e3f95829..b2a3528ae3 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsStreamAuthorizationTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsStreamAuthorizationTest.java @@ -1,106 +1,21 @@ package com.floci.test; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; -import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; -import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException; import software.amazon.awssdk.services.cloudwatchlogs.model.InvalidParameterException; -import software.amazon.awssdk.services.iam.IamClient; -import software.amazon.awssdk.services.iam.model.AccessKey; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertAll; @DisplayName("CloudWatch Logs stream resource permissions") -class CloudWatchLogsStreamAuthorizationTest { +class CloudWatchLogsStreamAuthorizationTest extends CloudWatchLogsAuthorizationFixture { - private IamClient iam; - private CloudWatchLogsClient root; - private CloudWatchLogsClient caller; - private String user; - private AccessKey key; - private String protectedGroup; - private String otherGroup; - private boolean policyCreated; - - @BeforeEach - void setUp() { - Assumptions.assumeFalse(TestFixtures.isRealAws(), "Uses emulator account-root credentials"); - iam = TestFixtures.iamClient("000000000000"); - root = client("000000000000", "test"); - String name = TestFixtures.uniqueName("logs-stream-permissions"); - iam.createUser(r -> r.userName(name)); - user = name; - key = iam.createAccessKey(r -> r.userName(user)).accessKey(); - caller = client(key.accessKeyId(), key.secretAccessKey()); - boolean enforced = false; - try { - caller.describeLogGroups(); - } catch (CloudWatchLogsException error) { - assertDenied(error); - enforced = true; - } - Assumptions.assumeTrue(enforced, "Requires floci.services.iam.enforcement-enabled=true"); - String group = name + "-protected"; - root.createLogGroup(r -> r.logGroupName(group).tags(Map.of("protected", "true"))); - protectedGroup = group; - String other = name + "-other"; - root.createLogGroup(r -> r.logGroupName(other).tags(Map.of("protected", "false"))); - otherGroup = other; - } - - @AfterEach - void cleanUp() { - assertAll("remove Logs and IAM fixtures and close every client", - () -> { - if (protectedGroup != null) { - root.deleteLogGroup(r -> r.logGroupName(protectedGroup)); - } - }, - () -> { - if (otherGroup != null) { - root.deleteLogGroup(r -> r.logGroupName(otherGroup)); - } - }, - () -> { - if (policyCreated) { - iam.deleteUserPolicy(r -> r.userName(user).policyName("streams")); - } - }, - () -> { - if (key != null) { - iam.deleteAccessKey(r -> r.userName(user).accessKeyId(key.accessKeyId())); - } - }, - () -> { - if (user != null) { - iam.deleteUser(r -> r.userName(user)); - } - }, - () -> { - if (caller != null) { - caller.close(); - } - }, - () -> { - if (root != null) { - root.close(); - } - }, - () -> { - if (iam != null) { - iam.close(); - } - }); + CloudWatchLogsStreamAuthorizationTest() { + super("logs-stream-permissions", "streams"); } @ParameterizedTest @@ -163,12 +78,6 @@ class CloudWatchLogsStreamAuthorizationTest { } } - private void policy(String statements) { - iam.putUserPolicy(r -> r.userName(user).policyName("streams") - .policyDocument("{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}")); - policyCreated = true; - } - private void invoke(boolean delete, String group) { invoke(delete, group, "selected"); } @@ -185,15 +94,4 @@ class CloudWatchLogsStreamAuthorizationTest { assertThat(root.describeLogStreams(r -> r.logGroupName(group)).logStreams().stream() .anyMatch(stream -> "selected".equals(stream.logStreamName()))).isEqualTo(expected); } - - private void assertDenied(CloudWatchLogsException error) { - assertThat(error.statusCode()).isEqualTo(400); - assertThat(error.awsErrorDetails().errorCode()).contains("AccessDenied"); - } - - private static CloudWatchLogsClient client(String accessKey, String secret) { - return CloudWatchLogsClient.builder().endpointOverride(TestFixtures.endpoint()).region(TestFixtures.region()) - .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secret))) - .build(); - } } diff --git a/docs/services/iam.md b/docs/services/iam.md index 7899f58857..83b4b3d029 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1266,11 +1266,27 @@ These identities always bypass enforcement (backward-compatible defaults): specific log-stream ARN, so policies can allow or deny one stream within a group. Their `aws:ResourceTag/` conditions read the owning log group's current tags in the request's account and region. Both stream operations check the documented group and stream name constraints -before changing storage, preventing delimiter aliases from targeting another stream. Other Logs -actions retain their existing wildcard resource evaluation. +before changing storage, preventing delimiter aliases from targeting another stream. These checks also apply to deletion: legacy streams with names containing `:` or `*` cannot be deleted through `DeleteLogStream`. Existing stored names are not automatically migrated. +**CloudWatch Logs ARN tagging.** For log groups, `logs:TagResource`, `logs:UntagResource` +and `logs:ListTagsForResource` evaluate the group's ARN without a trailing `:*`. The ARN must +identify a group in the request's account, region and partition; a different owner or resource +kind returns `ResourceNotFoundException` without reading or changing a local group's tags. +All three actions use the group's existing `aws:ResourceTag/` conditions. `TagResource` +also provides `aws:RequestTag/` and `aws:TagKeys`; `UntagResource` provides `aws:TagKeys`. +An unauthorized request cannot partially add or remove tags. These ownership checks also apply +when IAM enforcement is disabled. Shared tag mutations reject storage aliases whose stored group +name differs from the requested name, without migrating historical records. + +This support covers log groups. Tagging destinations and other CloudWatch Logs resource types +remains unsupported. Plain-name inputs are used literally, including incomplete prefixes such as +`arn:archive`; arbitrary `:log-group:` substrings never select a different group. Structurally complete +ARNs take precedence over plain-name interpretation and must identify a local group. A trailing `:*` +is accepted on a canonical local group ARN. These compatibility forms are not a claim that AWS accepts +them for these APIs. Other Logs actions retain their existing wildcard resource evaluation. + **IAM's own resources are named.** When enforcement evaluates a request, the target resource comes from `ResourceArnBuilder`, which builds an ARN for S3, Lambda, SQS, SNS, DynamoDB, Kinesis, Secrets Manager, SSM, KMS and IAM. Within IAM the resource type each action is evaluated against is the one @@ -1449,7 +1465,8 @@ floci populates: `ResourceId.N` or `InstanceId.N`), and for `s3:GetBucketTagging`, `s3:DeleteBucket` and the `s3:PutBucketTagging` that `DeleteBucketTagging` is checked as (the bucket). A request naming several EC2 resources is evaluated once per resource and denied when any of them fails the condition, as on AWS. - `logs:CreateLogStream` and `logs:DeleteLogStream` use the owning log group's tags. + `logs:CreateLogStream`, `logs:DeleteLogStream`, `logs:TagResource`, `logs:UntagResource` + and `logs:ListTagsForResource` use the owning log group's tags. - `s3:ExistingObjectTag/`: the tags already on the target object version, for `s3:GetObject`, `s3:GetObjectTagging`, `s3:GetObjectAcl`, `s3:PutObjectAcl`, `s3:DeleteObjectTagging`, `s3:PutObjectTagging` and the annotation actions, and for their diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java index 1717ab1782..5079a905be 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; +import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget; import io.github.hectorvent.floci.services.dynamodb.DynamoDbConditionKeys; import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbTableNames; @@ -106,7 +107,8 @@ public class IamConditionContextResolver { /** Stream access uses the owning log group's tags, in the handler's account and region. */ private Map> logStreamConditionContext(String action, ContainerRequestContext ctx) { - if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action))) { + if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action) + || LogGroupTagTarget.supports(action))) { return null; } JsonNode body = bufferedJsonBody(ctx); @@ -114,20 +116,39 @@ public class IamConditionContextResolver { 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 -> { + keys.add(entry.getKey()); + conditions.put(REQUEST_TAG_PREFIX + entry.getKey(), List.of(entry.getValue().asText())); + }); + if (!keys.isEmpty()) { + conditions.put("aws:TagKeys", keys); + } + } else if ("logs:UntagResource".equals(action)) { + List keys = new ArrayList<>(); + body.path("tagKeys").forEach(key -> keys.add(key.asText())); + if (!keys.isEmpty()) { + conditions.put("aws:TagKeys", keys); + } + } + String group = direct ? logsService.get().resolveTagTarget(body.path("resourceArn").asText(), region).name() + : body.path("logGroupName").asText(); Map tags; try { - tags = logsService.get().listTagsLogGroup(body.path("logGroupName").asText(), region); + 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. - return null; + return conditions.isEmpty() ? null : conditions; } if (tags == null || tags.isEmpty()) { - return null; + return conditions.isEmpty() ? null : conditions; } - Map> conditions = new LinkedHashMap<>(); tags.forEach((key, value) -> conditions.put(RESOURCE_TAG_PREFIX + key, List.of(value == null ? "" : value))); return conditions; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java index a32f1d334d..3150c331a9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java @@ -549,7 +549,7 @@ public class CloudWatchLogsHandler { private Response handleListTagsForResource(JsonNode request, String region) { String resourceArn = request.path("resourceArn").asText(); - String groupName = extractLogGroupNameFromArn(resourceArn); + String groupName = logsService.resolveTagTarget(resourceArn, region).name(); Map tags = logsService.listTagsLogGroup(groupName, region); ObjectNode response = objectMapper.createObjectNode(); @@ -561,7 +561,7 @@ public class CloudWatchLogsHandler { private Response handleTagResource(JsonNode request, String region) { String resourceArn = request.path("resourceArn").asText(); - String groupName = extractLogGroupNameFromArn(resourceArn); + String groupName = logsService.resolveTagTarget(resourceArn, region).name(); Map tags = extractTags(request.path("tags")); logsService.tagLogGroup(groupName, tags, region); return Response.ok(objectMapper.createObjectNode()).build(); @@ -569,7 +569,7 @@ public class CloudWatchLogsHandler { private Response handleUntagResource(JsonNode request, String region) { String resourceArn = request.path("resourceArn").asText(); - String groupName = extractLogGroupNameFromArn(resourceArn); + String groupName = logsService.resolveTagTarget(resourceArn, region).name(); List tagKeys = new ArrayList<>(); request.path("tagKeys").forEach(k -> tagKeys.add(k.asText())); logsService.untagLogGroup(groupName, tagKeys, region); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java index b1ce0e84f0..af4cc4695f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java @@ -373,9 +373,14 @@ public class CloudWatchLogsService implements ResourceProvider { groupStore.put(key, group); } + public LogGroupTagTarget resolveTagTarget(String resourceArn, String region) { + return LogGroupTagTarget.resolve(resourceArn, region, regionResolver.getAccountId(), regionResolver.getPartition()); + } + public void tagLogGroup(String groupName, Map tags, String region) { String key = groupKey(region, groupName); LogGroup group = groupStore.get(key) + .filter(stored -> groupName.equals(stored.getLogGroupName())) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "The specified log group does not exist: " + groupName, 400)); group.getTags().putAll(tags); @@ -385,6 +390,7 @@ public class CloudWatchLogsService implements ResourceProvider { public void untagLogGroup(String groupName, List tagKeys, String region) { String key = groupKey(region, groupName); LogGroup group = groupStore.get(key) + .filter(stored -> groupName.equals(stored.getLogGroupName())) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "The specified log group does not exist: " + groupName, 400)); tagKeys.forEach(group.getTags()::remove); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogGroupTagTarget.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogGroupTagTarget.java new file mode 100644 index 0000000000..bdab7dae56 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogGroupTagTarget.java @@ -0,0 +1,27 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs; + +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; + +/** The same locally owned group identity for direct tag authorization and execution. */ +public record LogGroupTagTarget(String name, String arn) { + + public static boolean supports(String action) { + return "logs:TagResource".equals(action) || "logs:UntagResource".equals(action) + || "logs:ListTagsForResource".equals(action); + } + + public static LogGroupTagTarget resolve(String input, String region, String account, String partition) { + String prefix = new AwsArnUtils.Arn(partition, "logs", region, account, "log-group:").toString(); + if (AwsArnUtils.isArn(input) && !input.startsWith(prefix)) { + throw new AwsException("ResourceNotFoundException", "The specified log group does not exist.", 400); + } + // Plain names remain literal; a marker inside a name must not select another group. + String name = input.startsWith(prefix) ? input.substring(prefix.length()) : input; + if (input.startsWith(prefix) && name.endsWith(":*")) { + name = name.substring(0, name.length() - 2); + } + return new LogGroupTagTarget(name, + new AwsArnUtils.Arn(partition, "logs", region, account, "log-group:" + name).toString()); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index 781b7b0615..a674f1e58c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.common.SigV4CredentialScope; +import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget; import io.github.hectorvent.floci.services.lambda.LambdaArnUtils; import io.github.hectorvent.floci.services.lambda.durable.DurableTokens; import jakarta.enterprise.context.ApplicationScoped; @@ -100,13 +101,17 @@ public class ResourceArnBuilder { /** Uses the serving operation, not an independently parsed target header. */ public List buildLogStreamResources(String action, ContainerRequestContext ctx, String region, String accountId, String partition) { - if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action))) { + if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action) + || LogGroupTagTarget.supports(action))) { return List.of("*"); } JsonNode body = readJsonBody(ctx); if (body == null) { return List.of("*"); } + if (LogGroupTagTarget.supports(action)) { + return List.of(LogGroupTagTarget.resolve(body.path("resourceArn").asText(), region, accountId, partition).arn()); + } // Match the handler's coercion and raw names, including whitespace and numeric values. String group = body.path("logGroupName").asText(); String stream = body.path("logStreamName").asText(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java index ee8eb55e17..21d1ae5ded 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java @@ -10,6 +10,8 @@ import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream; import io.github.hectorvent.floci.services.cloudwatch.logs.model.SubscriptionFilter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.util.ArrayList; import java.util.List; @@ -38,6 +40,34 @@ class CloudWatchLogsServiceTest { ); } + @ParameterizedTest + @ValueSource(strings = {"TagLogGroup", "UntagLogGroup"}) + void tagMutationCannotBorrowHistoricalGroupThroughRegionAlias(String action) { + String historical = "x::victim"; + String aliasRegion = REGION + "::x"; + service.createLogGroup(historical, null, Map.of("team", "blue"), REGION); + assertThrows(AwsException.class, () -> service.listTagsLogGroup("victim", aliasRegion)); + assertAll("the shared tag mutator preserves the stored group identity", + () -> { + AwsException error = assertThrows(AwsException.class, () -> { + if (action.equals("TagLogGroup")) { + service.tagLogGroup("victim", Map.of("team", "red"), aliasRegion); + } else { + service.untagLogGroup("victim", List.of("team"), aliasRegion); + } + }); + assertEquals("ResourceNotFoundException", error.getErrorCode()); + }, + () -> assertEquals(Map.of("team", "blue"), service.listTagsLogGroup(historical, REGION))); + if (action.equals("TagLogGroup")) { + service.tagLogGroup(historical, Map.of("team", "red"), REGION); + assertEquals(Map.of("team", "red"), service.listTagsLogGroup(historical, REGION)); + } else { + service.untagLogGroup(historical, List.of("team"), REGION); + assertEquals(Map.of(), service.listTagsLogGroup(historical, REGION)); + } + } + // ──────────────────────────── Log Groups ──────────────────────────── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LogsArnTagAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LogsArnTagAuthorizationIntegrationTest.java new file mode 100644 index 0000000000..9a4f0c2093 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsArnTagAuthorizationIntegrationTest.java @@ -0,0 +1,249 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.LogsAuthorizationFixtures; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.LogsAuthorizationFixtures.expectedTags; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class LogsArnTagAuthorizationIntegrationTest { + + private static final String ACCOUNT = "111111111111"; + private static final String REGION = "us-east-1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @TestHTTPResource + URI endpoint; + + @BeforeAll + static void configureContentTypes() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void exactBareGroupArnGrant(String action) { + String selected = group(); + String other = group(Map.of("team", "green")); + String caller = user(statement("Allow", action, arn(selected))); + invoke(caller, action, arn(other)).statusCode(400).body(containsString("AccessDeniedException")); + assertTags(other, Map.of("team", "green")); + assertSuccess(invoke(caller, action, arn(selected)), action); + assertTags(selected, expectedTags(action)); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void exactBareGroupArnDenyOverridesWildcard(String action) { + String selected = group(); + String other = group(); + String caller = user(statement("Allow", action, "*") + "," + statement("Deny", action, arn(selected))); + ValidatableResponse response = invoke(caller, action, arn(selected)); + assertAll("the exact deny prevents access and preserves tags", + () -> response.statusCode(400).body(containsString("AccessDeniedException")), + () -> assertTags(selected, Map.of("team", "blue"))); + assertSuccess(invoke(caller, action, arn(other)), action); + assertTags(other, expectedTags(action)); + } + + @ParameterizedTest + @CsvSource({"TagResource,account", "UntagResource,account", "ListTagsForResource,account", + "TagResource,region", "UntagResource,region", "ListTagsForResource,region", + "TagResource,partition", "UntagResource,partition", "ListTagsForResource,partition"}) + void foreignArnCannotBorrowLocalGroup(String action, String dimension) { + verifyForeignArn(action, dimension, false); + } + + @ParameterizedTest + @CsvSource({"TagResource,account", "UntagResource,account", "ListTagsForResource,account", + "TagResource,region", "UntagResource,region", "ListTagsForResource,region", + "TagResource,partition", "UntagResource,partition", "ListTagsForResource,partition"}) + void rootBypassCannotBorrowLocalGroup(String action, String dimension) { + verifyForeignArn(action, dimension, true); + } + + private void verifyForeignArn(String action, String dimension, boolean root) { + String local = group(); + String caller = root ? ACCOUNT : user(statement("Allow", action, "*")); + String foreign = switch (dimension) { + case "account" -> "arn:aws:logs:" + REGION + ":222222222222:log-group:" + local; + case "region" -> "arn:aws:logs:us-west-2:" + ACCOUNT + ":log-group:" + local; + case "partition" -> "arn:aws-cn:logs:" + REGION + ":" + ACCOUNT + ":log-group:" + local; + default -> throw new IllegalArgumentException(dimension); + }; + ValidatableResponse response = invoke(caller, action, foreign); + response.statusCode(400).body(containsString("ResourceNotFoundException")); + if (action.equals("ListTagsForResource")) { + Map returned = response.extract().path("tags"); + assertTrue(returned == null || !"blue".equals(returned.get("team")), + "foreign identity must not disclose the local tag entry"); + } + assertTags(local, Map.of("team", "blue")); + assertSuccess(invoke(caller, action, arn(local)), action); + assertTags(local, expectedTags(action)); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void incompleteArnPrefixRemainsALiteralLegacyName(String action) { + String name = groupNamed("arn:archive-" + UUID.randomUUID(), Map.of("team", "blue")); + String caller = user(statement("Allow", action, arn(name))); + assertSuccess(invoke(caller, action, name), action); + assertTags(name, expectedTags(action)); + } + + @ParameterizedTest + @CsvSource({"TagResource,uppercase,false", "TagResource,uppercase,true", + "TagResource,space,false", "TagResource,space,true", + "TagResource,marker,false", "TagResource,marker,true", + "UntagResource,uppercase,false", "UntagResource,uppercase,true", + "UntagResource,space,false", "UntagResource,space,true", + "UntagResource,marker,false", "UntagResource,marker,true", + "ListTagsForResource,uppercase,false", "ListTagsForResource,uppercase,true", + "ListTagsForResource,space,false", "ListTagsForResource,space,true", + "ListTagsForResource,marker,false", "ListTagsForResource,marker,true"}) + void noncanonicalMarkerInputCannotBorrowAnotherGroup(String action, String shape, boolean root) { + String local = group(); + String input = switch (shape) { + case "uppercase" -> "ARN:aws:logs:eu-west-1:999999999999:log-group:" + local; + case "space" -> " arn:aws:logs:eu-west-1:999999999999:log-group:" + local; + case "marker" -> "x:log-group:" + local; + default -> throw new IllegalArgumentException(shape); + }; + String caller = root ? ACCOUNT : user(statement("Allow", action, "*")); + ValidatableResponse response = invoke(caller, action, input); + assertAll("noncanonical input cannot access the shortened local name", + () -> response.statusCode(400).body(containsString("ResourceNotFoundException")), + () -> assertTags(local, Map.of("team", "blue"))); + String literal = groupNamed(input, Map.of("team", "blue")); + assertSuccess(invoke(caller, action, input), action); + assertTags(literal, expectedTags(action)); + assertTags(local, Map.of("team", "blue")); + assertSuccess(invoke(caller, action, arn(local)), action); + assertTags(local, expectedTags(action)); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void storedTagDenyUsesTheOwningGroup(String action) { + String selected = group(); + String other = group(Map.of("team", "green")); + String caller = user(statement("Allow", action, "*") + "," + + "{\"Effect\":\"Deny\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}}"); + invoke(caller, action, arn(selected)).statusCode(400).body(containsString("AccessDeniedException")); + assertTags(selected, Map.of("team", "blue")); + ValidatableResponse allowed = invoke(caller, action, arn(other)).statusCode(200); + if (action.equals("ListTagsForResource")) { + allowed.body("tags", equalTo(Map.of("team", "green"))); + assertTags(other, Map.of("team", "green")); + } else { + assertTags(other, expectedTags(action)); + } + } + + @Test + void requestedTagValuesAndKeysControlMutation() { + String selected = group(); + String caller = user("{\"Effect\":\"Allow\",\"Action\":\"logs:TagResource\",\"Resource\":\"" + + arn(selected) + "\",\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"red\"}," + + "\"ForAllValues:StringEquals\":{\"aws:TagKeys\":[\"team\"]}}}"); + for (Map denied : List.of(Map.of("team", "blue"), + Map.of("team", "red", "protected", "changed"))) { + call(endpoint.getPort(), caller, "TagResource", Map.of("resourceArn", arn(selected), "tags", denied)) + .statusCode(400).body(containsString("AccessDeniedException")); + assertTags(selected, Map.of("team", "blue")); + } + invoke(caller, "TagResource", arn(selected)).statusCode(200); + assertTags(selected, Map.of("team", "red")); + } + + @Test + void removalKeysDenyBeforeAnyTagIsRemoved() { + String selected = group(Map.of("team", "blue", "protected", "retained")); + String caller = user("{\"Effect\":\"Allow\",\"Action\":\"logs:UntagResource\",\"Resource\":\"" + + arn(selected) + "\",\"Condition\":{\"ForAllValues:StringEquals\":{\"aws:TagKeys\":[\"team\"]}}}"); + call(endpoint.getPort(), caller, "UntagResource", Map.of("resourceArn", arn(selected), + "tagKeys", List.of("team", "protected"))) + .statusCode(400).body(containsString("AccessDeniedException")); + assertTags(selected, Map.of("team", "blue", "protected", "retained")); + invoke(caller, "UntagResource", arn(selected)).statusCode(200); + assertTags(selected, Map.of("protected", "retained")); + } + + private void assertSuccess(ValidatableResponse response, String action) { + response.statusCode(200); + if (action.equals("ListTagsForResource")) { + response.body("tags", equalTo(Map.of("team", "blue"))); + } + } + + private String group() { + return group(Map.of("team", "blue")); + } + + private String group(Map tags) { + return groupNamed("logs-arn-tag-" + UUID.randomUUID(), tags); + } + + private String groupNamed(String name, Map tags) { + int port = endpoint.getPort(); + cleanup.register(() -> call(port, ACCOUNT, "DeleteLogGroup", Map.of("logGroupName", name)).statusCode(200)); + call(port, ACCOUNT, "CreateLogGroup", Map.of("logGroupName", name, "tags", tags)) + .statusCode(200); + return name; + } + + private String user(String statements) { + return LogsAuthorizationFixtures.user(cleanup, endpoint.getPort(), ACCOUNT, "logs-arn-tag-", + "arn-tags", statements); + } + + private static String statement(String effect, String action, String resource) { + return "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + action + + "\",\"Resource\":\"" + resource + "\"}"; + } + + private static String arn(String group) { + return "arn:aws:logs:" + REGION + ":" + ACCOUNT + ":log-group:" + group; + } + + private ValidatableResponse invoke(String caller, String action, String resource) { + return call(endpoint.getPort(), caller, action, LogsAuthorizationFixtures.tagBody(action, resource)); + } + + private void assertTags(String group, Map expected) { + Map actual = call(endpoint.getPort(), ACCOUNT, "ListTagsLogGroup", Map.of("logGroupName", group)) + .statusCode(200).extract().path("tags"); + assertEquals(expected, actual); + } + + private static ValidatableResponse call(int port, String caller, String action, Map body) { + return LogsAuthorizationFixtures.call(port, caller, REGION, action, body).then(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.java index a5791ca27e..1c7c7f27e3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.java @@ -1,6 +1,6 @@ package io.github.hectorvent.floci.services.iam; -import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.LogsAuthorizationFixtures; import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.common.http.TestHTTPResource; @@ -18,7 +18,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertAll; @@ -87,18 +86,13 @@ class LogsNoncommercialUnknownRegionAuthorizationIntegrationTest { "logEvents", List.of(Map.of("timestamp", System.currentTimeMillis(), "message", "retained")))) .then().statusCode(200); } - String user = "logs-partition-" + UUID.randomUUID(); - String root = EnforcementFixtures.auth(ACCOUNT, "iam"); - String caller = EnforcementFixtures.createUser(cleanup, port, root, user).accessKeyId(); String allow = deny ? "{\"Effect\":\"Allow\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\"}," : ""; String effect = deny ? "Deny" : "Allow"; String statement = "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + action + "\",\"Resource\":\"" + groupArn + ":log-stream:s\"}"; - given().port(port).header("Authorization", root).formParam("Action", "PutUserPolicy") - .formParam("UserName", user).formParam("PolicyName", "streams") - .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + allow + statement + "]}") - .when().post("/").then().statusCode(200); + String caller = LogsAuthorizationFixtures.user(cleanup, port, ACCOUNT, "logs-partition-", "streams", + allow + statement); Response response = call(caller, region, action, Map.of("logGroupName", group, "logStreamName", "s")); assertAll("canonical partition governs the same stream and retained events", () -> response.then().statusCode(deny ? 400 : 200), @@ -125,10 +119,6 @@ class LogsNoncommercialUnknownRegionAuthorizationIntegrationTest { } private Response call(String caller, String region, String action, Map body) { - String auth = "AWS4-HMAC-SHA256 Credential=" + caller + "/20261015/" + region - + "/logs/aws4_request, SignedHeaders=host, Signature=abc"; - return given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1") - .header("Authorization", auth).header("X-Amz-Target", "Logs_20140328." + action) - .body(body).when().post("/"); + return LogsAuthorizationFixtures.call(endpoint.getPort(), caller, region, action, body); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LogsStreamAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LogsStreamAuthorizationIntegrationTest.java index f8a5e97893..9d75a9fe8d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/LogsStreamAuthorizationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsStreamAuthorizationIntegrationTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import io.github.hectorvent.floci.testing.EnforcementFixtures; import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.LogsAuthorizationFixtures; import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.common.http.TestHTTPResource; @@ -19,7 +20,6 @@ import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.net.URI; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -399,15 +399,8 @@ class LogsStreamAuthorizationIntegrationTest { } private String user(String account, String statements) { - int port = endpoint.getPort(); - String name = "logs-stream-auth-" + UUID.randomUUID(); - String root = EnforcementFixtures.auth(account, "iam"); - EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser(cleanup, port, root, name); - given().port(port).header("Authorization", root).formParam("Action", "PutUserPolicy") - .formParam("UserName", name).formParam("PolicyName", "streams") - .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}") - .when().post("/").then().statusCode(200); - return credentials.accessKeyId(); + return LogsAuthorizationFixtures.user(cleanup, endpoint.getPort(), account, "logs-stream-auth-", + "streams", statements); } private static String policy(String effect, String action, String resource, String condition) { @@ -443,11 +436,6 @@ class LogsStreamAuthorizationIntegrationTest { } private static ValidatableResponse call(int port, String caller, String region, String action, Map body) { - String authorization = "AWS4-HMAC-SHA256 Credential=" + caller + "/20261015/" + region - + "/logs/aws4_request, SignedHeaders=host, Signature=abc"; - return given().port(port).contentType("application/x-amz-json-1.1") - .header("Authorization", authorization) - .header("X-Amz-Target", "Logs_20140328." + action) - .body(new LinkedHashMap<>(body)).when().post("/").then(); + return LogsAuthorizationFixtures.call(port, caller, region, action, body).then(); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LogsUnknownRegionAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LogsUnknownRegionAuthorizationIntegrationTest.java index 2b8cad9490..8acd9aa7f7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/LogsUnknownRegionAuthorizationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsUnknownRegionAuthorizationIntegrationTest.java @@ -1,7 +1,7 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; -import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.LogsAuthorizationFixtures; import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.common.http.TestHTTPResource; @@ -14,13 +14,14 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import java.net.URI; import java.util.List; import java.util.Map; import java.util.UUID; -import static io.restassured.RestAssured.given; +import static io.github.hectorvent.floci.testing.LogsAuthorizationFixtures.expectedTags; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertAll; @@ -55,6 +56,33 @@ class LogsUnknownRegionAuthorizationIntegrationTest { RestAssuredJsonUtils.configureAwsContentTypes(); } + @ParameterizedTest + @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) + void directTagArnRejectsColonRegionAndAcceptsUnambiguousUnknownRegion(String action) { + String region = "custom-region-1"; + String group = "logs-tag-marker-" + UUID.randomUUID(); + int port = endpoint.getPort(); + cleanup.register(() -> call(port, ACCOUNT, region, "DeleteLogGroup", Map.of("logGroupName", group)) + .then().statusCode(200)); + logsService.createLogGroupForAccount(ACCOUNT, group, null, Map.of("team", "blue"), region); + String caller = LogsAuthorizationFixtures.user(cleanup, port, ACCOUNT, "logs-tag-marker-", "marker-tags", + "{\"Effect\":\"Allow\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\"}"); + Map body = LogsAuthorizationFixtures.tagBody(action, + "arn:aws:logs:" + region + ":" + ACCOUNT + ":log-group:" + group); + call(port, caller, "custom:log-group:zone", action, body) + .then().statusCode(400).body(containsString("InvalidSignatureException")); + call(port, ACCOUNT, region, "ListTagsLogGroup", Map.of("logGroupName", group)) + .then().statusCode(200).body("tags", equalTo(Map.of("team", "blue"))); + Response result = call(port, caller, region, action, body); + result.then().statusCode(200); + Map expected = expectedTags(action); + if (action.equals("ListTagsForResource")) { + result.then().body("tags", equalTo(expected)); + } + call(port, ACCOUNT, region, "ListTagsLogGroup", Map.of("logGroupName", group)) + .then().statusCode(200).body("tags", equalTo(expected)); + } + @ParameterizedTest @CsvSource({"CreateLogStream,false,false", "DeleteLogStream,false,false", "CreateLogStream,true,false", "DeleteLogStream,true,false", "DeleteLogStream,false,true"}) @@ -81,18 +109,13 @@ class LogsUnknownRegionAuthorizationIntegrationTest { } } assertPresent(port, REGION, historical, historicalStream, delete); - String user = "logs-region-alias-" + UUID.randomUUID(); - String root = EnforcementFixtures.auth(ACCOUNT, "iam"); - String caller = EnforcementFixtures.createUser(cleanup, port, root, user).accessKeyId(); String condition = conditional ? ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}" : ""; String resources = "[\"arn:aws:logs:" + aliasRegion + ":" + ACCOUNT + ":log-group:" + group + ":log-stream:s\",\"arn:aws:logs:" + validUnknownRegion + ":" + ACCOUNT + ":log-group:" + group + ":log-stream:s\"]"; - given().port(port).header("Authorization", root).formParam("Action", "PutUserPolicy") - .formParam("UserName", user).formParam("PolicyName", "streams") - .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," - + "\"Action\":\"logs:" + action + "\",\"Resource\":" + resources + condition + "}]}") - .when().post("/").then().statusCode(200); + String caller = LogsAuthorizationFixtures.user(cleanup, port, ACCOUNT, "logs-region-alias-", "streams", + "{\"Effect\":\"Allow\",\"Action\":\"logs:" + action + + "\",\"Resource\":" + resources + condition + "}"); Response response = call(port, caller, aliasRegion, action, Map.of("logGroupName", group, "logStreamName", "s")); assertAll("preserve stored identity across an opted-in region delimiter", @@ -130,19 +153,14 @@ class LogsUnknownRegionAuthorizationIntegrationTest { logsService.putLogEventsForAccount(ACCOUNT, group, "s", List.of(Map.of("timestamp", System.currentTimeMillis(), "message", "retained")), region); } - String user = "logs-resource-owner-" + UUID.randomUUID(); - String root = EnforcementFixtures.auth(ACCOUNT, "iam"); - String caller = EnforcementFixtures.createUser(cleanup, port, root, user).accessKeyId(); String grant = effect.equals("Deny") ? "{\"Effect\":\"Allow\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\"}," : ""; String owner = actualOwner ? ACCOUNT : otherAccount; String statement = "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"aws:ResourceAccount\":\"" + owner + "\"}}}"; - given().port(port).header("Authorization", root).formParam("Action", "PutUserPolicy") - .formParam("UserName", user).formParam("PolicyName", "streams") - .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + grant + statement + "]}") - .when().post("/").then().statusCode(200); + String caller = LogsAuthorizationFixtures.user(cleanup, port, ACCOUNT, "logs-resource-owner-", "streams", + grant + statement); boolean allowed = effect.equals("Allow") == actualOwner; Response response = call(port, caller, region, action, Map.of("logGroupName", group, "logStreamName", "s")); assertAll("use the owning account in an admitted custom region", @@ -171,9 +189,6 @@ class LogsUnknownRegionAuthorizationIntegrationTest { } private static Response call(int port, String caller, String region, String action, Map body) { - String auth = "AWS4-HMAC-SHA256 Credential=" + caller + "/20261015/" + region - + "/logs/aws4_request, SignedHeaders=host, Signature=abc"; - return given().port(port).contentType("application/x-amz-json-1.1").header("Authorization", auth) - .header("X-Amz-Target", "Logs_20140328." + action).body(body).when().post("/"); + return LogsAuthorizationFixtures.call(port, caller, region, action, body); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index e0bd07efbc..423d3b2328 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -660,10 +660,23 @@ class ResourceArnBuilderTest { } } + @Test + void directLogTagTargetsUseBareArnAndServingAction() { + 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", "custom-region-1")) { + String partition = AwsRegions.partitionFor(region); + String arn = "arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":log-group:group"; + setJsonBody("{\"resourceArn\":\"" + arn + "\"}"); + when(ctx.getHeaderString("X-Amz-Target")).thenReturn("Logs_20140328.DeleteLogGroup"); + assertEquals(List.of(arn), builder.buildLogStreamResources(action, ctx, region, ACCOUNT, partition)); + } + } + } + @Test void excludedLogsActionsKeepWildcardResources() { for (String action : List.of("logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy", - "logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource", "logs:PutLogEvents")) { + "logs:DeleteRetentionPolicy", "logs:PutLogEvents")) { setJsonBody("{\"logGroupName\":\"group\",\"logStreamName\":\"stream\"}"); assertEquals(List.of("*"), builder.buildLogStreamResources(action, ctx, "us-east-1", ACCOUNT, "aws")); } diff --git a/src/test/java/io/github/hectorvent/floci/testing/LogsAuthorizationFixtures.java b/src/test/java/io/github/hectorvent/floci/testing/LogsAuthorizationFixtures.java new file mode 100644 index 0000000000..8a72820a1c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/LogsAuthorizationFixtures.java @@ -0,0 +1,56 @@ +package io.github.hectorvent.floci.testing; + +import io.restassured.response.Response; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; + +/** Shared signed requests and IAM users for Logs authorization tests. */ +public final class LogsAuthorizationFixtures { + private LogsAuthorizationFixtures() { + } + + public static String user(PartitionCleanup cleanup, int port, String account, String prefix, + String policyName, String statements) { + String name = prefix + UUID.randomUUID(); + String root = EnforcementFixtures.auth(account, "iam"); + String key = EnforcementFixtures.createUser(cleanup, port, root, name).accessKeyId(); + given().port(port).header("Authorization", root).formParam("Action", "PutUserPolicy") + .formParam("UserName", name).formParam("PolicyName", policyName) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}") + .when().post("/").then().statusCode(200); + return key; + } + + public static Response call(int port, String caller, String region, String action, Map body) { + String authorization = "AWS4-HMAC-SHA256 Credential=" + caller + "/20261015/" + region + + "/logs/aws4_request, SignedHeaders=host, Signature=abc"; + return given().port(port).contentType("application/x-amz-json-1.1") + .header("Authorization", authorization).header("X-Amz-Target", "Logs_20140328." + action) + .body(new LinkedHashMap<>(body)).when().post("/"); + } + + public static Map tagBody(String action, String resource) { + Map body = new LinkedHashMap<>(); + body.put("resourceArn", resource); + if (action.equals("TagResource")) { + body.put("tags", Map.of("team", "red")); + } else if (action.equals("UntagResource")) { + body.put("tagKeys", List.of("team")); + } + return body; + } + + public static Map expectedTags(String action) { + return switch (action) { + case "TagResource" -> Map.of("team", "red"); + case "UntagResource" -> Map.of(); + case "ListTagsForResource" -> Map.of("team", "blue"); + default -> throw new IllegalArgumentException(action); + }; + } +}