Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Franklin G. Mendoza5864b013d2c8
diff --git a/README.md b/README.md
index bb3a61122e..79c8a0ac8a 100644
--- a/README.md
+++ b/README.md
@@ -238,7 +238,7 @@ Floci supports local emulation for application services, data services, eventing
| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock Runtime, Bedrock AgentCore |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core, Amazon Connect |
-| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin), Identity Store, Amazon Macie, Control Tower, Service Catalog |
+| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin), Identity Store, Amazon Macie, Amazon Detective, Control Tower, Service Catalog |
| Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 10aef8febb..9736afba58 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -253,6 +253,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>macie2</artifactId>
</dependency>
+ <!-- Amazon Detective client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>detective</artifactId>
+ </dependency>
<!-- AWS Account Management client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 36184b46cc..5027fd9401 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -36,6 +36,7 @@ import software.amazon.awssdk.services.ssoadmin.SsoAdminClient;
import software.amazon.awssdk.services.identitystore.IdentitystoreClient;
import software.amazon.awssdk.services.budgets.BudgetsClient;
import software.amazon.awssdk.services.macie2.Macie2Client;
+import software.amazon.awssdk.services.detective.DetectiveClient;
import software.amazon.awssdk.services.rum.RumClient;
import software.amazon.awssdk.services.resourceexplorer2.ResourceExplorer2Client;
import software.amazon.awssdk.services.s3.S3AsyncClient;
@@ -274,10 +275,14 @@ public final class TestFixtures {
}
public static OrganizationsClient organizationsClient() {
+ return organizationsClient("test");
+ }
+
+ public static OrganizationsClient organizationsClient(String accountId) {
return OrganizationsClient.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
- .credentialsProvider(CREDENTIALS)
+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accountId, "test")))
.build();
}
@@ -341,6 +346,14 @@ public final class TestFixtures {
.build();
}
+ public static DetectiveClient detectiveClient(String accountId) {
+ return DetectiveClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accountId, "test")))
+ .build();
+ }
+
public static SsmClient ssmClient() {
return SsmClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DetectiveOrganizationAdministrationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DetectiveOrganizationAdministrationTest.java
new file mode 100644
index 0000000000..4c3cfd3438
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DetectiveOrganizationAdministrationTest.java
@@ -0,0 +1,71 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.detective.DetectiveClient;
+import software.amazon.awssdk.services.detective.model.Account;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+@DisplayName("Detective organization administration")
+class DetectiveOrganizationAdministrationTest {
+ private static final String MANAGEMENT_ACCOUNT = "222222222222";
+ private static final String ADMIN_ACCOUNT = MANAGEMENT_ACCOUNT;
+ private static final String MEMBER_ACCOUNT = "333333333333";
+
+ @Test
+ @DisplayName("uses AWS SDK models for organization graph and member operations")
+ void organizationAdministrationUsesAwsSdk() {
+ assumeFalse(TestFixtures.isRealAws(), "Avoids changing Detective organization settings in real AWS");
+
+ try (var organizations = TestFixtures.organizationsClient(MANAGEMENT_ACCOUNT);
+ DetectiveClient management = TestFixtures.detectiveClient(MANAGEMENT_ACCOUNT);
+ DetectiveClient administrator = TestFixtures.detectiveClient(ADMIN_ACCOUNT)) {
+ try {
+ organizations.describeOrganization();
+ } catch (software.amazon.awssdk.services.organizations.model.AwsOrganizationsNotInUseException e) {
+ organizations.createOrganization();
+ }
+
+ assertThat(management.listOrganizationAdminAccounts(request -> request.maxResults(200)).administrators())
+ .isEmpty();
+
+ management.enableOrganizationAdminAccount(request -> request.accountId(ADMIN_ACCOUNT));
+
+ assertThat(management.listOrganizationAdminAccounts(request -> request.maxResults(200)).administrators())
+ .extracting(administratorAccount -> administratorAccount.accountId())
+ .containsExactly(ADMIN_ACCOUNT);
+
+ String graphArn = administrator.listGraphs(request -> request.maxResults(200)).graphList().get(0).arn();
+ administrator.updateOrganizationConfiguration(request -> request.graphArn(graphArn).autoEnable(true));
+ assertThat(administrator.describeOrganizationConfiguration(request -> request.graphArn(graphArn)).autoEnable())
+ .isTrue();
+
+ var created = administrator.createMembers(request -> request
+ .graphArn(graphArn)
+ .accounts(List.of(Account.builder().accountId(MEMBER_ACCOUNT).build())));
+ assertThat(created.members()).extracting(member -> member.accountId()).containsExactly(MEMBER_ACCOUNT);
+ assertThat(created.unprocessedAccounts()).isEmpty();
+
+ var duplicate = administrator.createMembers(request -> request
+ .graphArn(graphArn)
+ .accounts(List.of(Account.builder().accountId(MEMBER_ACCOUNT).build())));
+ assertThat(duplicate.members()).isEmpty();
+ assertThat(duplicate.unprocessedAccounts())
+ .extracting(account -> account.accountId())
+ .containsExactly(MEMBER_ACCOUNT);
+
+ assertThat(administrator.listMembers(request -> request.graphArn(graphArn).maxResults(200)).memberDetails())
+ .extracting(member -> member.accountId())
+ .containsExactly(MEMBER_ACCOUNT);
+
+ administrator.startMonitoringMember(request -> request.graphArn(graphArn).accountId(MEMBER_ACCOUNT));
+ assertThat(administrator.listMembers(request -> request.graphArn(graphArn)).memberDetails())
+ .singleElement()
+ .satisfies(member -> assertThat(member.statusAsString()).isEqualTo("ENABLED"));
+ }
+ }
+}
diff --git a/docs/services/detective.md b/docs/services/detective.md
new file mode 100644
index 0000000000..205098d878
--- /dev/null
+++ b/docs/services/detective.md
@@ -0,0 +1,26 @@
+# Amazon Detective
+
+Floci implements the REST JSON Detective organization and behavior-graph operations used by local security-governance workflows.
+
+## Supported Actions
+
+<!-- floci:actions:start -->
+| Action | Description |
+| --- | --- |
+| `ListOrganizationAdminAccounts` | Lists the Detective administrator account configured for the organization. |
+| `EnableOrganizationAdminAccount` | Designates a Detective administrator account and enables its organization behavior graph. |
+| `ListGraphs` | Lists behavior graphs for the current account and Region. |
+| `DescribeOrganizationConfiguration` | Returns the organization auto-enable setting for a behavior graph. |
+| `UpdateOrganizationConfiguration` | Updates the organization auto-enable setting for a behavior graph. |
+| `ListMembers` | Lists organization member accounts in a behavior graph. |
+| `CreateMembers` | Enables organization accounts as behavior-graph members. |
+| `StartMonitoringMember` | Starts data contribution for an accepted but disabled member account. |
+<!-- floci:actions:end -->
+
+For organization behavior graphs, member accounts can be created without an email address. Duplicate member requests are returned through `UnprocessedAccounts`, while successfully processed accounts are returned through `Members`. `ListMembers` accepts the AWS-documented `MaxResults` range of 1 through 200.
+
+Organization configuration accepts an optional `AutoEnable` field and requires the behavior graph ARN. Successful `EnableOrganizationAdminAccount`, `UpdateOrganizationConfiguration`, and `StartMonitoringMember` operations return an empty HTTP 200 response body, matching the AWS API contract.
+
+Invalid graph, account, member, and pagination data returns modeled `ValidationException` or `ResourceNotFoundException` responses. Incompatible member transitions return `ConflictException`, and the 1,200-member behavior-graph quota is enforced with `ServiceQuotaExceededException`. Provider-side internal and throttling errors are not injected artificially.
+
+See the [Amazon Detective API Reference](https://docs.aws.amazon.com/detective/latest/APIReference/Welcome.html).
diff --git a/docs/services/index.md b/docs/services/index.md
index a33e7e7e25..6ce2f4d3c9 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -49,6 +49,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [IAM Identity Center (SSO Admin)](ssoadmin.md) | `POST /` + `X-Amz-Target: SWBExternalService.*` | JSON 1.1 | 13 |
| [Identity Store](identitystore.md) | `POST /` + `X-Amz-Target: AWSIdentityStore.*` | JSON 1.1 | 19 |
| [Amazon Macie](macie2.md) | `/admin`, `/macie`, `/admin/configuration` | REST JSON | 6 |
+| [Amazon Detective](detective.md) | `/orgs/*`, `/graphs/list`, `/graph/*` | REST JSON | 8 |
| [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 |
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 8 |
| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 7 |
diff --git a/mkdocs.yml b/mkdocs.yml
index 536fc45a67..5e98491033 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -125,6 +125,7 @@ nav:
- Identity Store: services/identitystore.md
- AWS Budgets: services/budgets.md
- Amazon Macie: services/macie2.md
+ - Amazon Detective: services/detective.md
- Control Tower: services/controltower.md
- AWS Service Catalog: services/service-catalog.md
- ElastiCache: services/elasticache.md
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index eee5ceddd6..86bf0fc647 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -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();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index fd1a980dab..ed3a8bd442 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -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),
diff --git a/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveController.java b/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveController.java
new file mode 100644
index 0000000000..31cd815103
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveController.java
@@ -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());
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveService.java b/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveService.java
new file mode 100644
index 0000000000..1fbfb8636a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/detective/DetectiveService.java
@@ -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);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/detective/model/DetectiveMember.java b/src/main/java/io/github/hectorvent/floci/services/detective/model/DetectiveMember.java
new file mode 100644
index 0000000000..ff4ed2d380
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/detective/model/DetectiveMember.java
@@ -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; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/detective/model/DetectiveState.java b/src/main/java/io/github/hectorvent/floci/services/detective/model/DetectiveState.java
new file mode 100644
index 0000000000..d2d2d9d8df
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/detective/model/DetectiveState.java
@@ -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; }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 555c15ef81..1bb8ae8fee 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -623,6 +623,8 @@ floci:
enabled: true
budgets:
enabled: true
+ detective:
+ enabled: true
controltower:
enabled: true
seed-landing-zone: false
diff --git a/src/test/java/io/github/hectorvent/floci/services/detective/DetectiveIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/detective/DetectiveIntegrationTest.java
new file mode 100644
index 0000000000..a54b680dd3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/detective/DetectiveIntegrationTest.java
@@ -0,0 +1,87 @@
+package io.github.hectorvent.floci.services.detective;
+
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+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;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@QuarkusTest
+class DetectiveIntegrationTest {
+ private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/detective/aws4_request";
+
+ @Inject
+ OrganizationsService organizationsService;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void organizationGraphAndMemberLifecycleMatchesAwsContract() {
+ organizationsService.createOrganization("000000000000", "ALL");
+ String enableBody = post("/orgs/enableAdminAccount", "{\"AccountId\":\"000000000000\"}")
+ .statusCode(200).extract().asString();
+ assertTrue(enableBody.isEmpty());
+
+ String graphArn = post("/graphs/list", "{\"MaxResults\":200}")
+ .statusCode(200)
+ .body("GraphList", hasSize(1))
+ .extract().path("GraphList[0].Arn");
+
+ String updateBody = post("/orgs/updateOrganizationConfiguration",
+ "{\"GraphArn\":\"" + graphArn + "\",\"AutoEnable\":true}")
+ .statusCode(200).extract().asString();
+ assertTrue(updateBody.isEmpty());
+ post("/orgs/updateOrganizationConfiguration", "{\"GraphArn\":\"" + graphArn + "\"}")
+ .statusCode(200);
+ post("/orgs/describeOrganizationConfiguration", "{\"GraphArn\":\"" + graphArn + "\"}")
+ .statusCode(200).body("AutoEnable", equalTo(true));
+
+ post("/graph/members", "{\"GraphArn\":\"" + graphArn
+ + "\",\"Accounts\":[{\"AccountId\":\"444444444444\"},{\"AccountId\":\"bad\"}]}")
+ .statusCode(400).body("__type", equalTo("ValidationException"));
+ post("/graph/members/list", "{\"GraphArn\":\"" + graphArn + "\"}")
+ .statusCode(200).body("MemberDetails", hasSize(0));
+
+ String create = "{\"GraphArn\":\"" + graphArn
+ + "\",\"Accounts\":[{\"AccountId\":\"111111111111\"}]}";
+ post("/graph/members", create)
+ .statusCode(200)
+ .body("Members[0].Status", equalTo("ACCEPTED_BUT_DISABLED"))
+ .body("UnprocessedAccounts", hasSize(0));
+ post("/graph/members", create)
+ .statusCode(200)
+ .body("Members", hasSize(0))
+ .body("UnprocessedAccounts[0].AccountId", equalTo("111111111111"));
+
+ String monitoringBody = post("/graph/member/monitoringstate",
+ "{\"GraphArn\":\"" + graphArn + "\",\"AccountId\":\"111111111111\"}")
+ .statusCode(200).extract().asString();
+ assertTrue(monitoringBody.isEmpty());
+ post("/graph/members/list", "{\"GraphArn\":\"" + graphArn + "\",\"MaxResults\":200}")
+ .statusCode(200).body("MemberDetails[0].Status", equalTo("ENABLED"));
+ }
+
+ @Test
+ void invalidAdminAccountIdReturnsValidationError() {
+ post("/orgs/enableAdminAccount", "{\"AccountId\":\"bad\"}")
+ .statusCode(400).body("__type", equalTo("ValidationException"));
+ }
+
+ private static io.restassured.response.ValidatableResponse post(String path, String body) {
+ return given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body(body)
+ .post(path)
+ .then();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/detective/DetectiveServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/detective/DetectiveServiceTest.java
new file mode 100644
index 0000000000..174ae42aaa
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/detective/DetectiveServiceTest.java
@@ -0,0 +1,130 @@
+package io.github.hectorvent.floci.services.detective;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.services.detective.model.DetectiveState;
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import io.github.hectorvent.floci.services.organizations.model.Organization;
+import io.github.hectorvent.floci.services.organizations.model.OrganizationAccount;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class DetectiveServiceTest {
+ private static final String REGION = "us-east-1";
+ private static final String MANAGEMENT_ACCOUNT = "222222222222";
+ private static final String ADMIN_ACCOUNT = MANAGEMENT_ACCOUNT;
+ private static final String MEMBER_ACCOUNT = "333333333333";
+
+ private RegionResolver regionResolver;
+ private OrganizationsService organizationsService;
+ private DetectiveService service;
+
+ @BeforeEach
+ void setUp() {
+ regionResolver = mock(RegionResolver.class);
+ organizationsService = mock(OrganizationsService.class);
+ when(regionResolver.getAccountId()).thenReturn(MANAGEMENT_ACCOUNT);
+
+ Organization organization = new Organization();
+ organization.setMasterAccountId(MANAGEMENT_ACCOUNT);
+ OrganizationAccount management = new OrganizationAccount();
+ management.setId(MANAGEMENT_ACCOUNT);
+ OrganizationAccount member = new OrganizationAccount();
+ member.setId(MEMBER_ACCOUNT);
+ when(organizationsService.describeOrganization(MANAGEMENT_ACCOUNT)).thenReturn(organization);
+ when(organizationsService.listAccounts(MANAGEMENT_ACCOUNT)).thenReturn(java.util.List.of(management, member));
+
+ service = new DetectiveService(
+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT), regionResolver, organizationsService);
+ }
+
+ @Test
+ void delegationCreatesGraphForAdministratorAccount() {
+ service.enableAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);
+
+ when(regionResolver.getAccountId()).thenReturn(ADMIN_ACCOUNT);
+ assertTrue(service.requireGraph(REGION).isGraph());
+ assertEquals(ADMIN_ACCOUNT, service.requireGraph(REGION).getAdminAccountId());
+ }
+
+ @Test
+ void organizationMemberDoesNotRequireEmailAddress() {
+ service.enableAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);
+ when(regionResolver.getAccountId()).thenReturn(ADMIN_ACCOUNT);
+ String graphArn = service.graphArn(REGION);
+
+ var member = service.createMember(REGION, graphArn, MEMBER_ACCOUNT, null);
+
+ assertEquals(MEMBER_ACCOUNT, member.getAccountId());
+ assertNull(member.getEmailAddress());
+ assertEquals("ACCEPTED_BUT_DISABLED", member.getStatus());
+ }
+
+ @Test
+ void omittedAutoEnableLeavesConfigurationUnchanged() {
+ service.enableAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);
+ when(regionResolver.getAccountId()).thenReturn(ADMIN_ACCOUNT);
+ String graphArn = service.graphArn(REGION);
+ service.updateOrganizationConfiguration(REGION, graphArn, true);
+
+ service.updateOrganizationConfiguration(REGION, graphArn, null);
+
+ assertTrue(service.requireGraph(REGION).isAutoEnable());
+ }
+
+ @Test
+ void startMonitoringRequiresAcceptedButDisabledMember() {
+ service.enableAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);
+ when(regionResolver.getAccountId()).thenReturn(ADMIN_ACCOUNT);
+ String graphArn = service.graphArn(REGION);
+ service.createMember(REGION, graphArn, MEMBER_ACCOUNT, null);
+
+ assertEquals("ENABLED", service.startMonitoring(REGION, MEMBER_ACCOUNT, graphArn).getStatus());
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.startMonitoring(REGION, MEMBER_ACCOUNT, graphArn));
+ assertEquals("ConflictException", error.getErrorCode());
+ }
+
+ @Test
+ void nonManagementAccountCannotDesignateAdministrator() {
+ String memberCaller = MEMBER_ACCOUNT;
+ Organization organization = new Organization();
+ organization.setMasterAccountId(MANAGEMENT_ACCOUNT);
+ when(organizationsService.describeOrganization(memberCaller)).thenReturn(organization);
+
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.enableAdmin(REGION, memberCaller, MANAGEMENT_ACCOUNT));
+
+ assertEquals("AccessDeniedException", error.getErrorCode());
+ assertNull(service.state(REGION).getAdminAccountId());
+ }
+
+ @Test
+ void administratorMustBelongToOrganization() {
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.enableAdmin(REGION, MANAGEMENT_ACCOUNT, "999999999999"));
+
+ assertEquals("ValidationException", error.getErrorCode());
+ assertNull(service.state(REGION).getAdminAccountId());
+ }
+
+ @Test
+ void clearRemovesAllDetectiveState() {
+ service.enableAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);
+ assertEquals(ADMIN_ACCOUNT, service.state(REGION).getAdminAccountId());
+
+ service.clear();
+
+ assertNull(service.state(REGION).getAdminAccountId());
+ assertFalse(service.state(REGION).isGraph());
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 4bd880d0e5..7b74120974 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -385,6 +385,8 @@ floci:
enabled: true
budgets:
enabled: true
+ detective:
+ enabled: true
controltower:
enabled: true
seed-landing-zone: true
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index 9bc8e2373e..a415ca6947 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -80,6 +80,10 @@ services:
doc: docs/services/translate.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/translate/TranslateJsonHandler.java, mode: switch }
+ - service: detective
+ doc: docs/services/detective.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/detective/DetectiveController.java, mode: rest }
- service: docdb
doc: docs/services/docdb.md
sources: