diff --git a/docs/services/iam.md b/docs/services/iam.md index dc16af3c15..90ac23052f 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3071,8 +3071,9 @@ floci populates: its type (`aws:ResourceTag/`, `secretsmanager:ResourceTag/`), which `regen_iam_request_resources.py` reads from the Service Reference for every namespace it reads, valued from the tags the type's service holds on that resource (`StoredResourceArns.storedTags`); a service that holds none leaves them absent. - Secrets Manager answers for its secrets, S3 Tables for its table buckets and tables, and EventBridge - Scheduler for its schedule groups. Tag keys differing only in case are one condition key holding every value. + Secrets Manager answers for its secrets, S3 Tables for its table buckets and tables, EventBridge Scheduler for + its schedule groups, and CloudFormation for its stacks, stack sets and change sets. 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 key names, an ARN for a key the Service Reference types as one. `resourceKeys` in diff --git a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java index 4aec68e485..68892179bb 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -26,10 +26,11 @@ import java.util.Optional; * permission sets are provisioned to; Resource Explorer, for its default view; OAM and RAM, for the sinks, * invitations and shares of other accounts they act on; Secrets Manager, for the secret a name or an ARN names, * random suffix included, and its tags; EventBridge Scheduler, for its default schedule group and its groups' tags; - * CloudFormation, for the stack or the stack set a name names, whose id it minted; S3 Tables, for the table a request - * names by its table bucket, namespace and name, and the tags of a table bucket or a table); looked up lazily by - * {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through {@code Instance} for - * the namespace a request or an ARN is of, so IAM never depends on that service directly.

+ * CloudFormation, for the stack or the stack set a name names, whose id it minted, and the tags of a stack, a stack set + * or a change set; S3 Tables, for the table a request names by its table bucket, namespace and name, and the tags of a + * table bucket or a table); looked up lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver} + * through {@code Instance} for the namespace a request or an ARN is of, so IAM never depends on + * that service directly.

* *

Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find}, * {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index e77391f90d..a2f829190f 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -425,6 +425,34 @@ public class CloudFormationService implements ResourceProvider { return Optional.ofNullable(resolveStack(stackNameOrArn, region, currentAccount())).map(Stack::getStackId); } + /** + * The tags of the live stack, or of the change set, stored under {@code arn} in the account and Region the ARN + * names, by key, which IAM gives a resource-tag condition; empty when there is none. Reads only, matching the + * stack's id or the change set's on the whole ARN. + */ + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "cloudformation")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String resource = parsed.resource(); + if (resource.startsWith("stack/")) { + Stack stack = resolveStack(arn, parsed.region(), parsed.accountId()); + return stack != null && arn.equals(stack.getStackId()) ? stack.tagsSnapshot() : Map.of(); + } + if (!resource.startsWith("changeSet/")) { + return Map.of(); + } + try { + Stack stack = findStackForChangeSetArn(arn, parsed.region(), parsed.accountId()); + ChangeSet changeSet = stack == null ? null + : stack.getChangeSets().get(resolveChangeSetName(arn, parsed.region(), parsed.accountId())); + return changeSet == null || changeSet.getTags() == null ? Map.of() : Map.copyOf(changeSet.getTags()); + } catch (AwsException expected) { + return Map.of(); + } + } + /** * The stack's current parameter values, or an empty map if it does not exist (yet). Used to * resolve {@code UsePreviousValue} on an update before the stack lookup that diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationStoredResourceArns.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationStoredResourceArns.java index 95a5f5a98b..23b34ae838 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationStoredResourceArns.java @@ -5,11 +5,13 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.List; +import java.util.Map; import java.util.Optional; /** * What IAM asks CloudFormation of the resources a request names: the ARN of the stack or the stack set a name names, - * whose id CloudFormation minted, so a request naming one by its name is checked on the ARN AWS checks. + * whose id CloudFormation minted, so a request naming one by its name is checked on the ARN AWS checks; and the tags + * of a stack, a stack set or a change set, which a resource-tag condition reads. */ @ApplicationScoped public class CloudFormationStoredResourceArns implements StoredResourceArns { @@ -39,4 +41,10 @@ public class CloudFormationStoredResourceArns implements StoredResourceArns { default -> Optional.empty(); }; } + + /** The tags of the stack, stack set or change set {@code arn} names, which a resource-tag condition reads. */ + @Override + public Map storedTags(String arn) { + return arn.contains(":stackset/") ? stackSets.storedTags(arn) : stacks.storedTags(arn); + } } diff --git a/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java b/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java index 608af77dd1..42a9ab0c70 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.ServicePrincipals; import io.floci.aws.core.common.SmithyValidationErrors; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.cloudformation.model.ChangeSet; @@ -66,6 +67,7 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen private static final String INSTANCE_CHANGE_SET = "stackset-instance"; private static final String UPDATE_CHANGE_SET = "stackset-update"; private static final String ORGANIZATIONS_ACCESS_KEY = "organizations-access"; + private static final String STACK_SET_RESOURCE = "stackset/"; private static final int STACK_SET_LIMIT = 1000; private static final Pattern STACK_SET_NAME = Pattern.compile("[A-Za-z][A-Za-z0-9-]{0,127}"); private static final Pattern OPERATION_ID = Pattern.compile("[A-Za-z0-9][-A-Za-z0-9]{0,127}"); @@ -211,7 +213,7 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen /** The stack set's ARN, {@code stackset/:} in the request's Region, as AWS gives its StackSetARN. */ /** The stack set's ARN in the Region given, the one the request naming it is in, whatever context runs it. */ public String stackSetArn(StackSet stackSet, String region) { - return regionResolver.buildArn("cloudformation", region, "stackset/" + stackSet.getStackSetId()); + return regionResolver.buildArn("cloudformation", region, STACK_SET_RESOURCE + stackSet.getStackSetId()); } /** @@ -222,6 +224,31 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen return name == null ? Optional.empty() : stackSets.get(name).map(stackSet -> stackSetArn(stackSet, region)); } + /** + * The tags of the stack set stored under {@code arn} in the account the ARN names, a pre-multi-account one of the + * default account read in place, by key, which IAM gives a resource-tag condition; empty when there is none. Reads + * only, matching the stack set's id, {@code :}, on the ARN. + */ + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "cloudformation")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String id = parsed.resource().startsWith(STACK_SET_RESOURCE) + ? parsed.resource().substring(STACK_SET_RESOURCE.length()) : ""; + if (id.indexOf(':') < 1) { + return Map.of(); + } + String name = id.substring(0, id.indexOf(':')); + String account = parsed.accountId(); + Optional stored = stackSets instanceof AccountAwareStorageBackend aware + ? aware.getForAccount(account, name).or(() -> aware.getLegacyForAccount(account, name)) + : stackSets.get(name); + return stored.filter(stackSet -> id.equals(stackSet.getStackSetId())) + .>map(stackSet -> Map.copyOf(stackSet.getTags())) + .orElse(Map.of()); + } + /** The StackSet's permission model, which says whether an update naming no administration role passes the default one. */ @Override public Optional stackSetPermissionModel(String stackSetName) { diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamIntegrationTest.java index b9c6f5b527..835a1c902c 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamIntegrationTest.java @@ -88,6 +88,31 @@ class CloudFormationIamIntegrationTest { "111122223333", "StackInstanceRegion", REGION)), "cloudformation:DescribeStackInstance"); } + /** A resource-tag condition reads the tags CloudFormation holds on the stack or the stack set a request names. */ + @Test + void aResourceTagConditionReadsTheTagsOfTheStackAndTheStackSet() { + String tagged = name(); + String untagged = name(); + call(ACCOUNT, "CreateStack", Map.of("StackName", tagged, "TemplateBody", TEMPLATE, + "Tags.member.1.Key", "team", "Tags.member.1.Value", "data")).statusCode(200); + cleanup.register(() -> call(ACCOUNT, "DeleteStack", Map.of("StackName", tagged))); + stack(untagged); + String taggedSet = name(); + String untaggedSet = name(); + call(ACCOUNT, "CreateStackSet", Map.of("StackSetName", taggedSet, "TemplateBody", TEMPLATE, + "Tags.member.1.Key", "team", "Tags.member.1.Value", "data")).statusCode(200); + cleanup.register(() -> call(ACCOUNT, "DeleteStackSet", Map.of("StackSetName", taggedSet))); + stackSet(untaggedSet); + String user = user("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":" + + "[\"cloudformation:DescribeStacks\",\"cloudformation:DescribeStackSet\"],\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}]}"); + + call(user, "DescribeStacks", Map.of("StackName", tagged)).statusCode(200); + denied(call(user, "DescribeStacks", Map.of("StackName", untagged)), "cloudformation:DescribeStacks"); + call(user, "DescribeStackSet", Map.of("StackSetName", taggedSet)).statusCode(200); + denied(call(user, "DescribeStackSet", Map.of("StackSetName", untaggedSet)), "cloudformation:DescribeStackSet"); + } + private String stack(String name) { String id = call(ACCOUNT, "CreateStack", Map.of("StackName", name, "TemplateBody", TEMPLATE)).statusCode(200) .extract().xmlPath().getString("CreateStackResponse.CreateStackResult.StackId"); diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStoredTagsTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStoredTagsTest.java new file mode 100644 index 0000000000..98639bc7b5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStoredTagsTest.java @@ -0,0 +1,39 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.services.cloudformation.model.ChangeSet; +import io.floci.aws.services.cloudformation.model.Stack; +import io.floci.aws.services.cloudformation.provisioners.CfnResourceDispatcher; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; + +class CloudFormationStoredTagsTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String TEMPLATE = + "{\"Resources\":{\"Handle\":{\"Type\":\"AWS::CloudFormation::WaitConditionHandle\"}}}"; + + /** + * The tags IAM gives a resource-tag condition: the stack's or the change set's, read on its whole ARN in the + * account and Region it names; none for anything else. + */ + @Test + void storedTagsReadsTheStackOrTheChangeSetItsArnNames() { + CloudFormationService cfn = CloudFormationServiceFixture.create(mock(CfnResourceDispatcher.class)); + ChangeSet changeSet = cfn.createChangeSet("tagged", "first", "CREATE", TEMPLATE, null, Map.of(), List.of(), + Map.of("team", "data"), REGION, ACCOUNT); + Stack stack = cfn.describeStacks("tagged", REGION, ACCOUNT).getFirst(); + + assertEquals(Map.of("team", "data"), cfn.storedTags(changeSet.getChangeSetId())); + assertEquals(stack.tagsSnapshot(), cfn.storedTags(stack.getStackId())); + assertEquals(Map.of(), cfn.storedTags(changeSet.getChangeSetId().replace("/first/", "/other/"))); + assertEquals(Map.of(), cfn.storedTags(stack.getStackId().replace(":" + ACCOUNT + ":", ":111122223333:"))); + assertEquals(Map.of(), cfn.storedTags(changeSet.getChangeSetId().replace(REGION, "eu-west-1"))); + assertEquals(Map.of(), cfn.storedTags("arn:aws:s3:::tagged")); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/StackSetTagReadTest.java b/src/test/java/io/floci/aws/services/cloudformation/StackSetTagReadTest.java index 4cd25a188e..8f91ddafbc 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/StackSetTagReadTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/StackSetTagReadTest.java @@ -26,6 +26,17 @@ class StackSetTagReadTest { service.createStackSet(SET, "{\"Resources\":{}}", null, null, initialTags, null); } + /** The tags IAM gives a resource-tag condition: the stack set's, read on its ARN in the account it names. */ + @Test + void storedTagsReadsTheStackSetItsArnNames() { + String arn = service.stackSetArn(SET, "us-east-1").orElseThrow(); + + assertEquals(initialTags, service.storedTags(arn)); + assertEquals(Map.of(), service.storedTags(arn.replace(":000000000000:", ":111122223333:"))); + assertEquals(Map.of(), service.storedTags(arn.substring(0, arn.lastIndexOf(':')) + ":not-its-id")); + assertEquals(Map.of(), service.storedTags(arn.replace("stackset/", "stack/"))); + } + @Test void updatingTagsLeavesAnActiveReadOnItsOriginalMap() { Map tagsBeingRead = service.describeStackSet(SET).getTags();