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.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 17:03:38 -04:00
1 parent 1c16ea57cd
commit 6afd82c9fb
8 files changed
+168 -16

No files matched your search

+3 -2
View File
@@ -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
@@ -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<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); 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
@@ -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<String> 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<String> find(String type, List<String> 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<String, String> 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<String, String> 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<Detector> 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<DetectorFeature> mergeDetectorFeatures(
@@ -16,7 +16,7 @@ public class Detector {
private String serviceRole;
private String createdAt;
private String updatedAt;
private Map<String, String> tags;
private volatile Map<String, String> tags;
private List<DetectorFeature> features;
private OrganizationConfiguration organizationConfiguration;
@@ -23,7 +23,7 @@ public class MalwareProtectionPlan {
private String status;
private String createdAt;
private String clientToken;
private Map<String, String> tags;
private volatile Map<String, String> tags;
public MalwareProtectionPlan() {
}
@@ -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"));
@@ -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<String, Detector> 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}"));
@@ -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}