From 66eb95661e7cb94cfa5148e3103785dbf2e5dd79 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:38:18 -0400 Subject: [PATCH] fix(ssm): give resource-tag conditions the tags of the resource a request names (#8691) The generated request resources give SSM's parameter, document and association types the aws:ResourceTag/ key (and ssm:resourceTag/ for the first two), but SsmService answered no tags, so a condition on an SSM resource's tags saw none. SsmService.storedTags now reads the parameter, document or association stored under the ARN in the account and Region it names, in place, matched on the whole ARN; a parameter ARN names / before , as tagging reads it. Tag writes now put a new map in place of the held one, a parameter's filled one entry at a time so the listed order holds, and the parameter tag writes the CloudFormation provisioner calls take the service's lock as the others do; the tag fields are volatile. --- docs/services/iam.md | 6 +- .../aws/core/common/StoredResourceArns.java | 7 +- .../io/floci/aws/services/ssm/SsmService.java | 89 ++++++++++++++++--- .../aws/services/ssm/model/Parameter.java | 2 +- .../services/ssm/model/SsmAssociation.java | 2 +- .../aws/services/ssm/model/SsmDocument.java | 2 +- ...estResourceEnforcementIntegrationTest.java | 62 +++++++++++-- .../aws/services/ssm/SsmServiceTest.java | 48 ++++++++++ 8 files changed, 191 insertions(+), 27 deletions(-) diff --git a/docs/services/iam.md b/docs/services/iam.md index 90e5f51033..cc4bb9a142 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3190,9 +3190,9 @@ floci populates: state machines, their versions and executions (the state machine's tags) and activities, CodeBuild for its projects and report groups, Athena for its workgroups and data catalogs, Redshift Serverless for its namespaces, workgroups and snapshots, DynamoDB for its tables and their indexes (the table's tags), ECR for its - repositories, and Redshift for its clusters, snapshots, parameter groups, subnet groups, snapshot copy grants, - snapshot schedules, event subscriptions and integrations. Tag keys differing only in case are one condition key - holding every value. + repositories, Redshift for its clusters, snapshots, parameter groups, subnet groups, snapshot copy grants, + snapshot schedules, event subscriptions and integrations, and SSM for its parameters, documents and associations. + 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 0ebdd62e1e..062004965c 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -36,9 +36,10 @@ import java.util.Optional; * workgroup or a data catalog; Redshift Serverless, for the tags of a namespace, a workgroup or a snapshot; DynamoDB, * for the tags of a table and its indexes; ECR, for the tags of a repository; Redshift, for the key a snapshot records * and the tags of a cluster, a snapshot, a parameter group, a subnet group, a snapshot copy grant, a snapshot - * schedule, an event subscription or an integration); 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.

+ * schedule, an event subscription or an integration; SSM, for the parameter a legacy ARN names, the document of + * another account an association runs and the tags of a parameter, a document or an association); 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/ssm/SsmService.java b/src/main/java/io/floci/aws/services/ssm/SsmService.java index 2b7adb5dfe..b31d2691e6 100644 --- a/src/main/java/io/floci/aws/services/ssm/SsmService.java +++ b/src/main/java/io/floci/aws/services/ssm/SsmService.java @@ -59,6 +59,8 @@ public class SsmService implements ResourceProvider, StoredResourceArns { private static final String PUBLIC_PARAMETER_PREFIX = "/aws/service/"; private static final String DOCUMENT_PREFIX = "document/"; + private static final String PARAMETER_PREFIX = "parameter/"; + private static final String ASSOCIATION_PREFIX = "association/"; private static final String ECS_AL2023_RECOMMENDED = "/aws/service/ecs/optimized-ami/amazon-linux-2023/recommended"; private static final String ECS_AL2023_ARM64_RECOMMENDED = @@ -1154,8 +1156,9 @@ public class SsmService implements ResourceProvider, StoredResourceArns { } /** - * Applies {@code change} to the tags of the document or association {@code resourceId} names and stores - * it; {@code false}, changing nothing, for any other {@code resourceType}. + * Applies {@code change} to a copy of the tags of the document or association {@code resourceId} names, puts the + * copy in place of the held map and stores it; {@code false}, changing nothing, for any other + * {@code resourceType}. */ private boolean updateTags(String resourceType, String resourceId, String region, Consumer> change) { @@ -1163,12 +1166,16 @@ public class SsmService implements ResourceProvider, StoredResourceArns { switch (resourceType) { case "Document" -> { SsmDocument document = taggableDocument(resourceId, region); - change.accept(document.getTags()); + Map updated = new LinkedHashMap<>(document.getTags()); + change.accept(updated); + document.setTags(updated); documentStore.put(storageKey, document); } case "Association" -> { SsmAssociation association = taggableAssociation(resourceId, region); - change.accept(association.getTags()); + Map updated = new LinkedHashMap<>(association.getTags()); + change.accept(updated); + association.setTags(updated); associationStore.put(storageKey, association); } default -> { @@ -1190,17 +1197,16 @@ public class SsmService implements ResourceProvider, StoredResourceArns { return new AwsException("InvalidResourceId", "Resource " + resourceId + " not found.", 400); } - public void addTagsToResource(String resourceId, Map tags, String region) { + public synchronized void addTagsToResource(String resourceId, Map tags, String region) { validateTagKeys(tags); String storageKey = regionKey(region, parameterTagName(resourceId, region)); Parameter param = parameterStore.get(storageKey) .orElseThrow(() -> new AwsException("InvalidResourceId", "Resource " + resourceId + " not found.", 400)); - if (param.getTags() == null) { - param.setTags(new HashMap<>()); - } - param.getTags().putAll(tags); + Map updated = copyOfTags(param); + updated.putAll(tags); + param.setTags(updated); parameterStore.put(storageKey, param); LOG.debugv("Added tags to parameter: {0}", resourceId); } @@ -1257,21 +1263,78 @@ public class SsmService implements ResourceProvider, StoredResourceArns { return param.getTags() != null ? param.getTags() : Map.of(); } - public void removeTagsFromResource(String resourceId, List tagKeys, String region) { + public synchronized void removeTagsFromResource(String resourceId, List tagKeys, String region) { String storageKey = regionKey(region, parameterTagName(resourceId, region)); Parameter param = parameterStore.get(storageKey) .orElseThrow(() -> new AwsException("InvalidResourceId", "Resource " + resourceId + " not found.", 400)); if (param.getTags() != null) { - for (String key : tagKeys) { - param.getTags().remove(key); - } + Map updated = copyOfTags(param); + tagKeys.forEach(updated::remove); + param.setTags(updated); parameterStore.put(storageKey, param); } LOG.debugv("Removed tags from parameter: {0}", resourceId); } + /** + * A new map of the parameter's tags, to put in place of the held one: filled one entry at a time, as the held map + * was, so ListTagsForResource lists them in the same order. + */ + private static Map copyOfTags(Parameter parameter) { + Map copy = new HashMap<>(); + if (parameter.getTags() != null) { + parameter.getTags().forEach(copy::put); + } + return copy; + } + + /** + * The tags held on the parameter, document or association stored under {@code arn}, in the account and Region it + * names, read in place and matched on the whole ARN; empty for an ARN naming nothing stored. A parameter ARN names + * {@code /} before {@code }, as the tagging operations read it. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "ssm")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String account = parsed.accountId(); + String region = parsed.region(); + String resource = parsed.resource(); + if (account.isEmpty() || !arn.equals(AwsArnUtils.Arn.of("ssm", region, account, resource).toString())) { + return Map.of(); + } + Map tags = null; + if (resource.startsWith(PARAMETER_PREFIX)) { + String name = resource.substring(PARAMETER_PREFIX.length()); + tags = AccountAwareStorageBackend.readInAccount(parameterStore, account, regionKey(region, "/" + name)) + .or(() -> AccountAwareStorageBackend.readInAccount(parameterStore, account, + regionKey(region, name))) + .filter(parameter -> arn.equals(parameter.getArn())) + .map(Parameter::getTags).orElse(null); + } else if (resource.startsWith(DOCUMENT_PREFIX)) { + tags = AccountAwareStorageBackend.readInAccount(documentStore, account, + regionKey(region, resource.substring(DOCUMENT_PREFIX.length()))).map(SsmDocument::getTags) + .orElse(null); + } else if (resource.startsWith(ASSOCIATION_PREFIX)) { + tags = AccountAwareStorageBackend.readInAccount(associationStore, account, + regionKey(region, resource.substring(ASSOCIATION_PREFIX.length()))).map(SsmAssociation::getTags) + .orElse(null); + } + Map held = new LinkedHashMap<>(); + if (tags != null) { + tags.forEach((key, value) -> { + if (key != null && value != null) { + held.put(key, value); + } + }); + } + return held; + } + /** * Attaches or replaces the parameter's resource policy. A parameter holds one policy, so * replacing it takes the current {@code policyId} and {@code policyHash}, which keeps two diff --git a/src/main/java/io/floci/aws/services/ssm/model/Parameter.java b/src/main/java/io/floci/aws/services/ssm/model/Parameter.java index aafd463b0d..219b6b7f26 100644 --- a/src/main/java/io/floci/aws/services/ssm/model/Parameter.java +++ b/src/main/java/io/floci/aws/services/ssm/model/Parameter.java @@ -59,7 +59,7 @@ public class Parameter { @JsonProperty("Tags") @JsonAlias({"tags", "Tags"}) - private Map tags = new HashMap<>(); + private volatile Map tags = new HashMap<>(); // The SecureString value as KMS encrypted it on PutParameter, returned by a read without WithDecryption. @JsonProperty("EncryptedValue") diff --git a/src/main/java/io/floci/aws/services/ssm/model/SsmAssociation.java b/src/main/java/io/floci/aws/services/ssm/model/SsmAssociation.java index a11338b2ba..26c94fe686 100644 --- a/src/main/java/io/floci/aws/services/ssm/model/SsmAssociation.java +++ b/src/main/java/io/floci/aws/services/ssm/model/SsmAssociation.java @@ -63,7 +63,7 @@ public class SsmAssociation { private String associationVersion; @JsonProperty("Tags") - private Map tags = new LinkedHashMap<>(); + private volatile Map tags = new LinkedHashMap<>(); public SsmAssociation() {} diff --git a/src/main/java/io/floci/aws/services/ssm/model/SsmDocument.java b/src/main/java/io/floci/aws/services/ssm/model/SsmDocument.java index 1ab3db761a..faf5832430 100644 --- a/src/main/java/io/floci/aws/services/ssm/model/SsmDocument.java +++ b/src/main/java/io/floci/aws/services/ssm/model/SsmDocument.java @@ -47,7 +47,7 @@ public class SsmDocument { private Map versions = new LinkedHashMap<>(); @JsonProperty("Tags") - private Map tags = new LinkedHashMap<>(); + private volatile Map tags = new LinkedHashMap<>(); public SsmDocument() {} diff --git a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java index ea5365fa1e..3713f50440 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -664,16 +664,68 @@ class IamRequestResourceEnforcementIntegrationTest { "{\"resourceArn\":\"" + arns + other + "\"}"), "ecr:ListTagsForResource"); } + /** + * An {@code ssm:resourceTag} or {@code aws:ResourceTag} condition reads the tags SSM holds on the parameter or the + * document a request names, so an allow on one team's tag lets the caller read that team's and not another's. + */ + @Test + void anSsmResourceTagConditionReadsTheTagsOfTheParameterAndTheDocument() { + String tagged = ssmParameter("/res-tag/" + suffix(), "data"); + String other = ssmParameter("/res-tag/" + suffix(), "web"); + String taggedDocument = ssmDocument("res-tag-doc-" + suffix(), "data"); + String otherDocument = ssmDocument("res-tag-doc-" + suffix(), "web"); + + User user = user("res-ssm-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":\"ssm:GetParameter\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"ssm:resourceTag/team\":\"data\"}}}," + + "{\"Effect\":\"Allow\",\"Action\":\"ssm:DescribeDocument\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + send(user, "ssm", "AmazonSSM.GetParameter", "1.1", "{\"Name\":\"" + tagged + "\"}").statusCode(200); + refusedJson(send(user, "ssm", "AmazonSSM.GetParameter", "1.1", "{\"Name\":\"" + other + "\"}"), + "ssm:GetParameter"); + send(user, "ssm", "AmazonSSM.DescribeDocument", "1.1", "{\"Name\":\"" + taggedDocument + "\"}") + .statusCode(200); + refusedJson(send(user, "ssm", "AmazonSSM.DescribeDocument", "1.1", "{\"Name\":\"" + otherDocument + "\"}"), + "ssm:DescribeDocument"); + } + + /** An SSM String parameter of the name, tagged with the team, deleted afterwards. */ + private String ssmParameter(String name, String team) { + return created("ssm", "AmazonSSM.PutParameter", "{\"Name\":\"" + name + "\",\"Value\":\"v\",\"Type\":" + + "\"String\",\"Tags\":" + teamTag(team) + "}", "AmazonSSM.DeleteParameter", + "{\"Name\":\"" + name + "\"}", name); + } + + /** An SSM Command document of the name, tagged with the team, deleted afterwards. */ + private String ssmDocument(String name, String team) { + return created("ssm", "AmazonSSM.CreateDocument", "{\"Name\":\"" + name + "\",\"DocumentType\":\"Command\"," + + "\"Content\":\"{\\\"schemaVersion\\\":\\\"2.2\\\",\\\"mainSteps\\\":[]}\",\"Tags\":" + + teamTag(team) + "}", "AmazonSSM.DeleteDocument", "{\"Name\":\"" + name + "\"}", name); + } + /** An ECR repository of the name, tagged with the team, deleted afterwards. */ private String ecrRepository(String name, String team) { - adminJson("ecr", "AmazonEC2ContainerRegistry_V20150921.CreateRepository").body("{\"repositoryName\":\"" - + name + "\",\"tags\":[{\"Key\":\"team\",\"Value\":\"" + team + "\"}]}").post("/").then() - .statusCode(200); - cleanup.register(() -> adminJson("ecr", "AmazonEC2ContainerRegistry_V20150921.DeleteRepository") - .body("{\"repositoryName\":\"" + name + "\",\"force\":true}").post("/")); + return created("ecr", "AmazonEC2ContainerRegistry_V20150921.CreateRepository", "{\"repositoryName\":\"" + + name + "\",\"tags\":" + teamTag(team) + "}", "AmazonEC2ContainerRegistry_V20150921.DeleteRepository", + "{\"repositoryName\":\"" + name + "\",\"force\":true}", name); + } + + /** + * {@code name}, after an administrator creates the resource with the JSON 1.1 {@code create} call and registers + * the {@code delete} call that removes it after the test. + */ + private String created(String service, String create, String createBody, String delete, String deleteBody, + String name) { + adminJson(service, create).body(createBody).post("/").then().statusCode(200); + cleanup.register(() -> adminJson(service, delete).body(deleteBody).post("/")); return name; } + /** A tag list holding the one tag {@code team=}. */ + private static String teamTag(String team) { + return "[{\"Key\":\"team\",\"Value\":\"" + team + "\"}]"; + } + @Test void aDeliveryStreamIsCheckedOnTheArnItsNameGives() { String name = "res-stream-" + suffix(); diff --git a/src/test/java/io/floci/aws/services/ssm/SsmServiceTest.java b/src/test/java/io/floci/aws/services/ssm/SsmServiceTest.java index 129edd84f4..68f2782626 100644 --- a/src/test/java/io/floci/aws/services/ssm/SsmServiceTest.java +++ b/src/test/java/io/floci/aws/services/ssm/SsmServiceTest.java @@ -1660,6 +1660,54 @@ class SsmServiceTest { assertEquals(Map.of("env", "dev"), ssmService.listTagsForResource("/arn/tagged", "us-east-1")); } + @Test + void storedTagsAreTheTagsOfTheParameterDocumentOrAssociationTheWholeArnNamesAndTaggingPutsANewMap() { + String region = "us-east-1"; + String arns = "arn:aws:ssm:us-east-1:000000000000:"; + ssmService.putParameter("/app/db", "v", "String", null, false, Map.of("team", "data"), region); + ssmService.putParameter("plain", "v", "String", null, false, Map.of("team", "web"), region); + ssmService.createDocument("RunIt", "{}", "Command", region); + ssmService.addTagsToResource("Document", "RunIt", Map.of("owner", "ops"), region); + String associationId = ssmService.createAssociation("RunIt", "nightly", null, "i-123", null, null, null, region) + .getAssociationId(); + ssmService.addTagsToResource("Association", associationId, Map.of("cadence", "daily"), region); + + assertEquals(Map.of("team", "data"), ssmService.storedTags(arns + "parameter/app/db")); + assertEquals(Map.of("team", "web"), ssmService.storedTags(arns + "parameter/plain")); + assertEquals(Map.of("owner", "ops"), ssmService.storedTags(arns + "document/RunIt")); + assertEquals(Map.of("cadence", "daily"), ssmService.storedTags(arns + "association/" + associationId)); + // Another Region, another account's parameter of that name, an ARN whose partition is not its Region's and a + // type Floci keeps no record of hold none. + assertEquals(Map.of(), ssmService.storedTags("arn:aws:ssm:us-west-2:000000000000:parameter/app/db")); + assertEquals(Map.of(), ssmService.storedTags("arn:aws:ssm:us-east-1:111122223333:parameter/app/db")); + assertEquals(Map.of(), ssmService.storedTags("arn:aws-us-gov:ssm:us-east-1:000000000000:parameter/app/db")); + assertEquals(Map.of(), ssmService.storedTags(arns + "maintenancewindow/mw-0123456789abcdef0")); + + Map heldParameterTags = ssmService.listTagsForResource("/app/db", region); + Map heldDocumentTags = ssmService.listTagsForResource("Document", "RunIt", region); + ssmService.addTagsToResource("/app/db", Map.of("env", "prod"), region); + ssmService.removeTagsFromResource("Document", "RunIt", List.of("owner"), region); + + assertEquals(Map.of("team", "data"), heldParameterTags); + assertEquals(Map.of("owner", "ops"), heldDocumentTags); + assertEquals(Map.of("team", "data", "env", "prod"), ssmService.storedTags(arns + "parameter/app/db")); + assertEquals(Map.of(), ssmService.storedTags(arns + "document/RunIt")); + } + + /** + * A top-level name stored both with and without its leading slash has one ARN, which AWS's format gives both; it + * names the slashed parameter, as the tagging operations read that ARN. + */ + @Test + void storedTagsOfATopLevelArnAreTheSlashedParametersWhenBothFormsAreStored() { + ssmService.putParameter("twin", "v", "String", null, false, Map.of("form", "bare"), "us-east-1"); + ssmService.putParameter("/twin", "v", "String", null, false, Map.of("form", "slashed"), "us-east-1"); + String arn = "arn:aws:ssm:us-east-1:000000000000:parameter/twin"; + + assertEquals(Map.of("form", "slashed"), ssmService.storedTags(arn)); + assertEquals(Map.of("form", "slashed"), ssmService.listTagsForResource(arn, "us-east-1")); + } + @Test void putParameterOverwriteClearsDescriptionWhenOmitted() { String region = "eu-west-1";