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 index d75700e3a1..16684294a3 100644 --- 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 @@ -40,17 +40,6 @@ class CloudWatchLogsArnTagAuthorizationTest extends CloudWatchLogsAuthorizationF 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) { 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 index fdf5ef18c1..5e234181d0 100644 --- 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 @@ -100,10 +100,14 @@ abstract class CloudWatchLogsAuthorizationFixture { final String createGroup(String name, Map tags) { root.createLogGroup(r -> r.logGroupName(name).tags(tags)); - groups.add(() -> root.deleteLogGroup(r -> r.logGroupName(name))); + groups.add(() -> deleteGroup(name)); return name; } + void deleteGroup(String name) { + root.deleteLogGroup(r -> r.logGroupName(name)); + } + final void policy(String statements) { iam.putUserPolicy(r -> r.userName(user).policyName(policyName) .policyDocument("{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}")); diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsGroupAuthorizationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsGroupAuthorizationTest.java new file mode 100644 index 0000000000..02d9b49e4b --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsGroupAuthorizationTest.java @@ -0,0 +1,154 @@ +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.model.CloudWatchLogsException; +import software.amazon.awssdk.services.cloudwatchlogs.model.LogGroup; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudWatch Logs group resource permissions") +class CloudWatchLogsGroupAuthorizationTest extends CloudWatchLogsAuthorizationFixture { + + CloudWatchLogsGroupAuthorizationTest() { + super("logs-group-permissions", "groups"); + } + + @Override + void deleteGroup(String name) { + if (groupExists(name)) { + super.deleteGroup(name); + } + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void exactGroupGrant(String action) { + prepare(action); + policy(statement("Allow", action, groupArn(protectedGroup))); + assertThatThrownBy(() -> invoke(action, otherGroup)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertState(action, otherGroup, false); + invoke(action, protectedGroup); + assertState(action, protectedGroup, true); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void bareGroupGrant(String action) { + prepare(action); + policy(statement("Allow", action, TestFixtures.arn("logs", "000000000000", "log-group:" + protectedGroup))); + assertThatThrownBy(() -> invoke(action, otherGroup)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertState(action, otherGroup, false); + invoke(action, protectedGroup); + assertState(action, protectedGroup, true); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void exactGroupDenyOverridesWildcard(String action) { + prepare(action); + policy(statement("Allow", action, "*") + "," + statement("Deny", action, groupArn(protectedGroup))); + assertThatThrownBy(() -> invoke(action, protectedGroup)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertState(action, protectedGroup, false); + invoke(action, otherGroup); + assertState(action, otherGroup, true); + } + + @ParameterizedTest + @ValueSource(strings = {"DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void groupTagDeny(String action) { + prepare(action); + policy(statement("Allow", action, "*") + "," + + "{\"Effect\":\"Deny\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/protected\":\"true\"}}}"); + assertThatThrownBy(() -> invoke(action, protectedGroup)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertState(action, protectedGroup, false); + invoke(action, otherGroup); + assertState(action, otherGroup, true); + } + + @ParameterizedTest + @ValueSource(strings = {"TagResource", "TagLogGroup"}) + void taggedCreateRequiresEitherPermission(String tagAction) { + prepare("CreateLogGroup"); + String primary = statement("Allow", "CreateLogGroup", groupArn(protectedGroup)); + policy(primary); + assertThatThrownBy(() -> caller.createLogGroup(r -> r.logGroupName(protectedGroup) + .tags(Map.of("team", "blue")))) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertState("CreateLogGroup", protectedGroup, false); + String resource = tagAction.equals("TagResource") + ? TestFixtures.arn("logs", "000000000000", "log-group:" + protectedGroup) + : groupArn(protectedGroup); + String unused = tagAction.equals("TagResource") ? "TagLogGroup" : "TagResource"; + policy(primary + "," + statement("Deny", unused, "*") + "," + + "{\"Effect\":\"Allow\",\"Action\":\"logs:" + tagAction + "\",\"Resource\":\"" + resource + + "\",\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\"}," + + "\"ForAllValues:StringEquals\":{\"aws:TagKeys\":[\"team\"]}}}"); + assertThatThrownBy(() -> caller.createLogGroup(r -> r.logGroupName(protectedGroup) + .tags(Map.of("team", "red")))) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertState("CreateLogGroup", protectedGroup, false); + caller.createLogGroup(r -> r.logGroupName(protectedGroup).tags(Map.of("team", "blue"))); + assertState("CreateLogGroup", protectedGroup, true); + assertThat(root.listTagsLogGroup(r -> r.logGroupName(protectedGroup)).tags()).containsEntry("team", "blue"); + } + + private void prepare(String action) { + if (action.equals("CreateLogGroup")) { + root.deleteLogGroup(r -> r.logGroupName(protectedGroup)); + root.deleteLogGroup(r -> r.logGroupName(otherGroup)); + } else if (action.equals("PutRetentionPolicy") || action.equals("DeleteRetentionPolicy")) { + root.putRetentionPolicy(r -> r.logGroupName(protectedGroup).retentionInDays(7)); + root.putRetentionPolicy(r -> r.logGroupName(otherGroup).retentionInDays(7)); + } + } + + private String statement(String effect, String action, String resource) { + return "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + action + + "\",\"Resource\":\"" + resource + "\"}"; + } + + private String groupArn(String group) { + return TestFixtures.arn("logs", "000000000000", "log-group:" + group + ":*"); + } + + private void invoke(String action, String group) { + switch (action) { + case "CreateLogGroup" -> caller.createLogGroup(r -> r.logGroupName(group)); + case "DeleteLogGroup" -> caller.deleteLogGroup(r -> r.logGroupName(group)); + case "PutRetentionPolicy" -> caller.putRetentionPolicy(r -> r.logGroupName(group).retentionInDays(14)); + case "DeleteRetentionPolicy" -> caller.deleteRetentionPolicy(r -> r.logGroupName(group)); + default -> throw new IllegalArgumentException(action); + } + } + + private void assertState(String action, String group, boolean changed) { + LogGroup found = root.describeLogGroupsPaginator(r -> r.logGroupNamePrefix(group)).logGroups().stream() + .filter(g -> group.equals(g.logGroupName())).findFirst().orElse(null); + boolean exists = action.equals("CreateLogGroup") ? changed : !action.equals("DeleteLogGroup") || !changed; + if (!exists) { + assertThat(found).isNull(); + return; + } + assertThat(found).isNotNull(); + if (action.equals("PutRetentionPolicy")) { + assertThat(found.retentionInDays()).isEqualTo(changed ? 14 : 7); + } else if (action.equals("DeleteRetentionPolicy")) { + assertThat(found.retentionInDays()).isEqualTo(changed ? null : 7); + } + } + + private boolean groupExists(String group) { + return root.describeLogGroupsPaginator(r -> r.logGroupNamePrefix(group)).logGroups().stream() + .anyMatch(g -> group.equals(g.logGroupName())); + } +} diff --git a/docs/services/iam.md b/docs/services/iam.md index f272d5156d..bbf712f0a6 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1271,6 +1271,18 @@ before changing storage, preventing delimiter aliases from targeting another str 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 groups.** `CreateLogGroup`, `DeleteLogGroup`, `PutRetentionPolicy` and +`DeleteRetentionPolicy` accept policy resources naming the selected group with a bare ARN +or its legacy `:*` form. Both forms participate in each statement, including explicit denies +and `NotResource`, without bypassing session, boundary or SCP ceilings. The three operations on +existing groups read that group's resource tags; creation uses the request's `tags` for +`aws:RequestTag/` and `aws:TagKeys`. Tagged creation additionally requires either +`logs:TagResource` on the bare group ARN or `logs:TagLogGroup` on either group ARN form. +The group name constraints apply before mutation, and deletion preserves streams and filters +whose stored group identity belongs to another historical group. These four operations reject `:` +or `*` in a group name. Historical names remain taggable through the ARN tagging APIs below; +they cannot be newly created or deleted through the group lifecycle APIs. Stored names are not 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 @@ -1466,8 +1478,9 @@ 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`, `logs:DeleteLogStream`, `logs:TagResource`, `logs:UntagResource` - and `logs:ListTagsForResource` use the owning log group's tags. + `logs:CreateLogStream`, `logs:DeleteLogStream`, `logs:TagResource`, `logs:UntagResource`, + `logs:ListTagsForResource`, `logs:DeleteLogGroup`, `logs:PutRetentionPolicy` and + `logs:DeleteRetentionPolicy` 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 5079a905be..4fbadbc182 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 @@ -100,19 +100,37 @@ public class IamConditionContextResolver { case "ec2" -> ec2ConditionContext(action, ctx); case "dynamodb" -> dynamoDbConditionContext(action, ctx); case "iam" -> iamConditionContext(action, ctx); - case "logs" -> logStreamConditionContext(action, ctx); + case "logs" -> logsConditionContext(action, ctx); default -> null; }; } - /** Stream access uses the owning log group's tags, in the handler's account and region. */ - private Map> logStreamConditionContext(String action, ContainerRequestContext ctx) { + /** Group mutations and stream access use the handler's group and request scope. */ + private Map> logsConditionContext(String action, ContainerRequestContext ctx) { if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action) - || LogGroupTagTarget.supports(action))) { + || LogGroupTagTarget.supports(action) || "logs:CreateLogGroup".equals(action) || "logs:DeleteLogGroup".equals(action) + || "logs:PutRetentionPolicy".equals(action) || "logs:DeleteRetentionPolicy".equals(action))) { return null; } JsonNode body = bufferedJsonBody(ctx); - if (body == null || !logsService.isResolvable()) { + if (body == null) { + return null; + } + if ("logs:CreateLogGroup".equals(action)) { + JsonNode tags = body.path("tags"); + if (!tags.isObject() || tags.isEmpty()) { + return null; + } + Map> conditions = new LinkedHashMap<>(); + List keys = new ArrayList<>(); + tags.properties().forEach(entry -> { + keys.add(entry.getKey()); + conditions.put("aws:RequestTag/" + entry.getKey(), List.of(entry.getValue().asText())); + }); + conditions.put("aws:TagKeys", keys); + return conditions; + } + if (!logsService.isResolvable()) { return null; } String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index ce20d80c87..40cdd58019 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -417,7 +417,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { List resources = resolveResourceArns(credentialScope, "logs".equals(credentialScope) - ? arnBuilder.buildLogStreamResources(action, ctx, region, accountId, requestPartition()) + ? arnBuilder.buildLogResources(action, ctx, region, accountId, requestPartition()) : arnBuilder.buildResources(credentialScope, ctx, region, accountId)); Optional presignedScope = iamService.presignedScope(akid); @@ -518,6 +518,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return; } + // Tagged group creation requires either tagging permission, using the same resolved + // caller (including session, boundary and SCP ceilings) as the primary operation. + if ("logs:CreateLogGroup".equals(action) && conditionContext != null + && !conditionContext.getOrDefault("aws:TagKeys", List.of()).isEmpty()) { + String groupResource = resources.getFirst(); + String taggingResource = groupResource.substring(0, groupResource.length() - 2); + Map> taggingContext = IamConditionContextResolver.withGlobalContext( + conditionContext, taggingResource, region, accountId, accountId); + Map> groupContext = IamConditionContextResolver.withGlobalContext( + conditionContext, groupResource, region, accountId, accountId); + if (evaluator.evaluate(caller, null, "logs:TagResource", taggingResource, taggingContext) == Decision.DENY + && evaluator.evaluate(caller, null, "logs:TagLogGroup", groupResource, groupContext) == Decision.DENY) { + LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", + akid, "logs:TagResource", taggingResource); + ctx.abortWith(accessDeniedForRequest("logs:TagResource", credentialScope, ctx, taggingResource)); + return; + } + } + // A PutObject carrying If-Match compares against the object it replaces, and S3 authorizes // that read as s3:GetObject, WITHOUT the object's tags in the request context. Measured // against real AWS: under a GetObject allow conditioned on s3:ExistingObjectTag the 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 3150c331a9..55c5b5f379 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 @@ -90,6 +90,7 @@ public class CloudWatchLogsHandler { private Response handleCreateLogGroup(JsonNode request, String region) { String name = request.path("logGroupName").asText(); + requireLogGroupName(name); Integer retentionInDays = request.has("retentionInDays") ? request.path("retentionInDays").asInt() : null; boolean deletionProtectionEnabled = request.path("deletionProtectionEnabled").asBoolean(false); @@ -101,6 +102,7 @@ public class CloudWatchLogsHandler { private Response handleDeleteLogGroup(JsonNode request, String region) { String name = request.path("logGroupName").asText(); + requireLogGroupName(name); logsService.deleteLogGroup(name, region); return Response.ok(objectMapper.createObjectNode()).build(); } @@ -264,10 +266,14 @@ public class CloudWatchLogsHandler { return Response.ok(objectMapper.createObjectNode()).build(); } - private static void requireLogStreamNames(String group, String stream) { + private static void requireLogGroupName(String group) { if (group.isEmpty() || group.length() > 512 || !LOG_GROUP_NAME.matcher(group).matches()) { throw new AwsException("InvalidParameterException", "Invalid logGroupName.", 400); } + } + + private static void requireLogStreamNames(String group, String stream) { + requireLogGroupName(group); int streamLength = stream.codePointCount(0, stream.length()); if (streamLength < 1 || streamLength > 512 || stream.indexOf(':') >= 0 || stream.indexOf('*') >= 0) { throw new AwsException("InvalidParameterException", "Invalid logStreamName.", 400); @@ -510,6 +516,7 @@ public class CloudWatchLogsHandler { private Response handlePutRetentionPolicy(JsonNode request, String region) { String groupName = request.path("logGroupName").asText(); + requireLogGroupName(groupName); int days = request.path("retentionInDays").asInt(); logsService.putRetentionPolicy(groupName, days, region); return Response.ok(objectMapper.createObjectNode()).build(); @@ -517,6 +524,7 @@ public class CloudWatchLogsHandler { private Response handleDeleteRetentionPolicy(JsonNode request, String region) { String groupName = request.path("logGroupName").asText(); + requireLogGroupName(groupName); logsService.deleteRetentionPolicy(groupName, region); return Response.ok(objectMapper.createObjectNode()).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterService.java index ce96c01230..ff53f37e6b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsMetricFilterService.java @@ -522,7 +522,11 @@ public class CloudWatchLogsMetricFilterService implements Resettable { synchronized (store) { String account = regionResolver.getAccountId(); String prefix = groupPrefix(event.region(), event.logGroupName()); - store.keys().stream().filter(key -> key.startsWith(prefix)).toList().forEach(store::delete); + store.keys().stream().filter(storedKey -> storedKey.startsWith(prefix) + && store.get(storedKey).map(filter -> event.logGroupName().equals(filter.getLogGroupName()) + && storedKey.equals(key(event.region(), event.logGroupName(), filter.getFilterName()))) + .orElse(false)) + .toList().forEach(store::delete); pending.values().removeIf(p -> p.owner().account().equals(account) && p.owner().region().equals(event.region()) && p.owner().group().equals(event.logGroupName())); forgetCompletedOutages(); 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 af4cc4695f..36c5a69790 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 @@ -285,6 +285,7 @@ public class CloudWatchLogsService implements ResourceProvider { synchronized (metricFilterStore) { String key = groupKey(region, name); LogGroup group = groupStore.get(key) + .filter(stored -> name.equals(stored.getLogGroupName())) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "The specified log group does not exist: " + name, 400)); if (group.isDeletionProtectionEnabled()) { @@ -301,15 +302,22 @@ public class CloudWatchLogsService implements ResourceProvider { .toList(); for (String sk : streamKeys) { LogStream stream = streamStore.get(sk).orElse(null); - if (stream != null) { + if (stream != null && name.equals(stream.getLogGroupName()) + && sk.equals(streamKey(region, name, stream.getLogStreamName()))) { deleteEventsForStream(region, name, stream.getLogStreamName()); streamStore.delete(sk); } } - metricFilterStore.keys().stream().filter(k -> k.startsWith(streamPrefix)) + metricFilterStore.keys().stream().filter(k -> k.startsWith(streamPrefix) + && metricFilterStore.get(k).map(filter -> name.equals(filter.getLogGroupName()) + && k.equals(streamPrefix + filter.getFilterName())).orElse(false)) .toList().forEach(metricFilterStore::delete); String subscriptionPrefix = subscriptionFilterKeyPrefix(region, name); - subscriptionFilterStore.keys().stream().filter(k -> k.startsWith(subscriptionPrefix)) + subscriptionFilterStore.keys().stream().filter(k -> k.startsWith(subscriptionPrefix) + && subscriptionFilterStore.get(k) + .map(filter -> name.equals(filter.getLogGroupName()) + && k.equals(subscriptionFilterKey(region, name, filter.getFilterName()))) + .orElse(false)) .toList().forEach(subscriptionFilterStore::delete); groupStore.delete(key); LOG.infov("Deleted log group: {0}", name); @@ -358,6 +366,7 @@ public class CloudWatchLogsService implements ResourceProvider { public void putRetentionPolicy(String groupName, int days, 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.setRetentionInDays(days); @@ -367,6 +376,7 @@ public class CloudWatchLogsService implements ResourceProvider { public void deleteRetentionPolicy(String groupName, 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.setRetentionInDays(null); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java index d1f785f877..bd80877bd0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java @@ -908,7 +908,7 @@ public class IamPolicyEvaluator { return false; } return matchesAction(stmt, action) - && matchesResource(stmt, resource, ctx) + && matchesResource(stmt, action, resource, ctx) && matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt)); } @@ -944,7 +944,7 @@ public class IamPolicyEvaluator { PrincipalMatch match = principalMatch(stmt, principal); if (match == PrincipalMatch.NONE || !matchesAction(stmt, action) - || !matchesResource(stmt, resource, ctx) + || !matchesResource(stmt, action, resource, ctx) || !matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt))) { return PrincipalMatch.NONE; } @@ -1121,7 +1121,7 @@ public class IamPolicyEvaluator { private boolean matchesStatement(PolicyStatement stmt, String action, String resource, Map> ctx) { return matchesAction(stmt, action) - && matchesResource(stmt, resource, ctx) + && matchesResource(stmt, action, resource, ctx) && matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt)); } @@ -1142,15 +1142,44 @@ public class IamPolicyEvaluator { } /** Resource: matches if any Resource pattern matches; NotResource: matches if NO pattern matches. */ - private boolean matchesResource(PolicyStatement stmt, String resource, + private boolean matchesResource(PolicyStatement stmt, String action, String resource, Map> ctx) { - if (stmt.getResources() != null) { - return matchesAnyResource(stmt.getResources(), resource, ctx, policyVariables(stmt)); + List patterns = stmt.getResources() != null ? stmt.getResources() : stmt.getNotResources(); + if (patterns == null) { + return false; } - if (stmt.getNotResources() != null) { - return !matchesAnyResource(stmt.getNotResources(), resource, ctx, policyVariables(stmt)); + String alias = logGroupResourceAlias(action, resource); + boolean matched = matchesAnyResource(patterns, resource, ctx, policyVariables(stmt)) + || alias != null && matchesAnyResource(patterns, alias, ctx, policyVariables(stmt)); + return stmt.getResources() != null ? matched : !matched; + } + + /** + * Group-management policies accept both documented bare group ARNs and legacy :* ARNs. + * Match them inside each statement so explicit denies, NotResource and caller ceilings + * retain their normal precedence. Stream actions and the three ARN tag APIs stay distinct. + */ + private static String logGroupResourceAlias(String action, String resource) { + if (action == null || !switch (action) { + case "logs:createloggroup", "logs:deleteloggroup", "logs:putretentionpolicy", + "logs:deleteretentionpolicy", "logs:tagloggroup" -> true; + default -> false; + } || !AwsArnUtils.isArnFor(resource, "logs")) { + return null; } - return false; + String target = AwsArnUtils.parse(resource).resource(); + if (!target.startsWith("log-group:")) { + return null; + } + String name = target.substring("log-group:".length()); + boolean suffixed = name.endsWith(":*"); + if (suffixed) { + name = name.substring(0, name.length() - 2); + } + if (name.isEmpty() || name.indexOf(':') >= 0 || name.indexOf('*') >= 0 || name.indexOf('?') >= 0) { + return null; + } + return suffixed ? resource.substring(0, resource.length() - 2) : resource + ":*"; } /** 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 a674f1e58c..ec5682a39f 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 @@ -98,11 +98,16 @@ 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) - || LogGroupTagTarget.supports(action))) { + /** Uses the serving operation and the same raw names as the handler. */ + public List buildLogResources(String action, ContainerRequestContext ctx, + String region, String accountId, String partition) { + boolean stream = "logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action); + boolean group = switch (action) { + case "logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy", + "logs:DeleteRetentionPolicy" -> true; + default -> false; + }; + if (!stream && !group && !LogGroupTagTarget.supports(action)) { return List.of("*"); } JsonNode body = readJsonBody(ctx); @@ -112,11 +117,10 @@ public class ResourceArnBuilder { 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(); - return List.of(new AwsArnUtils.Arn(partition, "logs", region, accountId, - "log-group:" + group + ":log-stream:" + stream).toString()); + String name = body.path("logGroupName").asText(); + String resource = "log-group:" + name + (stream + ? ":log-stream:" + body.path("logStreamName").asText() : ":*"); + return List.of(new AwsArnUtils.Arn(partition, "logs", region, accountId, resource).toString()); } // ── IAM ───────────────────────────────────────────────────────────────────── diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupDeletionObserverIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupDeletionObserverIntegrationTest.java new file mode 100644 index 0000000000..3199b2e233 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupDeletionObserverIntegrationTest.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs; + +import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter; +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +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.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 java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class CloudWatchLogsGroupDeletionObserverIntegrationTest { + + private static final String ACCOUNT = "111111111111"; + private static final String REGION = "us-east-1"; + + @Inject + CloudWatchLogsService logs; + + @Inject + CloudWatchLogsMetricFilterService metrics; + + @TestHTTPResource + URI endpoint; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureContentTypes() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void actualDeletionObserverPreservesHistoricalChildMetricFilters() { + assertNotNull(metrics); + String parent = "logs-observer-" + UUID.randomUUID(); + String child = parent + "::child"; + for (String group : List.of(parent, child)) { + cleanup.register(() -> RequestScopes.runAs(ACCOUNT, REGION, () -> { + if (logs.describeLogGroups(group, REGION).stream() + .anyMatch(stored -> group.equals(stored.getLogGroupName()))) { + logs.deleteLogGroup(group, REGION); + } + })); + logs.createLogGroupForAccount(ACCOUNT, group, null, Map.of(), REGION); + RequestScopes.runAs(ACCOUNT, REGION, () -> { + MetricFilter filter = new MetricFilter(); + filter.setLogGroupName(group); + filter.setFilterName("m"); + logs.metricFilterStore().put(REGION + "::" + group + "::m", filter); + assertNotNull(logs.metricFilterStore().get(REGION + "::" + group + "::m").orElse(null)); + }); + } + Response response = given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1") + .header("Authorization", EnforcementFixtures.auth(ACCOUNT, "logs")) + .header("X-Amz-Target", "Logs_20140328.DeleteLogGroup") + .body(Map.of("logGroupName", parent)).when().post("/"); + RequestScopes.runAs(ACCOUNT, REGION, () -> assertAll("real CDI observer retains the unrelated child filter", + () -> response.then().statusCode(200), + () -> assertNull(logs.metricFilterStore().get(REGION + "::" + parent + "::m").orElse(null)), + () -> assertNotNull(logs.metricFilterStore().get(REGION + "::" + child + "::m").orElse(null)))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupIsolationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupIsolationTest.java new file mode 100644 index 0000000000..d86449eca4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsGroupIsolationTest.java @@ -0,0 +1,122 @@ +package io.github.hectorvent.floci.services.cloudwatch.logs; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream; +import io.github.hectorvent.floci.services.cloudwatch.logs.model.MetricFilter; +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 static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class CloudWatchLogsGroupIsolationTest { + + private final InMemoryStorage groups = new InMemoryStorage<>(); + private final InMemoryStorage streams = new InMemoryStorage<>(); + private final InMemoryStorage events = new InMemoryStorage<>(); + private final InMemoryStorage subscriptions = new InMemoryStorage<>(); + private final InMemoryStorage metrics = new InMemoryStorage<>(); + private CloudWatchLogsService service; + + @BeforeEach + void setUp() { + service = new CloudWatchLogsService(groups, streams, events, subscriptions, metrics, + 10_000, new RegionResolver("us-east-1", "000000000000")); + } + + @ParameterizedTest + @ValueSource(strings = {"DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void collidingRegionAndNameCannotMutateAnotherStoredGroup(String action) { + LogGroup protectedGroup = new LogGroup(); + protectedGroup.setLogGroupName("x::victim"); + protectedGroup.setRetentionInDays(7); + groups.put("r::x::victim", protectedGroup); + assertNotNull(groups.get("r::x::victim").orElse(null)); + assertAll("reject mismatched stored identity and preserve group", + () -> assertThrows(AwsException.class, () -> { + switch (action) { + case "DeleteLogGroup" -> service.deleteLogGroup("victim", "r::x"); + case "PutRetentionPolicy" -> service.putRetentionPolicy("victim", 14, "r::x"); + case "DeleteRetentionPolicy" -> service.deleteRetentionPolicy("victim", "r::x"); + default -> throw new AssertionError(action); + } + }), + () -> assertEquals(protectedGroup, groups.get("r::x::victim").orElse(null)), + () -> assertEquals(7, protectedGroup.getRetentionInDays())); + } + + @Test + void deletingGroupRetainsHistoricalPrefixChildResources() { + service.createLogGroup("g", null, null, "us-east-1"); + LogGroup historical = new LogGroup(); + historical.setLogGroupName("g::child"); + groups.put("us-east-1::g::child", historical); + for (String group : new String[]{"g", "g::child"}) { + LogStream stream = new LogStream(); + stream.setLogGroupName(group); + stream.setLogStreamName("s"); + streams.put("us-east-1::" + group + "::s", stream); + MetricFilter metric = new MetricFilter(); + metric.setLogGroupName(group); + metric.setFilterName("m"); + metrics.put("us-east-1::" + group + "::m", metric); + SubscriptionFilter subscription = new SubscriptionFilter(); + subscription.setLogGroupName(group); + subscription.setFilterName("f"); + subscriptions.put("us-east-1::" + group + "::filter::f", subscription); + } + service.deleteLogGroup("g", "us-east-1"); + assertAll("remove owned resources but retain historical child", + () -> assertNull(groups.get("us-east-1::g").orElse(null)), + () -> assertNull(streams.get("us-east-1::g::s").orElse(null)), + () -> assertNull(metrics.get("us-east-1::g::m").orElse(null)), + () -> assertNull(subscriptions.get("us-east-1::g::filter::f").orElse(null)), + () -> assertEquals(historical, groups.get("us-east-1::g::child").orElse(null)), + () -> assertNotNull(streams.get("us-east-1::g::child::s").orElse(null)), + () -> assertNotNull(metrics.get("us-east-1::g::child::m").orElse(null)), + () -> assertNotNull(subscriptions.get("us-east-1::g::child::filter::f").orElse(null))); + } + + @ParameterizedTest + @ValueSource(strings = {"::g::x", "::g::filter::x"}) + void deletingGroupRetainsSameNamedGroupInAliasingRegion(String regionSuffix) { + String region = "us-east-1"; + String otherRegion = region + regionSuffix; + for (String ownerRegion : new String[]{region, otherRegion}) { + service.createLogGroup("g", null, null, ownerRegion); + LogStream stream = new LogStream(); + stream.setLogGroupName("g"); + stream.setLogStreamName("s"); + streams.put(ownerRegion + "::g::s", stream); + MetricFilter metric = new MetricFilter(); + metric.setLogGroupName("g"); + metric.setFilterName("m"); + metrics.put(ownerRegion + "::g::m", metric); + SubscriptionFilter subscription = new SubscriptionFilter(); + subscription.setLogGroupName("g"); + subscription.setFilterName("f"); + subscriptions.put(ownerRegion + "::g::filter::f", subscription); + } + service.deleteLogGroup("g", region); + assertAll("cleanup keeps the same named group's other region", + () -> assertNull(groups.get(region + "::g").orElse(null)), + () -> assertNull(streams.get(region + "::g::s").orElse(null)), + () -> assertNull(metrics.get(region + "::g::m").orElse(null)), + () -> assertNull(subscriptions.get(region + "::g::filter::f").orElse(null)), + () -> assertNotNull(groups.get(otherRegion + "::g").orElse(null)), + () -> assertNotNull(streams.get(otherRegion + "::g::s").orElse(null)), + () -> assertNotNull(metrics.get(otherRegion + "::g::m").orElse(null)), + () -> assertNotNull(subscriptions.get(otherRegion + "::g::filter::f").orElse(null))); + } + +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LogGroupArnPolicyCompatibilityTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LogGroupArnPolicyCompatibilityTest.java new file mode 100644 index 0000000000..b6e1ddaf97 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogGroupArnPolicyCompatibilityTest.java @@ -0,0 +1,180 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.iam.model.CallerContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.Map; + +import static io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LogGroupArnPolicyCompatibilityTest { + + private static final String GROUP = "arn:aws:logs:us-east-1:111111111111:log-group:/app/selected"; + private static final String OTHER = "arn:aws:logs:us-east-1:111111111111:log-group:/app/other"; + private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper()); + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy", "TagLogGroup"}) + void documentedGroupArnsAndLegacySuffixesSelectTheSameGroup(String operation) { + String action = "logs:" + operation; + for (String location : List.of("aws:logs:us-east-1", "aws-cn:logs:cn-north-1", "aws-us-gov:logs:us-gov-west-1")) { + String selected = "arn:" + location + ":111111111111:log-group:/app/selected"; + for (String policySuffix : List.of("", ":*")) { + String policy = document(statement("Allow", action, "Resource", selected + policySuffix)); + for (String requestSuffix : List.of("", ":*")) { + assertEquals(Decision.ALLOW, decide(policy, action, selected + requestSuffix)); + assertEquals(Decision.DENY, decide(policy, action, + selected.replace("/selected", "/other") + requestSuffix)); + assertEquals(Decision.DENY, decide(policy, action, + selected.replace("111111111111", "222222222222") + requestSuffix)); + } + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy", "TagLogGroup"}) + void explicitDenyWinsEvenWhenItsArnUsesTheOtherForm(String operation) { + String action = "logs:" + operation; + for (String denySuffix : List.of("", ":*")) { + String allowSuffix = denySuffix.isEmpty() ? ":*" : ""; + String policy = document(statement("Allow", action, "Resource", GROUP + allowSuffix), + statement("Deny", action, "Resource", GROUP + denySuffix)); + for (String requestSuffix : List.of("", ":*")) { + assertEquals(Decision.DENY, decide(policy, action, GROUP + requestSuffix)); + } + String control = document(statement("Allow", action, "Resource", "*"), + statement("Deny", action, "Resource", GROUP + denySuffix)); + assertEquals(Decision.ALLOW, decide(control, action, OTHER)); + } + } + + @Test + void notResourceExcludesTheGroupInEitherForm() { + String action = "logs:DeleteLogGroup"; + for (String excludedSuffix : List.of("", ":*")) { + String exclude = statement("Deny", action, "NotResource", GROUP + excludedSuffix); + String policy = document(statement("Allow", action, "Resource", "*"), exclude); + assertEquals(Decision.DENY, decide(policy, action, OTHER)); + assertEquals(Decision.ALLOW, decide(policy, action, GROUP)); + assertEquals(Decision.ALLOW, decide(policy, action, GROUP + ":*")); + String allowOutside = document(statement("Allow", action, "NotResource", GROUP + excludedSuffix)); + assertEquals(Decision.ALLOW, decide(allowOutside, action, OTHER)); + assertEquals(Decision.DENY, decide(allowOutside, action, GROUP)); + assertEquals(Decision.DENY, decide(allowOutside, action, GROUP + ":*")); + } + } + + @Test + void variablesResolveBeforeGroupMatchingAndMissingVariablesGrantNothing() { + String action = "logs:PutRetentionPolicy"; + String pattern = GROUP.replace("selected", "${aws:username}"); + Map> context = Map.of("aws:username", List.of("selected")); + String allow = document(statement("Allow", action, "Resource", pattern)); + CallerContext caller = CallerContext.of(List.of(allow)); + assertEquals(Decision.ALLOW, evaluator.evaluate(caller, null, action, GROUP + ":*", context)); + assertEquals(Decision.DENY, evaluator.evaluate(caller, null, action, GROUP + ":*", Map.of())); + assertEquals(Decision.DENY, evaluator.evaluate(caller, null, action, OTHER, context)); + String deny = document(statement("Allow", action, "Resource", "*"), + statement("Deny", action, "Resource", pattern)); + assertEquals(Decision.DENY, evaluator.evaluate(CallerContext.of(List.of(deny)), null, + action, GROUP + ":*", context)); + assertEquals(Decision.ALLOW, evaluator.evaluate(CallerContext.of(List.of(deny)), null, + action, GROUP + ":*", Map.of())); + String legacy = allow.replace("2012-10-17", "2008-10-17"); + assertEquals(Decision.DENY, evaluator.evaluate(CallerContext.of(List.of(legacy)), null, + action, GROUP + ":*", context)); + } + + @ParameterizedTest + @ValueSource(strings = {"session", "boundary", "scp"}) + void callerCeilingsMustAllowAndMustNotDenyEitherForm(String ceiling) { + String action = "logs:CreateLogGroup"; + String identity = document(statement("Allow", action, "Resource", GROUP + ":*")); + String grant = document(statement("Allow", action, "Resource", GROUP)); + String missingGrant = document(statement("Allow", action, "Resource", OTHER)); + String denial = document(statement("Allow", action, "Resource", "*"), + statement("Deny", action, "Resource", GROUP)); + assertEquals(Decision.ALLOW, evaluator.evaluate(caller(ceiling, identity, grant), null, + action, GROUP + ":*", Map.of())); + assertEquals(Decision.DENY, evaluator.evaluate(caller(ceiling, identity, missingGrant), null, + action, GROUP + ":*", Map.of())); + assertEquals(Decision.DENY, evaluator.evaluate(caller(ceiling, identity, denial), null, + action, GROUP + ":*", Map.of())); + String reverseIdentity = document(statement("Allow", action, "Resource", GROUP)); + String reverseDeny = document(statement("Allow", action, "Resource", "*"), + statement("Deny", action, "Resource", GROUP + ":*")); + assertEquals(Decision.DENY, evaluator.evaluate(caller(ceiling, reverseIdentity, reverseDeny), null, + action, GROUP, Map.of())); + } + + @Test + void resourcePolicyGrantAndDenyUseTheSameGroupIdentity() { + String action = "logs:DeleteLogGroup"; + String userArn = "arn:aws:iam::111111111111:user/alice"; + CallerContext caller = CallerContext.of(List.of()).withPrincipalArn(userArn); + String grant = document(resourceStatement("Allow", action, GROUP, userArn)); + assertEquals(Decision.ALLOW, evaluator.evaluate(caller, List.of(grant), action, GROUP + ":*", Map.of())); + String deny = document(resourceStatement("Deny", action, GROUP + ":*", userArn)); + CallerContext allowed = CallerContext.of(List.of(document(statement("Allow", action, "Resource", GROUP)))) + .withPrincipalArn(userArn); + assertEquals(Decision.DENY, evaluator.evaluate(allowed, List.of(deny), action, GROUP, Map.of())); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream", "TagResource", "UntagResource", "ListTagsForResource"}) + void otherLogsActionsDoNotAcquireGroupArnAliases(String operation) { + String action = "logs:" + operation; + String policy = document(statement("Allow", action, "Resource", GROUP)); + assertEquals(Decision.ALLOW, decide(policy, action, GROUP)); + assertEquals(Decision.DENY, decide(policy, action, GROUP + ":*")); + assertEquals(Decision.DENY, decide(policy, action, GROUP + ":log-stream:s")); + } + + @Test + void otherServicesCaseAndMalformedGroupIdentifiersDoNotBecomeAliases() { + String action = "logs:DeleteLogGroup"; + for (String resource : List.of(GROUP.replace(":logs:", ":s3:"), GROUP + ":child", + GROUP.substring(0, GROUP.lastIndexOf(':') + 1), "log-group:/app/selected")) { + String policy = document(statement("Allow", action, "Resource", resource)); + assertEquals(Decision.DENY, decide(policy, action, resource + ":*"), resource); + } + String policy = document(statement("Allow", action, "Resource", GROUP)); + assertEquals(Decision.DENY, decide(policy, action, GROUP.replace("/selected", "/Selected") + ":*")); + assertEquals(Decision.DENY, decide(policy, "s3:DeleteBucket", GROUP + ":*")); + String streamPattern = document(statement("Allow", action, "Resource", GROUP + ":log-stream:*")); + assertEquals(Decision.DENY, decide(streamPattern, action, GROUP + ":*")); + } + + private Decision decide(String policy, String action, String resource) { + return evaluator.evaluate(CallerContext.of(List.of(policy)), null, action, resource, Map.of()); + } + + private static CallerContext caller(String ceiling, String identity, String policy) { + return switch (ceiling) { + case "session" -> new CallerContext(List.of(identity), policy, null, null); + case "boundary" -> new CallerContext(List.of(identity), null, policy, null); + case "scp" -> new CallerContext(List.of(identity), null, null, List.of(List.of(policy))); + default -> throw new IllegalArgumentException(ceiling); + }; + } + + private static String document(String... statements) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[" + String.join(",", statements) + "]}"; + } + + private static String statement(String effect, String action, String resourceElement, String resource) { + return "{\"Effect\":\"" + effect + "\",\"Action\":\"" + action + "\",\"" + resourceElement + + "\":\"" + resource + "\"}"; + } + + private static String resourceStatement(String effect, String action, String resource, String principal) { + return "{\"Effect\":\"" + effect + "\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + + "\",\"Principal\":{\"AWS\":\"" + principal + "\"}}"; + } +} 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 index 9a4f0c2093..e9ca914c36 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/LogsArnTagAuthorizationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsArnTagAuthorizationIntegrationTest.java @@ -1,5 +1,7 @@ package io.github.hectorvent.floci.services.iam; +import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import io.github.hectorvent.floci.testing.IamEnforcementProfile; import io.github.hectorvent.floci.testing.LogsAuthorizationFixtures; import io.github.hectorvent.floci.testing.PartitionCleanup; @@ -8,6 +10,7 @@ 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 jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -40,6 +43,9 @@ class LogsArnTagAuthorizationIntegrationTest { @TestHTTPResource URI endpoint; + @Inject + CloudWatchLogsService logsService; + @BeforeAll static void configureContentTypes() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -111,7 +117,7 @@ class LogsArnTagAuthorizationIntegrationTest { @ParameterizedTest @ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"}) void incompleteArnPrefixRemainsALiteralLegacyName(String action) { - String name = groupNamed("arn:archive-" + UUID.randomUUID(), Map.of("team", "blue")); + String name = historicalGroupNamed("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)); @@ -140,7 +146,7 @@ class LogsArnTagAuthorizationIntegrationTest { 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")); + String literal = historicalGroupNamed(input, Map.of("team", "blue")); assertSuccess(invoke(caller, action, input), action); assertTags(literal, expectedTags(action)); assertTags(local, Map.of("team", "blue")); @@ -219,6 +225,12 @@ class LogsArnTagAuthorizationIntegrationTest { return name; } + private String historicalGroupNamed(String name, Map tags) { + cleanup.register(() -> RequestScopes.runAs(ACCOUNT, REGION, () -> logsService.deleteLogGroup(name, REGION))); + logsService.createLogGroupForAccount(ACCOUNT, name, null, tags, REGION); + return name; + } + private String user(String statements) { return LogsAuthorizationFixtures.user(cleanup, endpoint.getPort(), ACCOUNT, "logs-arn-tag-", "arn-tags", statements); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LogsGroupAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LogsGroupAuthorizationIntegrationTest.java new file mode 100644 index 0000000000..3d2d3d1157 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsGroupAuthorizationIntegrationTest.java @@ -0,0 +1,363 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.RequestScopes; +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; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +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.LinkedHashMap; +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; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class LogsGroupAuthorizationIntegrationTest { + + private static final String ACCOUNT = "111111111111"; + private static final String REGION = "us-east-1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @TestHTTPResource + URI endpoint; + + @Inject + CloudWatchLogsService logsService; + + @BeforeAll + static void configureContentTypes() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void exactGroupPermissionAllowsOnlyTheSelectedGroup(String action) { + String selected = group(action); + String other = group(action); + String caller = user(policy("Allow", action, arn(selected))); + Response denied = operation(caller, action, other).extract().response(); + assertAll("unrelated group denied without mutation", + () -> denied.then().statusCode(400).body(containsString("AccessDeniedException")), + () -> assertUnchanged(action, other)); + operation(caller, action, selected).statusCode(200); + assertChanged(action, selected); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void bareGroupPermissionAllowsOnlyTheSelectedGroup(String action) { + String selected = group(action); + String other = group(action); + String caller = user(policy("Allow", action, bareArn(selected))); + Response denied = operation(caller, action, other).extract().response(); + assertAll("bare group grant denies unrelated state changes", + () -> denied.then().statusCode(400).body(containsString("AccessDeniedException")), + () -> assertUnchanged(action, other)); + operation(caller, action, selected).statusCode(200); + assertChanged(action, selected); + } + + @ParameterizedTest + @CsvSource({"CreateLogGroup,false", "CreateLogGroup,true", "DeleteLogGroup,false", "DeleteLogGroup,true", + "PutRetentionPolicy,false", "PutRetentionPolicy,true", "DeleteRetentionPolicy,false", + "DeleteRetentionPolicy,true"}) + void oppositeGroupArnFormDenyOverridesExactAllow(String action, boolean bareAllow) { + String selected = group(action); + String other = group(action); + String selectedAllow = bareAllow ? bareArn(selected) : arn(selected); + String otherAllow = bareAllow ? bareArn(other) : arn(other); + String selectedDeny = bareAllow ? arn(selected) : bareArn(selected); + String caller = user(policy("Allow", action, selectedAllow) + "," + + policy("Allow", action, otherAllow) + "," + policy("Deny", action, selectedDeny)); + Response denied = operation(caller, action, selected).extract().response(); + assertAll("equivalent group ARN deny preserves the selected group", + () -> denied.then().statusCode(400).body(containsString("AccessDeniedException")), + () -> assertUnchanged(action, selected)); + operation(caller, action, other).statusCode(200); + assertChanged(action, other); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void exactGroupDenyOverridesWildcardAllow(String action) { + String selected = group(action); + String other = group(action); + String caller = user(policy("Allow", action, "*") + "," + policy("Deny", action, arn(selected))); + Response denied = operation(caller, action, selected).extract().response(); + assertAll("selected group denied without mutation", + () -> denied.then().statusCode(400).body(containsString("AccessDeniedException")), + () -> assertUnchanged(action, selected)); + operation(caller, action, other).statusCode(200); + assertChanged(action, other); + } + + @ParameterizedTest + @ValueSource(strings = {"DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void resourceTagDenyProtectsExistingGroup(String action) { + String selected = group(action); + String other = group(action); + call(endpoint.getPort(), ACCOUNT, "TagLogGroup", + Map.of("logGroupName", selected, "tags", Map.of("protected", "true"))).statusCode(200); + String condition = ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/protected\":\"true\"}}"; + String caller = user(policy("Allow", action, "*") + "," + + policy("Deny", action, "*", condition)); + Response denied = operation(caller, action, selected).extract().response(); + assertAll("group tag deny preserves state", + () -> denied.then().statusCode(400).body(containsString("AccessDeniedException")), + () -> assertUnchanged(action, selected)); + operation(caller, action, other).statusCode(200); + assertChanged(action, other); + } + + @Test + void createRequestTagsUseHandlerValues() { + String selected = group("CreateLogGroup"); + String other = group("CreateLogGroup"); + String condition = ",\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"42\"}}"; + String caller = user(policy("Allow", "CreateLogGroup", "*", condition) + + "," + policy("Allow", "TagResource", "*")); + call(endpoint.getPort(), caller, "CreateLogGroup", + Map.of("logGroupName", other, "tags", Map.of("team", "red"))) + .statusCode(400).body(containsString("AccessDeniedException")); + assertNull(find(other)); + call(endpoint.getPort(), caller, "CreateLogGroup", + Map.of("logGroupName", selected, "tags", Map.of("team", 42))).statusCode(200); + call(endpoint.getPort(), ACCOUNT, "ListTagsLogGroup", Map.of("logGroupName", selected)) + .statusCode(200).body("tags.team", equalTo("42")); + } + + @ParameterizedTest + @ValueSource(strings = {"none", "TagResource", "TagLogGroup"}) + void taggedCreateRequiresEitherTagPermission(String taggingAction) { + String selected = group("CreateLogGroup"); + String untagged = group("CreateLogGroup"); + String statements = policy("Allow", "CreateLogGroup", "*"); + if (!taggingAction.equals("none")) { + statements += "," + policy("Allow", taggingAction, "*"); + } + String caller = user(statements); + call(endpoint.getPort(), caller, "CreateLogGroup", Map.of("logGroupName", untagged)).statusCode(200); + assertNotNull(find(untagged)); + Response response = call(endpoint.getPort(), caller, "CreateLogGroup", + Map.of("logGroupName", selected, "tags", Map.of("team", "blue"))).extract().response(); + if (taggingAction.equals("none")) { + assertAll("tagged creation requires an alternative permission", + () -> response.then().statusCode(400).body(containsString("AccessDeniedException")), + () -> assertNull(find(selected))); + } else { + response.then().statusCode(200); + call(endpoint.getPort(), ACCOUNT, "ListTagsLogGroup", Map.of("logGroupName", selected)) + .statusCode(200).body("tags.team", equalTo("blue")); + } + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogGroup", "DeleteLogGroup", "PutRetentionPolicy", "DeleteRetentionPolicy"}) + void ambiguousGroupNamesCannotBecomeAuthorizedAliases(String action) { + String name = "logs-group-invalid-" + UUID.randomUUID() + ":child"; + if (!action.equals("CreateLogGroup")) { + cleanup.register(() -> RequestScopes.runAs(ACCOUNT, REGION, () -> logsService.deleteLogGroup(name, REGION))); + logsService.createLogGroupForAccount(ACCOUNT, name, 7, Map.of(), REGION); + } + String caller = user(policy("Allow", action, "*")); + operation(caller, action, name).statusCode(400).body(containsString("InvalidParameterException")); + assertUnchanged(action, name); + } + + @ParameterizedTest + @CsvSource({"TagResource,false,false", "TagResource,true,false", "TagLogGroup,false,false", + "TagLogGroup,true,false", "TagLogGroup,false,true", "TagLogGroup,true,true"}) + void createTagAlternativesUseTheirOwnArnAndConditions(String taggingAction, boolean primaryBare, + boolean taggingBare) { + String selected = group("CreateLogGroup"); + String otherAction = taggingAction.equals("TagResource") ? "TagLogGroup" : "TagResource"; + String resource = taggingAction.equals("TagResource") || taggingBare ? bareArn(selected) : arn(selected); + String condition = ",\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\"}," + + "\"ForAllValues:StringEquals\":{\"aws:TagKeys\":[\"team\"]}}"; + String caller = user(policy("Allow", "CreateLogGroup", primaryBare ? bareArn(selected) : arn(selected)) + "," + + policy("Allow", taggingAction, resource, condition) + "," + policy("Deny", otherAction, "*")); + for (Map rejected : List.of(Map.of("team", "red"), Map.of("team", "blue", "extra", "value"))) { + Response denied = call(endpoint.getPort(), caller, "CreateLogGroup", + Map.of("logGroupName", selected, "tags", rejected)).extract().response(); + assertAll("secondary permission conditions must reject before creating", + () -> denied.then().statusCode(400).body(containsString("AccessDeniedException")), + () -> assertNull(find(selected))); + } + call(endpoint.getPort(), caller, "CreateLogGroup", + Map.of("logGroupName", selected, "tags", Map.of("team", "blue"))).statusCode(200); + call(endpoint.getPort(), ACCOUNT, "ListTagsLogGroup", Map.of("logGroupName", selected)) + .statusCode(200).body("tags.team", equalTo("blue")); + } + + @ParameterizedTest + @ValueSource(strings = {"array", "text", "number", "empty-object", "null"}) + void ignoredOrEmptyTagsDoNotRequireTaggingPermission(String kind) { + String selected = group("CreateLogGroup"); + String caller = user(policy("Allow", "CreateLogGroup", arn(selected))); + Object tags = switch (kind) { + case "array" -> List.of("team"); + case "text" -> "team"; + case "number" -> 42; + case "empty-object" -> Map.of(); + case "null" -> null; + default -> throw new AssertionError(kind); + }; + Map body = new LinkedHashMap<>(); + body.put("logGroupName", selected); + body.put("tags", tags); + call(endpoint.getPort(), caller, "CreateLogGroup", body).statusCode(200); + assertEquals(Map.of(), call(endpoint.getPort(), ACCOUNT, "ListTagsLogGroup", + Map.of("logGroupName", selected)).statusCode(200).extract().path("tags")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void taggedCreationRetainsAssumedRoleSessionCeilings(boolean taggingAllowed) { + String selected = group("CreateLogGroup"); + String untagged = group("CreateLogGroup"); + String role = "logs-group-session-" + UUID.randomUUID(); + int port = endpoint.getPort(); + String root = EnforcementFixtures.auth(ACCOUNT, "iam"); + cleanup.register(() -> EnforcementFixtures.removeRole(port, root, role)); + String roleArn = given().port(port).header("Authorization", root) + .formParam("Action", "CreateRole").formParam("RoleName", role) + .formParam("AssumeRolePolicyDocument", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"*"},"Action":"sts:AssumeRole"}]} + """).post("/").then().statusCode(200).extract().xmlPath() + .getString("CreateRoleResponse.CreateRoleResult.Role.Arn"); + String create = policy("Allow", "CreateLogGroup", "*"); + String tagging = policy("Allow", "TagResource", "*"); + given().port(port).header("Authorization", root).formParam("Action", "PutRolePolicy") + .formParam("RoleName", role).formParam("PolicyName", "groups") + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + create + "," + tagging + "]}") + .post("/").then().statusCode(200); + String sessionPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[" + + create + (taggingAllowed ? "," + tagging : "") + "]}"; + Response assumed = given().port(port).header("Authorization", EnforcementFixtures.auth(ACCOUNT, "sts")) + .formParam("Action", "AssumeRole").formParam("RoleArn", roleArn) + .formParam("RoleSessionName", "groups").formParam("Policy", sessionPolicy) + .post("/").then().statusCode(200).extract().response(); + String key = assumed.xmlPath().getString("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"); + String token = assumed.xmlPath().getString("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"); + sessionCreate(port, key, token, Map.of("logGroupName", untagged)).then().statusCode(200); + assertNotNull(find(untagged)); + Response response = sessionCreate(port, key, token, + Map.of("logGroupName", selected, "tags", Map.of("team", "blue"))); + assertAll("secondary permission must retain the issued session policy", + () -> response.then().statusCode(taggingAllowed ? 200 : 400), + () -> assertEquals(taggingAllowed, find(selected) != null), + () -> { + if (!taggingAllowed) { + response.then().body(containsString("AccessDeniedException")); + } + }); + } + + private static Response sessionCreate(int port, String key, String token, Map body) { + return given().port(port).contentType("application/x-amz-json-1.1") + .header("Authorization", EnforcementFixtures.auth(key, "logs")) + .header("X-Amz-Security-Token", token).header("X-Amz-Target", "Logs_20140328.CreateLogGroup") + .body(body).when().post("/"); + } + + private String group(String action) { + String name = "logs-group-auth-" + UUID.randomUUID(); + int port = endpoint.getPort(); + cleanup.register(() -> { + if (find(name) != null) { + call(port, ACCOUNT, "DeleteLogGroup", Map.of("logGroupName", name)).statusCode(200); + } + }); + if (!action.equals("CreateLogGroup")) { + call(port, ACCOUNT, "CreateLogGroup", Map.of("logGroupName", name)).statusCode(200); + call(port, ACCOUNT, "PutRetentionPolicy", Map.of("logGroupName", name, "retentionInDays", 7)) + .statusCode(200); + } + return name; + } + + private String user(String statements) { + return LogsAuthorizationFixtures.user(cleanup, endpoint.getPort(), ACCOUNT, "logs-group-auth-", + "groups", statements); + } + + private static String policy(String effect, String action, String resource) { + return policy(effect, action, resource, ""); + } + + private static String policy(String effect, String action, String resource, String condition) { + return "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + action + + "\",\"Resource\":\"" + resource + "\"" + condition + "}"; + } + + private static String bareArn(String group) { + return "arn:aws:logs:" + REGION + ":" + ACCOUNT + ":log-group:" + group; + } + + private static String arn(String group) { + return bareArn(group) + ":*"; + } + + private ValidatableResponse operation(String caller, String action, String group) { + Map body = action.equals("PutRetentionPolicy") + ? Map.of("logGroupName", group, "retentionInDays", 14) : Map.of("logGroupName", group); + return call(endpoint.getPort(), caller, action, body); + } + + private Map find(String group) { + List> groups = call(endpoint.getPort(), ACCOUNT, "DescribeLogGroups", + Map.of("logGroupNamePrefix", group)).statusCode(200).extract().path("logGroups"); + return groups.stream().filter(item -> group.equals(item.get("logGroupName"))).findFirst().orElse(null); + } + + private void assertUnchanged(String action, String group) { + if (action.equals("CreateLogGroup")) { + assertNull(find(group)); + } else { + Map stored = find(group); + assertNotNull(stored); + assertEquals(7, stored.get("retentionInDays")); + } + } + + private void assertChanged(String action, String group) { + if (action.equals("DeleteLogGroup")) { + assertNull(find(group)); + } else { + Map stored = find(group); + assertNotNull(stored); + assertEquals(action.equals("PutRetentionPolicy") ? 14 : null, stored.get("retentionInDays")); + } + } + + private static ValidatableResponse call(int port, String caller, String action, Map body) { + return LogsAuthorizationFixtures.call(port, caller, "20261016", REGION, action, body).then(); + } +} 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 9d75a9fe8d..2387a7076a 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 @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.iam; +import io.github.hectorvent.floci.core.common.RequestScopes; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import io.github.hectorvent.floci.testing.EnforcementFixtures; import io.github.hectorvent.floci.testing.IamEnforcementProfile; @@ -261,7 +262,7 @@ class LogsStreamAuthorizationIntegrationTest { String group = "logs-key-alias-" + UUID.randomUUID(); String protectedGroup = group + "::x"; createGroup(ACCOUNT, REGION, group, Map.of("team", "blue")); - createGroup(ACCOUNT, REGION, protectedGroup, Map.of("team", "red")); + seedHistoricalGroup(protectedGroup, Map.of("team", "red")); seedHistoricalStream(protectedGroup, "s"); assertPresent(protectedGroup, "s", true); assertEvent(protectedGroup, "s"); @@ -280,7 +281,7 @@ class LogsStreamAuthorizationIntegrationTest { String group = "logs-arn-alias-" + UUID.randomUUID(); String actualGroup = group + ":log-stream:x"; createGroup(ACCOUNT, REGION, group, Map.of()); - createGroup(ACCOUNT, REGION, actualGroup, Map.of()); + seedHistoricalGroup(actualGroup, Map.of()); boolean delete = action.equals("DeleteLogStream"); if (delete) { seedHistoricalStream(actualGroup, "s"); @@ -362,6 +363,11 @@ class LogsStreamAuthorizationIntegrationTest { } /** Existing service storage APIs seed historical invalid names without bypassing the HTTP request under test. */ + private void seedHistoricalGroup(String group, Map tags) { + cleanup.register(() -> RequestScopes.runAs(ACCOUNT, REGION, () -> logsService.deleteLogGroup(group, REGION))); + logsService.createLogGroupForAccount(ACCOUNT, group, null, tags, REGION); + } + private void seedHistoricalStream(String group, String stream) { seedHistoricalStream(group, stream, "retained"); } 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 8acd9aa7f7..2e45242f73 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,5 +1,6 @@ package io.github.hectorvent.floci.services.iam; +import io.github.hectorvent.floci.core.common.RequestScopes; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import io.github.hectorvent.floci.testing.LogsAuthorizationFixtures; import io.github.hectorvent.floci.testing.PartitionCleanup; @@ -93,8 +94,8 @@ class LogsUnknownRegionAuthorizationIntegrationTest { String historicalStream = streamAlias ? "x::" + group + "::s" : "s"; String aliasRegion = streamAlias ? REGION + "::" + group + "::x" : REGION + "::x"; String validUnknownRegion = "custom-region-1"; - cleanup.register(() -> call(port, ACCOUNT, REGION, "DeleteLogGroup", Map.of("logGroupName", historical)) - .then().statusCode(200)); + cleanup.register(() -> RequestScopes.runAs(ACCOUNT, REGION, + () -> logsService.deleteLogGroup(historical, REGION))); cleanup.register(() -> call(port, ACCOUNT, validUnknownRegion, "DeleteLogGroup", Map.of("logGroupName", group)) .then().statusCode(200)); logsService.createLogGroupForAccount(ACCOUNT, historical, null, Map.of("team", "blue"), REGION); @@ -178,6 +179,43 @@ class LogsUnknownRegionAuthorizationIntegrationTest { }); } + @ParameterizedTest + @CsvSource({"TagResource,Allow", "TagLogGroup,Allow", "TagResource,Deny", "TagLogGroup,Deny"}) + void taggedGroupCreationUsesCanonicalOwnerForBothAlternatives(String taggingAction, String effect) { + int port = endpoint.getPort(); + String region = "custom-222222222222"; + String group = "logs-create-owner-" + UUID.randomUUID(); + cleanup.register(() -> { + List> groups = call(port, ACCOUNT, region, "DescribeLogGroups", + Map.of("logGroupNamePrefix", group)).then().statusCode(200).extract().path("logGroups"); + if (groups.stream().anyMatch(item -> group.equals(item.get("logGroupName")))) { + call(port, ACCOUNT, region, "DeleteLogGroup", Map.of("logGroupName", group)).then().statusCode(200); + } + }); + String statements = "{\"Effect\":\"Allow\",\"Action\":\"logs:CreateLogGroup\",\"Resource\":\"*\"},"; + if (effect.equals("Deny")) { + statements += "{\"Effect\":\"Allow\",\"Action\":\"logs:" + taggingAction + "\",\"Resource\":\"*\"},"; + } + statements += "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + taggingAction + + "\",\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"aws:ResourceAccount\":\"" + + ACCOUNT + "\"}}}"; + String caller = LogsAuthorizationFixtures.user(cleanup, port, ACCOUNT, "logs-create-owner-", + "tagging-owner", statements); + Response response = call(port, caller, region, "CreateLogGroup", + Map.of("logGroupName", group, "tags", Map.of("team", "blue"))); + List> groups = call(port, ACCOUNT, region, "DescribeLogGroups", + Map.of("logGroupNamePrefix", group)).then().statusCode(200).extract().path("logGroups"); + boolean allowed = effect.equals("Allow"); + assertAll("both tagging alternatives use the actual storage owner", + () -> response.then().statusCode(allowed ? 200 : 400), + () -> assertEquals(allowed, groups.stream().anyMatch(item -> group.equals(item.get("logGroupName")))), + () -> { + if (!allowed) { + response.then().body(containsString("AccessDeniedException")); + } + }); + } + private static void assertPresent(int port, String region, String group, boolean expected) { assertPresent(port, region, group, "s", expected); } 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 423d3b2328..386cca463a 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 @@ -655,7 +655,21 @@ class ResourceArnBuilderTest { when(ctx.getHeaderString("X-Amz-Target")).thenReturn("Logs_20140328.DeleteLogGroup"); assertEquals(List.of("arn:" + AwsRegions.partitionFor(region) + ":logs:" + region + ":123456789012:log-group: /group :log-stream:42"), - builder.buildLogStreamResources(action, ctx, region, "123456789012", AwsRegions.partitionFor(region))); + builder.buildLogResources(action, ctx, region, "123456789012", AwsRegions.partitionFor(region))); + } + } + } + + @Test + void logGroupTargetsUseTheServingActionAndRequestPartition() { + for (String action : List.of("logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy", + "logs:DeleteRetentionPolicy")) { + for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) { + setJsonBody("{\"logGroupName\":42}"); + when(ctx.getHeaderString("X-Amz-Target")).thenReturn("Logs_20140328.DeleteLogStream"); + assertEquals(List.of("arn:" + AwsRegions.partitionFor(region) + + ":logs:" + region + ":123456789012:log-group:42:*"), + builder.buildLogResources(action, ctx, region, "123456789012", AwsRegions.partitionFor(region))); } } } @@ -668,17 +682,16 @@ class ResourceArnBuilderTest { 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)); + assertEquals(List.of(arn), builder.buildLogResources(action, ctx, region, ACCOUNT, partition)); } } } @Test void excludedLogsActionsKeepWildcardResources() { - for (String action : List.of("logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy", - "logs:DeleteRetentionPolicy", "logs:PutLogEvents")) { + for (String action : List.of("logs:PutLogEvents")) { setJsonBody("{\"logGroupName\":\"group\",\"logStreamName\":\"stream\"}"); - assertEquals(List.of("*"), builder.buildLogStreamResources(action, ctx, "us-east-1", ACCOUNT, "aws")); + assertEquals(List.of("*"), builder.buildLogResources(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 index 8a72820a1c..14d074fe45 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/LogsAuthorizationFixtures.java +++ b/src/test/java/io/github/hectorvent/floci/testing/LogsAuthorizationFixtures.java @@ -27,7 +27,11 @@ public final class LogsAuthorizationFixtures { } public static Response call(int port, String caller, String region, String action, Map body) { - String authorization = "AWS4-HMAC-SHA256 Credential=" + caller + "/20261015/" + region + return call(port, caller, "20261015", region, action, body); + } + + public static Response call(int port, String caller, String date, String region, String action, Map body) { + String authorization = "AWS4-HMAC-SHA256 Credential=" + caller + "/" + date + "/" + 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)