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 /<name> before <name>, 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.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 21:38:18 -04:00
1 parent 8b1de6cdbe
commit 66eb95661e
8 files changed
+191 -27

No files matched your search

+3 -3
View File
@@ -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
@@ -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<StoredResourceArns>} for the namespace a request or an
* ARN is of, so IAM never depends on that service directly.</p>
* 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<StoredResourceArns>}
* for the namespace a request or an ARN is of, so IAM never depends on that service directly.</p>
*
* <p>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
@@ -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<Map<String, String>> 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<String, String> 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<String, String> 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<String, String> tags, String region) {
public synchronized void addTagsToResource(String resourceId, Map<String, String> 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<String, String> 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<String> tagKeys, String region) {
public synchronized void removeTagsFromResource(String resourceId, List<String> 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<String, String> 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<String, String> copyOfTags(Parameter parameter) {
Map<String, String> 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 /<name>} before {@code <name>}, as the tagging operations read it.
*/
@Override
public Map<String, String> 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<String, String> 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<String, String> 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
@@ -59,7 +59,7 @@ public class Parameter {
@JsonProperty("Tags")
@JsonAlias({"tags", "Tags"})
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
// The SecureString value as KMS encrypted it on PutParameter, returned by a read without WithDecryption.
@JsonProperty("EncryptedValue")
@@ -63,7 +63,7 @@ public class SsmAssociation {
private String associationVersion;
@JsonProperty("Tags")
private Map<String, String> tags = new LinkedHashMap<>();
private volatile Map<String, String> tags = new LinkedHashMap<>();
public SsmAssociation() {}
@@ -47,7 +47,7 @@ public class SsmDocument {
private Map<String, String> versions = new LinkedHashMap<>();
@JsonProperty("Tags")
private Map<String, String> tags = new LinkedHashMap<>();
private volatile Map<String, String> tags = new LinkedHashMap<>();
public SsmDocument() {}
@@ -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=<team>}. */
private static String teamTag(String team) {
return "[{\"Key\":\"team\",\"Value\":\"" + team + "\"}]";
}
@Test
void aDeliveryStreamIsCheckedOnTheArnItsNameGives() {
String name = "res-stream-" + suffix();
@@ -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<String, String> heldParameterTags = ssmService.listTagsForResource("/app/db", region);
Map<String, String> 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";