From dbe7fdb92eead73e315c836ddcda97b182f05604 Mon Sep 17 00:00:00 2001 From: David Phillips Date: Thu, 15 Oct 2026 11:42:14 +0800 Subject: [PATCH] fix(logs): enforce stream resource permissions (#5694) * fix(logs): enforce stream resource permissions * fix(logs): retain request partitions for stream permissions --- ...CloudWatchLogsStreamAuthorizationTest.java | 199 ++++++++ docs/services/iam.md | 10 + .../core/common/AwsJson11Controller.java | 2 +- .../common/IamConditionContextResolver.java | 34 ++ .../core/common/IamEnforcementFilter.java | 8 +- .../logs/CloudWatchLogsHandler.java | 15 + .../logs/CloudWatchLogsService.java | 8 +- .../services/iam/ResourceArnBuilder.java | 17 + .../IamConditionContextResolverTest.java | 50 +- .../dynamodb/backend/DynamoDbFacadeTest.java | 2 +- ...ownRegionAuthorizationIntegrationTest.java | 13 + ...ownRegionAuthorizationIntegrationTest.java | 134 ++++++ ...ogsStreamAuthorizationIntegrationTest.java | 453 ++++++++++++++++++ ...ownRegionAuthorizationIntegrationTest.java | 179 +++++++ .../services/iam/ResourceArnBuilderTest.java | 23 + 15 files changed, 1142 insertions(+), 5 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsStreamAuthorizationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/LogsGovUnknownRegionAuthorizationIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/LogsStreamAuthorizationIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/LogsUnknownRegionAuthorizationIntegrationTest.java 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 new file mode 100644 index 0000000000..b6e3f95829 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsStreamAuthorizationTest.java @@ -0,0 +1,199 @@ +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 { + + 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(); + } + }); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @DisplayName("exact stream grants do not allow another group's stream") + void exactStreamPermission(boolean delete) { + prepare(delete); + String action = delete ? "DeleteLogStream" : "CreateLogStream"; + String arn = TestFixtures.arn("logs", "000000000000", "log-group:" + protectedGroup + ":log-stream:selected"); + policy("{\"Effect\":\"Allow\",\"Action\":\"logs:" + action + "\",\"Resource\":\"" + arn + "\"}"); + assertThatThrownBy(() -> invoke(delete, otherGroup)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertPresent(otherGroup, delete); + invoke(delete, protectedGroup); + assertPresent(protectedGroup, !delete); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @DisplayName("a parent-group tag deny overrides wildcard stream permission") + void parentGroupTagDeny(boolean delete) { + prepare(delete); + String action = delete ? "DeleteLogStream" : "CreateLogStream"; + policy("{\"Effect\":\"Allow\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\"}," + + "{\"Effect\":\"Deny\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/protected\":\"true\"}}}"); + assertThatThrownBy(() -> invoke(delete, protectedGroup)) + .isInstanceOfSatisfying(CloudWatchLogsException.class, this::assertDenied); + assertPresent(protectedGroup, delete); + invoke(delete, otherGroup); + assertPresent(otherGroup, !delete); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @DisplayName("stream name constraints reject aliases and preserve valid Unicode names") + void nameConstraintsPreventAmbiguousTargets(boolean delete) { + prepare(delete); + String action = delete ? "DeleteLogStream" : "CreateLogStream"; + policy("{\"Effect\":\"Allow\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\"}"); + for (String invalid : new String[]{"", "bad::stream", "bad*stream", "s".repeat(513)}) { + assertThatThrownBy(() -> invoke(delete, protectedGroup, invalid)) + .isInstanceOfSatisfying(InvalidParameterException.class, error -> + assertThat(error.statusCode()).isEqualTo(400)); + } + assertPresent(protectedGroup, delete); + String maximum = "🚀".repeat(512); + if (delete) { + root.createLogStream(r -> r.logGroupName(protectedGroup).logStreamName(maximum)); + } + invoke(delete, protectedGroup, maximum); + assertThat(root.describeLogStreams(r -> r.logGroupName(protectedGroup)).logStreams().stream() + .anyMatch(stream -> maximum.equals(stream.logStreamName()))).isEqualTo(!delete); + } + + private void prepare(boolean delete) { + if (delete) { + root.createLogStream(r -> r.logGroupName(protectedGroup).logStreamName("selected")); + root.createLogStream(r -> r.logGroupName(otherGroup).logStreamName("selected")); + } + } + + 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"); + } + + private void invoke(boolean delete, String group, String stream) { + if (delete) { + caller.deleteLogStream(r -> r.logGroupName(group).logStreamName(stream)); + } else { + caller.createLogStream(r -> r.logGroupName(group).logStreamName(stream)); + } + } + + private void assertPresent(String group, boolean expected) { + 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 a59ef0f531..4ed61be371 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1194,6 +1194,15 @@ These identities always bypass enforcement (backward-compatible defaults): | No `Authorization` header | **Rejected** for a JSON, CBOR or Query management call, unless AWS serves the operation without credentials. Allowed for a REST request such as a health check (see [Unsigned requests](#unsigned-requests)) | | Unresolvable IAM action for the request | Allowed — unknown mappings are permissive | +**CloudWatch Logs streams.** `logs:CreateLogStream` and `logs:DeleteLogStream` evaluate the +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. +These checks also apply to deletion: legacy streams with names containing `:` or `*` cannot be +deleted through `DeleteLogStream`. Existing stored names are not automatically migrated. + **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 @@ -1372,6 +1381,7 @@ floci populates: `ResourceId.N` or `InstanceId.N`), and for `s3:GetBucketTagging`, `s3:DeleteBucketTagging` and `s3:DeleteBucket` (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. - `s3:ExistingObjectTag/`: the tags already on the target object version, for `s3:GetObject`, `s3:GetObjectTagging`, `s3:GetObjectAcl`, `s3:PutObjectAcl`, `s3:DeleteObjectTagging` and `s3:PutObjectTagging`. A `versionId` in the request selects the diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index d27dc680ec..859dc6d866 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -314,7 +314,7 @@ public class AwsJson11Controller { case "elasticmapreduce" -> emrHandler.handle(action, request, region); case "wafv2" -> wafV2Handler.handle(action, request, region); case "memorydb" -> memoryDbHandler.handle(action, request, region); - case "logs" -> cloudWatchLogsHandler.handle(action, request, region); + case "logs" -> cloudWatchLogsHandler.handle(action, request, regionResolver.getRegion()); case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region, IamEnforcementFilter.requestAuthorization( httpHeaders.getHeaderString("Authorization"), uriInfo.getQueryParameters())); 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 cbdcdd4d9e..97fb5d9261 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 @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common; 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.dynamodb.DynamoDbConditionKeys; import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbTableNames; @@ -70,6 +71,7 @@ public class IamConditionContextResolver { private final Instance dynamoDbFacade; private final Instance ec2Service; private final Instance s3Service; + private final Instance logsService; private final RequestContext requestContext; private final EmulatorConfig config; @@ -77,11 +79,13 @@ public class IamConditionContextResolver { public IamConditionContextResolver(Instance dynamoDbFacade, Instance ec2Service, Instance s3Service, + Instance logsService, RequestContext requestContext, EmulatorConfig config) { this.dynamoDbFacade = dynamoDbFacade; this.ec2Service = ec2Service; this.s3Service = s3Service; + this.logsService = logsService; this.requestContext = requestContext; this.config = config; } @@ -93,10 +97,40 @@ public class IamConditionContextResolver { case "ec2" -> ec2ConditionContext(action, ctx); case "dynamodb" -> dynamoDbConditionContext(action, ctx); case "iam" -> iamConditionContext(action, ctx); + case "logs" -> logStreamConditionContext(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) { + if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action))) { + return null; + } + JsonNode body = bufferedJsonBody(ctx); + if (body == null || !logsService.isResolvable()) { + return null; + } + String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion(); + Map tags; + try { + tags = logsService.get().listTagsLogGroup(body.path("logGroupName").asText(), 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; + } + if (tags == null || tags.isEmpty()) { + return null; + } + Map> conditions = new LinkedHashMap<>(); + tags.forEach((key, value) -> conditions.put(RESOURCE_TAG_PREFIX + key, + List.of(value == null ? "" : value))); + return conditions; + } + private static Map> iamConditionContext(String action, ContainerRequestContext ctx) { return switch (action) { case "iam:AttachRolePolicy", "iam:DetachRolePolicy", "iam:AttachUserPolicy", 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 e1711dc4a6..7edc6638a0 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 @@ -416,7 +416,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } List resources = resolveResourceArns(credentialScope, - arnBuilder.buildResources(credentialScope, ctx, region, accountId)); + "logs".equals(credentialScope) + ? arnBuilder.buildLogStreamResources(action, ctx, region, accountId, requestPartition()) + : arnBuilder.buildResources(credentialScope, ctx, region, accountId)); Optional presignedScope = iamService.presignedScope(akid); if (presignedScope.isPresent()) { @@ -750,6 +752,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter { for (Map> targetContext : targetContexts) { Map> effectiveContext = IamConditionContextResolver.withGlobalContext( targetContext, resource, region, accountId, resourceOwnerAccountId); + if ("logs".equals(credentialScope) + && ("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action))) { + effectiveContext.put("aws:ResourceAccount", List.of(accountId)); + } if ("dynamodb".equals(credentialScope)) { Map> batchContext = conditionContextResolver.dynamoDbBatchConditionContext(action, ctx, resource); 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 efe66ca3fe..a32f1d334d 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 @@ -22,10 +22,13 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.regex.Pattern; @ApplicationScoped public class CloudWatchLogsHandler { + private static final Pattern LOG_GROUP_NAME = Pattern.compile("[._/#A-Za-z0-9-]+"); + private final CloudWatchLogsService logsService; private final CloudWatchLogsCrossAccountService crossAccountService; private final CloudWatchLogsMetricFilterHandler metricFilterHandler; @@ -248,6 +251,7 @@ public class CloudWatchLogsHandler { private Response handleCreateLogStream(JsonNode request, String region) { String groupName = request.path("logGroupName").asText(); String streamName = request.path("logStreamName").asText(); + requireLogStreamNames(groupName, streamName); logsService.createLogStream(groupName, streamName, region); return Response.ok(objectMapper.createObjectNode()).build(); } @@ -255,10 +259,21 @@ public class CloudWatchLogsHandler { private Response handleDeleteLogStream(JsonNode request, String region) { String groupName = request.path("logGroupName").asText(); String streamName = request.path("logStreamName").asText(); + requireLogStreamNames(groupName, streamName); logsService.deleteLogStream(groupName, streamName, region); return Response.ok(objectMapper.createObjectNode()).build(); } + private static void requireLogStreamNames(String group, String stream) { + if (group.isEmpty() || group.length() > 512 || !LOG_GROUP_NAME.matcher(group).matches()) { + throw new AwsException("InvalidParameterException", "Invalid logGroupName.", 400); + } + 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); + } + } + private Response handleDescribeLogStreams(JsonNode request, String region) { String groupName = resolveLogGroupName(request); String prefix = request.path("logStreamNamePrefix").asText(null); 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 6c1d33f5d9..b1ce0e84f0 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 @@ -424,6 +424,7 @@ public class CloudWatchLogsService implements ResourceProvider { public Map listTagsLogGroup(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)); return group.getTags(); @@ -439,6 +440,7 @@ public class CloudWatchLogsService implements ResourceProvider { String accountId, String groupName, String streamName, String region) { String groupKey = groupKey(region, groupName); getForAccount(groupStore, accountId, groupKey) + .filter(stored -> groupName.equals(stored.getLogGroupName())) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "The specified log group does not exist: " + groupName, 400)); @@ -460,6 +462,8 @@ public class CloudWatchLogsService implements ResourceProvider { public void deleteLogStream(String groupName, String streamName, String region) { String streamKey = streamKey(region, groupName, streamName); streamStore.get(streamKey) + .filter(stored -> groupName.equals(stored.getLogGroupName()) + && streamName.equals(stored.getLogStreamName())) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "The specified log stream does not exist: " + streamName, 400)); @@ -1264,8 +1268,10 @@ public class CloudWatchLogsService implements ResourceProvider { private void deleteEventsForStream(String region, String groupName, String streamName) { String eventPrefix = eventKeyPrefix(region, groupName, streamName); + String groupPrefix = streamKeyPrefix(region, groupName); List keys = eventStore.keys().stream() - .filter(k -> k.startsWith(eventPrefix)) + .filter(k -> k.startsWith(eventPrefix) + && streamName.equals(streamNameFromEventKey(k, groupPrefix))) .toList(); keys.forEach(eventStore::delete); } 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 0a42832371..31166b9ea9 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 @@ -97,6 +97,23 @@ 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))) { + return List.of("*"); + } + JsonNode body = readJsonBody(ctx); + if (body == null) { + return List.of("*"); + } + // 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()); + } + // ── IAM ───────────────────────────────────────────────────────────────────── /** A stored entity's ARN and path, the two things a target ARN is built from. */ diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java index e196ef4513..d0e404450c 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.dynamodb.backend.NativeDynamoDbBackend; @@ -36,9 +37,12 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -50,6 +54,7 @@ class IamConditionContextResolverTest { private Instance dynamoDbFacadeInstance; private Ec2Service ec2Service; private S3Service s3Service; + private CloudWatchLogsService logsService; private RequestContext requestContext; private EmulatorConfig config; private IamConditionContextResolver resolver; @@ -71,12 +76,55 @@ class IamConditionContextResolverTest { Instance s3ServiceInstance = mock(Instance.class); when(s3ServiceInstance.isResolvable()).thenReturn(true); when(s3ServiceInstance.get()).thenReturn(s3Service); + logsService = mock(CloudWatchLogsService.class); + Instance logsServiceInstance = mock(Instance.class); + when(logsServiceInstance.isResolvable()).thenReturn(true); + when(logsServiceInstance.get()).thenReturn(logsService); requestContext = new RequestContext(); requestContext.setRegion("us-east-1"); config = mock(EmulatorConfig.class); when(config.defaultRegion()).thenReturn("us-east-1"); resolver = new IamConditionContextResolver( - dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, requestContext, config); + dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, requestContext, config); + } + + @Test + void logStreamTagsUseRawParentNameAndRequestRegion() throws Exception { + ContainerRequestContext request = mock(ContainerRequestContext.class); + when(request.getProperty("floci.bufferedJsonBody")) + .thenReturn(mapper.readTree("{\"logGroupName\":\" group \",\"logStreamName\":42}")); + when(logsService.listTagsLogGroup(" group ", "eu-west-1")).thenReturn(Map.of("team", "blue")); + requestContext.setRegion("eu-west-1"); + for (String action : List.of("logs:CreateLogStream", "logs:DeleteLogStream")) { + assertEquals(Map.of("aws:ResourceTag/team", List.of("blue")), resolver.resolve("logs", action, request)); + } + requestContext.setRegion(null); + when(logsService.listTagsLogGroup(" group ", "us-east-1")).thenReturn(Map.of("team", "red")); + assertEquals(Map.of("aws:ResourceTag/team", List.of("red")), + resolver.resolve("logs", "logs:CreateLogStream", request)); + } + + @Test + void missingLogGroupTagsDoNotReplaceTheHandlersMissingResourceError() throws Exception { + ContainerRequestContext request = mock(ContainerRequestContext.class); + when(request.getProperty("floci.bufferedJsonBody")).thenReturn(mapper.readTree("{\"logGroupName\":42}")); + when(logsService.listTagsLogGroup("42", "us-east-1")) + .thenThrow(new AwsException("ResourceNotFoundException", "missing", 400)); + assertNull(resolver.resolve("logs", "logs:DeleteLogStream", request)); + } + + @Test + void unexpectedLogGroupLookupFailuresCannotEraseTagDenies() throws Exception { + ContainerRequestContext request = mock(ContainerRequestContext.class); + when(request.getProperty("floci.bufferedJsonBody")).thenReturn(mapper.readTree("{\"logGroupName\":\"group\"}")); + AwsException failure = new AwsException("InternalFailure", "storage unavailable", 500); + when(logsService.listTagsLogGroup("group", "us-east-1")).thenThrow(failure); + assertSame(failure, assertThrows(AwsException.class, + () -> resolver.resolve("logs", "logs:CreateLogStream", request))); + IllegalStateException unexpected = new IllegalStateException("unavailable"); + doThrow(unexpected).when(logsService).listTagsLogGroup("group", "us-east-1"); + assertSame(unexpected, assertThrows(IllegalStateException.class, + () -> resolver.resolve("logs", "logs:DeleteLogStream", request))); } /** A form request whose body can be read again, as a real request's restored stream can. */ diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java index bed8bea6aa..8a5ab76e00 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java @@ -152,7 +152,7 @@ class DynamoDbFacadeTest { RequestContext requestContext = new RequestContext(); requestContext.setRegion(OTHER_REGION); IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb, - mock(Instance.class), mock(Instance.class), requestContext, mock(EmulatorConfig.class)); + mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext, mock(EmulatorConfig.class)); ContainerRequestContext request = mock(ContainerRequestContext.class); JsonNode body = mapper.readTree(""" {"TableName": "recorded-table", "Key": {"id": {"S": "USER_alice"}}} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LogsGovUnknownRegionAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LogsGovUnknownRegionAuthorizationIntegrationTest.java new file mode 100644 index 0000000000..30ca1d83b3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsGovUnknownRegionAuthorizationIntegrationTest.java @@ -0,0 +1,13 @@ +package io.github.hectorvent.floci.services.iam; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; + +@QuarkusTest +@TestProfile(LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.GovProfile.class) +class LogsGovUnknownRegionAuthorizationIntegrationTest extends LogsNoncommercialUnknownRegionAuthorizationIntegrationTest { + @Override + String deploymentPartition() { + return "aws-us-gov"; + } +} 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 new file mode 100644 index 0000000000..a5791ca27e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.java @@ -0,0 +1,134 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +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.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +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 java.net.URI; +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; + +@QuarkusTest +@TestProfile(LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.ChinaProfile.class) +class LogsNoncommercialUnknownRegionAuthorizationIntegrationTest { + public static class ChinaProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.enforcement-enabled", "true", + "floci.partitions.allow-unknown-regions", "true", "floci.default-region", "cn-north-1"); + } + } + + public static class GovProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.enforcement-enabled", "true", + "floci.partitions.allow-unknown-regions", "true", "floci.default-region", "us-gov-west-1"); + } + } + + private static final String ACCOUNT = "111111111111"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + @TestHTTPResource + URI endpoint; + + @BeforeAll + static void configureContentTypes() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @CsvSource({"CreateLogStream,false,polygondwanaland-west-1", "DeleteLogStream,false,polygondwanaland-west-1", + "CreateLogStream,true,polygondwanaland-west-1", "DeleteLogStream,true,polygondwanaland-west-1", + "CreateLogStream,false,cn-north-1", "DeleteLogStream,false,cn-north-1", + "CreateLogStream,true,cn-north-1", "DeleteLogStream,true,cn-north-1", + "CreateLogStream,false,us-gov-west-1", "DeleteLogStream,false,us-gov-west-1", + "CreateLogStream,true,us-gov-west-1", "DeleteLogStream,true,us-gov-west-1", + "CreateLogStream,false,us-east-1", "DeleteLogStream,false,us-east-1", + "CreateLogStream,true,us-east-1", "DeleteLogStream,true,us-east-1"}) + void streamPoliciesUseTheSamePartitionAsTheStoredGroup(String action, boolean deny, String region) { + int port = endpoint.getPort(); + String group = "logs-partition-" + UUID.randomUUID(); + cleanup.register(() -> call(ACCOUNT, region, "DeleteLogGroup", Map.of("logGroupName", group)) + .then().statusCode(200)); + call(ACCOUNT, region, "CreateLogGroup", Map.of("logGroupName", group)).then().statusCode(200); + String partition = switch (region) { + case "cn-north-1" -> "aws-cn"; + case "us-gov-west-1" -> "aws-us-gov"; + case "us-east-1" -> "aws"; + default -> deploymentPartition(); + }; + String groupArn = "arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":log-group:" + group; + call(ACCOUNT, region, "DescribeLogGroups", Map.of("logGroupNamePrefix", group)) + .then().statusCode(200).body("logGroups[0].arn", equalTo(groupArn + ":*")); + boolean delete = action.equals("DeleteLogStream"); + if (delete) { + call(ACCOUNT, region, "CreateLogStream", Map.of("logGroupName", group, "logStreamName", "s")) + .then().statusCode(200); + call(ACCOUNT, region, "PutLogEvents", Map.of("logGroupName", group, "logStreamName", "s", + "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); + 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), + () -> { + if (deny) { + response.then().body(containsString("AccessDeniedException")); + } + }, + () -> { + List> streams = call(ACCOUNT, region, "DescribeLogStreams", + Map.of("logGroupName", group)).then().statusCode(200).extract().path("logStreams"); + assertEquals(deny == delete, streams.stream().anyMatch(s -> "s".equals(s.get("logStreamName")))); + }, + () -> { + if (deny && delete) { + call(ACCOUNT, region, "GetLogEvents", Map.of("logGroupName", group, "logStreamName", "s")) + .then().statusCode(200).body("events[0].message", equalTo("retained")); + } + }); + } + + String deploymentPartition() { + return "aws-cn"; + } + + 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("/"); + } +} 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 new file mode 100644 index 0000000000..f8a5e97893 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsStreamAuthorizationIntegrationTest.java @@ -0,0 +1,453 @@ +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.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 io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +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.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.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class LogsStreamAuthorizationIntegrationTest { + + 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 = {"CreateLogStream", "DeleteLogStream"}) + void exactStreamPermissionAllowsOnlyThatStream(String action) { + String group = group(Map.of()); + prepare(action, group, "selected"); + prepare(action, group, "other"); + String caller = user(policy("Allow", action, streamArn(group, "selected"), "")); + + stream(caller, action, group, "other").statusCode(400) + .body(containsString("AccessDeniedException")); + assertPresent(group, "other", action.equals("DeleteLogStream")); + stream(caller, action, group, "selected").statusCode(200); + assertPresent(group, "selected", action.equals("CreateLogStream")); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void groupTagDenyPreventsMutationEvenWithWildcardAllow(String action) { + String group = group(Map.of("protected", "true")); + prepare(action, group, "selected"); + String caller = user(policy("Allow", action, "*", "") + "," + + policy("Deny", action, "*", + ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/protected\":\"true\"}}")); + + stream(caller, action, group, "selected").statusCode(400) + .body(containsString("AccessDeniedException")); + assertPresent(group, "selected", action.equals("DeleteLogStream")); + if (action.equals("DeleteLogStream")) { + assertEvent(group, "selected"); + } + for (Map tags : List.of(Map.of("protected", "false"), Map.of())) { + String allowed = group(tags); + prepare(action, allowed, "selected"); + stream(caller, action, allowed, "selected").statusCode(200); + assertPresent(allowed, "selected", action.equals("CreateLogStream")); + } + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void resourceTagAllowReadsTheOwningGroup(String action) { + String group = group(Map.of("team", "blue")); + String other = group(Map.of("team", "red")); + String untagged = group(Map.of()); + prepare(action, group, "selected"); + prepare(action, other, "selected"); + prepare(action, untagged, "selected"); + String caller = user(policy("Allow", action, "*", + ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}")); + + stream(caller, action, other, "selected").statusCode(400) + .body(containsString("AccessDeniedException")); + assertPresent(other, "selected", action.equals("DeleteLogStream")); + stream(caller, action, untagged, "selected").statusCode(400) + .body(containsString("AccessDeniedException")); + assertPresent(untagged, "selected", action.equals("DeleteLogStream")); + stream(caller, action, group, "selected").statusCode(200); + assertPresent(group, "selected", action.equals("CreateLogStream")); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void exactDenyOverridesWildcardAllowWithoutChangingTheStream(String action) { + String group = group(Map.of()); + prepare(action, group, "protected"); + prepare(action, group, "allowed"); + String caller = user(policy("Allow", action, "*", "") + "," + + policy("Deny", action, streamArn(group, "protected"), "")); + stream(caller, action, group, "protected").statusCode(400) + .body(containsString("AccessDeniedException")); + assertPresent(group, "protected", action.equals("DeleteLogStream")); + if (action.equals("DeleteLogStream")) { + assertEvent(group, "protected"); + } + stream(caller, action, group, "allowed").statusCode(200); + assertPresent(group, "allowed", action.equals("CreateLogStream")); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void numericNamesUseTheSameTargetAsTheHandler(String action) { + String group = group(Map.of()); + prepare(action, group, "42"); + String caller = user(policy("Allow", action, "*", "") + "," + + policy("Deny", action, streamArn(group, "42"), "")); + call(endpoint.getPort(), caller, action, Map.of("logGroupName", group, "logStreamName", 42)) + .statusCode(400).body(containsString("AccessDeniedException")); + assertPresent(group, "42", action.equals("DeleteLogStream")); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void sameNamedGroupsKeepTheirAccountAndRegionTags(String action) { + String group = "logs-stream-scope-" + UUID.randomUUID(); + String otherAccount = "222222222222"; + String otherRegion = "eu-west-1"; + createGroup(ACCOUNT, REGION, group, Map.of("team", "blue")); + createGroup(ACCOUNT, otherRegion, group, Map.of("team", "red")); + createGroup(otherAccount, REGION, group, Map.of("team", "red")); + if (action.equals("DeleteLogStream")) { + for (String[] scope : List.of(new String[]{ACCOUNT, REGION}, new String[]{ACCOUNT, otherRegion}, + new String[]{otherAccount, REGION})) { + call(endpoint.getPort(), scope[0], scope[1], "CreateLogStream", + Map.of("logGroupName", group, "logStreamName", "selected")).statusCode(200); + } + } + String statements = policy("Allow", action, "*", + ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}"); + String caller = user(statements); + String otherCaller = user(otherAccount, statements); + call(endpoint.getPort(), caller, otherRegion, action, + Map.of("logGroupName", group, "logStreamName", "selected")) + .statusCode(400).body(containsString("AccessDeniedException")); + call(endpoint.getPort(), otherCaller, REGION, action, + Map.of("logGroupName", group, "logStreamName", "selected")) + .statusCode(400).body(containsString("AccessDeniedException")); + assertPresent(ACCOUNT, otherRegion, group, "selected", action.equals("DeleteLogStream")); + assertPresent(otherAccount, REGION, group, "selected", action.equals("DeleteLogStream")); + stream(caller, action, group, "selected").statusCode(200); + assertPresent(group, "selected", action.equals("CreateLogStream")); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void missingGroupKeepsTheHandlersResourceNotFoundResponse(String action) { + String caller = user(policy("Allow", action, "*", "")); + stream(caller, action, "missing-" + UUID.randomUUID(), "selected") + .statusCode(400).body(containsString("ResourceNotFoundException")); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void queryCredentialsAuthorizeAndMutateTheSameRegion(String action) { + String group = "logs-query-scope-" + UUID.randomUUID(); + String region = "eu-west-1"; + createGroup(ACCOUNT, REGION, group, Map.of("team", "red")); + createGroup(ACCOUNT, region, group, Map.of("team", "blue")); + if (action.equals("DeleteLogStream")) { + for (String targetRegion : List.of(REGION, region)) { + call(endpoint.getPort(), ACCOUNT, targetRegion, "CreateLogStream", + Map.of("logGroupName", group, "logStreamName", "selected")).statusCode(200); + } + } + String resource = "arn:aws:logs:" + region + ":" + ACCOUNT + ":log-group:" + group + ":log-stream:selected"; + String caller = user(policy("Allow", action, resource, + ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}")); + given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1") + .queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256") + .queryParam("X-Amz-Credential", caller + "/20261015/" + region + "/logs/aws4_request") + .queryParam("X-Amz-Signature", "abc") + .header("X-Amz-Target", "Logs_20140328." + action) + .body(Map.of("logGroupName", group, "logStreamName", "selected")) + .when().post("/").then().statusCode(200); + assertPresent(ACCOUNT, REGION, group, "selected", action.equals("DeleteLogStream")); + assertPresent(ACCOUNT, region, group, "selected", action.equals("CreateLogStream")); + // A real Authorization header remains authoritative over conflicting query credentials. + given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1") + .header("Authorization", EnforcementFixtures.auth(caller, "logs")) + .queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256") + .queryParam("X-Amz-Credential", caller + "/20261015/" + region + "/logs/aws4_request") + .header("X-Amz-Target", "Logs_20140328." + action) + .body(Map.of("logGroupName", group, "logStreamName", "selected")) + .when().post("/").then().statusCode(400).body(containsString("AccessDeniedException")); + assertPresent(ACCOUNT, REGION, group, "selected", action.equals("DeleteLogStream")); + assertPresent(ACCOUNT, region, group, "selected", action.equals("CreateLogStream")); + } + + @ParameterizedTest + @CsvSource({"CreateLogStream,blank-header", "DeleteLogStream,blank-header", + "CreateLogStream,missing-algorithm", "DeleteLogStream,missing-algorithm"}) + void credentialEdgeCasesKeepTheCanonicalRequestRegion(String action, String mode) { + String account = "000000000000"; + String remote = "eu-west-1"; + String group = "logs-query-edge-" + UUID.randomUUID(); + boolean blankHeader = mode.equals("blank-header"); + String selectedRegion = blankHeader ? remote : REGION; + String otherRegion = blankHeader ? REGION : remote; + createGroup(account, selectedRegion, group, Map.of("team", "blue")); + createGroup(account, otherRegion, group, Map.of("team", "red")); + if (action.equals("DeleteLogStream")) { + for (String region : List.of(REGION, remote)) { + call(endpoint.getPort(), account, region, "CreateLogStream", + Map.of("logGroupName", group, "logStreamName", "selected")).statusCode(200); + } + } + String resource = "arn:aws:logs:" + selectedRegion + ":" + account + + ":log-group:" + group + ":log-stream:selected"; + String caller = user(account, policy("Allow", action, resource, + ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}")); + RequestSpecification request = given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1") + .queryParam("X-Amz-Credential", caller + "/20261015/" + remote + "/logs/aws4_request") + .queryParam("X-Amz-Signature", "abc") + .header("X-Amz-Target", "Logs_20140328." + action) + .body(Map.of("logGroupName", group, "logStreamName", "selected")); + if (blankHeader) { + request.header("Authorization", "").queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256"); + } + request.when().post("/").then().statusCode(200); + assertPresent(account, otherRegion, group, "selected", action.equals("DeleteLogStream")); + assertPresent(account, selectedRegion, group, "selected", action.equals("CreateLogStream")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void storageKeyAliasesCannotDeleteAnotherGroupsStream(boolean exactGrant) { + 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")); + seedHistoricalStream(protectedGroup, "s"); + assertPresent(protectedGroup, "s", true); + assertEvent(protectedGroup, "s"); + String caller = user(policy("Allow", "DeleteLogStream", exactGrant ? streamArn(group, "x::s") : "*", + ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}")); + Response response = stream(caller, "DeleteLogStream", group, "x::s").extract().response(); + assertAll("reject storage alias and retain historical stream and event", + () -> response.then().statusCode(400).body(containsString("InvalidParameterException")), + () -> assertPresent(protectedGroup, "s", true), + () -> assertEvent(protectedGroup, "s")); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void arnDelimiterAliasesCannotGrantAccessToAnotherGroup(String action) { + 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()); + boolean delete = action.equals("DeleteLogStream"); + if (delete) { + seedHistoricalStream(actualGroup, "s"); + } + prepare(action, group, "safe"); + assertPresent(actualGroup, "s", delete); + String caller = user(policy("Allow", action, streamArn(group, "x:log-stream:s"), "") + + "," + policy("Allow", action, streamArn(group, "safe"), "")); + Response response = stream(caller, action, actualGroup, "s").extract().response(); + assertAll("reject ambiguous ARN identity without changing the stored target", + () -> response.then().statusCode(400).body(containsString("InvalidParameterException")), + () -> assertPresent(actualGroup, "s", delete), + () -> { + if (delete) { + assertEvent(actualGroup, "s"); + } + }); + stream(caller, action, group, "safe").statusCode(200); + assertPresent(group, "safe", !delete); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void publicStreamNamesFollowTheDocumentedConstraints(String action) { + String group = group(Map.of()); + String caller = user(policy("Allow", action, "*", "")); + prepare(action, group, "selected"); + for (String invalid : List.of("", "bad:group", "bad*group", "bad group", "g".repeat(513))) { + stream(caller, action, invalid, "selected").statusCode(400) + .body(containsString("InvalidParameterException")); + } + for (String invalid : List.of("", "bad:stream", "bad*stream", "s".repeat(513))) { + stream(caller, action, group, invalid).statusCode(400) + .body(containsString("InvalidParameterException")); + } + assertPresent(group, "selected", action.equals("DeleteLogStream")); + if (action.equals("DeleteLogStream")) { + assertEvent(group, "selected"); + } + stream(caller, action, group, "selected").statusCode(200); + assertPresent(group, "selected", action.equals("CreateLogStream")); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateLogStream", "DeleteLogStream"}) + void maximumLengthAndWhitespaceStreamNamesRemainUsable(String action) { + String prefix = "logs-name-boundary-" + UUID.randomUUID(); + String group = prefix + "g".repeat(512 - prefix.length()); + createGroup(ACCOUNT, REGION, group, Map.of()); + String caller = user(policy("Allow", action, "*", "")); + for (String stream : List.of("s", " ", "🚀".repeat(512))) { + prepare(action, group, stream); + stream(caller, action, group, stream).statusCode(200); + assertPresent(group, stream, action.equals("CreateLogStream")); + } + } + + @ParameterizedTest + @ValueSource(strings = {"s::child", "s::child::nested"}) + void deletingAnAuthorizedStreamPreservesHistoricalSiblingEvents(String sibling) { + String group = group(Map.of()); + seedHistoricalStream(group, "s", "selected-event"); + seedHistoricalStream(group, sibling, "protected-sibling-event"); + assertPresent(group, "s", true); + assertPresent(group, sibling, true); + call(endpoint.getPort(), ACCOUNT, "GetLogEvents", Map.of("logGroupName", group, "logStreamName", sibling)) + .statusCode(200).body("events[0].message", equalTo("protected-sibling-event")); + String caller = user(policy("Allow", "DeleteLogStream", streamArn(group, "s"), "")); + stream(caller, "DeleteLogStream", group, "s").statusCode(200); + assertAll("delete only the selected stream and its emitted events", + () -> assertPresent(group, "s", false), + () -> assertPresent(group, sibling, true), + () -> call(endpoint.getPort(), ACCOUNT, "GetLogEvents", + Map.of("logGroupName", group, "logStreamName", sibling)) + .statusCode(200).body("events[0].message", equalTo("protected-sibling-event")), + () -> call(endpoint.getPort(), ACCOUNT, "GetLogEvents", + Map.of("logGroupName", group, "logStreamName", "s")) + .statusCode(200).body("events.message", not(hasItem("selected-event")))); + } + + /** Existing service storage APIs seed historical invalid names without bypassing the HTTP request under test. */ + private void seedHistoricalStream(String group, String stream) { + seedHistoricalStream(group, stream, "retained"); + } + + private void seedHistoricalStream(String group, String stream, String message) { + logsService.createLogStreamForAccount(ACCOUNT, group, stream, REGION); + logsService.putLogEventsForAccount(ACCOUNT, group, stream, + List.of(Map.of("timestamp", System.currentTimeMillis(), "message", message)), REGION); + } + + private void prepare(String action, String group, String name) { + if (action.equals("DeleteLogStream")) { + stream(ACCOUNT, "CreateLogStream", group, name).statusCode(200); + call(endpoint.getPort(), ACCOUNT, "PutLogEvents", Map.of("logGroupName", group, + "logStreamName", name, "logEvents", List.of(Map.of("timestamp", System.currentTimeMillis(), + "message", "retained")))).statusCode(200); + } + } + + private String group(Map tags) { + String group = "logs-stream-auth-" + UUID.randomUUID(); + createGroup(ACCOUNT, REGION, group, tags); + return group; + } + + private void createGroup(String account, String region, String group, Map tags) { + int port = endpoint.getPort(); + cleanup.register(() -> call(port, account, region, "DeleteLogGroup", Map.of("logGroupName", group)) + .statusCode(200)); + call(port, account, region, "CreateLogGroup", Map.of("logGroupName", group, "tags", tags)).statusCode(200); + } + + private String user(String statements) { + return user(ACCOUNT, statements); + } + + 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(); + } + + private static String policy(String effect, String action, String resource, String condition) { + return "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + action + + "\",\"Resource\":\"" + resource + "\"" + condition + "}"; + } + + private static String streamArn(String group, String stream) { + return "arn:aws:logs:" + REGION + ":" + ACCOUNT + ":log-group:" + group + ":log-stream:" + stream; + } + + private ValidatableResponse stream(String caller, String action, String group, String stream) { + return call(endpoint.getPort(), caller, action, Map.of("logGroupName", group, "logStreamName", stream)); + } + + private void assertPresent(String group, String stream, boolean expected) { + assertPresent(ACCOUNT, REGION, group, stream, expected); + } + + private void assertEvent(String group, String stream) { + call(endpoint.getPort(), ACCOUNT, "GetLogEvents", Map.of("logGroupName", group, "logStreamName", stream)) + .statusCode(200).body("events[0].message", equalTo("retained")); + } + + private void assertPresent(String account, String region, String group, String stream, boolean expected) { + List> streams = call(endpoint.getPort(), account, region, "DescribeLogStreams", + Map.of("logGroupName", group)).statusCode(200).extract().path("logStreams"); + assertEquals(expected, streams.stream().anyMatch(item -> stream.equals(item.get("logStreamName")))); + } + + private static ValidatableResponse call(int port, String caller, String action, Map body) { + return call(port, caller, REGION, action, body); + } + + 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(); + } +} 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 new file mode 100644 index 0000000000..69e28ef1c6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/LogsUnknownRegionAuthorizationIntegrationTest.java @@ -0,0 +1,179 @@ +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.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.QuarkusTestProfile; +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.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +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.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; + +@QuarkusTest +@TestProfile(LogsUnknownRegionAuthorizationIntegrationTest.UnknownRegionProfile.class) +class LogsUnknownRegionAuthorizationIntegrationTest { + + public static class UnknownRegionProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.enforcement-enabled", "true", + "floci.partitions.allow-unknown-regions", "true"); + } + } + + 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 + @CsvSource({"CreateLogStream,false,false", "DeleteLogStream,false,false", "CreateLogStream,true,false", + "DeleteLogStream,true,false", "DeleteLogStream,false,true"}) + void optedInRegionLabelsCannotAliasHistoricalGroupNames(String action, boolean conditional, boolean streamAlias) { + int port = endpoint.getPort(); + String group = "logs-region-alias-" + UUID.randomUUID(); + String historical = streamAlias ? group : "x::" + group; + 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(() -> call(port, ACCOUNT, validUnknownRegion, "DeleteLogGroup", Map.of("logGroupName", group)) + .then().statusCode(200)); + logsService.createLogGroupForAccount(ACCOUNT, historical, null, Map.of("team", "blue"), REGION); + logsService.createLogGroupForAccount(ACCOUNT, group, null, Map.of("team", "blue"), validUnknownRegion); + boolean delete = action.equals("DeleteLogStream"); + if (delete) { + for (String[] target : List.of(new String[]{historical, REGION, historicalStream}, + new String[]{group, validUnknownRegion, "s"})) { + logsService.createLogStreamForAccount(ACCOUNT, target[0], target[2], target[1]); + logsService.putLogEventsForAccount(ACCOUNT, target[0], target[2], + List.of(Map.of("timestamp", System.currentTimeMillis(), "message", "retained")), target[1]); + } + } + 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); + Response response = call(port, caller, aliasRegion, action, + Map.of("logGroupName", group, "logStreamName", "s")); + assertAll("preserve stored identity across an opted-in region delimiter", + () -> response.then().statusCode(400).body(containsString( + conditional ? "AccessDeniedException" : "ResourceNotFoundException")), + () -> assertPresent(port, REGION, historical, historicalStream, delete), + () -> { + if (delete) { + call(port, ACCOUNT, REGION, "GetLogEvents", + Map.of("logGroupName", historical, "logStreamName", historicalStream)) + .then().statusCode(200).body("events[0].message", equalTo("retained")); + } + }); + call(port, caller, validUnknownRegion, action, Map.of("logGroupName", group, "logStreamName", "s")) + .then().statusCode(200); + assertPresent(port, validUnknownRegion, group, !delete); + } + + @ParameterizedTest + @CsvSource({"CreateLogStream,Allow,false", "DeleteLogStream,Allow,false", + "CreateLogStream,Allow,true", "DeleteLogStream,Allow,true", + "CreateLogStream,Deny,false", "DeleteLogStream,Deny,false", + "CreateLogStream,Deny,true", "DeleteLogStream,Deny,true"}) + void resourceAccountUsesStorageOwnerInOptedInRegion(String action, String effect, boolean actualOwner) { + int port = endpoint.getPort(); + String otherAccount = "222222222222"; + String region = "custom:" + otherAccount; + String group = "logs-resource-owner-" + UUID.randomUUID(); + cleanup.register(() -> call(port, ACCOUNT, region, "DeleteLogGroup", Map.of("logGroupName", group)) + .then().statusCode(200)); + logsService.createLogGroupForAccount(ACCOUNT, group, null, null, region); + boolean delete = action.equals("DeleteLogStream"); + if (delete) { + logsService.createLogStreamForAccount(ACCOUNT, group, "s", region); + 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); + boolean allowed = effect.equals("Allow") == actualOwner; + Response response = call(port, caller, region, action, Map.of("logGroupName", group, "logStreamName", "s")); + assertAll("use the canonical account independently of region punctuation", + () -> response.then().statusCode(allowed ? 200 : 400), + () -> assertPresent(port, region, group, allowed != delete), + () -> { + if (!allowed) { + response.then().body(containsString("AccessDeniedException")); + if (delete) { + call(port, ACCOUNT, region, "GetLogEvents", + Map.of("logGroupName", group, "logStreamName", "s")) + .then().statusCode(200).body("events[0].message", equalTo("retained")); + } + } + }); + } + + private static void assertPresent(int port, String region, String group, boolean expected) { + assertPresent(port, region, group, "s", expected); + } + + private static void assertPresent(int port, String region, String group, String name, boolean expected) { + List> streams = call(port, ACCOUNT, region, "DescribeLogStreams", + Map.of("logGroupName", group)).then().statusCode(200).extract().path("logStreams"); + assertEquals(expected, streams.stream().anyMatch(stream -> name.equals(stream.get("logStreamName")))); + } + + 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("/"); + } +} 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 f64fe2a854..2b38fcd593 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 @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.iam; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -646,6 +647,28 @@ class ResourceArnBuilderTest { }).when(ctx).setEntityStream(any(InputStream.class)); } + @Test + void logStreamTargetsUseTheServingActionAndRequestPartition() { + for (String action : List.of("logs:CreateLogStream", "logs:DeleteLogStream")) { + for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) { + setJsonBody("{\"logGroupName\":\" /group \",\"logStreamName\":42}"); + 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))); + } + } + } + + @Test + void excludedLogsActionsKeepWildcardResources() { + for (String action : List.of("logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy", + "logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource", "logs:PutLogEvents")) { + setJsonBody("{\"logGroupName\":\"group\",\"logStreamName\":\"stream\"}"); + assertEquals(List.of("*"), builder.buildLogStreamResources(action, ctx, "us-east-1", ACCOUNT, "aws")); + } + } + // ── DynamoDB ───────────────────────────────────────────────────────────────── @Test