From b6489ac933791cee05da263da038bbb358a1fb75 Mon Sep 17 00:00:00 2001 From: "Franklin G. Mendoza" Date: Sat, 5 Sep 2026 12:29:30 -0400 Subject: [PATCH] feat(guardduty): add member account operations (#3052) * feat(guardduty): add member account operations * fix(guardduty): align member creation semantics --- docs/services/guardduty.md | 4 +- .../guardduty/GuardDutyController.java | 36 ++++++ .../services/guardduty/GuardDutyService.java | 106 +++++++++++++++- .../guardduty/model/MemberAccount.java | 7 ++ .../GuardDutyMembersIntegrationTest.java | 113 ++++++++++++++++++ .../guardduty/GuardDutyServiceTest.java | 8 +- 6 files changed, 271 insertions(+), 3 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/MemberAccount.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMembersIntegrationTest.java diff --git a/docs/services/guardduty.md b/docs/services/guardduty.md index ba36c728b1..da26edc8a2 100644 --- a/docs/services/guardduty.md +++ b/docs/services/guardduty.md @@ -22,6 +22,8 @@ region and use the configured Floci storage mode. | `EnableOrganizationAdminAccount` | `POST /admin/enable` | Designate the delegated administrator account | | `DisableOrganizationAdminAccount` | `POST /admin/disable` | Remove the delegated administrator account | | `ListOrganizationAdminAccounts` | `GET /admin` | List the delegated administrator account | +| `CreateMembers` | `POST /detector/{detectorId}/member` | Create GuardDuty member accounts for a detector | +| `ListMembers` | `GET /detector/{detectorId}/member` | List detector members with pagination and association filtering | | `TagResource` | `POST /tags/{resourceArn}` | Add tags to a detector | | `UntagResource` | `DELETE /tags/{resourceArn}` | Remove tags from a detector | | `ListTagsForResource` | `GET /tags/{resourceArn}` | List detector tags | @@ -78,6 +80,6 @@ aws guardduty delete-detector --detector-id "$DETECTOR_ID" `aws_guardduty_organization_admin_account` resources in a single-account workflow. - No findings are generated: detection, malware scans, and the findings APIs (`ListFindings`, `GetFindings`, filters, and publishing destinations) are not implemented. -- Member, invitation, IP-set, threat-intel, and coverage APIs are not implemented. +- Member creation and listing are implemented. Invitation, IP-set, threat-intel, and coverage APIs are not implemented. - The deprecated `dataSources` request/response structures are not modeled; the Terraform provider treats their absence as "not configured". diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java index d02d118c72..8619267244 100644 --- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.guardduty.model.AdminAccount; +import io.github.hectorvent.floci.services.guardduty.model.MemberAccount; import io.github.hectorvent.floci.services.guardduty.model.Detector; import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature; import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; @@ -139,6 +140,41 @@ public class GuardDutyController { return Response.ok(objectMapper.createObjectNode()).build(); } + @GET + @Path("/detector/{detectorId}/member") + public Response listMembers(@Context HttpHeaders headers, @PathParam("detectorId") String detectorId, + @QueryParam("maxResults") String maxResults, + @QueryParam("nextToken") String nextToken, + @QueryParam("onlyAssociated") String onlyAssociated) { + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode members = response.putArray("members"); + GuardDutyService.Page page = service.listMembers( + regionResolver.resolveRegion(headers), detectorId, maxResults, nextToken, onlyAssociated); + for (MemberAccount member : page.items()) { + ObjectNode node = members.addObject(); + node.put("accountId", member.accountId()); + node.put("administratorId", member.administratorId()); + node.put("masterId", member.administratorId()); + node.put("detectorId", member.detectorId()); + node.put("email", member.email()); + node.put("invitedAt", member.invitedAt()); + node.put("relationshipStatus", member.relationshipStatus()); + node.put("updatedAt", member.updatedAt()); + } + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + @POST + @Path("/detector/{detectorId}/member") + public Response createMembers(@Context HttpHeaders headers, @PathParam("detectorId") String detectorId, String body) { + service.createMembers(regionResolver.resolveRegion(headers), detectorId, parse(body)); + ObjectNode response = objectMapper.createObjectNode(); + response.putArray("unprocessedAccounts"); + return Response.ok(response).build(); + } + @GET @Path("/detector/{detectorId}/admin") public Response describeOrganizationConfiguration( diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java index 784f3b553e..dbbfdf75ad 100644 --- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.guardduty.model.AdminAccount; +import io.github.hectorvent.floci.services.guardduty.model.MemberAccount; import io.github.hectorvent.floci.services.guardduty.model.Detector; import io.github.hectorvent.floci.services.guardduty.model.DetectorAdditionalConfiguration; import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature; @@ -72,6 +73,7 @@ public class GuardDutyService { private final StorageBackend detectorStore; private final StorageBackend adminAccountStore; + private final StorageBackend memberStore; @Inject public GuardDutyService(StorageFactory storageFactory) { @@ -84,14 +86,21 @@ public class GuardDutyService { "guardduty", "guardduty-admin-accounts.json", new TypeReference>() { + }), + storageFactory.create( + "guardduty", + "guardduty-members.json", + new TypeReference>() { })); } GuardDutyService( StorageBackend detectorStore, - StorageBackend adminAccountStore) { + StorageBackend adminAccountStore, + StorageBackend memberStore) { this.detectorStore = detectorStore; this.adminAccountStore = adminAccountStore; + this.memberStore = memberStore; } public synchronized Detector createDetector(String region, String accountId, JsonNode request) { @@ -227,6 +236,89 @@ public class GuardDutyService { return new Page<>(accounts.subList(offset, end), responseToken); } + public synchronized void createMembers(String region, String detectorId, JsonNode request) { + Detector detector = getDetector(region, detectorId); + JsonNode details = request.get("accountDetails"); + if (details == null || !details.isArray() || details.size() < 1 || details.size() > 50) { + throw badRequest("accountDetails must contain between 1 and 50 accounts."); + } + String administratorId = accountIdFromServiceRole(detector.getServiceRole()); + boolean organizationDelegatedAdministrator = adminAccountStore.get(storageKey(region, administratorId)) + .map(account -> "ENABLED".equals(account.getAdminStatus())) + .orElse(false); + String relationshipStatus = organizationDelegatedAdministrator ? "Enabled" : "Created"; + String now = Instant.now().toString(); + List writes = new ArrayList<>(details.size()); + for (JsonNode detail : details) { + String accountId = requireText(detail, "accountId"); + if (!ACCOUNT_ID_PATTERN.matcher(accountId).matches()) { + throw badRequest("accountId must be a 12-digit account ID."); + } + String email = requireText(detail, "email"); + if (!validMemberEmail(email)) { + throw badRequest("email must be a valid GuardDuty member email address."); + } + String key = region + "::" + detectorId + "::" + accountId; + MemberAccount existing = memberStore.get(key).orElse(null); + writes.add(new MemberWrite(key, new MemberAccount( + accountId, + email, + relationshipStatus, + administratorId, + detectorId, + existing == null ? now : existing.invitedAt(), + now))); + } + for (MemberWrite write : writes) { + memberStore.put(write.key(), write.member()); + } + } + + public Page listMembers(String region, String detectorId, String maxResults, + String nextToken, String onlyAssociated) { + Detector detector = getDetector(region, detectorId); + int limit = parseMaxResults(maxResults); + if (onlyAssociated != null && !onlyAssociated.equalsIgnoreCase("true") + && !onlyAssociated.equalsIgnoreCase("false")) { + throw badRequest("onlyAssociated must be true or false."); + } + String prefix = region + "::" + detectorId + "::"; + List members = memberStore.scan(key -> key.startsWith(prefix)).stream() + .filter(member -> !"true".equalsIgnoreCase(onlyAssociated) + || isAssociatedRelationship(member.relationshipStatus())) + .sorted(Comparator.comparing(MemberAccount::accountId)).toList(); + int offset = decodeOffset(nextToken, members.size()); + int end = Math.min(members.size(), offset + limit); + return new Page<>(members.subList(offset, end), end < members.size() ? encodeOffset(end) : null); + } + + public List listMembers(String region, String detectorId) { + return listMembers(region, detectorId, null, null, null).items(); + } + + private static boolean isAssociatedRelationship(String status) { + return "Enabled".equals(status) || "Invited".equals(status) || "EmailVerificationInProgress".equals(status); + } + + private static boolean validMemberEmail(String email) { + if (email == null || email.length() < 6 || email.length() > 64 || !email.chars().allMatch(ch -> ch < 128)) { + return false; + } + int at = email.indexOf('@'); + if (at <= 0 || at != email.lastIndexOf('@') || at == email.length() - 1) { + return false; + } + String local = email.substring(0, at); + String domain = email.substring(at + 1); + if (local.startsWith(".") || local.matches(".*[\\s\"'()<>\\[\\]:,\\\\|%&].*")) { + return false; + } + if (!domain.matches("[A-Za-z0-9.-]+") || !domain.contains(".") + || domain.startsWith(".") || domain.endsWith(".") || domain.startsWith("-") || domain.endsWith("-")) { + return false; + } + return true; + } public Map listTags(String arn) { Detector detector = detectorFromArn(arn); return detector.getTags() == null ? Map.of() : detector.getTags(); @@ -535,6 +627,15 @@ public class GuardDutyService { return new AwsException("BadRequestException", message, 400); } + private static String accountIdFromServiceRole(String serviceRole) { + if (serviceRole == null) { + return "000000000000"; + } + String[] parts = serviceRole.split(":", 6); + return parts.length > 4 && ACCOUNT_ID_PATTERN.matcher(parts[4]).matches() ? parts[4] : "000000000000"; + } + + public record Page(List items, String nextToken) { public Page { items = List.copyOf(items); @@ -546,4 +647,7 @@ public class GuardDutyService { return storageKey(region, detectorId); } } + + private record MemberWrite(String key, MemberAccount member) { + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/MemberAccount.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/MemberAccount.java new file mode 100644 index 0000000000..6340e5bdc4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/MemberAccount.java @@ -0,0 +1,7 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public record MemberAccount(String accountId, String email, String relationshipStatus, + String administratorId, String detectorId, String invitedAt, String updatedAt) {} diff --git a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMembersIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMembersIntegrationTest.java new file mode 100644 index 0000000000..63c2104166 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMembersIntegrationTest.java @@ -0,0 +1,113 @@ +package io.github.hectorvent.floci.services.guardduty; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; + +@QuarkusTest +class GuardDutyMembersIntegrationTest { + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void createsUnassociatedMembersByDefault() { + String detectorId = createDetector("111111111111"); + + given().contentType("application/json") + .header("Authorization", auth("111111111111")) + .body("{\"accountDetails\":[{\"accountId\":\"222222222222\",\"email\":\"member@example.com\"}]}") + .post("/detector/" + detectorId + "/member") + .then().statusCode(200) + .body("unprocessedAccounts", hasSize(0)); + + given().header("Authorization", auth("111111111111")) + .get("/detector/" + detectorId + "/member") + .then().statusCode(200) + .body("members", hasSize(1)) + .body("members[0].accountId", equalTo("222222222222")) + .body("members[0].email", equalTo("member@example.com")) + .body("members[0].relationshipStatus", equalTo("Created")); + + given().header("Authorization", auth("111111111111")) + .queryParam("onlyAssociated", true) + .get("/detector/" + detectorId + "/member") + .then().statusCode(200) + .body("members", hasSize(0)); + } + + @Test + void delegatedAdministratorCreatesEnabledOrganizationMembers() { + given().contentType("application/json") + .header("Authorization", auth("444444444444")) + .body("{\"adminAccountId\":\"444444444444\"}") + .post("/admin/enable") + .then().statusCode(200); + + String detectorId = createDetector("444444444444"); + + given().contentType("application/json") + .header("Authorization", auth("444444444444")) + .body("{\"accountDetails\":[{\"accountId\":\"555555555555\",\"email\":\"org-member@example.com\"}]}") + .post("/detector/" + detectorId + "/member") + .then().statusCode(200); + + given().header("Authorization", auth("444444444444")) + .queryParam("onlyAssociated", true) + .get("/detector/" + detectorId + "/member") + .then().statusCode(200) + .body("members", hasSize(1)) + .body("members[0].relationshipStatus", equalTo("Enabled")); + } + + @Test + void rejectsInvalidMemberAccountId() { + String detectorId = createDetector("333333333333"); + + given().contentType("application/json") + .header("Authorization", auth("333333333333")) + .body("{\"accountDetails\":[{\"accountId\":\"bad\",\"email\":\"member@example.com\"}]}") + .post("/detector/" + detectorId + "/member") + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + void rejectedMixedBatchDoesNotPersistValidPrefix() { + String detectorId = createDetector("666666666666"); + + given().contentType("application/json") + .header("Authorization", auth("666666666666")) + .body("{\"accountDetails\":[" + + "{\"accountId\":\"777777777777\",\"email\":\"valid@example.com\"}," + + "{\"accountId\":\"bad\",\"email\":\"invalid@example.com\"}]}") + .post("/detector/" + detectorId + "/member") + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + + given().header("Authorization", auth("666666666666")) + .get("/detector/" + detectorId + "/member") + .then().statusCode(200) + .body("members", hasSize(0)); + } + + private static String createDetector(String accountId) { + return given() + .contentType("application/json") + .header("Authorization", auth(accountId)) + .body("{\"enable\":true}") + .post("/detector") + .then().statusCode(200) + .extract().path("detectorId"); + } + + private static String auth(String accountId) { + return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260904/us-east-1/guardduty/aws4_request"; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java index 0511dcf3b3..3a8691e6ca 100644 --- a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.guardduty.model.AdminAccount; import io.github.hectorvent.floci.services.guardduty.model.Detector; import io.github.hectorvent.floci.services.guardduty.model.DetectorAdditionalConfiguration; import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature; +import io.github.hectorvent.floci.services.guardduty.model.MemberAccount; import io.github.hectorvent.floci.services.guardduty.model.OrganizationAdditionalConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature; @@ -32,7 +33,7 @@ class GuardDutyServiceTest { private final ObjectMapper objectMapper = new ObjectMapper(); private final GuardDutyService service = - new GuardDutyService(new InMemoryStorage<>(), new InMemoryStorage<>()); + new GuardDutyService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); @Test void createDetectorAppliesDefaultsAndGeneratesIdentifiers() throws Exception { @@ -319,10 +320,13 @@ class GuardDutyServiceTest { void detectorSurvivesPersistentStorageReloadWithOrderIntact(@TempDir Path tempDir) throws Exception { Path detectorFile = tempDir.resolve("detectors.json"); Path adminFile = tempDir.resolve("admins.json"); + Path memberFile = tempDir.resolve("members.json"); GuardDutyService firstService = new GuardDutyService( loadedStore(detectorFile, new TypeReference>() { }), loadedStore(adminFile, new TypeReference>() { + }), + loadedStore(memberFile, new TypeReference>() { })); Detector created = firstService.createDetector(REGION, ACCOUNT, request(""" {"enable":true,"tags":{"env":"test"},"features":[ @@ -340,6 +344,8 @@ class GuardDutyServiceTest { loadedStore(detectorFile, new TypeReference>() { }), loadedStore(adminFile, new TypeReference>() { + }), + loadedStore(memberFile, new TypeReference>() { })); Detector reloaded = reloadedService.getDetector(REGION, created.getId());