From 6afd82c9fb069e6e32e286f0e570ec476c842d49 Mon Sep 17 00:00:00 2001
From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
Date: Wed, 18 Nov 2026 17:03:38 -0400
Subject: [PATCH] fix(guardduty): give resource-tag conditions the tags of the
detector or plan a request names (#8909)
The generated request resources give GuardDuty's detector and
malwareprotectionplan types the aws:ResourceTag/ key, but no service
answered the guardduty namespace's stored tags, so a condition on a
detector's or a Malware Protection plan's tags saw none.
GuardDutyService now answers it: storedTags reads the detector or plan
stored under the Region the ARN names and its id, in the request's
account, where the tag handlers read, in place. A plan is matched on the
ARN it records; a detector, which records none, on the ARN its Region,
the account of its service role and its id give. Tag calls already run
one at a time and give the resource a new map; the tags fields are now
volatile.
---
docs/services/iam.md | 5 +-
.../aws/core/common/StoredResourceArns.java | 7 +-
.../services/guardduty/GuardDutyService.java | 68 +++++++++++++++++--
.../services/guardduty/model/Detector.java | 2 +-
.../model/MalwareProtectionPlan.java | 2 +-
...dDutyMalwareProtectionPlanServiceTest.java | 16 +++++
.../guardduty/GuardDutyServiceTest.java | 42 ++++++++++++
...amRestRouteEnforcementIntegrationTest.java | 42 ++++++++++--
8 files changed, 168 insertions(+), 16 deletions(-)
diff --git a/docs/services/iam.md b/docs/services/iam.md
index bccb60b19c..c2f34e39ca 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -3516,8 +3516,9 @@ floci populates:
custom action types, DataSync for its agents, locations and tasks, Global Accelerator for its accelerators, listeners
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, and Control Tower for its landing zones and
- enabled controls. Tag keys differing only in case are one condition key holding every value.
+ 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.
- 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 f253f32c9b..0695d3981a 100644
--- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java
+++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java
@@ -55,9 +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); 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.
+ * 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} 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/guardduty/GuardDutyService.java b/src/main/java/io/floci/aws/services/guardduty/GuardDutyService.java
index 3d0b98bee4..c504573e11 100644
--- a/src/main/java/io/floci/aws/services/guardduty/GuardDutyService.java
+++ b/src/main/java/io/floci/aws/services/guardduty/GuardDutyService.java
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.common.ServicePrincipals;
+import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
@@ -34,6 +35,7 @@ import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
@@ -48,7 +50,7 @@ import java.util.stream.Collectors;
* account's credentials, while detector and member resources remain scoped to their owning account.
*/
@ApplicationScoped
-public class GuardDutyService {
+public class GuardDutyService implements StoredResourceArns {
/**
* The Terraform AWS provider matches this exact message to translate a
@@ -82,6 +84,7 @@ public class GuardDutyService {
private static final int PLAN_PAGE_SIZE = 100;
private static final String PLAN_TOKEN_PREFIX = "guardduty:v1:plan:";
private static final String PLAN_ARN_RESOURCE_PREFIX = "malware-protection-plan/";
+ private static final String DETECTOR_ARN_RESOURCE_PREFIX = "detector/";
static final String PLAN_NOT_FOUND_MESSAGE =
"The request is rejected because the input malwareProtectionPlanId is not owned by the current account.";
private static final Set ORG_AUTO_ENABLE_VALUES = Set.of("NEW", "NONE", "ALL");
@@ -812,6 +815,63 @@ public class GuardDutyService {
detectorStore.put(ref.key(), detector);
}
+ @Override
+ public String namespace() {
+ return "guardduty";
+ }
+
+ /** A request names a detector or a plan by the id GuardDuty minted, which its ARN ends in: nothing to find. */
+ @Override
+ public Optional find(String type, List names, String region) {
+ return Optional.empty();
+ }
+
+ /**
+ * The tags of the detector or the Malware Protection plan whose ARN is {@code arn}, in the request's account, where
+ * the tag handlers read: an ARN of another account names none. Read in place under the Region the ARN names and the
+ * id, a record stored before storage was account-aware included. A plan is matched on the ARN it records; a
+ * detector, which records none, on the ARN its Region, the account of its service role and its id give. Tags are
+ * only ever replaced by a new, unmodifiable map under this service's lock, so the read is of one whole set.
+ */
+ @Override
+ public Map storedTags(String arn) {
+ if (!AwsArnUtils.isArnFor(arn, "guardduty")) {
+ return Map.of();
+ }
+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
+ String account = parsed.accountId();
+ if (parsed.region().isEmpty() || !isRequestAccount(account)) {
+ return Map.of();
+ }
+ String resource = parsed.resource();
+ Map tags;
+ if (resource.startsWith(PLAN_ARN_RESOURCE_PREFIX)) {
+ tags = AccountAwareStorageBackend.readInAccount(malwareProtectionPlanStore, account,
+ storageKey(parsed.region(), resource.substring(PLAN_ARN_RESOURCE_PREFIX.length())))
+ .filter(plan -> arn.equals(plan.getArn()))
+ .map(MalwareProtectionPlan::getTags)
+ .orElse(Map.of());
+ } else if (resource.startsWith(DETECTOR_ARN_RESOURCE_PREFIX)) {
+ String detectorId = resource.substring(DETECTOR_ARN_RESOURCE_PREFIX.length());
+ tags = AccountAwareStorageBackend.readInAccount(detectorStore, account,
+ storageKey(parsed.region(), detectorId))
+ .filter(detector -> arn.equals(AwsArnUtils.Arn.of("guardduty", parsed.region(),
+ accountIdFromServiceRole(detector.getServiceRole()),
+ DETECTOR_ARN_RESOURCE_PREFIX + detectorId).toString()))
+ .map(Detector::getTags)
+ .orElse(Map.of());
+ } else {
+ return Map.of();
+ }
+ return new LinkedHashMap<>(tags);
+ }
+
+ /** Whether {@code account} is the request's, the one the stores answer for; a store not scoped by account, any. */
+ private boolean isRequestAccount(String account) {
+ return !(detectorStore instanceof AccountAwareStorageBackend scoped)
+ || account.equals(scoped.accountId());
+ }
+
private Detector detectorFromArn(String arn) {
DetectorRef ref = parseDetectorArn(arn);
return detectorStore.get(ref.key()).orElseThrow(GuardDutyService::detectorNotFound);
@@ -824,12 +884,12 @@ public class GuardDutyService {
} catch (IllegalArgumentException e) {
throw badRequest("The request is rejected because an invalid resource ARN is specified: " + arn);
}
- String prefix = "detector/";
String resource = parsed.resource();
- if (!resource.startsWith(prefix) || resource.length() == prefix.length()) {
+ if (!resource.startsWith(DETECTOR_ARN_RESOURCE_PREFIX)
+ || resource.length() == DETECTOR_ARN_RESOURCE_PREFIX.length()) {
throw badRequest("The request is rejected because an invalid resource ARN is specified: " + arn);
}
- return new DetectorRef(parsed.region(), resource.substring(prefix.length()));
+ return new DetectorRef(parsed.region(), resource.substring(DETECTOR_ARN_RESOURCE_PREFIX.length()));
}
private static List mergeDetectorFeatures(
diff --git a/src/main/java/io/floci/aws/services/guardduty/model/Detector.java b/src/main/java/io/floci/aws/services/guardduty/model/Detector.java
index 4757bcfce5..b98a4b6e37 100644
--- a/src/main/java/io/floci/aws/services/guardduty/model/Detector.java
+++ b/src/main/java/io/floci/aws/services/guardduty/model/Detector.java
@@ -16,7 +16,7 @@ public class Detector {
private String serviceRole;
private String createdAt;
private String updatedAt;
- private Map tags;
+ private volatile Map tags;
private List features;
private OrganizationConfiguration organizationConfiguration;
diff --git a/src/main/java/io/floci/aws/services/guardduty/model/MalwareProtectionPlan.java b/src/main/java/io/floci/aws/services/guardduty/model/MalwareProtectionPlan.java
index b4c0a3736e..49b50bd25a 100644
--- a/src/main/java/io/floci/aws/services/guardduty/model/MalwareProtectionPlan.java
+++ b/src/main/java/io/floci/aws/services/guardduty/model/MalwareProtectionPlan.java
@@ -23,7 +23,7 @@ public class MalwareProtectionPlan {
private String status;
private String createdAt;
private String clientToken;
- private Map tags;
+ private volatile Map tags;
public MalwareProtectionPlan() {
}
diff --git a/src/test/java/io/floci/aws/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java b/src/test/java/io/floci/aws/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java
index c96cbe4123..ee781f7989 100644
--- a/src/test/java/io/floci/aws/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java
+++ b/src/test/java/io/floci/aws/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java
@@ -289,6 +289,22 @@ class GuardDutyMalwareProtectionPlanServiceTest {
assertEquals(Map.of("b", "2"), service.getMalwareProtectionPlan(REGION, plan.getId()).getTags());
}
+ /**
+ * IAM's lookup reads the tags of the plan the ARN names, as the tag calls leave them, and nothing for another
+ * account's, another Region's or an unknown plan.
+ */
+ @Test
+ void storedTagsAreTheTagsOfThePlanTheArnNames() {
+ MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-stored-tags"));
+ service.tagResource(plan.getArn(), Map.of("team", "data", "env", "dev"));
+ service.untagResource(plan.getArn(), List.of("env"));
+
+ assertEquals(Map.of("team", "data"), service.storedTags(plan.getArn()));
+ assertTrue(service.storedTags(plan.getArn().replace(ACCOUNT, "111122223333")).isEmpty());
+ assertTrue(service.storedTags(plan.getArn().replace(REGION, "us-west-2")).isEmpty());
+ assertTrue(service.storedTags(plan.getArn().replace(plan.getId(), "missing")).isEmpty());
+ }
+
@Test
void aKeyInsideTheDocumentedPatternIsAccepted() {
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-tag-ok"));
diff --git a/src/test/java/io/floci/aws/services/guardduty/GuardDutyServiceTest.java b/src/test/java/io/floci/aws/services/guardduty/GuardDutyServiceTest.java
index c681619eff..2643982e02 100644
--- a/src/test/java/io/floci/aws/services/guardduty/GuardDutyServiceTest.java
+++ b/src/test/java/io/floci/aws/services/guardduty/GuardDutyServiceTest.java
@@ -24,6 +24,7 @@ import java.nio.file.Path;
import java.util.ArrayList;
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.assertNotEquals;
@@ -55,6 +56,47 @@ class GuardDutyServiceTest {
assertNull(detector.getFeatures());
}
+ /**
+ * IAM's lookup reads the tags of the detector the ARN names, as the tag calls leave them, and nothing for another
+ * account's, another Region's or an unknown detector, or an ARN of another service.
+ */
+ @Test
+ void storedTagsAreTheTagsOfTheDetectorTheArnNames() throws Exception {
+ Detector detector = service.createDetector(REGION, ACCOUNT,
+ request("{\"enable\":true,\"tags\":{\"team\":\"web\"}}"));
+ String arn = "arn:aws:guardduty:" + REGION + ":" + ACCOUNT + ":detector/" + detector.getId();
+ service.tagResource(arn, Map.of("team", "data", "env", "dev"));
+ service.untagResource(arn, List.of("env"));
+
+ assertEquals("guardduty", service.namespace());
+ assertEquals(Map.of("team", "data"), service.storedTags(arn));
+ assertTrue(service.storedTags(arn.replace(ACCOUNT, "111122223333")).isEmpty());
+ assertTrue(service.storedTags(arn.replace(REGION, "us-west-2")).isEmpty());
+ assertTrue(service.storedTags(arn.replace(detector.getId(), "missing")).isEmpty());
+ assertTrue(service.storedTags("arn:aws:securityhub:us-east-1:000000000000:hub/default").isEmpty());
+ }
+
+ /**
+ * A detector stored before storage was account-aware is read in place, the lookup migrating nothing, and an ARN of
+ * an account other than the request's reads nothing.
+ */
+ @Test
+ void storedTagsReadAPreAccountAwareDetectorInPlace() throws Exception {
+ InMemoryStorage raw = new InMemoryStorage<>();
+ GuardDutyService legacyState = new GuardDutyService(new AccountAwareStorageBackend<>(raw, null, ACCOUNT),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+ Detector detector = legacyState.createDetector(REGION, ACCOUNT,
+ request("{\"enable\":true,\"tags\":{\"team\":\"data\"}}"));
+ String key = REGION + "::" + detector.getId();
+ raw.put(key, raw.get(ACCOUNT + "/" + key).orElseThrow());
+ raw.delete(ACCOUNT + "/" + key);
+ String arn = "arn:aws:guardduty:" + REGION + ":" + ACCOUNT + ":detector/" + detector.getId();
+
+ assertEquals(Map.of("team", "data"), legacyState.storedTags(arn));
+ assertTrue(legacyState.storedTags(arn.replace(ACCOUNT, "111122223333")).isEmpty());
+ assertEquals(Set.of(key), raw.keys());
+ }
+
@Test
void createDetectorRejectsSecondDetectorInSameRegion() throws Exception {
service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}"));
diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java
index 5a1dc16999..1fef73e243 100644
--- a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java
@@ -976,11 +976,7 @@ class IamRestRouteEnforcementIntegrationTest {
String user = user("route-detector");
String region = "eu-west-3";
refused(as(user, region, "guardduty").get("/detector").then(), "guardduty:ListDetectors");
- String detector = given().header("Authorization", auth(ADMIN, region, "guardduty"))
- .contentType("application/json").body("{\"enable\":true}").post("/detector")
- .then().statusCode(200).extract().path("detectorId");
- cleanup.register(() -> given().header("Authorization", auth(ADMIN, region, "guardduty"))
- .delete("/detector/" + detector));
+ String detector = guardDutyDetector(region, null);
String arn = "arn:aws:guardduty:" + region + ":" + ACCOUNT + ":detector/" + detector;
refused(as(user, region, "guardduty").get("/detector/" + detector).then(), "guardduty:GetDetector");
@@ -995,6 +991,42 @@ class IamRestRouteEnforcementIntegrationTest {
as(user, region, "guardduty").get("/detector").then().statusCode(200);
}
+ /**
+ * An {@code aws:ResourceTag} condition reads the tags GuardDuty holds on the detector a request names, as
+ * TagResource leaves them, so an allow on one team's tag lets the caller read that team's detector and not
+ * another's. An account has one detector a Region, so the two are in two Regions.
+ */
+ @Test
+ void aGuardDutyResourceTagConditionReadsTheTagsOfTheDetector() {
+ String taggedRegion = "eu-north-1";
+ String otherRegion = "eu-south-2";
+ String tagged = guardDutyDetector(taggedRegion, "web");
+ String other = guardDutyDetector(otherRegion, "web");
+ String taggedArn = "arn:aws:guardduty:" + taggedRegion + ":" + ACCOUNT + ":detector/" + tagged;
+ given().header("Authorization", auth(ADMIN, taggedRegion, "guardduty")).contentType("application/json")
+ .body("{\"tags\":{\"team\":\"data\"}}")
+ .post("/tags/{arn}", taggedArn).then().statusCode(204);
+ String user = user("route-detector-tags");
+
+ policy(user, onTeam("Allow", "guardduty:GetDetector", "data"));
+ as(user, taggedRegion, "guardduty").get("/detector/" + tagged).then().statusCode(200);
+ refused(as(user, otherRegion, "guardduty").get("/detector/" + other).then(), "guardduty:GetDetector");
+ }
+
+ /**
+ * The id of a detector an administrator creates in {@code region}, tagged with the team if one is given, deleted
+ * after the test.
+ */
+ private String guardDutyDetector(String region, String team) {
+ String detector = given().header("Authorization", auth(ADMIN, region, "guardduty"))
+ .contentType("application/json")
+ .body("{\"enable\":true" + (team == null ? "" : ",\"tags\":{\"team\":\"" + team + "\"}") + "}")
+ .post("/detector").then().statusCode(200).extract().path("detectorId");
+ cleanup.register(() -> given().header("Authorization", auth(ADMIN, region, "guardduty"))
+ .delete("/detector/" + detector));
+ return detector;
+ }
+
/**
* A GuardDuty malware protection plan request, which GuardDutyRouteFilter moves onto {@code /_guardduty}, is
* checked as the model's route for it, on the plan its path names, and so is one sent to {@code /_guardduty}