feat(detective): add organization member operations (#3190)

* feat(detective): add organization member operations

* fix(detective): align organization operations with AWS

* docs(detective): clarify member listing

* fix(detective): enforce organization administration contracts
This commit is contained in:
Franklin G. Mendoza authored and GitHub committed 2026-09-07 18:31:48 -04:00
1 parent 2869502e7c
commit 5864b013d2
18 files changed
+821 -2

No files matched your search

@@ -715,6 +715,7 @@ public interface EmulatorConfig {
AccessAnalyzerServiceConfig accessanalyzer();
IdentityStoreServiceConfig identitystore();
BudgetsServiceConfig budgets();
DetectiveServiceConfig detective();
ServiceQuotasServiceConfig servicequotas();
RamServiceConfig ram();
ControlTowerServiceConfig controltower();
@@ -768,6 +769,11 @@ public interface EmulatorConfig {
boolean enabled();
}
interface DetectiveServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface ApsServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -35,6 +35,7 @@ import io.github.hectorvent.floci.services.guardduty.GuardDutyController;
import io.github.hectorvent.floci.services.macie2.MacieController;
import io.github.hectorvent.floci.services.account.AccountController;
import io.github.hectorvent.floci.services.accessanalyzer.AccessAnalyzerController;
import io.github.hectorvent.floci.services.detective.DetectiveController;
import io.github.hectorvent.floci.services.aps.ApsController;
import io.github.hectorvent.floci.services.controltower.ControlTowerControlController;
import io.github.hectorvent.floci.services.controltower.ControlTowerController;
@@ -426,6 +427,9 @@ public class ResolvedServiceCatalog {
descriptor("budgets", "budgets", config.services().budgets().enabled(), true,
"budgets", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON), Set.of("AWSBudgetServiceGateway."), Set.of("budgets"), Set.of(), Set.of()),
descriptor("detective", "detective", config.services().detective().enabled(), true,
"detective", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("detective"), Set.of(), Set.of(DetectiveController.class)),
descriptor("autoscaling", "autoscaling", config.services().autoscaling().enabled(), true,
"autoscaling", config.storage().mode(), 5000L, AwsNamespaces.AUTOSCALING, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
@@ -0,0 +1,232 @@
package io.github.hectorvent.floci.services.detective;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.detective.model.DetectiveMember;
import io.github.hectorvent.floci.services.detective.model.DetectiveState;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.List;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DetectiveController {
private final DetectiveService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public DetectiveController(DetectiveService service, RegionResolver regionResolver, ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@POST
@Path("/orgs/adminAccountslist")
public Response listOrganizationAdminAccounts(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
validatePageRequest(request);
DetectiveState state = service.state(region(headers));
var response = objectMapper.createObjectNode();
var administrators = response.putArray("Administrators");
if (state.getAdminAccountId() != null) {
administrators.addObject().put("AccountId", state.getAdminAccountId());
}
return Response.ok(response).build();
}
@POST
@Path("/orgs/enableAdminAccount")
public Response enableOrganizationAdminAccount(@Context HttpHeaders headers, String body) {
service.enableAdmin(region(headers), regionResolver.getAccountId(),
parse(body).path("AccountId").asText(null));
return Response.ok().build();
}
@POST
@Path("/graphs/list")
public Response listGraphs(@Context HttpHeaders headers, String body) {
String region = region(headers);
validatePageRequest(parse(body));
DetectiveState state = service.state(region);
var response = objectMapper.createObjectNode();
var graphs = response.putArray("GraphList");
if (state.isGraph()) {
graphs.addObject().put("Arn", service.graphArn(region));
}
return Response.ok(response).build();
}
@POST
@Path("/orgs/describeOrganizationConfiguration")
public Response describeOrganizationConfiguration(@Context HttpHeaders headers, String body) {
String region = region(headers);
JsonNode request = parse(body);
service.requireGraphArn(region, request.path("GraphArn").asText(null));
DetectiveState state = service.requireGraph(region);
var response = objectMapper.createObjectNode();
response.put("AutoEnable", state.isAutoEnable());
return Response.ok(response).build();
}
@POST
@Path("/orgs/updateOrganizationConfiguration")
public Response updateOrganizationConfiguration(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
Boolean autoEnable = null;
if (request.has("AutoEnable") && !request.get("AutoEnable").isNull()) {
if (!request.get("AutoEnable").isBoolean()) {
throw new AwsException("ValidationException", "AutoEnable must be a boolean.", 400);
}
autoEnable = request.get("AutoEnable").booleanValue();
}
service.updateOrganizationConfiguration(region(headers), request.path("GraphArn").asText(null), autoEnable);
return Response.ok().build();
}
@POST
@Path("/graph/members/list")
public Response listMembers(@Context HttpHeaders headers, String body) {
String region = region(headers);
JsonNode request = parse(body);
List<DetectiveMember> all = service.listMembers(region, request.path("GraphArn").asText(null));
Integer maxResults = integer(request, "MaxResults");
int limit = maxResults == null ? 200 : maxResults;
if (limit < 1 || limit > 200) {
throw new AwsException("ValidationException", "MaxResults must be between 1 and 200.", 400);
}
int offset = offset(request.path("NextToken").asText(null), all.size());
int end = Math.min(all.size(), offset + limit);
var response = objectMapper.createObjectNode();
var members = response.putArray("MemberDetails");
for (DetectiveMember member : all.subList(offset, end)) {
members.add(memberNode(region, member));
}
if (end < all.size()) {
response.put("NextToken", Integer.toString(end));
}
return Response.ok(response).build();
}
@POST
@Path("/graph/members")
public Response createMembers(@Context HttpHeaders headers, String body) {
String region = region(headers);
JsonNode request = parse(body);
String graphArn = request.path("GraphArn").asText(null);
JsonNode accounts = request.get("Accounts");
if (accounts == null || !accounts.isArray() || accounts.isEmpty() || accounts.size() > 50) {
throw new AwsException("ValidationException", "Accounts must contain between 1 and 50 members.", 400);
}
List<String> accountIds = new java.util.ArrayList<>(accounts.size());
for (JsonNode account : accounts) {
accountIds.add(account.path("AccountId").asText(null));
}
service.validateCreateMembers(region, graphArn, accountIds);
var response = objectMapper.createObjectNode();
var members = response.putArray("Members");
var unprocessed = response.putArray("UnprocessedAccounts");
for (JsonNode account : accounts) {
String accountId = account.path("AccountId").asText(null);
try {
DetectiveMember member = service.createMember(region, graphArn,
accountId, account.path("EmailAddress").asText(null));
members.add(memberNode(region, member));
} catch (AwsException e) {
if (!"ConflictException".equals(e.getErrorCode())) {
throw e;
}
unprocessed.addObject()
.put("AccountId", accountId)
.put("Reason", "The account is already a member of the behavior graph.");
}
}
return Response.ok(response).build();
}
@POST
@Path("/graph/member/monitoringstate")
public Response startMonitoringMember(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
service.startMonitoring(region(headers), request.path("AccountId").asText(null),
request.path("GraphArn").asText(null));
return Response.ok().build();
}
private com.fasterxml.jackson.databind.node.ObjectNode memberNode(String region, DetectiveMember member) {
var node = objectMapper.createObjectNode();
node.put("AccountId", member.getAccountId());
node.put("EmailAddress", member.getEmailAddress());
node.put("Status", member.getStatus());
node.put("GraphArn", service.graphArn(region));
node.put("AdministratorId", regionResolver.getAccountId());
node.put("InvitationType", "ORGANIZATION");
return node;
}
private static Integer integer(JsonNode request, String field) {
JsonNode value = request.get(field);
if (value == null || value.isNull()) {
return null;
}
if (!value.isIntegralNumber()) {
throw new AwsException("ValidationException", field + " must be an integer.", 400);
}
return value.intValue();
}
private static int offset(String nextToken, int size) {
if (nextToken == null || nextToken.isBlank()) {
return 0;
}
try {
int value = Integer.parseInt(nextToken);
if (value < 0 || value > size) {
throw new NumberFormatException();
}
return value;
} catch (NumberFormatException e) {
throw new AwsException("ValidationException", "NextToken is invalid.", 400);
}
}
private static void validatePageRequest(JsonNode request) {
Integer maxResults = integer(request, "MaxResults");
if (maxResults != null && (maxResults < 1 || maxResults > 200)) {
throw new AwsException("ValidationException", "MaxResults must be between 1 and 200.", 400);
}
JsonNode token = request.get("NextToken");
if (token != null && !token.isNull()) {
if (!token.isTextual() || token.textValue().isEmpty() || token.textValue().length() > 1024) {
throw new AwsException("ValidationException", "NextToken is invalid.", 400);
}
}
}
private String region(HttpHeaders headers) {
return regionResolver.resolveRegion(headers);
}
private JsonNode parse(String body) {
try {
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
} catch (Exception e) {
throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse());
}
}
}
@@ -0,0 +1,179 @@
package io.github.hectorvent.floci.services.detective;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.detective.model.DetectiveMember;
import io.github.hectorvent.floci.services.detective.model.DetectiveState;
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class DetectiveService implements Resettable {
private static final int MAX_MEMBERS = 1200;
private static final String ACCEPTED_BUT_DISABLED = "ACCEPTED_BUT_DISABLED";
private static final String ENABLED = "ENABLED";
private final AccountAwareStorageBackend<DetectiveState> states;
private final RegionResolver regionResolver;
private final OrganizationsService organizationsService;
@Inject
public DetectiveService(StorageFactory storageFactory, RegionResolver regionResolver,
OrganizationsService organizationsService) {
this(storageFactory.create("detective", "detective-state.json",
new TypeReference<Map<String, DetectiveState>>() {}), regionResolver, organizationsService);
}
DetectiveService(AccountAwareStorageBackend<DetectiveState> states, RegionResolver regionResolver,
OrganizationsService organizationsService) {
this.states = states;
this.regionResolver = regionResolver;
this.organizationsService = organizationsService;
}
public DetectiveState state(String region) {
return states.get(region).orElseGet(DetectiveState::new);
}
public String graphArn(String region) {
return graphArnForAccount(regionResolver.getAccountId(), region);
}
public synchronized void enableAdmin(String region, String callerAccountId, String accountId) {
requireAccountId(accountId);
var organization = organizationsService.describeOrganization(callerAccountId);
if (!callerAccountId.equals(organization.getMasterAccountId())) {
throw new AwsException("AccessDeniedException",
"Only the organization management account can designate the Detective administrator account.", 403);
}
boolean accountInOrganization = organizationsService.listAccounts(callerAccountId).stream()
.anyMatch(account -> accountId.equals(account.getId()));
if (!accountInOrganization) {
throw new AwsException("ValidationException",
"AccountId must identify an account in the organization.", 400);
}
DetectiveState management = state(region);
if (management.getAdminAccountId() != null && !management.getAdminAccountId().equals(accountId)) {
throw new AwsException("ConflictException",
"A different Detective administrator account is already configured.", 409);
}
management.setAdminAccountId(accountId);
states.put(region, management);
DetectiveState delegated = states.getForAccount(accountId, region).orElseGet(DetectiveState::new);
delegated.setAdminAccountId(accountId);
delegated.setGraph(true);
states.putForAccount(accountId, region, delegated);
}
public synchronized void updateOrganizationConfiguration(String region, String graphArn, Boolean autoEnable) {
requireGraphArn(region, graphArn);
DetectiveState state = requireGraph(region);
if (autoEnable != null) {
state.setAutoEnable(autoEnable);
states.put(region, state);
}
}
public synchronized DetectiveMember createMember(String region, String graphArn,
String accountId, String emailAddress) {
requireGraphArn(region, graphArn);
requireAccountId(accountId);
DetectiveState state = requireGraph(region);
if (state.getMembers().containsKey(accountId)) {
throw new AwsException("ConflictException",
"The account is already a member of the behavior graph.", 409);
}
if (state.getMembers().size() >= MAX_MEMBERS) {
throw new AwsException("ServiceQuotaExceededException",
"The behavior graph member quota has been exceeded.", 402);
}
DetectiveMember member = new DetectiveMember(accountId, emailAddress, ACCEPTED_BUT_DISABLED);
state.getMembers().put(accountId, member);
states.put(region, state);
return member;
}
public synchronized void validateCreateMembers(String region, String graphArn, List<String> accountIds) {
requireGraphArn(region, graphArn);
DetectiveState state = requireGraph(region);
int newMembers = 0;
java.util.Set<String> seen = new java.util.HashSet<>();
for (String accountId : accountIds) {
requireAccountId(accountId);
if (seen.add(accountId) && !state.getMembers().containsKey(accountId)) {
newMembers++;
}
}
if (state.getMembers().size() + newMembers > MAX_MEMBERS) {
throw new AwsException("ServiceQuotaExceededException",
"The behavior graph member quota has been exceeded.", 402);
}
}
public synchronized DetectiveMember startMonitoring(String region, String accountId, String graphArn) {
requireGraphArn(region, graphArn);
requireAccountId(accountId);
DetectiveState state = requireGraph(region);
DetectiveMember member = state.getMembers().get(accountId);
if (member == null) {
throw new AwsException("ResourceNotFoundException", "Member account not found.", 404);
}
if (ENABLED.equals(member.getStatus())) {
throw new AwsException("ConflictException",
"The member account is already contributing data to the behavior graph.", 409);
}
if (!ACCEPTED_BUT_DISABLED.equals(member.getStatus())) {
throw new AwsException("ConflictException",
"The member account is not in a state that can start monitoring.", 409);
}
member.setStatus(ENABLED);
states.put(region, state);
return member;
}
public List<DetectiveMember> listMembers(String region, String graphArn) {
requireGraphArn(region, graphArn);
return requireGraph(region).getMembers().values().stream()
.sorted(java.util.Comparator.comparing(DetectiveMember::getAccountId))
.toList();
}
@Override
public void clear() {
states.clear();
}
public DetectiveState requireGraph(String region) {
DetectiveState state = state(region);
if (!state.isGraph()) {
throw new AwsException("ResourceNotFoundException", "Behavior graph not found.", 404);
}
return state;
}
public void requireGraphArn(String region, String graphArn) {
if (graphArn == null || !graphArnForAccount(regionResolver.getAccountId(), region).equals(graphArn)) {
throw new AwsException("ResourceNotFoundException", "Behavior graph not found.", 404);
}
}
private static String graphArnForAccount(String accountId, String region) {
return "arn:aws:detective:" + region + ":" + accountId
+ ":graph:00000000000000000000000000000001";
}
private static void requireAccountId(String accountId) {
if (accountId == null || !accountId.matches("\\d{12}")) {
throw new AwsException("ValidationException", "AccountId must be a 12 digit account ID.", 400);
}
}
}
@@ -0,0 +1,28 @@
package io.github.hectorvent.floci.services.detective.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class DetectiveMember {
private String accountId;
private String emailAddress;
private String status;
public DetectiveMember() {
}
public DetectiveMember(String accountId, String emailAddress, String status) {
this.accountId = accountId;
this.emailAddress = emailAddress;
this.status = status;
}
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getEmailAddress() { return emailAddress; }
public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
}
@@ -0,0 +1,28 @@
package io.github.hectorvent.floci.services.detective.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.LinkedHashMap;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class DetectiveState {
private String adminAccountId;
private boolean graph;
private boolean autoEnable;
private Map<String, DetectiveMember> members = new LinkedHashMap<>();
public DetectiveState() {
}
public String getAdminAccountId() { return adminAccountId; }
public void setAdminAccountId(String adminAccountId) { this.adminAccountId = adminAccountId; }
public boolean isGraph() { return graph; }
public void setGraph(boolean graph) { this.graph = graph; }
public boolean isAutoEnable() { return autoEnable; }
public void setAutoEnable(boolean autoEnable) { this.autoEnable = autoEnable; }
public Map<String, DetectiveMember> getMembers() { return members; }
public void setMembers(Map<String, DetectiveMember> members) { this.members = members; }
}