fix(cloudmap): give resource-tag conditions the tags of the namespace or service a request names (#8932)

The generated request resources give Cloud Map's namespace and service
types the aws:ResourceTag/ key, but no service answered the
servicediscovery namespace's stored tags, so a condition on their tags
saw none. CloudMapService now answers it: storedTags reads the namespace
or the service by the id its ARN ends in, in the request's account, in
place, the id the handlers find it by in every Region, so a request sent
to another Region is checked with the tags of the resource it acts on; a
tag without a value reads as an empty one. TagResource and UntagResource
changed the tag map in place with no lock; they now give the resource a
new map one call at a time, and the tags fields are volatile.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 21:05:39 -04:00
1 parent 813f89bd8e
commit 26dc6d79ed
7 files changed
+214 -18

No files matched your search

+2 -2
View File
@@ -3526,8 +3526,8 @@ floci populates:
and endpoint groups, EMR Serverless for its applications, job runs and sessions, EMR on EKS for its virtual clusters,
job runs, managed endpoints, job templates and security configurations, Cost Explorer for its anomaly monitors and
subscriptions, Security Hub for its hubs and configuration policies, Control Tower for its landing zones and enabled
controls, and GuardDuty for its detectors and Malware Protection plans. Tag keys differing only in case are one
condition key holding every value.
controls, GuardDuty for its detectors and Malware Protection plans, and Cloud Map for its namespaces and services. 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
@@ -55,10 +55,10 @@ import java.util.Optional;
* Serverless, for the tags of an application, a job run or a session; EMR on EKS, for the tags of a virtual cluster, a
* job run, a managed endpoint, a job template or a security configuration; Cost Explorer, for the tags of an anomaly
* monitor or subscription; Security Hub, for the tags of a hub or a configuration policy; Control Tower, for the tags
* of a landing zone or an enabled control; GuardDuty, for the tags of a detector or a Malware Protection plan); 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>
* of a landing zone or an enabled control; GuardDuty, for the tags of a detector or a Malware Protection plan; Cloud
* Map, for the tags of a namespace or a service); 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
@@ -14,6 +14,7 @@ import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.common.dns.DnsAnswer;
import io.floci.aws.core.common.dns.DnsRecord;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
@@ -56,9 +57,12 @@ import java.util.function.Function;
* whose status reaches SUCCESS immediately (or after a configurable delay).
*/
@ApplicationScoped
public class CloudMapService {
public class CloudMapService implements StoredResourceArns {
private static final Logger LOG = Logger.getLogger(CloudMapService.class);
private static final String SERVICE = "servicediscovery";
private static final String NAMESPACE_RESOURCE = "namespace/";
private static final String SERVICE_RESOURCE = "service/";
private static final String ALNUM = "abcdefghijklmnopqrstuvwxyz0123456789";
/** Route 53 answers a service discovery query with at most eight records. */
private static final int MAX_DNS_ANSWERS = 8;
@@ -161,7 +165,7 @@ public class CloudMapService {
if (tags != null) {
ns.setTags(tags);
}
ns.setArn(regionResolver.buildArn("servicediscovery", region, "namespace/" + ns.getId()));
ns.setArn(regionResolver.buildArn(SERVICE, region, NAMESPACE_RESOURCE + ns.getId()));
return ns;
}
@@ -259,7 +263,7 @@ public class CloudMapService {
if (tags != null) {
service.setTags(tags);
}
service.setArn(regionResolver.buildArn("servicediscovery", region, "service/" + service.getId()));
service.setArn(regionResolver.buildArn(SERVICE, region, SERVICE_RESOURCE + service.getId()));
serviceStore.put(service.getId(), service);
if (nsId != null) {
namespaceStore.get(nsId).ifPresent(n -> {
@@ -860,28 +864,83 @@ public class CloudMapService {
return taggable(resourceArn).getTags();
}
public void tagResource(String resourceArn, Map<String, String> tags) {
/**
* Gives the namespace or the service a new map holding its tags and {@code tags}. Tag calls run one at a time, so
* two of them never lose one's tags, and a lookup reads one whole set.
*/
public synchronized void tagResource(String resourceArn, Map<String, String> tags) {
Object resource = taggableRaw(resourceArn);
if (resource instanceof Namespace ns) {
ns.getTags().putAll(tags);
Map<String, String> merged = new LinkedHashMap<>(ns.getTags());
merged.putAll(tags);
ns.setTags(merged);
namespaceStore.put(ns.getId(), ns);
} else if (resource instanceof Service s) {
s.getTags().putAll(tags);
Map<String, String> merged = new LinkedHashMap<>(s.getTags());
merged.putAll(tags);
s.setTags(merged);
serviceStore.put(s.getId(), s);
}
}
public void untagResource(String resourceArn, List<String> tagKeys) {
/** Gives the namespace or the service a new map without {@code tagKeys}, one tag call at a time. */
public synchronized void untagResource(String resourceArn, List<String> tagKeys) {
Object resource = taggableRaw(resourceArn);
if (resource instanceof Namespace ns) {
tagKeys.forEach(ns.getTags()::remove);
Map<String, String> remaining = new LinkedHashMap<>(ns.getTags());
tagKeys.forEach(remaining::remove);
ns.setTags(remaining);
namespaceStore.put(ns.getId(), ns);
} else if (resource instanceof Service s) {
tagKeys.forEach(s.getTags()::remove);
Map<String, String> remaining = new LinkedHashMap<>(s.getTags());
tagKeys.forEach(remaining::remove);
s.setTags(remaining);
serviceStore.put(s.getId(), s);
}
}
@Override
public String namespace() {
return SERVICE;
}
/** A request names a namespace or a service by the id its ARN ends in: nothing to find. */
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
/**
* The tags of the namespace or the service whose ARN is {@code arn}, in the request's account, where the tag
* handlers read: an ARN of another account names none. Each is read in place by the id its ARN ends in, one stored
* before storage was account-aware included. That is the id the handlers find it by, in every Region, so an ARN
* naming another Region than the resource's reads its tags too, as a request sent there acts on it. A tag without
* a value reads as an empty one. Tag calls give the resource a new map, so the read is of one whole set.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, SERVICE)) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String account = regionResolver.getAccountId();
if (!parsed.accountId().equals(account)) {
return Map.of();
}
String resource = parsed.resource();
Optional<Map<String, String>> tags = Optional.empty();
if (resource.startsWith(NAMESPACE_RESOURCE)) {
tags = AccountAwareStorageBackend.readInAccount(namespaceStore, account,
resource.substring(NAMESPACE_RESOURCE.length())).map(Namespace::getTags);
} else if (resource.startsWith(SERVICE_RESOURCE)) {
tags = AccountAwareStorageBackend.readInAccount(serviceStore, account,
resource.substring(SERVICE_RESOURCE.length())).map(Service::getTags);
}
Map<String, String> copy = new LinkedHashMap<>();
tags.orElse(Map.of()).forEach((key, value) -> copy.put(key, value == null ? "" : value));
return copy;
}
private interface Taggable { Map<String, String> getTags(); }
private Taggable taggable(String resourceArn) {
@@ -896,7 +955,7 @@ public class CloudMapService {
if (resourceArn == null) {
throw new AwsException("InvalidInput", "ResourceARN is required.", 400);
}
String id = AwsArnUtils.resourceIfArnFor(resourceArn, "servicediscovery")
String id = AwsArnUtils.resourceIfArnFor(resourceArn, SERVICE)
.map(resource -> resource.substring(resource.lastIndexOf('/') + 1))
.orElse(resourceArn);
Optional<Namespace> ns = namespaceStore.get(id);
@@ -25,7 +25,7 @@ public class Namespace {
private String region;
private String vpc;
private String hostedZoneId;
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
public Namespace() {}
@@ -30,7 +30,7 @@ public class Service {
private String creatorRequestId;
private String region;
private long revision;
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
public Service() {}
@@ -0,0 +1,77 @@
package io.floci.aws.services.cloudmap;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.cloudmap.model.Namespace;
import io.floci.aws.services.cloudmap.model.Service;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
/** IAM's lookup of the tags Cloud Map holds on a namespace or a service. */
class CloudMapStoredTagsTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
/**
* The lookup reads the tags of the namespace or the service the ARN names, as the tag calls leave them, a tag
* without a value as an empty one, and those of the one the handlers find by its id for an ARN naming another
* Region; nothing for another account's, an unknown resource's or another service's ARN.
*/
@Test
void storedTagsAreTheTagsOfTheNamespaceOrServiceTheArnNames() {
CloudMapService service = service(new InMemoryStorageFactory(ACCOUNT));
String namespaceId = service.createHttpNamespace("stored-tags", null, null,
Map.of("team", "web", "env", "dev"), REGION).getTargets().get("NAMESPACE");
String namespaceArn = service.getNamespace(namespaceId).getArn();
service.tagResource(namespaceArn, Map.of("team", "data"));
service.untagResource(namespaceArn, List.of("env"));
Map<String, String> noValue = new HashMap<>();
noValue.put("owner", null);
Service svc = service.createService("stored-tags", namespaceId, null, null, null, null, null, null,
noValue, REGION);
service.tagResource(svc.getArn(), Map.of("team", "ops"));
assertEquals("servicediscovery", service.namespace());
assertEquals(Map.of("team", "data"), service.storedTags(namespaceArn));
assertEquals(Map.of("owner", "", "team", "ops"), service.storedTags(svc.getArn()));
assertTrue(service.storedTags(namespaceArn.replace(ACCOUNT, "111122223333")).isEmpty());
assertEquals(Map.of("team", "data"), service.storedTags(namespaceArn.replace(REGION, "us-west-2")));
assertTrue(service.storedTags(namespaceArn.replace(namespaceId, "ns-missing")).isEmpty());
assertTrue(service.storedTags(svc.getArn().replace("service/", "namespace/")).isEmpty());
assertTrue(service.storedTags("arn:aws:ec2:us-east-1:000000000000:instance/i-0123456789abcdef0").isEmpty());
}
/** A namespace stored before storage was account-aware is read in place: the lookup migrates nothing. */
@Test
void storedTagsReadAPreAccountAwareNamespaceInPlace() {
InMemoryStorage<String, Namespace> raw = new InMemoryStorage<>();
CloudMapService service =
service(new InMemoryStorageFactory(ACCOUNT).withStore("cloudmap-namespaces.json", raw));
Namespace legacy = new Namespace();
legacy.setId("ns-legacy");
legacy.setArn("arn:aws:servicediscovery:us-east-1:000000000000:namespace/ns-legacy");
legacy.setTags(Map.of("team", "data"));
raw.put("ns-legacy", legacy);
assertEquals(Map.of("team", "data"), service.storedTags(legacy.getArn()));
assertEquals(Set.of("ns-legacy"), raw.keys());
}
private CloudMapService service(InMemoryStorageFactory storage) {
return new CloudMapService(storage, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
new RegionResolver(REGION, ACCOUNT), new ObjectMapper(), null);
}
}
@@ -1116,6 +1116,66 @@ class IamRequestResourceEnforcementIntegrationTest {
"servicediscovery:CreateService");
}
/**
* An {@code aws:ResourceTag} condition reads the tags Cloud Map holds on the namespace or the service a request
* names by its id, as a tag call or the create leaves them, so an allow on one team's tag lets the caller read that
* team's namespace and service and not another's.
*/
@Test
void aCloudMapResourceTagConditionReadsTheTagsOfTheNamespaceAndTheService() {
String tagged = cloudMapNamespace("res-ns-team-" + suffix());
String other = cloudMapNamespace("res-ns-team-" + suffix());
adminJson("servicediscovery", "Route53AutoNaming_v20170314.TagResource").body("{\"ResourceARN\":\""
+ "arn:aws:servicediscovery:" + REGION + ":" + ACCOUNT + ":namespace/" + tagged + "\",\"Tags\":"
+ teamTag("data") + "}").post("/").then().statusCode(200);
String taggedService = cloudMapService(tagged, "data");
String otherService = cloudMapService(other, "web");
User user = user("res-cloud-map-team");
user.policy(onTeam("servicediscovery:GetNamespace") + "," + onTeam("servicediscovery:GetService"));
cloudMap(user, "GetNamespace", tagged).statusCode(200);
refusedJson(cloudMap(user, "GetNamespace", other), "servicediscovery:GetNamespace");
cloudMap(user, "GetService", taggedService).statusCode(200);
refusedJson(cloudMap(user, "GetService", otherService), "servicediscovery:GetService");
}
/**
* Cloud Map's handlers find a namespace by its id in every Region, so a request sent to another Region acts on it
* and is checked with its tags: a deny on its team's tag holds there too.
*/
@Test
void aCloudMapTagDenyHoldsForARequestSentToAnotherRegion() {
String namespaceId = cloudMapNamespace("res-ns-deny-" + suffix());
adminJson("servicediscovery", "Route53AutoNaming_v20170314.TagResource").body("{\"ResourceARN\":\""
+ "arn:aws:servicediscovery:" + REGION + ":" + ACCOUNT + ":namespace/" + namespaceId + "\",\"Tags\":"
+ teamTag("data") + "}").post("/").then().statusCode(200);
User user = user("res-cloud-map-deny");
user.policy(allowOn("servicediscovery:GetNamespace", "*") + ",{\"Effect\":\"Deny\",\"Action\":"
+ "\"servicediscovery:GetNamespace\",\"Resource\":\"*\",\"Condition\":{\"StringEquals\":"
+ "{\"aws:ResourceTag/team\":\"data\"}}}");
refusedJson(given().header("Authorization", auth(user.accessKeyId(), "us-west-2", "servicediscovery"))
.header("X-Amz-Target", "Route53AutoNaming_v20170314.GetNamespace")
.contentType("application/x-amz-json-1.1").body("{\"Id\":\"" + namespaceId + "\"}").post("/").then(),
"servicediscovery:GetNamespace");
}
/** An allow of {@code action} on every resource whose {@code team} tag is {@code data}. */
private static String onTeam(String action) {
return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}";
}
/** A Cloud Map service in the namespace, tagged with the team when created and deleted after the test; its id. */
private String cloudMapService(String namespaceId, String team) {
String id = adminJson("servicediscovery", "Route53AutoNaming_v20170314.CreateService")
.body("{\"Name\":\"res-svc-" + suffix() + "\",\"NamespaceId\":\"" + namespaceId + "\",\"Tags\":"
+ teamTag(team) + "}").post("/").then().statusCode(200).extract().path("Service.Id");
cleanup.register(() -> adminJson("servicediscovery", "Route53AutoNaming_v20170314.DeleteService")
.body("{\"Id\":\"" + id + "\"}").post("/").then().statusCode(200));
return id;
}
/** A service's tags are checked on the service it creates, not on the namespace it creates it in. */
@Test
void aServicesTagsAreCheckedOnTheServiceNotItsNamespace() {