diff --git a/docs/services/iam.md b/docs/services/iam.md index 484db06a55..13d8a46d63 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -4019,7 +4019,9 @@ floci populates: Aurora DSQL for its clusters, MemoryDB for its clusters, users and ACLs, EKS for its clusters, node groups, Fargate profiles, add-ons, Pod Identity associations and access entries, Resource Groups for its groups, CloudWatch Logs for its log groups, destinations, delivery sources, delivery destinations and deliveries, Pricing Calculator for its workload - estimates, and Amazon Managed Service for Prometheus for its workspaces and rule groups namespaces. Tag keys + estimates, AWS Config for its rules, aggregators, conformance packs and the other resources it tags, EFS for its + file systems and access points, Route 53 Resolver for its endpoints, rules and firewall domain lists, and Amazon + Managed Service for Prometheus for its workspaces and rule groups namespaces. Tag keys differing only in case are one condition key holding every value. - EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and `ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the diff --git a/src/main/java/io/floci/aws/services/configservice/ConfigStoredResourceArns.java b/src/main/java/io/floci/aws/services/configservice/ConfigStoredResourceArns.java index 9e0e771c6d..8efeabcb36 100644 --- a/src/main/java/io/floci/aws/services/configservice/ConfigStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/configservice/ConfigStoredResourceArns.java @@ -1,10 +1,14 @@ package io.floci.aws.services.configservice; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.StoredResourceArns; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Optional; /** @@ -34,4 +38,28 @@ public class ConfigStoredResourceArns implements StoredResourceArns { } return config.storedArn(type, region, names.getFirst()).filter(arn -> !arn.isBlank()); } + + /** + * {@inheritDoc} + * + *

The tags of the rule, aggregator, conformance pack or other resource the ARN names, as {@code + * ListTagsForResource} reads them: under the lock the resource's tag changes hold, so a concurrent change is seen + * whole or not at all, and none for a resource Config does not hold in the ARN's Region. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "config")) { + return Map.of(); + } + Map found = new LinkedHashMap<>(); + try { + for (Map tag : config.listTagsForResource(AwsArnUtils.parse(arn).region(), arn)) { + found.put(tag.get("Key"), tag.get("Value")); + } + } catch (AwsException expected) { + // A resource the service does not hold has no stored tags for IAM to read. + return Map.of(); + } + return StoredResourceArns.withEmptyValues(found); + } } diff --git a/src/main/java/io/floci/aws/services/efs/EfsService.java b/src/main/java/io/floci/aws/services/efs/EfsService.java index 5f821f0220..a0c41919b0 100644 --- a/src/main/java/io/floci/aws/services/efs/EfsService.java +++ b/src/main/java/io/floci/aws/services/efs/EfsService.java @@ -43,6 +43,7 @@ import org.jboss.logging.Logger; import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -379,6 +380,33 @@ public class EfsService implements Resettable { return res; } + /** + * The tags of the caller's file system or access point of the id, as a copy taken under the lock its tag changes + * hold, so a concurrent change is seen whole or not at all; empty when EFS holds no such resource in the Region or + * the one it holds has another ARN than {@code arn}. + */ + public Map storedTags(String region, String resourceId, String arn) { + synchronized (lockFor(regionKey(region, resourceId))) { + List tags; + if (resourceId.startsWith("fs-")) { + tags = findFileSystem(region, resourceId).filter(fs -> arn.equals(fs.getFileSystemArn())) + .map(FileSystem::getTags).orElse(null); + } else if (resourceId.startsWith("fsap-")) { + tags = findAccessPoint(region, resourceId).filter(ap -> arn.equals(ap.getAccessPointArn())) + .map(AccessPointDescription::getTags).orElse(null); + } else { + tags = null; + } + Map found = new LinkedHashMap<>(); + for (Tag tag : tags == null ? List.of() : tags) { + if (tag.getKey() != null) { + found.put(tag.getKey(), tag.getValue()); + } + } + return found; + } + } + private List getResourceTags(String region, String resourceId) { if (resourceId.startsWith("fs-")) { return getFileSystem(region, resourceId).getTags(); diff --git a/src/main/java/io/floci/aws/services/efs/EfsStoredResourceArns.java b/src/main/java/io/floci/aws/services/efs/EfsStoredResourceArns.java index 56766aad35..c799877774 100644 --- a/src/main/java/io/floci/aws/services/efs/EfsStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/efs/EfsStoredResourceArns.java @@ -1,5 +1,7 @@ package io.floci.aws.services.efs; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.services.efs.model.AccessPointDescription; import io.floci.aws.services.efs.model.FileSystem; @@ -7,6 +9,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.List; +import java.util.Map; import java.util.Optional; /** @@ -17,10 +20,12 @@ import java.util.Optional; public class EfsStoredResourceArns implements StoredResourceArns { private final EfsService efs; + private final RegionResolver regionResolver; @Inject - public EfsStoredResourceArns(EfsService efs) { + public EfsStoredResourceArns(EfsService efs, RegionResolver regionResolver) { this.efs = efs; + this.regionResolver = regionResolver; } @Override @@ -54,4 +59,27 @@ public class EfsStoredResourceArns implements StoredResourceArns { }; return arn.filter(stored -> !stored.isBlank()).stream().toList(); } + + /** + * {@inheritDoc} + * + *

The tags of the caller's file system or access point the ARN names ({@code file-system/fs-...}, + * {@code access-point/fsap-...}), as EFS stores them on it; none for an ARN of another account, which EFS keeps no + * resource of for the caller, or one whose stored resource has another ARN. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "elasticfilesystem")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + if (!parsed.accountId().equals(regionResolver.getAccountId()) || parsed.region().isBlank()) { + return Map.of(); + } + String[] resource = parsed.resource().split("/", 2); + if (resource.length != 2 || !(resource[0].equals("file-system") || resource[0].equals("access-point"))) { + return Map.of(); + } + return StoredResourceArns.withEmptyValues(efs.storedTags(parsed.region(), resource[1], arn)); + } } diff --git a/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverService.java b/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverService.java index c59d9abd3f..99a261babf 100644 --- a/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverService.java +++ b/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverService.java @@ -829,6 +829,31 @@ public class Route53ResolverService { * the caller owns it, so another account cannot claim it by naming its ARN. AWS-managed * firewall domain lists are not stored and so are not taggable here. */ + /** + * The tags of the caller's endpoint, rule or firewall domain list the ARN names, by key, as {@link #tagResource} + * set them; empty for a resource of another account, Region or ARN, or one this service holds none of. Read under + * the monitor tag changes hold, so the set read is one whole set. + */ + public synchronized Map storedTags(String arn, String accountId) { + if (!AwsArnUtils.isArnFor(arn, "route53resolver")) { + return Map.of(); + } + String region = AwsArnUtils.parse(arn).region(); + try { + requireTaggable(arn, region, accountId); + } catch (AwsException expected) { + // A resource the service does not hold has no stored tags for IAM to read. + return Map.of(); + } + ObjectNode stored = tagStore.get(arn).orElse(null); + if (stored == null) { + return Map.of(); + } + Map tags = new LinkedHashMap<>(); + stored.fields().forEachRemaining(tag -> tags.put(tag.getKey(), tag.getValue().asText(""))); + return tags; + } + private ObjectNode requireTaggable(String arn, String region, String accountId) { if (arn == null || arn.isBlank()) { throw new AwsException(INVALID_PARAMETER, "ResourceArn is required", 400); diff --git a/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverStoredResourceArns.java b/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverStoredResourceArns.java index bb11166163..2141b1f76d 100644 --- a/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/route53resolver/Route53ResolverStoredResourceArns.java @@ -1,11 +1,14 @@ package io.floci.aws.services.route53resolver; +import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.StoredResourceArns; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.List; +import java.util.Map; import java.util.Optional; /** @@ -16,10 +19,12 @@ import java.util.Optional; public class Route53ResolverStoredResourceArns implements StoredResourceArns { private final Route53ResolverService resolver; + private final RegionResolver regionResolver; @Inject - public Route53ResolverStoredResourceArns(Route53ResolverService resolver) { + public Route53ResolverStoredResourceArns(Route53ResolverService resolver, RegionResolver regionResolver) { this.resolver = resolver; + this.regionResolver = regionResolver; } @Override @@ -43,4 +48,18 @@ public class Route53ResolverStoredResourceArns implements StoredResourceArns { return Optional.empty(); } } + + /** + * {@inheritDoc} + * + *

The tags of the caller's resolver endpoint, resolver rule or firewall domain list the ARN names, as Route 53 + * Resolver stores them; none for an ARN of another account, whose resources it keeps none of for the caller. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "route53resolver")) { + return Map.of(); + } + return StoredResourceArns.withEmptyValues(resolver.storedTags(arn, regionResolver.getAccountId())); + } } diff --git a/src/test/java/io/floci/aws/services/efs/EfsStoredResourceArnsTest.java b/src/test/java/io/floci/aws/services/efs/EfsStoredResourceArnsTest.java index 7c7b090199..5ec17f5a8a 100644 --- a/src/test/java/io/floci/aws/services/efs/EfsStoredResourceArnsTest.java +++ b/src/test/java/io/floci/aws/services/efs/EfsStoredResourceArnsTest.java @@ -27,7 +27,7 @@ class EfsStoredResourceArnsTest { @BeforeEach void setUp() { service = new EfsService(new InMemoryStorageFactory(ACCOUNT), new RegionResolver(REGION, ACCOUNT)); - stored = new EfsStoredResourceArns(service); + stored = new EfsStoredResourceArns(service, new RegionResolver(REGION, ACCOUNT)); fileSystem = service.createFileSystem(new CreateFileSystemRequest(), REGION); } diff --git a/src/test/java/io/floci/aws/services/iam/StoredResourceTagIamIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StoredResourceTagIamIntegrationTest.java new file mode 100644 index 0000000000..46dc6673a2 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/StoredResourceTagIamIntegrationTest.java @@ -0,0 +1,147 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.Route53ResolverRequests; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.config.ConfigClient; +import software.amazon.awssdk.services.config.model.Owner; +import software.amazon.awssdk.services.efs.EfsClient; + +import java.net.URI; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A condition on {@code aws:ResourceTag} reads the tags a service keeps on the resource a request names, for the types + * the request-resources table gives resource-tag keys: a Config rule, an EFS file system and a Route 53 Resolver rule. + * A caller allowed an action only on resources tagged {@code team=blue} may act on the blue one and is refused the red + * one. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class StoredResourceTagIamIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final Region REGION = Region.US_EAST_1; + private static final String BLUE_ONLY = "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}"; + + @TestHTTPResource("/") + URI endpoint; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aConfigRuleIsCheckedWithItsTags() { + String blue = "blue-" + suffix(); + String red = "red-" + suffix(); + try (ConfigClient admin = AwsTestClients.create(ConfigClient.builder(), ACCOUNT, REGION, endpoint)) { + for (String[] rule : new String[][] {{blue, "blue"}, {red, "red"}}) { + admin.putConfigRule(r -> r.configRule(c -> c.configRuleName(rule[0]).source(s -> s.owner(Owner.AWS) + .sourceIdentifier("S3_BUCKET_VERSIONING_ENABLED"))).tags(t -> t.key("team").value(rule[1]))); + } + cleanup.register(() -> { + try (ConfigClient owner = AwsTestClients.create(ConfigClient.builder(), ACCOUNT, REGION, endpoint)) { + owner.deleteConfigRule(r -> r.configRuleName(red)); + } + }); + } + UserCredentials user = user("config:DeleteConfigRule"); + try (ConfigClient caller = AwsTestClients.create(ConfigClient.builder(), user.accessKeyId(), + user.secretAccessKey(), REGION, endpoint)) { + denied(() -> caller.deleteConfigRule(r -> r.configRuleName(red))); + caller.deleteConfigRule(r -> r.configRuleName(blue)); + } + } + + @Test + void anEfsFileSystemIsCheckedWithItsTags() { + String blue; + String red; + try (EfsClient admin = AwsTestClients.create(EfsClient.builder(), ACCOUNT, REGION, endpoint)) { + blue = admin.createFileSystem(r -> r.creationToken("blue-" + suffix()) + .tags(t -> t.key("team").value("blue"))).fileSystemId(); + red = admin.createFileSystem(r -> r.creationToken("red-" + suffix()) + .tags(t -> t.key("team").value("red"))).fileSystemId(); + for (String id : new String[] {blue, red}) { + cleanup.register(() -> { + try (EfsClient owner = AwsTestClients.create(EfsClient.builder(), ACCOUNT, REGION, endpoint)) { + owner.deleteFileSystem(r -> r.fileSystemId(id)); + } + }); + } + } + UserCredentials user = user("elasticfilesystem:DescribeFileSystems"); + try (EfsClient caller = AwsTestClients.create(EfsClient.builder(), user.accessKeyId(), user.secretAccessKey(), + REGION, endpoint)) { + denied(() -> caller.describeFileSystems(r -> r.fileSystemId(red))); + assertEquals(blue, caller.describeFileSystems(r -> r.fileSystemId(blue)).fileSystems().getFirst() + .fileSystemId()); + } + } + + @Test + void aResolverRuleIsCheckedWithItsTags() { + String admin = auth(ACCOUNT, REGION.id(), "route53resolver"); + String blue = resolverRule(admin, "blue"); + String red = resolverRule(admin, "red"); + UserCredentials user = user("route53resolver:GetResolverRule"); + String caller = auth(user.accessKeyId(), REGION.id(), "route53resolver"); + Route53ResolverRequests.call("GetResolverRule", "{\"ResolverRuleId\":\"" + red + "\"}", caller) + .statusCode(400).body(containsString("AccessDeniedException")) + .body(containsString("not authorized to perform: route53resolver:GetResolverRule")); + Route53ResolverRequests.call("GetResolverRule", "{\"ResolverRuleId\":\"" + blue + "\"}", caller) + .statusCode(200); + } + + private String resolverRule(String authorization, String team) { + String id = Route53ResolverRequests.call("CreateResolverRule", """ + {"CreatorRequestId":"%s","Name":"%s","RuleType":"SYSTEM","DomainName":"%s.example.com", + "Tags":[{"Key":"team","Value":"%s"}]}""".formatted(suffix(), team + "-" + suffix(), team, team), + authorization).statusCode(200).extract().path("ResolverRule.Id"); + cleanup.register(() -> Route53ResolverRequests.call("DeleteResolverRule", + "{\"ResolverRuleId\":\"" + id + "\"}", authorization)); + return id; + } + + private UserCredentials user(String action) { + String name = "tags-" + suffix(); + String authorization = auth(ACCOUNT, REGION.id(), "iam"); + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, name); + EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, name, "blue", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"%s","Resource":"*",%s}]}""" + .formatted(action, BLUE_ONLY)); + return credentials; + } + + private static void denied(Runnable call) { + AwsServiceException e = assertThrows(AwsServiceException.class, call::run); + assertTrue(e.awsErrorDetails().errorCode().startsWith("AccessDenied"), e.awsErrorDetails().errorCode()); + } + + private static String suffix() { + return UUID.randomUUID().toString().substring(0, 8); + } +}