Light, fluffy, and always free - The AWS Local Emulator alternative
feat(inspector2): add organization configuration operations (#3162)
Franklin G. Mendoza4944764fa381
diff --git a/README.md b/README.mdindex 41085886ea..295b76e725 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, Redshift Data API, 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, Amazon Detective, Control Catalog, Control Tower, Service Catalog |+| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, 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 Catalog, 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.xmlindex dc66b024f0..cbce717077 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -262,6 +262,11 @@<groupId>software.amazon.awssdk</groupId><artifactId>detective</artifactId></dependency>+ <!-- Amazon Inspector client -->+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>inspector2</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.javaindex cf8d32aea5..5ffaa84e0c 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@@ -38,6 +38,7 @@ 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.controlcatalog.ControlCatalogClient;+import software.amazon.awssdk.services.inspector2.Inspector2Client;import software.amazon.awssdk.services.detective.DetectiveClient;import software.amazon.awssdk.services.rum.RumClient;import software.amazon.awssdk.services.resourceexplorer2.ResourceExplorer2Client;@@ -364,6 +365,14 @@ public final class TestFixtures {.build();}+ public static Inspector2Client inspector2Client(String accountId) {+ return Inspector2Client.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/Inspector2OrganizationConfigurationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Inspector2OrganizationConfigurationTest.javanew file mode 100644index 0000000000..01f595f9cb--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Inspector2OrganizationConfigurationTest.java@@ -0,0 +1,157 @@+package com.floci.test;++import org.jboss.logging.Logger;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.inspector2.Inspector2Client;+import software.amazon.awssdk.services.inspector2.model.AutoEnable;+import software.amazon.awssdk.services.inspector2.model.ResourceScanType;+import software.amazon.awssdk.services.organizations.OrganizationsClient;+import software.amazon.awssdk.services.organizations.model.AlreadyInOrganizationException;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assumptions.assumeFalse;++@DisplayName("Amazon Inspector organization configuration")+class Inspector2OrganizationConfigurationTest {+ private static final Logger LOG = Logger.getLogger(Inspector2OrganizationConfigurationTest.class);+ private static final String MANAGEMENT_ACCOUNT = "test";++ @Test+ void organizationConfigurationUsesAwsSdk() {+ assumeFalse(TestFixtures.isRealAws(), "Avoids changing Amazon Inspector organization settings in real AWS");++ try (OrganizationsClient organizations = TestFixtures.organizationsClient()) {+ boolean createdOrganization = ensureOrganization(organizations);+ String adminAccount = null;+ String memberAccount = null;+ boolean delegatedAdminEnabled = false;++ try {+ adminAccount = createMemberAccount(organizations, "inspector-admin");+ memberAccount = createMemberAccount(organizations, "inspector-member");+ String delegatedAdminAccount = adminAccount;+ String inspectedMemberAccount = memberAccount;++ try (Inspector2Client management = TestFixtures.inspector2Client(MANAGEMENT_ACCOUNT);+ Inspector2Client administrator = TestFixtures.inspector2Client(delegatedAdminAccount)) {+ assertThat(management.listDelegatedAdminAccounts(request -> {}).delegatedAdminAccounts()).isEmpty();++ var enabled = management.enableDelegatedAdminAccount(request -> request+ .delegatedAdminAccountId(delegatedAdminAccount));+ delegatedAdminEnabled = true;+ assertThat(enabled.delegatedAdminAccountId()).isEqualTo(delegatedAdminAccount);++ assertThat(management.listDelegatedAdminAccounts(request -> {}).delegatedAdminAccounts())+ .singleElement()+ .satisfies(account -> {+ assertThat(account.accountId()).isEqualTo(delegatedAdminAccount);+ assertThat(account.statusAsString()).isEqualTo("ENABLED");+ });++ var enableMember = administrator.enable(request -> request+ .accountIds(inspectedMemberAccount)+ .resourceTypes(ResourceScanType.EC2));+ assertThat(enableMember.accounts()).singleElement().satisfies(account -> {+ assertThat(account.accountId()).isEqualTo(inspectedMemberAccount);+ assertThat(account.resourceStatus().ec2AsString()).isEqualTo("ENABLING");+ assertThat(account.resourceStatus().ecrAsString()).isEqualTo("DISABLED");+ });++ var firstStatus = administrator.batchGetAccountStatus(+ request -> request.accountIds(inspectedMemberAccount));+ assertThat(firstStatus.accounts()).singleElement().satisfies(account -> {+ assertThat(account.accountId()).isEqualTo(inspectedMemberAccount);+ assertThat(account.state().statusAsString()).isEqualTo("ENABLING");+ assertThat(account.resourceState().ec2().statusAsString()).isEqualTo("ENABLING");+ assertThat(account.resourceState().ecr().statusAsString()).isEqualTo("DISABLED");+ });+ var converged = administrator.batchGetAccountStatus(+ request -> request.accountIds(inspectedMemberAccount));+ assertThat(converged.accounts()).singleElement().satisfies(account -> {+ assertThat(account.state().statusAsString()).isEqualTo("ENABLED");+ assertThat(account.resourceState().ec2().statusAsString()).isEqualTo("ENABLED");+ assertThat(account.resourceState().ecr().statusAsString()).isEqualTo("DISABLED");+ });++ var updated = administrator.updateOrganizationConfiguration(request -> request+ .autoEnable(AutoEnable.builder()+ .ec2(true)+ .ecr(true)+ .lambda(false)+ .lambdaCode(false)+ .codeRepository(true)+ .build()));+ assertThat(updated.autoEnable().ec2()).isTrue();+ assertThat(updated.autoEnable().ecr()).isTrue();+ assertThat(updated.autoEnable().codeRepository()).isTrue();++ var described = administrator.describeOrganizationConfiguration(request -> {});+ assertThat(described.autoEnable().codeRepository()).isTrue();++ var disabled = management.disableDelegatedAdminAccount(request -> request+ .delegatedAdminAccountId(delegatedAdminAccount));+ delegatedAdminEnabled = false;+ assertThat(disabled.delegatedAdminAccountId()).isEqualTo(delegatedAdminAccount);+ }+ } finally {+ if (delegatedAdminEnabled) {+ disableDelegatedAdminBestEffort(adminAccount);+ }+ removeAccountBestEffort(organizations, memberAccount);+ removeAccountBestEffort(organizations, adminAccount);+ if (createdOrganization) {+ deleteOrganizationBestEffort(organizations);+ }+ }+ }+ }++ private static boolean ensureOrganization(OrganizationsClient organizations) {+ try {+ organizations.createOrganization(request -> request.featureSet("ALL"));+ return true;+ } catch (AlreadyInOrganizationException e) {+ LOG.debugf(e, "Default compatibility account already belongs to an AWS organization");+ return false;+ }+ }++ private static void disableDelegatedAdminBestEffort(String accountId) {+ if (accountId == null) {+ return;+ }+ try (Inspector2Client management = TestFixtures.inspector2Client(MANAGEMENT_ACCOUNT)) {+ management.disableDelegatedAdminAccount(request -> request.delegatedAdminAccountId(accountId));+ } catch (RuntimeException e) {+ LOG.warnf(e, "Inspector2 compatibility cleanup could not disable delegated administrator %s", accountId);+ }+ }++ private static void removeAccountBestEffort(OrganizationsClient organizations, String accountId) {+ if (accountId == null) {+ return;+ }+ try {+ organizations.removeAccountFromOrganization(request -> request.accountId(accountId));+ } catch (RuntimeException e) {+ LOG.warnf(e, "Inspector2 compatibility cleanup could not remove account %s", accountId);+ }+ }++ private static void deleteOrganizationBestEffort(OrganizationsClient organizations) {+ try {+ organizations.deleteOrganization();+ } catch (RuntimeException e) {+ LOG.warnf(e, "Inspector2 compatibility cleanup could not delete the temporary organization");+ }+ }++ private static String createMemberAccount(OrganizationsClient organizations, String prefix) {+ String suffix = TestFixtures.uniqueName(prefix);+ var response = organizations.createAccount(request -> request+ .accountName(suffix)+ .email(suffix + "@example.com"));+ return response.createAccountStatus().accountId();+ }+}diff --git a/docs/services/index.md b/docs/services/index.mdindex aabaac0d1c..1664fedff0 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 Inspector](inspector2.md) | `/delegatedadminaccounts/*`, `/status/batch/get`, `/enable`, `/organizationconfiguration/*` | REST JSON | 7 || [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 |diff --git a/docs/services/inspector2.md b/docs/services/inspector2.mdnew file mode 100644index 0000000000..e4a40419c7--- /dev/null+++ b/docs/services/inspector2.md@@ -0,0 +1,43 @@+# Amazon Inspector++**Protocol:** REST JSON++**Endpoint:** `http://localhost:4566`++Floci implements the Amazon Inspector organization operations used by local security-governance workflows.++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `ListDelegatedAdminAccounts` | - |+| `EnableDelegatedAdminAccount` | - |+| `DisableDelegatedAdminAccount` | - |+| `BatchGetAccountStatus` | - |+| `Enable` | - |+| `UpdateOrganizationConfiguration` | - |+| `DescribeOrganizationConfiguration` | - |+<!-- floci:actions:end -->++## Supported behavior++The supported surface includes delegated administrator management, `BatchGetAccountStatus`, Inspector enablement, and organization auto-enable configuration. Delegation is reflected into the delegated account so organization configuration can be managed through credentials for that administrator account.++`BatchGetAccountStatus` accepts an omitted or empty `accountIds` list and resolves it to the caller account. Explicit enablement supports `EC2`, `ECR`, `LAMBDA`, `LAMBDA_CODE`, and `CODE_REPOSITORY`, with the documented request-size limits. Explicit enablement uses the account-state values `ENABLING` and `ENABLED` so SDK and deployment waiters can converge.++Organization auto-enable supports `ec2`, `ecr`, `lambda`, `lambdaCode`, and `codeRepository`. Only the delegated administrator account can update or describe organization configuration.++## AWS-compatible failures++Invalid account IDs, resource types, pagination input, and request shapes return `ValidationException`. Conflicting delegated-administrator state returns `ConflictException`. Organization configuration from a non-administrator account returns `AccessDeniedException`, and disabling an administrator that is not configured returns `ResourceNotFoundException`.++AWS also models internal and throttling failures. Floci does not synthesize provider-side failures without a local triggering condition.++See the [Amazon Inspector API Reference](https://docs.aws.amazon.com/inspector/v2/APIReference/Welcome.html).++## Configuration++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_INSPECTOR2_ENABLED` | `true` | Enable or disable Amazon Inspector |diff --git a/mkdocs.yml b/mkdocs.ymlindex 580fc47de8..cfdb1aec81 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 Inspector: services/inspector2.md- Amazon Detective: services/detective.md- Control Catalog: services/controlcatalog.md- Control Tower: services/controltower.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex b86deca7f2..9c5e862d28 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -729,6 +729,7 @@ public interface EmulatorConfig {AccessAnalyzerServiceConfig accessanalyzer();IdentityStoreServiceConfig identitystore();BudgetsServiceConfig budgets();+ Inspector2ServiceConfig inspector2();DetectiveServiceConfig detective();ServiceQuotasServiceConfig servicequotas();RamServiceConfig ram();@@ -784,6 +785,11 @@ public interface EmulatorConfig {boolean enabled();}+ interface Inspector2ServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface DetectiveServiceConfig {@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.javaindex 2799a51eab..238b3299d5 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.inspector2.Inspector2Controller;import io.github.hectorvent.floci.services.detective.DetectiveController;import io.github.hectorvent.floci.services.aps.ApsController;import io.github.hectorvent.floci.services.controlcatalog.ControlCatalogController;@@ -436,6 +437,9 @@ public class ResolvedServiceCatalog {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("inspector2", "inspector2", config.services().inspector2().enabled(), true,+ "inspector2", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,+ protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("inspector2"), Set.of(), Set.of(Inspector2Controller.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/inspector2/Inspector2Controller.java b/src/main/java/io/github/hectorvent/floci/services/inspector2/Inspector2Controller.javanew file mode 100644index 0000000000..5d2d263639--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/inspector2/Inspector2Controller.java@@ -0,0 +1,200 @@+package io.github.hectorvent.floci.services.inspector2;++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.core.common.RequestContext;+import io.github.hectorvent.floci.services.inspector2.model.InspectorState;+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;++@Path("/")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class Inspector2Controller {+ private final Inspector2Service service;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;+ private final RequestContext requestContext;++ @Inject+ public Inspector2Controller(Inspector2Service service, RegionResolver regionResolver, ObjectMapper objectMapper,+ RequestContext requestContext) {+ this.service = service;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ this.requestContext = requestContext;+ }++ @POST+ @Path("/delegatedadminaccounts/list")+ public Response listDelegatedAdminAccounts(@Context HttpHeaders headers, String body) {+ JsonNode request = parse(body);+ if (request.has("maxResults")) {+ JsonNode maxResults = request.get("maxResults");+ if (!maxResults.canConvertToInt() || maxResults.intValue() < 1 || maxResults.intValue() > 5) {+ throw new AwsException("ValidationException", "maxResults must be between 1 and 5.", 400);+ }+ }+ if (request.hasNonNull("nextToken") && !request.path("nextToken").asText().isBlank()) {+ throw new AwsException("ValidationException", "nextToken is invalid.", 400);+ }+ InspectorState state = service.delegatedAdminState(region(headers), requestContext.getAccountId());+ var response = objectMapper.createObjectNode();+ var accounts = response.putArray("delegatedAdminAccounts");+ if (state.getAdminAccountId() != null) {+ accounts.addObject().put("accountId", state.getAdminAccountId()).put("status", "ENABLED");+ }+ return Response.ok(response).build();+ }++ @POST+ @Path("/delegatedadminaccounts/enable")+ public Response enableDelegatedAdminAccount(@Context HttpHeaders headers, String body) {+ JsonNode request = parse(body);+ String accountId = request.path("delegatedAdminAccountId").asText(null);+ service.enableDelegatedAdmin(region(headers), requestContext.getAccountId(), accountId);+ var response = objectMapper.createObjectNode();+ response.put("delegatedAdminAccountId", accountId);+ return Response.ok(response).build();+ }++ @POST+ @Path("/delegatedadminaccounts/disable")+ public Response disableDelegatedAdminAccount(@Context HttpHeaders headers, String body) {+ JsonNode request = parse(body);+ String accountId = request.path("delegatedAdminAccountId").asText(null);+ service.disableDelegatedAdmin(region(headers), requestContext.getAccountId(), accountId);+ var response = objectMapper.createObjectNode();+ response.put("delegatedAdminAccountId", accountId);+ return Response.ok(response).build();+ }++ @POST+ @Path("/status/batch/get")+ public Response batchGetAccountStatus(@Context HttpHeaders headers, String body) {+ JsonNode request = parse(body);+ JsonNode accountIds = request.get("accountIds");+ if (accountIds != null && (!accountIds.isArray() || accountIds.size() > 100)) {+ throw new AwsException("ValidationException",+ "accountIds must contain at most 100 account IDs.", 400);+ }+ java.util.List<String> requestedAccounts = requestedAccounts(accountIds);+ var response = objectMapper.createObjectNode();+ var accounts = response.putArray("accounts");+ for (String accountId : requestedAccounts) {+ InspectorState state = service.accountStatus(+ region(headers), requestContext.getAccountId(), accountId);+ var account = accounts.addObject();+ account.put("accountId", accountId);+ account.set("state", stateNode(state.getStatus()));+ account.set("resourceState", resourceState(state));+ }+ response.putArray("failedAccounts");+ return Response.ok(response).build();+ }++ @POST+ @Path("/enable")+ public Response enable(@Context HttpHeaders headers, String body) {+ JsonNode request = parse(body);+ var enabled = service.enable(region(headers), requestContext.getAccountId(), request);+ var response = objectMapper.createObjectNode();+ var accounts = response.putArray("accounts");+ enabled.forEach((accountId, state) -> {+ var account = accounts.addObject();+ account.put("accountId", accountId);+ account.put("status", state.getStatus());+ account.set("resourceStatus", resourceStatus(state));+ });+ response.putArray("failedAccounts");+ return Response.ok(response).build();+ }++ @POST+ @Path("/organizationconfiguration/update")+ public Response updateOrganizationConfiguration(@Context HttpHeaders headers, String body) {+ InspectorState state = service.updateOrganizationConfiguration(+ region(headers), requestContext.getAccountId(), parse(body));+ return Response.ok(organizationConfigurationResponse(state)).build();+ }++ @POST+ @Path("/organizationconfiguration/describe")+ public Response describeOrganizationConfiguration(@Context HttpHeaders headers, String body) {+ InspectorState state = service.organizationConfiguration(region(headers), requestContext.getAccountId());+ return Response.ok(organizationConfigurationResponse(state)).build();+ }++ private com.fasterxml.jackson.databind.node.ObjectNode organizationConfigurationResponse(InspectorState state) {+ var response = objectMapper.createObjectNode();+ var autoEnable = response.putObject("autoEnable");+ autoEnable.put("ec2", state.isAutoEnableEc2());+ autoEnable.put("ecr", state.isAutoEnableEcr());+ autoEnable.put("lambda", state.isAutoEnableLambda());+ autoEnable.put("lambdaCode", state.isAutoEnableLambdaCode());+ autoEnable.put("codeRepository", state.isAutoEnableCodeRepository());+ response.put("maxAccountLimitReached", false);+ return response;+ }++ private java.util.List<String> requestedAccounts(JsonNode accountIds) {+ if (accountIds == null || accountIds.isEmpty()) {+ return java.util.List.of(requestContext.getAccountId());+ }+ java.util.List<String> result = new java.util.ArrayList<>(accountIds.size());+ for (JsonNode accountId : accountIds) {+ Inspector2Service.requireAccountId(accountId.asText(null));+ result.add(accountId.asText());+ }+ return result;+ }++ private com.fasterxml.jackson.databind.node.ObjectNode resourceState(InspectorState state) {+ var resources = objectMapper.createObjectNode();+ resources.set("ec2", stateNode(state.getEc2Status()));+ resources.set("ecr", stateNode(state.getEcrStatus()));+ resources.set("lambda", stateNode(state.getLambdaStatus()));+ resources.set("lambdaCode", stateNode(state.getLambdaCodeStatus()));+ resources.set("codeRepository", stateNode(state.getCodeRepositoryStatus()));+ return resources;+ }++ private com.fasterxml.jackson.databind.node.ObjectNode resourceStatus(InspectorState state) {+ var resources = objectMapper.createObjectNode();+ resources.put("ec2", state.getEc2Status());+ resources.put("ecr", state.getEcrStatus());+ resources.put("lambda", state.getLambdaStatus());+ resources.put("lambdaCode", state.getLambdaCodeStatus());+ resources.put("codeRepository", state.getCodeRepositoryStatus());+ return resources;+ }++ private com.fasterxml.jackson.databind.node.ObjectNode stateNode(String status) {+ var state = objectMapper.createObjectNode();+ state.put("status", status);+ return state;+ }++ 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/inspector2/Inspector2Service.java b/src/main/java/io/github/hectorvent/floci/services/inspector2/Inspector2Service.javanew file mode 100644index 0000000000..b8a6d8a8d8--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/inspector2/Inspector2Service.java@@ -0,0 +1,313 @@+package io.github.hectorvent.floci.services.inspector2;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsException;+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.inspector2.model.InspectorState;+import io.github.hectorvent.floci.services.organizations.OrganizationsService;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++@ApplicationScoped+public class Inspector2Service implements Resettable {+ private static final Set<String> RESOURCE_TYPES = Set.of(+ "EC2", "ECR", "LAMBDA", "LAMBDA_CODE", "CODE_REPOSITORY");++ private final AccountAwareStorageBackend<InspectorState> states;+ private final OrganizationsService organizationsService;++ @Inject+ public Inspector2Service(StorageFactory storageFactory, OrganizationsService organizationsService) {+ this(storageFactory.create("inspector2", "inspector2-state.json",+ new TypeReference<Map<String, InspectorState>>() {}), organizationsService);+ }++ Inspector2Service(AccountAwareStorageBackend<InspectorState> states, OrganizationsService organizationsService) {+ this.states = states;+ this.organizationsService = organizationsService;+ }++ public InspectorState state(String region) {+ return states.get(region).orElseGet(InspectorState::new);+ }++ public InspectorState delegatedAdminState(String region, String callerAccountId) {+ requireManagementAccount(callerAccountId);+ return stateForAccount(callerAccountId, region);+ }++ public synchronized void enableDelegatedAdmin(String region, String callerAccountId, String accountId) {+ requireAccountId(accountId);+ String managementAccountId = requireManagementAccount(callerAccountId);+ requireSameOrganization(managementAccountId, accountId);++ InspectorState management = stateForAccount(managementAccountId, region);+ if (management.getAdminAccountId() != null && !management.getAdminAccountId().equals(accountId)) {+ throw new AwsException("ConflictException",+ "A different delegated administrator is already configured.", 409);+ }+ management.setAdminAccountId(accountId);+ states.putForAccount(managementAccountId, region, management);++ InspectorState delegated = stateForAccount(accountId, region);+ delegated.setAdminAccountId(accountId);+ for (String resourceType : RESOURCE_TYPES) {+ delegated.setResourceStatus(resourceType, "ENABLED");+ }+ delegated.setStatus("ENABLED");+ delegated.setEnablingPollsRemaining(0);+ states.putForAccount(accountId, region, delegated);+ }++ public synchronized void disableDelegatedAdmin(String region, String callerAccountId, String accountId) {+ requireAccountId(accountId);+ String managementAccountId = requireManagementAccount(callerAccountId);+ requireSameOrganization(managementAccountId, accountId);+ InspectorState management = stateForAccount(managementAccountId, region);+ if (!accountId.equals(management.getAdminAccountId())) {+ throw new AwsException("ResourceNotFoundException",+ "The specified delegated administrator was not found.", 404);+ }+ management.setAdminAccountId(null);+ states.putForAccount(managementAccountId, region, management);+ InspectorState delegated = stateForAccount(accountId, region);+ delegated.setAdminAccountId(null);+ states.putForAccount(accountId, region, delegated);+ }++ public synchronized InspectorState accountStatus(String region, String callerAccountId, String accountId) {+ requireAccountId(accountId);+ authorizeAccountAccess(region, callerAccountId, accountId);+ InspectorState state = stateForAccount(accountId, region);+ if ("ENABLING".equals(state.getStatus()) && state.getEnablingPollsRemaining() > 0) {+ InspectorState response = copyState(state);+ state.setEnablingPollsRemaining(state.getEnablingPollsRemaining() - 1);+ states.putForAccount(accountId, region, state);+ return response;+ }+ if ("ENABLING".equals(state.getStatus())) {+ for (String resourceType : RESOURCE_TYPES) {+ if ("ENABLING".equals(state.resourceStatus(resourceType))) {+ state.setResourceStatus(resourceType, "ENABLED");+ }+ }+ state.setStatus(overallStatus(state));+ states.putForAccount(accountId, region, state);+ }+ return copyState(state);+ }++ public synchronized Map<String, InspectorState> enable(+ String region, String callerAccountId, JsonNode request) {+ List<String> resourceTypes = resourceTypes(request);+ List<String> accountIds = accountIds(request, callerAccountId);++ for (String accountId : accountIds) {+ authorizeAccountAccess(region, callerAccountId, accountId);+ }++ Map<String, InspectorState> result = new LinkedHashMap<>();+ for (String accountId : accountIds) {+ InspectorState state = stateForAccount(accountId, region);+ boolean changed = false;+ for (String resourceType : resourceTypes) {+ String current = state.resourceStatus(resourceType);+ if (!"ENABLED".equals(current) && !"ENABLING".equals(current)) {+ state.setResourceStatus(resourceType, "ENABLING");+ changed = true;+ }+ }+ if (changed) {+ state.setStatus("ENABLING");+ state.setEnablingPollsRemaining(1);+ states.putForAccount(accountId, region, state);+ }+ result.put(accountId, copyState(state));+ }+ return result;+ }++ public synchronized InspectorState updateOrganizationConfiguration(+ String region, String callerAccountId, JsonNode request) {+ InspectorState state = requireAdministrator(region, callerAccountId);+ JsonNode autoEnable = request.get("autoEnable");+ if (autoEnable == null || !autoEnable.isObject()) {+ throw new AwsException("ValidationException", "autoEnable is required.", 400);+ }++ boolean ec2 = requiredBoolean(autoEnable, "ec2");+ boolean ecr = requiredBoolean(autoEnable, "ecr");+ boolean lambda = optionalBoolean(autoEnable, "lambda");+ boolean lambdaCode = optionalBoolean(autoEnable, "lambdaCode");+ boolean codeRepository = optionalBoolean(autoEnable, "codeRepository");++ state.setAutoEnableEc2(ec2);+ state.setAutoEnableEcr(ecr);+ state.setAutoEnableLambda(lambda);+ state.setAutoEnableLambdaCode(lambdaCode);+ state.setAutoEnableCodeRepository(codeRepository);+ states.putForAccount(callerAccountId, region, state);+ return copyState(state);+ }++ public InspectorState organizationConfiguration(String region, String callerAccountId) {+ return copyState(requireAdministrator(region, callerAccountId));+ }++ private InspectorState requireAdministrator(String region, String callerAccountId) {+ String managementAccountId = managementAccountFor(callerAccountId)+ .orElseThrow(() -> new AwsException("AccessDeniedException",+ "Only the delegated Amazon Inspector administrator can manage organization configuration.", 403));+ InspectorState management = stateForAccount(managementAccountId, region);+ if (management.getAdminAccountId() == null || !callerAccountId.equals(management.getAdminAccountId())) {+ throw new AwsException("AccessDeniedException",+ "Only the delegated Amazon Inspector administrator can manage organization configuration.", 403);+ }+ return stateForAccount(callerAccountId, region);+ }++ private void authorizeAccountAccess(String region, String callerAccountId, String targetAccountId) {+ if (callerAccountId.equals(targetAccountId)) {+ return;+ }+ String managementAccountId = managementAccountFor(callerAccountId)+ .orElseThrow(() -> accessDenied("The caller cannot manage the requested Amazon Inspector account."));+ requireSameOrganization(managementAccountId, targetAccountId);+ InspectorState management = stateForAccount(managementAccountId, region);+ if (!callerAccountId.equals(management.getAdminAccountId())) {+ throw accessDenied("Only the delegated Amazon Inspector administrator can manage member accounts.");+ }+ }++ private String requireManagementAccount(String callerAccountId) {+ String managementAccountId = managementAccountFor(callerAccountId)+ .orElseThrow(() -> accessDenied("Only the AWS Organizations management account can perform this operation."));+ if (!callerAccountId.equals(managementAccountId)) {+ throw accessDenied("Only the AWS Organizations management account can perform this operation.");+ }+ return managementAccountId;+ }++ private void requireSameOrganization(String managementAccountId, String accountId) {+ String targetManagementAccount = managementAccountFor(accountId)+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "The specified AWS account is not a member of the organization.", 404));+ if (!managementAccountId.equals(targetManagementAccount)) {+ throw new AwsException("ResourceNotFoundException",+ "The specified AWS account is not a member of the organization.", 404);+ }+ }++ private java.util.Optional<String> managementAccountFor(String accountId) {+ return organizationsService.findManagementAccountForResource(accountId);+ }++ private InspectorState stateForAccount(String accountId, String region) {+ return states.getForAccount(accountId, region).orElseGet(InspectorState::new);+ }++ private static List<String> resourceTypes(JsonNode request) {+ JsonNode resourceTypes = request.get("resourceTypes");+ if (resourceTypes == null || !resourceTypes.isArray() || resourceTypes.isEmpty() || resourceTypes.size() > 5) {+ throw new AwsException("ValidationException",+ "resourceTypes must contain between 1 and 5 resource types.", 400);+ }+ List<String> result = new ArrayList<>(resourceTypes.size());+ for (JsonNode resourceType : resourceTypes) {+ if (!resourceType.isTextual() || !RESOURCE_TYPES.contains(resourceType.textValue())) {+ throw new AwsException("ValidationException", "resourceTypes contains an invalid resource type.", 400);+ }+ if (!result.contains(resourceType.textValue())) {+ result.add(resourceType.textValue());+ }+ }+ return result;+ }++ private static List<String> accountIds(JsonNode request, String callerAccountId) {+ JsonNode accountIds = request.get("accountIds");+ if (accountIds != null && (!accountIds.isArray() || accountIds.size() > 100)) {+ throw new AwsException("ValidationException", "accountIds must contain at most 100 account IDs.", 400);+ }+ if (accountIds == null || accountIds.isEmpty()) {+ return List.of(callerAccountId);+ }+ List<String> result = new ArrayList<>(accountIds.size());+ for (JsonNode accountId : accountIds) {+ requireAccountId(accountId.asText(null));+ result.add(accountId.asText());+ }+ return result;+ }++ private static String overallStatus(InspectorState state) {+ boolean enabling = RESOURCE_TYPES.stream().anyMatch(type -> "ENABLING".equals(state.resourceStatus(type)));+ if (enabling) {+ return "ENABLING";+ }+ boolean enabled = RESOURCE_TYPES.stream().anyMatch(type -> "ENABLED".equals(state.resourceStatus(type)));+ return enabled ? "ENABLED" : "DISABLED";+ }++ private static InspectorState copyState(InspectorState source) {+ InspectorState copy = new InspectorState();+ copy.setAdminAccountId(source.getAdminAccountId());+ copy.setStatus(source.getStatus());+ copy.setEnablingPollsRemaining(source.getEnablingPollsRemaining());+ copy.setEc2Status(source.getEc2Status());+ copy.setEcrStatus(source.getEcrStatus());+ copy.setLambdaStatus(source.getLambdaStatus());+ copy.setLambdaCodeStatus(source.getLambdaCodeStatus());+ copy.setCodeRepositoryStatus(source.getCodeRepositoryStatus());+ copy.setAutoEnableEc2(source.isAutoEnableEc2());+ copy.setAutoEnableEcr(source.isAutoEnableEcr());+ copy.setAutoEnableLambda(source.isAutoEnableLambda());+ copy.setAutoEnableLambdaCode(source.isAutoEnableLambdaCode());+ copy.setAutoEnableCodeRepository(source.isAutoEnableCodeRepository());+ return copy;+ }++ private static boolean requiredBoolean(JsonNode node, String field) {+ JsonNode value = node.get(field);+ if (value == null || !value.isBoolean()) {+ throw new AwsException("ValidationException", "autoEnable." + field + " is required.", 400);+ }+ return value.booleanValue();+ }++ private static boolean optionalBoolean(JsonNode node, String field) {+ JsonNode value = node.get(field);+ if (value == null || value.isNull()) {+ return false;+ }+ if (!value.isBoolean()) {+ throw new AwsException("ValidationException", "autoEnable." + field + " must be a boolean.", 400);+ }+ return value.booleanValue();+ }++ private static AwsException accessDenied(String message) {+ return new AwsException("AccessDeniedException", message, 403);+ }++ @Override+ public void clear() {+ states.clear();+ }++ static void requireAccountId(String accountId) {+ if (accountId == null || !accountId.matches("\\d{12}")) {+ throw new AwsException("ValidationException",+ "accountId must be a 12 digit AWS account ID.", 400);+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/inspector2/model/InspectorState.java b/src/main/java/io/github/hectorvent/floci/services/inspector2/model/InspectorState.javanew file mode 100644index 0000000000..69600a69cb--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/inspector2/model/InspectorState.java@@ -0,0 +1,74 @@+package io.github.hectorvent.floci.services.inspector2.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class InspectorState {+ private String adminAccountId;+ private String status = "DISABLED";+ private int enablingPollsRemaining;+ private String ec2Status = "DISABLED";+ private String ecrStatus = "DISABLED";+ private String lambdaStatus = "DISABLED";+ private String lambdaCodeStatus = "DISABLED";+ private String codeRepositoryStatus = "DISABLED";+ private boolean autoEnableEc2;+ private boolean autoEnableEcr;+ private boolean autoEnableLambda;+ private boolean autoEnableLambdaCode;+ private boolean autoEnableCodeRepository;++ public InspectorState() {+ }++ public String getAdminAccountId() { return adminAccountId; }+ public void setAdminAccountId(String adminAccountId) { this.adminAccountId = adminAccountId; }+ public String getStatus() { return status; }+ public void setStatus(String status) { this.status = status; }+ public int getEnablingPollsRemaining() { return enablingPollsRemaining; }+ public void setEnablingPollsRemaining(int enablingPollsRemaining) { this.enablingPollsRemaining = enablingPollsRemaining; }+ public String getEc2Status() { return ec2Status; }+ public void setEc2Status(String value) { ec2Status = value; }+ public String getEcrStatus() { return ecrStatus; }+ public void setEcrStatus(String value) { ecrStatus = value; }+ public String getLambdaStatus() { return lambdaStatus; }+ public void setLambdaStatus(String value) { lambdaStatus = value; }+ public String getLambdaCodeStatus() { return lambdaCodeStatus; }+ public void setLambdaCodeStatus(String value) { lambdaCodeStatus = value; }+ public String getCodeRepositoryStatus() { return codeRepositoryStatus; }+ public void setCodeRepositoryStatus(String value) { codeRepositoryStatus = value; }+ public boolean isAutoEnableEc2() { return autoEnableEc2; }+ public void setAutoEnableEc2(boolean value) { autoEnableEc2 = value; }+ public boolean isAutoEnableEcr() { return autoEnableEcr; }+ public void setAutoEnableEcr(boolean value) { autoEnableEcr = value; }+ public boolean isAutoEnableLambda() { return autoEnableLambda; }+ public void setAutoEnableLambda(boolean value) { autoEnableLambda = value; }+ public boolean isAutoEnableLambdaCode() { return autoEnableLambdaCode; }+ public void setAutoEnableLambdaCode(boolean value) { autoEnableLambdaCode = value; }+ public boolean isAutoEnableCodeRepository() { return autoEnableCodeRepository; }+ public void setAutoEnableCodeRepository(boolean value) { autoEnableCodeRepository = value; }++ public String resourceStatus(String resourceType) {+ return switch (resourceType) {+ case "EC2" -> ec2Status;+ case "ECR" -> ecrStatus;+ case "LAMBDA" -> lambdaStatus;+ case "LAMBDA_CODE" -> lambdaCodeStatus;+ case "CODE_REPOSITORY" -> codeRepositoryStatus;+ default -> throw new IllegalArgumentException("Unknown Inspector resource type: " + resourceType);+ };+ }++ public void setResourceStatus(String resourceType, String value) {+ switch (resourceType) {+ case "EC2" -> ec2Status = value;+ case "ECR" -> ecrStatus = value;+ case "LAMBDA" -> lambdaStatus = value;+ case "LAMBDA_CODE" -> lambdaCodeStatus = value;+ case "CODE_REPOSITORY" -> codeRepositoryStatus = value;+ default -> throw new IllegalArgumentException("Unknown Inspector resource type: " + resourceType);+ }+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex d717724111..8dff78629b 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -629,6 +629,8 @@ floci:enabled: truebudgets:enabled: true+ inspector2:+ enabled: truedetective:enabled: truecontroltower:diff --git a/src/test/java/io/github/hectorvent/floci/services/inspector2/Inspector2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/inspector2/Inspector2IntegrationTest.javanew file mode 100644index 0000000000..4b2d9029f2--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/inspector2/Inspector2IntegrationTest.java@@ -0,0 +1,169 @@+package io.github.hectorvent.floci.services.inspector2;++import io.github.hectorvent.floci.services.organizations.OrganizationsService;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+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 Inspector2IntegrationTest {++ @Inject+ OrganizationsService organizationsService;++ @Test+ void delegatedAdminEnablementAndOrganizationConfiguration() {+ String management = "940000000001";+ String administrator = "940000000002";+ createOrganization(management, administrator);++ given().contentType("application/json").header("Authorization", auth(management)).body("{}")+ .post("/delegatedadminaccounts/list").then().statusCode(200);+ given().contentType("application/json").header("Authorization", auth(management))+ .body("{\"delegatedAdminAccountId\":\"" + administrator + "\"}")+ .post("/delegatedadminaccounts/enable").then().statusCode(200)+ .body("delegatedAdminAccountId", equalTo(administrator));+ given().contentType("application/json").header("Authorization", auth(administrator))+ .body("{\"autoEnable\":{\"ec2\":true,\"ecr\":true,\"lambda\":true,"+ + "\"lambdaCode\":true,\"codeRepository\":true}}")+ .post("/organizationconfiguration/update").then().statusCode(200)+ .body("autoEnable.codeRepository", equalTo(true));+ given().contentType("application/json").header("Authorization", auth(administrator)).body("{}")+ .post("/organizationconfiguration/describe").then().statusCode(200)+ .body("autoEnable.ec2", equalTo(true))+ .body("autoEnable.ecr", equalTo(true))+ .body("autoEnable.lambda", equalTo(true))+ .body("autoEnable.lambdaCode", equalTo(true))+ .body("autoEnable.codeRepository", equalTo(true));+ }++ @Test+ void managementAuthorizationAndMembershipAreEnforced() {+ String management = "940000000011";+ String administrator = "940000000012";+ String member = "940000000013";+ String outsider = "950000000014";+ createOrganization(management, administrator, member);++ given().contentType("application/json").header("Authorization", auth(member))+ .body("{\"delegatedAdminAccountId\":\"" + administrator + "\"}")+ .post("/delegatedadminaccounts/enable").then().statusCode(403)+ .body("__type", equalTo("AccessDeniedException"));+ given().contentType("application/json").header("Authorization", auth(management))+ .body("{\"delegatedAdminAccountId\":\"" + outsider + "\"}")+ .post("/delegatedadminaccounts/enable").then().statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ @Test+ void delegatedAdminManagesMemberPerResourceState() {+ String management = "940000000021";+ String administrator = "940000000022";+ String member = "940000000023";+ createOrganization(management, administrator, member);+ designateAdministrator(management, administrator);++ given().contentType("application/json").header("Authorization", auth(administrator))+ .body("{\"accountIds\":[\"" + member + "\"],\"resourceTypes\":[\"EC2\"]}")+ .post("/enable").then().statusCode(200)+ .body("accounts[0].accountId", equalTo(member))+ .body("accounts[0].resourceStatus.ec2", equalTo("ENABLING"))+ .body("accounts[0].resourceStatus.ecr", equalTo("DISABLED"));++ String body = "{\"accountIds\":[\"" + member + "\"]}";+ given().contentType("application/json").header("Authorization", auth(administrator)).body(body)+ .post("/status/batch/get").then().statusCode(200)+ .body("accounts", hasSize(1))+ .body("accounts[0].accountId", equalTo(member))+ .body("accounts[0].state.status", equalTo("ENABLING"))+ .body("accounts[0].resourceState.ec2.status", equalTo("ENABLING"))+ .body("accounts[0].resourceState.ecr.status", equalTo("DISABLED"));+ given().contentType("application/json").header("Authorization", auth(administrator)).body(body)+ .post("/status/batch/get").then().statusCode(200)+ .body("accounts[0].state.status", equalTo("ENABLED"))+ .body("accounts[0].resourceState.ec2.status", equalTo("ENABLED"))+ .body("accounts[0].resourceState.ecr.status", equalTo("DISABLED"));+ }++ @Test+ void memberCanEnableItselfWithOmittedAccountIds() {+ String management = "940000000031";+ String member = "940000000032";+ createOrganization(management, member);++ given().contentType("application/json").header("Authorization", auth(member))+ .body("{\"resourceTypes\":[\"ECR\"]}")+ .post("/enable").then().statusCode(200)+ .body("accounts[0].accountId", equalTo(member))+ .body("accounts[0].resourceStatus.ecr", equalTo("ENABLING"));+ given().contentType("application/json").header("Authorization", auth(member)).body("{}")+ .post("/status/batch/get").then().statusCode(200)+ .body("accounts", hasSize(1))+ .body("accounts[0].accountId", equalTo(member));+ }++ @Test+ void failedOrganizationUpdateDoesNotPartiallyMutateState() {+ String management = "940000000041";+ String administrator = "940000000042";+ createOrganization(management, administrator);+ designateAdministrator(management, administrator);++ given().contentType("application/json").header("Authorization", auth(administrator))+ .body("{\"autoEnable\":{\"ec2\":false,\"ecr\":false}}")+ .post("/organizationconfiguration/update").then().statusCode(200);+ given().contentType("application/json").header("Authorization", auth(administrator))+ .body("{\"autoEnable\":{\"ec2\":true}}")+ .post("/organizationconfiguration/update").then().statusCode(400)+ .body("__type", equalTo("ValidationException"));+ given().contentType("application/json").header("Authorization", auth(administrator)).body("{}")+ .post("/organizationconfiguration/describe").then().statusCode(200)+ .body("autoEnable.ec2", equalTo(false))+ .body("autoEnable.ecr", equalTo(false));+ }++ @Test+ void delegatedAdminCanBeDisabledByManagementAccount() {+ String management = "940000000051";+ String administrator = "940000000052";+ createOrganization(management, administrator);+ designateAdministrator(management, administrator);+ given().contentType("application/json").header("Authorization", auth(management))+ .body("{\"delegatedAdminAccountId\":\"" + administrator + "\"}")+ .post("/delegatedadminaccounts/disable").then().statusCode(200)+ .body("delegatedAdminAccountId", equalTo(administrator));+ }++ @Test+ void invalidAccountIdReturnsValidationException() {+ String management = "940000000061";+ organizationsService.createOrganization(management, "ALL");+ given().contentType("application/json").header("Authorization", auth(management))+ .body("{\"delegatedAdminAccountId\":\"bad\"}")+ .post("/delegatedadminaccounts/enable").then().statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ private void createOrganization(String managementAccountId, String... members) {+ organizationsService.createOrganization(managementAccountId, "ALL");+ for (String member : members) {+ var handshake = organizationsService.inviteAccountToOrganization(+ managementAccountId, member, "ACCOUNT", null);+ organizationsService.acceptHandshake(member, handshake.getId());+ }+ }++ private void designateAdministrator(String managementAccountId, String administratorAccountId) {+ given().contentType("application/json").header("Authorization", auth(managementAccountId))+ .body("{\"delegatedAdminAccountId\":\"" + administratorAccountId + "\"}")+ .post("/delegatedadminaccounts/enable").then().statusCode(200);+ }++ private static String auth(String accountId) {+ return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260101/us-east-1/inspector2/aws4_request";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/inspector2/Inspector2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/inspector2/Inspector2ServiceTest.javanew file mode 100644index 0000000000..bfd906c710--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/inspector2/Inspector2ServiceTest.java@@ -0,0 +1,146 @@+package io.github.hectorvent.floci.services.inspector2;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.services.inspector2.model.InspectorState;+import io.github.hectorvent.floci.services.organizations.OrganizationsService;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.Optional;++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 Inspector2ServiceTest {+ private static final String REGION = "us-east-1";+ private static final String MANAGEMENT_ACCOUNT = "222222222222";+ private static final String ADMIN_ACCOUNT = "111111111111";+ private static final String MEMBER_ACCOUNT = "333333333333";+ private static final String OUTSIDE_ACCOUNT = "444444444444";++ private final ObjectMapper objectMapper = new ObjectMapper();+ private Inspector2Service service;++ @BeforeEach+ void setUp() {+ OrganizationsService organizations = mock(OrganizationsService.class);+ when(organizations.findManagementAccountForResource(MANAGEMENT_ACCOUNT))+ .thenReturn(Optional.of(MANAGEMENT_ACCOUNT));+ when(organizations.findManagementAccountForResource(ADMIN_ACCOUNT))+ .thenReturn(Optional.of(MANAGEMENT_ACCOUNT));+ when(organizations.findManagementAccountForResource(MEMBER_ACCOUNT))+ .thenReturn(Optional.of(MANAGEMENT_ACCOUNT));+ when(organizations.findManagementAccountForResource(OUTSIDE_ACCOUNT))+ .thenReturn(Optional.of(OUTSIDE_ACCOUNT));+ service = new Inspector2Service(+ AccountAwareStorageBackend.<InspectorState>inMemory(MANAGEMENT_ACCOUNT), organizations);+ }++ @Test+ void onlyManagementAccountCanDesignateDelegatedAdministrator() {+ AwsException denied = assertThrows(AwsException.class,+ () -> service.enableDelegatedAdmin(REGION, MEMBER_ACCOUNT, ADMIN_ACCOUNT));+ assertEquals("AccessDeniedException", denied.getErrorCode());++ AwsException outsider = assertThrows(AwsException.class,+ () -> service.enableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, OUTSIDE_ACCOUNT));+ assertEquals("ResourceNotFoundException", outsider.getErrorCode());+ }++ @Test+ void delegatedAdministratorOwnsOrganizationConfiguration() throws Exception {+ service.enableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);++ InspectorState state = service.updateOrganizationConfiguration(REGION, ADMIN_ACCOUNT,+ objectMapper.readTree("{\"autoEnable\":{\"ec2\":true,\"ecr\":true,\"codeRepository\":true}}"));++ assertTrue(state.isAutoEnableEc2());+ assertTrue(state.isAutoEnableEcr());+ assertTrue(state.isAutoEnableCodeRepository());+ }++ @Test+ void failedOrganizationConfigurationUpdateIsAtomic() throws Exception {+ service.enableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);+ service.updateOrganizationConfiguration(REGION, ADMIN_ACCOUNT,+ objectMapper.readTree("{\"autoEnable\":{\"ec2\":false,\"ecr\":false}}"));++ AwsException error = assertThrows(AwsException.class,+ () -> service.updateOrganizationConfiguration(REGION, ADMIN_ACCOUNT,+ objectMapper.readTree("{\"autoEnable\":{\"ec2\":true}}")));++ assertEquals("ValidationException", error.getErrorCode());+ InspectorState current = service.organizationConfiguration(REGION, ADMIN_ACCOUNT);+ assertFalse(current.isAutoEnableEc2());+ assertFalse(current.isAutoEnableEcr());+ }++ @Test+ void delegatedAdministratorEnablesMemberAndOnlyRequestedResourceTypes() throws Exception {+ service.enableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);++ service.enable(REGION, ADMIN_ACCOUNT, objectMapper.readTree(+ "{\"accountIds\":[\"" + MEMBER_ACCOUNT + "\"],\"resourceTypes\":[\"EC2\"]}"));++ InspectorState first = service.accountStatus(REGION, ADMIN_ACCOUNT, MEMBER_ACCOUNT);+ assertEquals("ENABLING", first.getStatus());+ assertEquals("ENABLING", first.getEc2Status());+ assertEquals("DISABLED", first.getEcrStatus());+ assertEquals("DISABLED", first.getLambdaStatus());+ InspectorState converged = service.accountStatus(REGION, ADMIN_ACCOUNT, MEMBER_ACCOUNT);+ assertEquals("ENABLED", converged.getStatus());+ assertEquals("ENABLED", converged.getEc2Status());+ assertEquals("DISABLED", converged.getEcrStatus());+ }++ @Test+ void memberMayEnableItselfButCannotManageAnotherAccount() throws Exception {+ service.enable(REGION, MEMBER_ACCOUNT, objectMapper.readTree(+ "{\"resourceTypes\":[\"ECR\"]}"));+ assertEquals("ENABLING", service.accountStatus(REGION, MEMBER_ACCOUNT, MEMBER_ACCOUNT).getEcrStatus());++ AwsException denied = assertThrows(AwsException.class,+ () -> service.enable(REGION, MEMBER_ACCOUNT, objectMapper.readTree(+ "{\"accountIds\":[\"" + ADMIN_ACCOUNT + "\"],\"resourceTypes\":[\"EC2\"]}")));+ assertEquals("AccessDeniedException", denied.getErrorCode());+ }++ @Test+ void managementAccountCannotUpdateOrganizationConfiguration() throws Exception {+ service.enableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);++ AwsException error = assertThrows(AwsException.class,+ () -> service.updateOrganizationConfiguration(REGION, MANAGEMENT_ACCOUNT,+ objectMapper.readTree("{\"autoEnable\":{\"ec2\":true,\"ecr\":true}}")));++ assertEquals("AccessDeniedException", error.getErrorCode());+ }++ @Test+ void disableRequiresManagementAndCurrentAdministrator() {+ service.enableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);++ AwsException denied = assertThrows(AwsException.class,+ () -> service.disableDelegatedAdmin(REGION, ADMIN_ACCOUNT, ADMIN_ACCOUNT));+ assertEquals("AccessDeniedException", denied.getErrorCode());++ AwsException missing = assertThrows(AwsException.class,+ () -> service.disableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, MEMBER_ACCOUNT));+ assertEquals("ResourceNotFoundException", missing.getErrorCode());+ }++ @Test+ void clearRemovesState() {+ service.enableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);+ service.clear();++ assertNull(service.state(REGION).getAdminAccountId());+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 358361c874..bbb140e5e4 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -390,6 +390,8 @@ floci:enabled: truebudgets:enabled: true+ inspector2:+ enabled: truedetective:enabled: truecontroltower:diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex 4bc2d508f2..4123929ff1 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -168,6 +168,10 @@ services:- { path: src/main/java/io/github/hectorvent/floci/services/securityadmin/SecurityAdminController.java, mode: rest }rename_actions:ListAdmin: ListOrganizationAdminAccounts+ - service: inspector2+ doc: docs/services/inspector2.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/inspector2/Inspector2Controller.java, mode: rest }- service: neptunedoc: docs/services/neptune.mdsources: