From 6779aa8270f092728a0799f8bbe0dd4e438f4360 Mon Sep 17 00:00:00 2001 From: Tucker Date: Mon, 17 Aug 2026 01:40:12 -0400 Subject: [PATCH] feat(guardduty): add GuardDuty detector and organization configuration emulation (#2346) --- compatibility-tests/compat-opentofu/main.tf | 44 ++ .../compat-opentofu/provider.tf | 1 + .../compat-opentofu/test/opentofu.bats | 14 + compatibility-tests/compat-terraform/main.tf | 85 ++- .../compat-terraform/provider.tf | 1 + .../compat-terraform/test/terraform.bats | 37 ++ compatibility-tests/sdk-test-java/pom.xml | 5 + .../java/com/floci/test/TestFixtures.java | 9 + .../java/com/floci/test/GuardDutyTest.java | 192 ++++++ docs/services/guardduty.md | 83 +++ docs/services/index.md | 3 +- mkdocs.yml | 1 + .../floci/config/EmulatorConfig.java | 14 + .../core/common/ResolvedServiceCatalog.java | 9 +- .../guardduty/GuardDutyController.java | 202 +++++++ .../services/guardduty/GuardDutyService.java | 549 ++++++++++++++++++ .../guardduty/GuardDutyTagHandler.java | 46 ++ .../guardduty/model/AdminAccount.java | 36 ++ .../services/guardduty/model/Detector.java | 118 ++++ .../DetectorAdditionalConfiguration.java | 46 ++ .../guardduty/model/DetectorFeature.java | 67 +++ .../OrganizationAdditionalConfiguration.java | 36 ++ .../model/OrganizationConfiguration.java | 49 ++ .../guardduty/model/OrganizationFeature.java | 55 ++ src/main/resources/application.yml | 4 + .../GuardDutyControllerIntegrationTest.java | 314 ++++++++++ .../guardduty/GuardDutyServiceTest.java | 373 ++++++++++++ src/test/resources/application.yml | 4 + 28 files changed, 2388 insertions(+), 9 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GuardDutyTest.java create mode 100644 docs/services/guardduty.md create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyTagHandler.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/AdminAccount.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/Detector.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/DetectorAdditionalConfiguration.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/DetectorFeature.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationAdditionalConfiguration.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationConfiguration.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationFeature.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyControllerIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java diff --git a/compatibility-tests/compat-opentofu/main.tf b/compatibility-tests/compat-opentofu/main.tf index ab420dca0d..8854f38c7f 100644 --- a/compatibility-tests/compat-opentofu/main.tf +++ b/compatibility-tests/compat-opentofu/main.tf @@ -342,3 +342,47 @@ resource "aws_ses_active_receipt_rule_set" "compat" { output "ses_rule_set_name" { value = aws_ses_receipt_rule_set.compat.rule_set_name } + +# -- GuardDuty ----------------------------------------------------------------- +# Detector, per-feature configuration, and organization configuration mirror the +# resource set an org security-baseline stack manages. additional_configuration +# is an ordered list block: Floci must echo it back in submitted order or every +# re-plan proposes a replacement. +resource "aws_guardduty_detector" "compat" { + enable = true + finding_publishing_frequency = "SIX_HOURS" + + tags = { + Environment = "compat-test" + } +} + +resource "aws_guardduty_detector_feature" "runtime_monitoring" { + detector_id = aws_guardduty_detector.compat.id + name = "RUNTIME_MONITORING" + status = "ENABLED" + + additional_configuration { + name = "ECS_FARGATE_AGENT_MANAGEMENT" + status = "ENABLED" + } + + additional_configuration { + name = "EC2_AGENT_MANAGEMENT" + status = "ENABLED" + } + + additional_configuration { + name = "EKS_ADDON_MANAGEMENT" + status = "DISABLED" + } +} + +resource "aws_guardduty_organization_configuration" "compat" { + detector_id = aws_guardduty_detector.compat.id + auto_enable_organization_members = "ALL" +} + +output "guardduty_detector_id" { + value = aws_guardduty_detector.compat.id +} diff --git a/compatibility-tests/compat-opentofu/provider.tf b/compatibility-tests/compat-opentofu/provider.tf index a3d35ce3ad..2c269ad9c0 100644 --- a/compatibility-tests/compat-opentofu/provider.tf +++ b/compatibility-tests/compat-opentofu/provider.tf @@ -37,5 +37,6 @@ provider "aws" { ec2 = var.endpoint route53 = var.endpoint ses = var.endpoint + guardduty = var.endpoint } } diff --git a/compatibility-tests/compat-opentofu/test/opentofu.bats b/compatibility-tests/compat-opentofu/test/opentofu.bats index cfeedf2d79..1ecdc2e9ba 100644 --- a/compatibility-tests/compat-opentofu/test/opentofu.bats +++ b/compatibility-tests/compat-opentofu/test/opentofu.bats @@ -202,3 +202,17 @@ setup() { assert_success assert_output "GZIP" } + +@test "OpenTofu: GuardDuty detector is created with organization configuration" { + run aws_cmd guardduty list-detectors --query "DetectorIds[0]" --output text + assert_success + DETECTOR_ID="$output" + run aws_cmd guardduty get-detector --detector-id "$DETECTOR_ID" \ + --query "Status" --output text + assert_success + assert_output "ENABLED" + run aws_cmd guardduty describe-organization-configuration --detector-id "$DETECTOR_ID" \ + --query "AutoEnableOrganizationMembers" --output text + assert_success + assert_output "ALL" +} diff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tf index cc5e4ecc74..6ef11a7c57 100644 --- a/compatibility-tests/compat-terraform/main.tf +++ b/compatibility-tests/compat-terraform/main.tf @@ -115,13 +115,13 @@ resource "aws_secretsmanager_secret_version" "db_creds" { # -- RDS DB Instance ----------------------------------------------------------- resource "aws_db_instance" "app" { - identifier = "floci-compat-db" - engine = "postgres" - engine_version = "15" - instance_class = "db.t3.micro" - allocated_storage = 20 - username = "admin" - password = "Password1!" + identifier = "floci-compat-db" + engine = "postgres" + engine_version = "15" + instance_class = "db.t3.micro" + allocated_storage = 20 + username = "admin" + password = "Password1!" skip_final_snapshot = true } @@ -496,3 +496,74 @@ output "tagged_role_arn" { output "tagged_policy_arn" { value = aws_iam_policy.tagged.arn } + +# -- GuardDuty ----------------------------------------------------------------- +# Detector, per-feature configuration, and organization configuration mirror the +# resource set an org security-baseline stack manages. additional_configuration +# is an ordered list block: Floci must echo it back in submitted order or every +# re-plan proposes a replacement. +resource "aws_guardduty_detector" "compat" { + enable = true + finding_publishing_frequency = "SIX_HOURS" + + tags = { + Environment = "compat-test" + } +} + +resource "aws_guardduty_detector_feature" "runtime_monitoring" { + detector_id = aws_guardduty_detector.compat.id + name = "RUNTIME_MONITORING" + status = "ENABLED" + + additional_configuration { + name = "ECS_FARGATE_AGENT_MANAGEMENT" + status = "ENABLED" + } + + additional_configuration { + name = "EC2_AGENT_MANAGEMENT" + status = "ENABLED" + } + + additional_configuration { + name = "EKS_ADDON_MANAGEMENT" + status = "DISABLED" + } +} + +resource "aws_guardduty_organization_configuration" "compat" { + detector_id = aws_guardduty_detector.compat.id + auto_enable_organization_members = "ALL" +} + +resource "aws_guardduty_organization_configuration_feature" "runtime_monitoring" { + detector_id = aws_guardduty_detector.compat.id + name = "RUNTIME_MONITORING" + auto_enable = "ALL" + + additional_configuration { + name = "ECS_FARGATE_AGENT_MANAGEMENT" + auto_enable = "ALL" + } + + additional_configuration { + name = "EC2_AGENT_MANAGEMENT" + auto_enable = "ALL" + } + + additional_configuration { + name = "EKS_ADDON_MANAGEMENT" + auto_enable = "NONE" + } + + depends_on = [aws_guardduty_organization_configuration.compat] +} + +output "guardduty_detector_id" { + value = aws_guardduty_detector.compat.id +} + +output "guardduty_detector_arn" { + value = aws_guardduty_detector.compat.arn +} diff --git a/compatibility-tests/compat-terraform/provider.tf b/compatibility-tests/compat-terraform/provider.tf index 4c653085d6..2001fad068 100644 --- a/compatibility-tests/compat-terraform/provider.tf +++ b/compatibility-tests/compat-terraform/provider.tf @@ -41,5 +41,6 @@ provider "aws" { route53 = var.endpoint appautoscaling = var.endpoint ses = var.endpoint + guardduty = var.endpoint } } diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.bats index 9d33e4ef12..2984e10e39 100644 --- a/compatibility-tests/compat-terraform/test/terraform.bats +++ b/compatibility-tests/compat-terraform/test/terraform.bats @@ -347,3 +347,40 @@ setup() { fi [ "$status" -eq 0 ] } + +@test "Terraform: GuardDuty detector is created with features" { + run aws_cmd guardduty list-detectors --query "DetectorIds[0]" --output text + assert_success + DETECTOR_ID="$output" + run aws_cmd guardduty get-detector --detector-id "$DETECTOR_ID" \ + --query "[Status, FindingPublishingFrequency]" --output text + assert_success + assert_output --partial "ENABLED" + assert_output --partial "SIX_HOURS" +} + +@test "Terraform: GuardDuty organization configuration round-trips" { + run aws_cmd guardduty list-detectors --query "DetectorIds[0]" --output text + assert_success + DETECTOR_ID="$output" + run aws_cmd guardduty describe-organization-configuration --detector-id "$DETECTOR_ID" \ + --query "AutoEnableOrganizationMembers" --output text + assert_success + assert_output "ALL" +} + +# additional_configuration is an ordered list block; drift here means the +# emulator reordered the list on read-back. +@test "Terraform: re-planning GuardDuty reports no changes" { + cd "$TF_DIR" + run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode \ + -target=aws_guardduty_detector.compat \ + -target=aws_guardduty_detector_feature.runtime_monitoring \ + -target=aws_guardduty_organization_configuration.compat \ + -target=aws_guardduty_organization_configuration_feature.runtime_monitoring + if [ "$status" -eq 2 ]; then + echo "# drift detected on re-plan:" >&3 + echo "$output" >&3 + fi + [ "$status" -eq 0 ] +} diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 50858c1c9e..8af8fb70cb 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -258,6 +258,11 @@ software.amazon.awssdk rum + + + software.amazon.awssdk + guardduty + software.amazon.awssdk 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 6cd406fa73..7063e5b814 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 @@ -26,6 +26,7 @@ import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.opensearch.OpenSearchClient; import software.amazon.awssdk.services.neptune.NeptuneClient; import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.guardduty.GuardDutyClient; import software.amazon.awssdk.services.rum.RumClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.endpoints.Endpoint; @@ -719,6 +720,14 @@ public final class TestFixtures { .build(); } + public static GuardDutyClient guardDutyClient() { + return GuardDutyClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static NeptuneClient neptuneClient() { return NeptuneClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GuardDutyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GuardDutyTest.java new file mode 100644 index 0000000000..7a6be56b3c --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GuardDutyTest.java @@ -0,0 +1,192 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.guardduty.GuardDutyClient; +import software.amazon.awssdk.services.guardduty.model.AdminStatus; +import software.amazon.awssdk.services.guardduty.model.AutoEnableMembers; +import software.amazon.awssdk.services.guardduty.model.BadRequestException; +import software.amazon.awssdk.services.guardduty.model.CreateDetectorResponse; +import software.amazon.awssdk.services.guardduty.model.DescribeOrganizationConfigurationResponse; +import software.amazon.awssdk.services.guardduty.model.DetectorFeature; +import software.amazon.awssdk.services.guardduty.model.DetectorFeatureConfiguration; +import software.amazon.awssdk.services.guardduty.model.DetectorAdditionalConfiguration; +import software.amazon.awssdk.services.guardduty.model.DetectorStatus; +import software.amazon.awssdk.services.guardduty.model.FeatureAdditionalConfiguration; +import software.amazon.awssdk.services.guardduty.model.FeatureStatus; +import software.amazon.awssdk.services.guardduty.model.FindingPublishingFrequency; +import software.amazon.awssdk.services.guardduty.model.GetDetectorResponse; +import software.amazon.awssdk.services.guardduty.model.ListOrganizationAdminAccountsResponse; +import software.amazon.awssdk.services.guardduty.model.OrgFeature; +import software.amazon.awssdk.services.guardduty.model.OrgFeatureAdditionalConfiguration; +import software.amazon.awssdk.services.guardduty.model.OrgFeatureStatus; +import software.amazon.awssdk.services.guardduty.model.OrganizationAdditionalConfiguration; +import software.amazon.awssdk.services.guardduty.model.OrganizationFeatureConfiguration; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("GuardDuty") +class GuardDutyTest { + + @Test + void detectorLifecycleUsesAwsSdkWireShapes() throws Exception { + try (GuardDutyClient guardduty = TestFixtures.guardDutyClient()) { + CreateDetectorResponse created = guardduty.createDetector(request -> request + .enable(true) + .findingPublishingFrequency(FindingPublishingFrequency.SIX_HOURS) + .features(List.of( + DetectorFeatureConfiguration.builder() + .name(DetectorFeature.RUNTIME_MONITORING) + .status(FeatureStatus.ENABLED) + .additionalConfiguration(List.of( + DetectorAdditionalConfiguration.builder() + .name(FeatureAdditionalConfiguration + .ECS_FARGATE_AGENT_MANAGEMENT) + .status(FeatureStatus.ENABLED) + .build(), + DetectorAdditionalConfiguration.builder() + .name(FeatureAdditionalConfiguration.EC2_AGENT_MANAGEMENT) + .status(FeatureStatus.ENABLED) + .build(), + DetectorAdditionalConfiguration.builder() + .name(FeatureAdditionalConfiguration.EKS_ADDON_MANAGEMENT) + .status(FeatureStatus.DISABLED) + .build())) + .build(), + DetectorFeatureConfiguration.builder() + .name(DetectorFeature.S3_DATA_EVENTS) + .status(FeatureStatus.ENABLED) + .build())) + .tags(Map.of("env", "compat"))); + String detectorId = created.detectorId(); + assertThat(detectorId).hasSize(32); + + try (AutoCloseable deleteDetector = () -> + guardduty.deleteDetector(request -> request.detectorId(detectorId))) { + GetDetectorResponse detector = + guardduty.getDetector(request -> request.detectorId(detectorId)); + assertThat(detector.status()).isEqualTo(DetectorStatus.ENABLED); + assertThat(detector.findingPublishingFrequency()) + .isEqualTo(FindingPublishingFrequency.SIX_HOURS); + assertThat(detector.serviceRole()).contains(":role/aws-service-role/guardduty"); + assertThat(detector.tags()).containsEntry("env", "compat"); + assertThat(detector.features()) + .extracting(feature -> feature.name().toString()) + .containsExactly("RUNTIME_MONITORING", "S3_DATA_EVENTS"); + assertThat(detector.features().get(0).additionalConfiguration()) + .extracting(configuration -> configuration.name().toString()) + .containsExactly( + "ECS_FARGATE_AGENT_MANAGEMENT", + "EC2_AGENT_MANAGEMENT", + "EKS_ADDON_MANAGEMENT"); + + assertThat(guardduty.listDetectors(request -> { + }).detectorIds()).contains(detectorId); + + guardduty.updateDetector(request -> request + .detectorId(detectorId) + .enable(false) + .findingPublishingFrequency(FindingPublishingFrequency.ONE_HOUR)); + GetDetectorResponse updated = + guardduty.getDetector(request -> request.detectorId(detectorId)); + assertThat(updated.status()).isEqualTo(DetectorStatus.DISABLED); + assertThat(updated.findingPublishingFrequency()) + .isEqualTo(FindingPublishingFrequency.ONE_HOUR); + + String detectorArn = + "arn:aws:guardduty:us-east-1:000000000000:detector/" + detectorId; + guardduty.tagResource(request -> request + .resourceArn(detectorArn) + .tags(Map.of("team", "security"))); + assertThat(guardduty.listTagsForResource(request -> request.resourceArn(detectorArn)) + .tags()).containsEntry("team", "security").containsEntry("env", "compat"); + guardduty.untagResource(request -> request + .resourceArn(detectorArn) + .tagKeys(List.of("env"))); + assertThat(guardduty.listTagsForResource(request -> request.resourceArn(detectorArn)) + .tags()).containsOnlyKeys("team"); + } + + assertThatThrownBy(() -> guardduty.getDetector(request -> request.detectorId(detectorId))) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("is not owned by the current account"); + } + } + + @Test + void organizationConfigurationRoundTripsThroughTheSdk() throws Exception { + try (GuardDutyClient guardduty = TestFixtures.guardDutyClient()) { + String detectorId = guardduty.createDetector(request -> request.enable(true)).detectorId(); + + try (AutoCloseable deleteDetector = () -> + guardduty.deleteDetector(request -> request.detectorId(detectorId))) { + guardduty.updateOrganizationConfiguration(request -> request + .detectorId(detectorId) + .autoEnableOrganizationMembers(AutoEnableMembers.ALL) + .features(List.of(OrganizationFeatureConfiguration.builder() + .name(OrgFeature.RUNTIME_MONITORING) + .autoEnable(OrgFeatureStatus.ALL) + .additionalConfiguration(List.of( + OrganizationAdditionalConfiguration.builder() + .name(OrgFeatureAdditionalConfiguration + .ECS_FARGATE_AGENT_MANAGEMENT) + .autoEnable(OrgFeatureStatus.ALL) + .build(), + OrganizationAdditionalConfiguration.builder() + .name(OrgFeatureAdditionalConfiguration.EC2_AGENT_MANAGEMENT) + .autoEnable(OrgFeatureStatus.ALL) + .build(), + OrganizationAdditionalConfiguration.builder() + .name(OrgFeatureAdditionalConfiguration.EKS_ADDON_MANAGEMENT) + .autoEnable(OrgFeatureStatus.NONE) + .build())) + .build()))); + + DescribeOrganizationConfigurationResponse configuration = + guardduty.describeOrganizationConfiguration(request -> + request.detectorId(detectorId)); + assertThat(configuration.autoEnableOrganizationMembers()).isEqualTo(AutoEnableMembers.ALL); + assertThat(configuration.memberAccountLimitReached()).isFalse(); + assertThat(configuration.features()) + .extracting(feature -> feature.name().toString()) + .containsExactly("RUNTIME_MONITORING"); + assertThat(configuration.features().get(0).additionalConfiguration()) + .extracting(feature -> feature.name().toString()) + .containsExactly( + "ECS_FARGATE_AGENT_MANAGEMENT", + "EC2_AGENT_MANAGEMENT", + "EKS_ADDON_MANAGEMENT"); + } + } + } + + @Test + void organizationAdminAccountLifecycle() { + try (GuardDutyClient guardduty = TestFixtures.guardDutyClient()) { + guardduty.enableOrganizationAdminAccount(request -> + request.adminAccountId("111111111111")); + try { + ListOrganizationAdminAccountsResponse accounts = + guardduty.listOrganizationAdminAccounts(request -> { + }); + assertThat(accounts.adminAccounts()) + .anySatisfy(account -> { + assertThat(account.adminAccountId()).isEqualTo("111111111111"); + assertThat(account.adminStatus()).isEqualTo(AdminStatus.ENABLED); + }); + } finally { + guardduty.disableOrganizationAdminAccount(request -> + request.adminAccountId("111111111111")); + } + + assertThatThrownBy(() -> guardduty.disableOrganizationAdminAccount(request -> + request.adminAccountId("111111111111"))) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("already been disabled"); + } + } +} diff --git a/docs/services/guardduty.md b/docs/services/guardduty.md new file mode 100644 index 0000000000..ba36c728b1 --- /dev/null +++ b/docs/services/guardduty.md @@ -0,0 +1,83 @@ +# GuardDuty + +**Protocol:** REST JSON + +**Endpoint:** `http://localhost:4566` + +Floci implements the GuardDuty detector management lifecycle and organization-configuration +readback for local SDK, CLI, and Terraform workflows. Detectors are isolated by account and +region and use the configured Floci storage mode. + +## Supported Operations + +| Operation | Method and path | Description | +|---|---|---| +| `CreateDetector` | `POST /detector` | Create the account's detector (one per account and region) | +| `GetDetector` | `GET /detector/{detectorId}` | Return detector status, frequency, features, and tags | +| `UpdateDetector` | `POST /detector/{detectorId}` | Update status, frequency, and features | +| `DeleteDetector` | `DELETE /detector/{detectorId}` | Delete the detector | +| `ListDetectors` | `GET /detector` | List detector IDs with pagination | +| `DescribeOrganizationConfiguration` | `GET /detector/{detectorId}/admin` | Return organization auto-enablement configuration | +| `UpdateOrganizationConfiguration` | `POST /detector/{detectorId}/admin` | Update organization auto-enablement configuration | +| `EnableOrganizationAdminAccount` | `POST /admin/enable` | Designate the delegated administrator account | +| `DisableOrganizationAdminAccount` | `POST /admin/disable` | Remove the delegated administrator account | +| `ListOrganizationAdminAccounts` | `GET /admin` | List the delegated administrator account | +| `TagResource` | `POST /tags/{resourceArn}` | Add tags to a detector | +| `UntagResource` | `DELETE /tags/{resourceArn}` | Remove tags from a detector | +| `ListTagsForResource` | `GET /tags/{resourceArn}` | List detector tags | + +Feature lists and each feature's `additionalConfiguration` list are returned in the order +they were submitted, so Terraform's ordered list blocks re-plan cleanly. A missing detector +is reported as `BadRequestException` with the exact message the Terraform AWS provider +matches for not-found detection, mirroring AWS. + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_GUARDDUTY_ENABLED` | `true` | Enable or disable GuardDuty | +| `FLOCI_STORAGE_SERVICES_GUARDDUTY_MODE` | *(inherits global)* | Optional GuardDuty storage-mode override | +| `FLOCI_STORAGE_SERVICES_GUARDDUTY_FLUSH_INTERVAL_MS` | `5000` | Hybrid storage flush interval in milliseconds | + +Unless a GuardDuty-specific override is set, detector state follows the global +`FLOCI_STORAGE_MODE` setting. Persistent, hybrid, and write-ahead-log modes restore +detectors across restarts. + +## Example + +```bash +export AWS_ENDPOINT_URL=http://localhost:4566 + +DETECTOR_ID=$(aws guardduty create-detector \ + --enable \ + --finding-publishing-frequency SIX_HOURS \ + --tags env=local \ + --query DetectorId --output text) + +aws guardduty get-detector --detector-id "$DETECTOR_ID" +aws guardduty list-detectors + +aws guardduty update-organization-configuration \ + --detector-id "$DETECTOR_ID" \ + --auto-enable-organization-members ALL +aws guardduty describe-organization-configuration --detector-id "$DETECTOR_ID" + +aws guardduty delete-detector --detector-id "$DETECTOR_ID" +``` + +## Current Scope + +- Detector status, finding-publishing frequency, features (including + `additionalConfiguration` sub-features), tags, and timestamps are modeled. +- Organization semantics are readback-only. Floci has no Organizations service, so + `adminAccountId` membership is not validated, delegated-administrator permissions are not + enforced on the organization endpoints, and auto-enablement is never fanned out to member + accounts. Organization configuration is stored per calling account and echoed back as + submitted — sufficient for Terraform's `aws_guardduty_organization_configuration`, + `aws_guardduty_organization_configuration_feature`, and + `aws_guardduty_organization_admin_account` resources in a single-account workflow. +- No findings are generated: detection, malware scans, and the findings APIs + (`ListFindings`, `GetFindings`, filters, and publishing destinations) are not implemented. +- Member, invitation, IP-set, threat-intel, and coverage APIs are not implemented. +- The deprecated `dataSources` request/response structures are not modeled; the Terraform + provider treats their absence as "not configured". diff --git a/docs/services/index.md b/docs/services/index.md index 5244f9e8dc..88772e1f80 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -1,6 +1,6 @@ # Services Overview -Floci emulates 70 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification. +Floci emulates 71 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification. This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table. @@ -38,6 +38,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 17 | | [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 11 | | [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 | +| [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 13 | | [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 | | [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 14 | diff --git a/mkdocs.yml b/mkdocs.yml index f54402bbf5..c5dffe8f84 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -113,6 +113,7 @@ nav: - EventBridge Scheduler: services/scheduler.md - CloudWatch: services/cloudwatch.md - CloudWatch RUM: services/rum.md + - GuardDuty: services/guardduty.md - ACM: services/acm.md - ECS: services/ecs.md - ECR: services/ecr.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 43fd50f421..6673cbeb5e 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -282,6 +282,7 @@ public interface EmulatorConfig { ElasticBeanstalkStorageConfig elasticbeanstalk(); CloudTrailStorageConfig cloudtrail(); RumStorageConfig rum(); + GuardDutyStorageConfig guardduty(); } interface SsmStorageConfig { @@ -504,6 +505,13 @@ public interface EmulatorConfig { long flushIntervalMs(); } + interface GuardDutyStorageConfig { + Optional mode(); + + @WithDefault("5000") + long flushIntervalMs(); + } + interface CodeDeployStorageConfig { Optional mode(); @@ -610,6 +618,7 @@ public interface EmulatorConfig { IotDataServiceConfig iotdata(); CloudHsmV2ServiceConfig cloudhsmv2(); RumServiceConfig rum(); + GuardDutyServiceConfig guardduty(); } interface IotServiceConfig { @@ -643,6 +652,11 @@ public interface EmulatorConfig { boolean enabled(); } + interface GuardDutyServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface LightsailServiceConfig { @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 9025f34749..56f788177d 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 @@ -28,6 +28,7 @@ import io.github.hectorvent.floci.services.route53.Route53Controller; import io.github.hectorvent.floci.services.ses.SesController; import io.github.hectorvent.floci.services.appsync.AppSyncController; import io.github.hectorvent.floci.services.rdsdata.RdsDataController; +import io.github.hectorvent.floci.services.guardduty.GuardDutyController; import io.github.hectorvent.floci.services.rum.RumController; import io.github.hectorvent.floci.services.s3vectors.S3VectorsController; import io.github.hectorvent.floci.services.s3tables.S3TablesController; @@ -461,7 +462,13 @@ public class ResolvedServiceCatalog { "rum", storageMode(config.storage().services().rum().mode(), config.storage().mode()), config.storage().services().rum().flushIntervalMs(), null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), - Set.of(), Set.of("rum"), Set.of(), Set.of(RumController.class)) + Set.of(), Set.of("rum"), Set.of(), Set.of(RumController.class)), + descriptor("guardduty", "guardduty", config.services().guardduty().enabled(), true, + "guardduty", + storageMode(config.storage().services().guardduty().mode(), config.storage().mode()), + config.storage().services().guardduty().flushIntervalMs(), null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("guardduty"), Set.of(), Set.of(GuardDutyController.class)) )); } diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java new file mode 100644 index 0000000000..d02d118c72 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java @@ -0,0 +1,202 @@ +package io.github.hectorvent.floci.services.guardduty; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.guardduty.model.AdminAccount; +import io.github.hectorvent.floci.services.guardduty.model.Detector; +import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature; +import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; +import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +/** + * GuardDuty (Smithy restJson1) — detector lifecycle and organization configuration. + * + *

The literal {@code /detector} and {@code /admin} paths take JAX-RS precedence over S3's + * {@code /{bucket}} and {@code /{bucket}/{key}} template routes, so these routes win with no + * extra routing wiring. Tag operations ({@code /tags/{arn}}) are served by + * {@code SharedTagsController} via {@link GuardDutyTagHandler}. + * + *

GuardDuty reports every client error as {@code BadRequestException} (HTTP 400); the + * Terraform AWS provider matches specific message texts to detect missing resources, so those + * messages must not change. + */ +@Path("/") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class GuardDutyController { + + private final GuardDutyService service; + private final ObjectMapper objectMapper; + private final RegionResolver regionResolver; + + @Inject + public GuardDutyController( + GuardDutyService service, ObjectMapper objectMapper, RegionResolver regionResolver) { + this.service = service; + this.objectMapper = objectMapper; + this.regionResolver = regionResolver; + } + + private JsonNode parse(String body) { + if (body == null || body.isBlank()) { + return objectMapper.createObjectNode(); + } + try { + JsonNode request = objectMapper.readTree(body); + if (request == null || !request.isObject()) { + throw new AwsException("BadRequestException", "Request body must be a JSON object.", 400); + } + return request; + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw new AwsException("BadRequestException", "Request body is not valid JSON.", 400); + } + } + + @POST + @Path("/detector") + public Response createDetector(@Context HttpHeaders headers, String body) { + Detector detector = service.createDetector( + regionResolver.resolveRegion(headers), regionResolver.getAccountId(), parse(body)); + ObjectNode response = objectMapper.createObjectNode(); + response.put("detectorId", detector.getId()); + return Response.ok(response).build(); + } + + @GET + @Path("/detector") + public Response listDetectors( + @Context HttpHeaders headers, + @QueryParam("maxResults") String maxResults, + @QueryParam("nextToken") String nextToken) { + GuardDutyService.Page page = service.listDetectorIds( + regionResolver.resolveRegion(headers), maxResults, nextToken); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode ids = response.putArray("detectorIds"); + page.items().forEach(ids::add); + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + @GET + @Path("/detector/{detectorId}") + public Response getDetector(@Context HttpHeaders headers, @PathParam("detectorId") String detectorId) { + Detector detector = service.getDetector(regionResolver.resolveRegion(headers), detectorId); + ObjectNode response = objectMapper.createObjectNode(); + response.put("createdAt", detector.getCreatedAt()); + if (detector.getFindingPublishingFrequency() != null) { + response.put("findingPublishingFrequency", detector.getFindingPublishingFrequency()); + } + response.put("serviceRole", detector.getServiceRole()); + response.put("status", detector.getStatus()); + response.put("updatedAt", detector.getUpdatedAt()); + if (detector.getTags() != null && !detector.getTags().isEmpty()) { + ObjectNode tags = response.putObject("tags"); + detector.getTags().forEach(tags::put); + } + if (detector.getFeatures() != null) { + ArrayNode features = response.putArray("features"); + for (DetectorFeature feature : detector.getFeatures()) { + features.add(objectMapper.valueToTree(feature)); + } + } + return Response.ok(response).build(); + } + + @POST + @Path("/detector/{detectorId}") + public Response updateDetector( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId, String body) { + service.updateDetector(regionResolver.resolveRegion(headers), detectorId, parse(body)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @DELETE + @Path("/detector/{detectorId}") + public Response deleteDetector( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId) { + service.deleteDetector(regionResolver.resolveRegion(headers), detectorId); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @GET + @Path("/detector/{detectorId}/admin") + public Response describeOrganizationConfiguration( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId) { + OrganizationConfiguration configuration = service.describeOrganizationConfiguration( + regionResolver.resolveRegion(headers), detectorId); + ObjectNode response = objectMapper.createObjectNode(); + response.put("autoEnable", Boolean.TRUE.equals(configuration.getAutoEnable())); + response.put("memberAccountLimitReached", false); + response.put("autoEnableOrganizationMembers", configuration.getAutoEnableOrganizationMembers()); + ArrayNode features = response.putArray("features"); + if (configuration.getFeatures() != null) { + for (OrganizationFeature feature : configuration.getFeatures()) { + features.add(objectMapper.valueToTree(feature)); + } + } + return Response.ok(response).build(); + } + + @POST + @Path("/detector/{detectorId}/admin") + public Response updateOrganizationConfiguration( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId, String body) { + service.updateOrganizationConfiguration( + regionResolver.resolveRegion(headers), detectorId, parse(body)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @POST + @Path("/admin/enable") + public Response enableOrganizationAdminAccount(@Context HttpHeaders headers, String body) { + service.enableOrganizationAdminAccount(regionResolver.resolveRegion(headers), parse(body)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @POST + @Path("/admin/disable") + public Response disableOrganizationAdminAccount(@Context HttpHeaders headers, String body) { + service.disableOrganizationAdminAccount(regionResolver.resolveRegion(headers), parse(body)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @GET + @Path("/admin") + public Response listOrganizationAdminAccounts( + @Context HttpHeaders headers, + @QueryParam("maxResults") String maxResults, + @QueryParam("nextToken") String nextToken) { + GuardDutyService.Page page = service.listOrganizationAdminAccounts( + regionResolver.resolveRegion(headers), maxResults, nextToken); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode accounts = response.putArray("adminAccounts"); + for (AdminAccount account : page.items()) { + accounts.add(objectMapper.valueToTree(account)); + } + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } + return Response.ok(response).build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java new file mode 100644 index 0000000000..784f3b553e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java @@ -0,0 +1,549 @@ +package io.github.hectorvent.floci.services.guardduty; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.guardduty.model.AdminAccount; +import io.github.hectorvent.floci.services.guardduty.model.Detector; +import io.github.hectorvent.floci.services.guardduty.model.DetectorAdditionalConfiguration; +import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature; +import io.github.hectorvent.floci.services.guardduty.model.OrganizationAdditionalConfiguration; +import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; +import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * GuardDuty detector lifecycle and organization configuration backed by the configured + * Floci storage mode. + * + *

Organization semantics are readback-only: Floci has no Organizations service, so + * {@code adminAccountId} membership is not validated, delegated-administrator permissions are + * not enforced, and member accounts are not fanned out. Organization configuration is stored + * per calling account and echoed back as submitted. + */ +@ApplicationScoped +public class GuardDutyService { + + /** + * The Terraform AWS provider matches this exact message to translate a + * {@code BadRequestException} into resource removal from state. + */ + static final String DETECTOR_NOT_FOUND_MESSAGE = + "The request is rejected because the input detectorId is not owned by the current account."; + + /** Also matched verbatim by the Terraform AWS provider on delegated-admin delete. */ + static final String ADMIN_ALREADY_DISABLED_MESSAGE = + "The request failed because the delegated administrator account has already been disabled " + + "and/or GuardDuty protection has been disabled."; + + private static final int DEFAULT_MAX_RESULTS = 50; + private static final int MAX_RESULTS = 50; + private static final String TOKEN_PREFIX = "guardduty:v1:"; + private static final Pattern ACCOUNT_ID_PATTERN = Pattern.compile("[0-9]{12}"); + private static final Set FINDING_PUBLISHING_FREQUENCIES = + Set.of("FIFTEEN_MINUTES", "ONE_HOUR", "SIX_HOURS"); + private static final Set FEATURE_STATUSES = Set.of("ENABLED", "DISABLED"); + private static final Set ORG_AUTO_ENABLE_VALUES = Set.of("NEW", "NONE", "ALL"); + private static final Set DETECTOR_FEATURE_NAMES = Set.of( + "S3_DATA_EVENTS", "EKS_AUDIT_LOGS", "EBS_MALWARE_PROTECTION", "RDS_LOGIN_EVENTS", + "LAMBDA_NETWORK_LOGS", "EKS_RUNTIME_MONITORING", "RUNTIME_MONITORING", + "AI_PROTECTION", "AI_ANALYST"); + private static final Set ORG_FEATURE_NAMES = Set.of( + "S3_DATA_EVENTS", "EKS_AUDIT_LOGS", "EBS_MALWARE_PROTECTION", "RDS_LOGIN_EVENTS", + "LAMBDA_NETWORK_LOGS", "EKS_RUNTIME_MONITORING", "RUNTIME_MONITORING", "AI_PROTECTION"); + private static final Set ADDITIONAL_CONFIGURATION_NAMES = + Set.of("EKS_ADDON_MANAGEMENT", "ECS_FARGATE_AGENT_MANAGEMENT", "EC2_AGENT_MANAGEMENT"); + + private final StorageBackend detectorStore; + private final StorageBackend adminAccountStore; + + @Inject + public GuardDutyService(StorageFactory storageFactory) { + this(storageFactory.create( + "guardduty", + "guardduty-detectors.json", + new TypeReference>() { + }), + storageFactory.create( + "guardduty", + "guardduty-admin-accounts.json", + new TypeReference>() { + })); + } + + GuardDutyService( + StorageBackend detectorStore, + StorageBackend adminAccountStore) { + this.detectorStore = detectorStore; + this.adminAccountStore = adminAccountStore; + } + + public synchronized Detector createDetector(String region, String accountId, JsonNode request) { + boolean enable = requireBoolean(request, "enable"); + String frequency = readFindingPublishingFrequency(request, "SIX_HOURS"); + List features = readDetectorFeatures(request); + Map tags = readTags(request); + + if (!detectorStore.scan(key -> key.startsWith(region + "::")).isEmpty()) { + throw badRequest("The request is rejected because a detector already exists for the current account."); + } + + String now = isoTimestamp(); + Detector detector = new Detector( + UUID.randomUUID().toString().replace("-", ""), + enable ? "ENABLED" : "DISABLED", + frequency, + serviceRoleArn(accountId), + now, + now, + tags, + features, + null); + detectorStore.put(storageKey(region, detector.getId()), detector); + return detector; + } + + public Detector getDetector(String region, String detectorId) { + return detectorStore.get(storageKey(region, detectorId)).orElseThrow(GuardDutyService::detectorNotFound); + } + + public synchronized void updateDetector(String region, String detectorId, JsonNode request) { + String key = storageKey(region, detectorId); + Detector detector = detectorStore.get(key).orElseThrow(GuardDutyService::detectorNotFound); + + if (request.has("enable")) { + detector.setStatus(requireBoolean(request, "enable") ? "ENABLED" : "DISABLED"); + } + if (request.has("findingPublishingFrequency")) { + detector.setFindingPublishingFrequency(readFindingPublishingFrequency(request, null)); + } + if (request.has("features")) { + detector.setFeatures(mergeDetectorFeatures(detector.getFeatures(), readDetectorFeatures(request))); + } + detector.setUpdatedAt(isoTimestamp()); + detectorStore.put(key, detector); + } + + public synchronized void deleteDetector(String region, String detectorId) { + String key = storageKey(region, detectorId); + if (detectorStore.get(key).isEmpty()) { + throw detectorNotFound(); + } + detectorStore.delete(key); + } + + public Page listDetectorIds(String region, String maxResultsValue, String nextToken) { + int maxResults = parseMaxResults(maxResultsValue); + List detectors = detectorStore.scan(key -> key.startsWith(region + "::")); + detectors.sort(Comparator.comparing(Detector::getId)); + List ids = detectors.stream().map(Detector::getId).toList(); + + int offset = decodeOffset(nextToken, ids.size()); + int end = Math.min(offset + maxResults, ids.size()); + String responseToken = end < ids.size() ? encodeOffset(end) : null; + return new Page<>(ids.subList(offset, end), responseToken); + } + + public OrganizationConfiguration describeOrganizationConfiguration(String region, String detectorId) { + Detector detector = getDetector(region, detectorId); + OrganizationConfiguration configuration = detector.getOrganizationConfiguration(); + if (configuration == null) { + return new OrganizationConfiguration(false, "NONE", List.of()); + } + return configuration; + } + + public synchronized void updateOrganizationConfiguration(String region, String detectorId, JsonNode request) { + String key = storageKey(region, detectorId); + Detector detector = detectorStore.get(key).orElseThrow(GuardDutyService::detectorNotFound); + + OrganizationConfiguration current = detector.getOrganizationConfiguration(); + boolean autoEnable = current != null && Boolean.TRUE.equals(current.getAutoEnable()); + String members = current == null ? "NONE" : current.getAutoEnableOrganizationMembers(); + List features = current == null ? List.of() : current.getFeatures(); + + if (request.has("autoEnableOrganizationMembers")) { + members = requireText(request, "autoEnableOrganizationMembers"); + if (!ORG_AUTO_ENABLE_VALUES.contains(members)) { + throw badRequest("autoEnableOrganizationMembers must be one of NEW, ALL, or NONE."); + } + autoEnable = !"NONE".equals(members); + } else if (request.has("autoEnable")) { + autoEnable = requireBoolean(request, "autoEnable"); + members = autoEnable ? "NEW" : "NONE"; + } + if (request.has("features")) { + features = mergeOrganizationFeatures(features, readOrganizationFeatures(request)); + } + + detector.setOrganizationConfiguration(new OrganizationConfiguration(autoEnable, members, features)); + detectorStore.put(key, detector); + } + + public synchronized void enableOrganizationAdminAccount(String region, JsonNode request) { + String adminAccountId = readAdminAccountId(request); + List existing = adminAccountStore.scan(key -> key.startsWith(region + "::")); + if (!existing.isEmpty() && !existing.get(0).getAdminAccountId().equals(adminAccountId)) { + throw badRequest("The request is rejected because the organization already has a " + + "delegated administrator account for GuardDuty."); + } + adminAccountStore.put(storageKey(region, adminAccountId), new AdminAccount(adminAccountId, "ENABLED")); + } + + public synchronized void disableOrganizationAdminAccount(String region, JsonNode request) { + String adminAccountId = readAdminAccountId(request); + String key = storageKey(region, adminAccountId); + if (adminAccountStore.get(key).isEmpty()) { + throw badRequest(ADMIN_ALREADY_DISABLED_MESSAGE); + } + adminAccountStore.delete(key); + } + + public Page listOrganizationAdminAccounts( + String region, String maxResultsValue, String nextToken) { + int maxResults = parseMaxResults(maxResultsValue); + List accounts = adminAccountStore.scan(key -> key.startsWith(region + "::")); + accounts.sort(Comparator.comparing(AdminAccount::getAdminAccountId)); + + int offset = decodeOffset(nextToken, accounts.size()); + int end = Math.min(offset + maxResults, accounts.size()); + String responseToken = end < accounts.size() ? encodeOffset(end) : null; + return new Page<>(accounts.subList(offset, end), responseToken); + } + + public Map listTags(String arn) { + Detector detector = detectorFromArn(arn); + return detector.getTags() == null ? Map.of() : detector.getTags(); + } + + public synchronized void tagResource(String arn, Map tags) { + DetectorRef ref = parseDetectorArn(arn); + Detector detector = detectorStore.get(ref.key()).orElseThrow(GuardDutyService::detectorNotFound); + Map merged = new LinkedHashMap<>(); + if (detector.getTags() != null) { + merged.putAll(detector.getTags()); + } + merged.putAll(tags); + detector.setTags(merged); + detectorStore.put(ref.key(), detector); + } + + public synchronized void untagResource(String arn, List tagKeys) { + DetectorRef ref = parseDetectorArn(arn); + Detector detector = detectorStore.get(ref.key()).orElseThrow(GuardDutyService::detectorNotFound); + if (detector.getTags() == null) { + return; + } + Map remaining = new LinkedHashMap<>(detector.getTags()); + tagKeys.forEach(remaining::remove); + detector.setTags(remaining); + detectorStore.put(ref.key(), detector); + } + + private Detector detectorFromArn(String arn) { + DetectorRef ref = parseDetectorArn(arn); + return detectorStore.get(ref.key()).orElseThrow(GuardDutyService::detectorNotFound); + } + + private static DetectorRef parseDetectorArn(String arn) { + AwsArnUtils.Arn parsed; + try { + parsed = AwsArnUtils.parse(arn); + } catch (IllegalArgumentException e) { + throw badRequest("The request is rejected because an invalid resource ARN is specified: " + arn); + } + String prefix = "detector/"; + String resource = parsed.resource(); + if (!resource.startsWith(prefix) || resource.length() == prefix.length()) { + throw badRequest("The request is rejected because an invalid resource ARN is specified: " + arn); + } + return new DetectorRef(parsed.region(), resource.substring(prefix.length())); + } + + private static List mergeDetectorFeatures( + List current, List submitted) { + List merged = current == null ? new ArrayList<>() : new ArrayList<>(current); + for (DetectorFeature update : submitted) { + DetectorFeature existing = merged.stream() + .filter(feature -> feature.getName().equals(update.getName())) + .findFirst() + .orElse(null); + if (existing == null) { + merged.add(update); + } else { + existing.setStatus(update.getStatus()); + existing.setUpdatedAt(update.getUpdatedAt()); + if (update.getAdditionalConfiguration() != null) { + existing.setAdditionalConfiguration(update.getAdditionalConfiguration()); + } + } + } + return merged; + } + + private static List mergeOrganizationFeatures( + List current, List submitted) { + List merged = current == null ? new ArrayList<>() : new ArrayList<>(current); + for (OrganizationFeature update : submitted) { + OrganizationFeature existing = merged.stream() + .filter(feature -> feature.getName().equals(update.getName())) + .findFirst() + .orElse(null); + if (existing == null) { + merged.add(update); + } else { + existing.setAutoEnable(update.getAutoEnable()); + if (update.getAdditionalConfiguration() != null) { + existing.setAdditionalConfiguration(update.getAdditionalConfiguration()); + } + } + } + return merged; + } + + private static List readDetectorFeatures(JsonNode request) { + if (!request.has("features")) { + return null; + } + JsonNode featuresNode = request.get("features"); + if (!featuresNode.isArray()) { + throw badRequest("features must be an array."); + } + long now = Instant.now().getEpochSecond(); + List features = new ArrayList<>(featuresNode.size()); + for (JsonNode featureNode : featuresNode) { + requireObject(featureNode, "features member"); + String name = requireText(featureNode, "name"); + if (!DETECTOR_FEATURE_NAMES.contains(name)) { + throw badRequest("features contains an unsupported feature name: " + name); + } + String status = requireText(featureNode, "status"); + if (!FEATURE_STATUSES.contains(status)) { + throw badRequest("features contains an invalid status: " + status); + } + features.add(new DetectorFeature( + name, status, now, readDetectorAdditionalConfiguration(featureNode, now))); + } + return features; + } + + private static List readDetectorAdditionalConfiguration( + JsonNode featureNode, long now) { + if (!featureNode.has("additionalConfiguration")) { + return null; + } + JsonNode configurationNode = featureNode.get("additionalConfiguration"); + if (!configurationNode.isArray()) { + throw badRequest("additionalConfiguration must be an array."); + } + List configurations = new ArrayList<>(configurationNode.size()); + for (JsonNode node : configurationNode) { + requireObject(node, "additionalConfiguration member"); + String name = requireText(node, "name"); + if (!ADDITIONAL_CONFIGURATION_NAMES.contains(name)) { + throw badRequest("additionalConfiguration contains an unsupported name: " + name); + } + String status = requireText(node, "status"); + if (!FEATURE_STATUSES.contains(status)) { + throw badRequest("additionalConfiguration contains an invalid status: " + status); + } + configurations.add(new DetectorAdditionalConfiguration(name, status, now)); + } + return configurations; + } + + private static List readOrganizationFeatures(JsonNode request) { + JsonNode featuresNode = request.get("features"); + if (!featuresNode.isArray()) { + throw badRequest("features must be an array."); + } + List features = new ArrayList<>(featuresNode.size()); + for (JsonNode featureNode : featuresNode) { + requireObject(featureNode, "features member"); + String name = requireText(featureNode, "name"); + if (!ORG_FEATURE_NAMES.contains(name)) { + throw badRequest("features contains an unsupported feature name: " + name); + } + String autoEnable = requireText(featureNode, "autoEnable"); + if (!ORG_AUTO_ENABLE_VALUES.contains(autoEnable)) { + throw badRequest("features contains an invalid autoEnable value: " + autoEnable); + } + features.add(new OrganizationFeature( + name, autoEnable, readOrganizationAdditionalConfiguration(featureNode))); + } + return features; + } + + private static List readOrganizationAdditionalConfiguration( + JsonNode featureNode) { + if (!featureNode.has("additionalConfiguration")) { + return null; + } + JsonNode configurationNode = featureNode.get("additionalConfiguration"); + if (!configurationNode.isArray()) { + throw badRequest("additionalConfiguration must be an array."); + } + List configurations = new ArrayList<>(configurationNode.size()); + for (JsonNode node : configurationNode) { + requireObject(node, "additionalConfiguration member"); + String name = requireText(node, "name"); + if (!ADDITIONAL_CONFIGURATION_NAMES.contains(name)) { + throw badRequest("additionalConfiguration contains an unsupported name: " + name); + } + String autoEnable = requireText(node, "autoEnable"); + if (!ORG_AUTO_ENABLE_VALUES.contains(autoEnable)) { + throw badRequest("additionalConfiguration contains an invalid autoEnable value: " + autoEnable); + } + configurations.add(new OrganizationAdditionalConfiguration(name, autoEnable)); + } + return configurations; + } + + private static String readFindingPublishingFrequency(JsonNode request, String defaultValue) { + if (!request.has("findingPublishingFrequency")) { + return defaultValue; + } + String frequency = requireText(request, "findingPublishingFrequency"); + if (!FINDING_PUBLISHING_FREQUENCIES.contains(frequency)) { + throw badRequest("findingPublishingFrequency must be one of FIFTEEN_MINUTES, ONE_HOUR, or SIX_HOURS."); + } + return frequency; + } + + private static Map readTags(JsonNode request) { + if (!request.has("tags")) { + return null; + } + JsonNode tagsNode = request.get("tags"); + if (!tagsNode.isObject() || tagsNode.size() > 50) { + throw badRequest("tags must be an object with at most 50 entries."); + } + Map tags = new LinkedHashMap<>(); + tagsNode.fields().forEachRemaining(entry -> { + JsonNode valueNode = entry.getValue(); + if (!valueNode.isTextual()) { + throw badRequest("tags contains a non-string value."); + } + tags.put(entry.getKey(), valueNode.textValue()); + }); + return tags; + } + + private static String readAdminAccountId(JsonNode request) { + String adminAccountId = requireText(request, "adminAccountId"); + if (!ACCOUNT_ID_PATTERN.matcher(adminAccountId).matches()) { + throw badRequest("adminAccountId must be a 12-digit account ID."); + } + return adminAccountId; + } + + private static String storageKey(String region, String id) { + return region + "::" + id; + } + + private static String serviceRoleArn(String accountId) { + return "arn:aws:iam::" + accountId + + ":role/aws-service-role/guardduty.amazonaws.com/AWSServiceRoleForAmazonGuardDuty"; + } + + private static String isoTimestamp() { + return Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MILLIS).toString(); + } + + private static void requireObject(JsonNode value, String field) { + if (value == null || !value.isObject()) { + throw badRequest(field + " must be a JSON object."); + } + } + + private static String requireText(JsonNode parent, String field) { + JsonNode value = parent.get(field); + if (value == null || !value.isTextual()) { + throw badRequest(field + " must be a string."); + } + return value.textValue(); + } + + private static boolean requireBoolean(JsonNode parent, String field) { + JsonNode value = parent.get(field); + if (value == null || !value.isBoolean()) { + throw badRequest(field + " must be a boolean."); + } + return value.booleanValue(); + } + + private static int parseMaxResults(String value) { + if (value == null) { + return DEFAULT_MAX_RESULTS; + } + try { + int parsed = Integer.parseInt(value); + if (parsed < 1 || parsed > MAX_RESULTS) { + throw badRequest("maxResults must be between 1 and " + MAX_RESULTS + "."); + } + return parsed; + } catch (NumberFormatException e) { + throw badRequest("maxResults must be an integer between 1 and " + MAX_RESULTS + "."); + } + } + + private static int decodeOffset(String token, int resultSize) { + if (token == null) { + return 0; + } + try { + String decoded = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8); + if (!decoded.startsWith(TOKEN_PREFIX)) { + throw badRequest("nextToken is invalid."); + } + int offset = Integer.parseInt(decoded.substring(TOKEN_PREFIX.length())); + if (offset < 1 || offset >= resultSize) { + throw badRequest("nextToken is invalid."); + } + return offset; + } catch (IllegalArgumentException e) { + throw badRequest("nextToken is invalid."); + } + } + + private static String encodeOffset(int offset) { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString((TOKEN_PREFIX + offset).getBytes(StandardCharsets.UTF_8)); + } + + private static AwsException detectorNotFound() { + return badRequest(DETECTOR_NOT_FOUND_MESSAGE); + } + + private static AwsException badRequest(String message) { + return new AwsException("BadRequestException", message, 400); + } + + public record Page(List items, String nextToken) { + public Page { + items = List.copyOf(items); + } + } + + private record DetectorRef(String region, String detectorId) { + String key() { + return storageKey(region, detectorId); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyTagHandler.java new file mode 100644 index 0000000000..b32342f4b8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyTagHandler.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.services.guardduty; + +import io.github.hectorvent.floci.core.common.TagHandler; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; + +/** + * {@link TagHandler} implementation for GuardDuty. + * + *

ARN format: {@code arn:aws:guardduty:::detector/}. GuardDuty's + * tag wire shape matches every {@code TagHandler} default: a {@code tags} map in the body and a + * {@code tagKeys} query parameter on untag. + */ +@ApplicationScoped +public class GuardDutyTagHandler implements TagHandler { + + private final GuardDutyService service; + + @Inject + public GuardDutyTagHandler(GuardDutyService service) { + this.service = service; + } + + @Override + public String serviceKey() { + return "guardduty"; + } + + @Override + public Map listTags(String region, String arn) { + return service.listTags(arn); + } + + @Override + public void tagResource(String region, String arn, Map tags) { + service.tagResource(arn, tags); + } + + @Override + public void untagResource(String region, String arn, List tagKeys) { + service.untagResource(arn, tagKeys); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/AdminAccount.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/AdminAccount.java new file mode 100644 index 0000000000..4c815ff4f4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/AdminAccount.java @@ -0,0 +1,36 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** The GuardDuty delegated administrator account for a region. */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AdminAccount { + private String adminAccountId; + private String adminStatus; + + public AdminAccount() { + } + + public AdminAccount(String adminAccountId, String adminStatus) { + this.adminAccountId = adminAccountId; + this.adminStatus = adminStatus; + } + + public String getAdminAccountId() { + return adminAccountId; + } + + public void setAdminAccountId(String adminAccountId) { + this.adminAccountId = adminAccountId; + } + + public String getAdminStatus() { + return adminStatus; + } + + public void setAdminStatus(String adminStatus) { + this.adminStatus = adminStatus; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/Detector.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/Detector.java new file mode 100644 index 0000000000..169fea86c0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/Detector.java @@ -0,0 +1,118 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Map; + +/** A GuardDuty detector. Serialized with GuardDuty's lowerCamelCase member names. */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Detector { + private String id; + private String status; + private String findingPublishingFrequency; + private String serviceRole; + private String createdAt; + private String updatedAt; + private Map tags; + private List features; + private OrganizationConfiguration organizationConfiguration; + + public Detector() { + } + + public Detector( + String id, + String status, + String findingPublishingFrequency, + String serviceRole, + String createdAt, + String updatedAt, + Map tags, + List features, + OrganizationConfiguration organizationConfiguration) { + this.id = id; + this.status = status; + this.findingPublishingFrequency = findingPublishingFrequency; + this.serviceRole = serviceRole; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + setTags(tags); + setFeatures(features); + this.organizationConfiguration = organizationConfiguration; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getFindingPublishingFrequency() { + return findingPublishingFrequency; + } + + public void setFindingPublishingFrequency(String findingPublishingFrequency) { + this.findingPublishingFrequency = findingPublishingFrequency; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public String getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(String createdAt) { + this.createdAt = createdAt; + } + + public String getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(String updatedAt) { + this.updatedAt = updatedAt; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags == null ? null : Map.copyOf(tags); + } + + public List getFeatures() { + return features; + } + + public void setFeatures(List features) { + this.features = features == null ? null : List.copyOf(features); + } + + public OrganizationConfiguration getOrganizationConfiguration() { + return organizationConfiguration; + } + + public void setOrganizationConfiguration(OrganizationConfiguration organizationConfiguration) { + this.organizationConfiguration = organizationConfiguration; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/DetectorAdditionalConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/DetectorAdditionalConfiguration.java new file mode 100644 index 0000000000..e92fc2a17b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/DetectorAdditionalConfiguration.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** Sub-feature configuration of a detector feature (e.g. EKS_ADDON_MANAGEMENT). */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DetectorAdditionalConfiguration { + private String name; + private String status; + private Long updatedAt; + + public DetectorAdditionalConfiguration() { + } + + public DetectorAdditionalConfiguration(String name, String status, Long updatedAt) { + this.name = name; + this.status = status; + this.updatedAt = updatedAt; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Long getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Long updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/DetectorFeature.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/DetectorFeature.java new file mode 100644 index 0000000000..fdd222e1b3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/DetectorFeature.java @@ -0,0 +1,67 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +/** + * A detector feature (e.g. S3_DATA_EVENTS). List positions are preserved as submitted: + * {@code additionalConfiguration} is a list block in the Terraform provider, so a reordered + * read-back makes every subsequent plan propose a replacement. + */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DetectorFeature { + private String name; + private String status; + private Long updatedAt; + private List additionalConfiguration; + + public DetectorFeature() { + } + + public DetectorFeature( + String name, + String status, + Long updatedAt, + List additionalConfiguration) { + this.name = name; + this.status = status; + this.updatedAt = updatedAt; + setAdditionalConfiguration(additionalConfiguration); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Long getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Long updatedAt) { + this.updatedAt = updatedAt; + } + + public List getAdditionalConfiguration() { + return additionalConfiguration; + } + + public void setAdditionalConfiguration(List additionalConfiguration) { + this.additionalConfiguration = + additionalConfiguration == null ? null : List.copyOf(additionalConfiguration); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationAdditionalConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationAdditionalConfiguration.java new file mode 100644 index 0000000000..15a902def3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationAdditionalConfiguration.java @@ -0,0 +1,36 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** Organization auto-enablement for a sub-feature (e.g. EKS_ADDON_MANAGEMENT). */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class OrganizationAdditionalConfiguration { + private String name; + private String autoEnable; + + public OrganizationAdditionalConfiguration() { + } + + public OrganizationAdditionalConfiguration(String name, String autoEnable) { + this.name = name; + this.autoEnable = autoEnable; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAutoEnable() { + return autoEnable; + } + + public void setAutoEnable(String autoEnable) { + this.autoEnable = autoEnable; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationConfiguration.java new file mode 100644 index 0000000000..f35d514d85 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationConfiguration.java @@ -0,0 +1,49 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +/** Organization-wide GuardDuty configuration attached to a detector. */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class OrganizationConfiguration { + private Boolean autoEnable; + private String autoEnableOrganizationMembers; + private List features; + + public OrganizationConfiguration() { + } + + public OrganizationConfiguration( + Boolean autoEnable, String autoEnableOrganizationMembers, List features) { + this.autoEnable = autoEnable; + this.autoEnableOrganizationMembers = autoEnableOrganizationMembers; + setFeatures(features); + } + + public Boolean getAutoEnable() { + return autoEnable; + } + + public void setAutoEnable(Boolean autoEnable) { + this.autoEnable = autoEnable; + } + + public String getAutoEnableOrganizationMembers() { + return autoEnableOrganizationMembers; + } + + public void setAutoEnableOrganizationMembers(String autoEnableOrganizationMembers) { + this.autoEnableOrganizationMembers = autoEnableOrganizationMembers; + } + + public List getFeatures() { + return features; + } + + public void setFeatures(List features) { + this.features = features == null ? null : List.copyOf(features); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationFeature.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationFeature.java new file mode 100644 index 0000000000..a29cdd6fac --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/OrganizationFeature.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +/** + * Organization auto-enablement for a detector feature. {@code additionalConfiguration} + * order is preserved as submitted; see {@link DetectorFeature}. + */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class OrganizationFeature { + private String name; + private String autoEnable; + private List additionalConfiguration; + + public OrganizationFeature() { + } + + public OrganizationFeature( + String name, + String autoEnable, + List additionalConfiguration) { + this.name = name; + this.autoEnable = autoEnable; + setAdditionalConfiguration(additionalConfiguration); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAutoEnable() { + return autoEnable; + } + + public void setAutoEnable(String autoEnable) { + this.autoEnable = autoEnable; + } + + public List getAdditionalConfiguration() { + return additionalConfiguration; + } + + public void setAdditionalConfiguration(List additionalConfiguration) { + this.additionalConfiguration = + additionalConfiguration == null ? null : List.copyOf(additionalConfiguration); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 53a0ac2cdf..6afe99a0d5 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -144,6 +144,8 @@ floci: flush-interval-ms: 5000 rum: flush-interval-ms: 5000 + guardduty: + flush-interval-ms: 5000 dns: # Extra hostname suffixes resolved to Floci's container IP by the embedded DNS server. @@ -495,3 +497,5 @@ floci: cloudhsmv2: rum: enabled: true + guardduty: + enabled: true diff --git a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyControllerIntegrationTest.java new file mode 100644 index 0000000000..6fe8bdb941 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyControllerIntegrationTest.java @@ -0,0 +1,314 @@ +package io.github.hectorvent.floci.services.guardduty; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Verifies the GuardDuty restJson1 detector lifecycle, organization readback, and isolation. */ +@QuarkusTest +class GuardDutyControllerIntegrationTest { + + private static final String EAST = "us-east-1"; + private static final String WEST = "us-west-2"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void detectorCreateGetUpdateDeleteLifecycle() { + String authorization = auth("000000000201", EAST); + String detectorId = createDetector(authorization, """ + {"enable":true,"findingPublishingFrequency":"SIX_HOURS","tags":{"env":"compat"}} + """); + + Response detector = given() + .header("Authorization", authorization) + .when() + .get("/detector/" + detectorId) + .then() + .statusCode(200) + .body("status", equalTo("ENABLED")) + .body("findingPublishingFrequency", equalTo("SIX_HOURS")) + .body("serviceRole", notNullValue()) + .body("tags.env", equalTo("compat")) + .extract().response(); + assertTrue(detector.path("createdAt").toString().endsWith("Z")); + + given() + .contentType("application/json") + .header("Authorization", authorization) + .body("{\"enable\":false,\"findingPublishingFrequency\":\"ONE_HOUR\"}") + .when() + .post("/detector/" + detectorId) + .then() + .statusCode(200); + + given() + .header("Authorization", authorization) + .when() + .get("/detector/" + detectorId) + .then() + .statusCode(200) + .body("status", equalTo("DISABLED")) + .body("findingPublishingFrequency", equalTo("ONE_HOUR")); + + given() + .header("Authorization", authorization) + .when() + .get("/detector") + .then() + .statusCode(200) + .body("detectorIds", equalTo(List.of(detectorId))); + + given() + .header("Authorization", authorization) + .when() + .delete("/detector/" + detectorId) + .then() + .statusCode(200); + + given() + .header("Authorization", authorization) + .when() + .get("/detector/" + detectorId) + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE)); + } + + @Test + void featureOrderIsPreservedOnReadBack() { + String authorization = auth("000000000202", EAST); + String detectorId = createDetector(authorization, """ + {"enable":true,"features":[ + {"name":"RUNTIME_MONITORING","status":"ENABLED","additionalConfiguration":[ + {"name":"ECS_FARGATE_AGENT_MANAGEMENT","status":"ENABLED"}, + {"name":"EC2_AGENT_MANAGEMENT","status":"ENABLED"}, + {"name":"EKS_ADDON_MANAGEMENT","status":"DISABLED"} + ]}, + {"name":"S3_DATA_EVENTS","status":"ENABLED"} + ]} + """); + + Response detector = given() + .header("Authorization", authorization) + .when() + .get("/detector/" + detectorId) + .then() + .statusCode(200) + .extract().response(); + + assertEquals(List.of("RUNTIME_MONITORING", "S3_DATA_EVENTS"), + detector.path("features.name")); + assertEquals( + List.of("ECS_FARGATE_AGENT_MANAGEMENT", "EC2_AGENT_MANAGEMENT", "EKS_ADDON_MANAGEMENT"), + detector.path("features[0].additionalConfiguration.name")); + } + + @Test + void organizationConfigurationLifecycle() { + String authorization = auth("000000000203", EAST); + String detectorId = createDetector(authorization, "{\"enable\":true}"); + + given() + .header("Authorization", authorization) + .when() + .get("/detector/" + detectorId + "/admin") + .then() + .statusCode(200) + .body("autoEnable", equalTo(false)) + .body("memberAccountLimitReached", equalTo(false)) + .body("autoEnableOrganizationMembers", equalTo("NONE")); + + given() + .contentType("application/json") + .header("Authorization", authorization) + .body(""" + {"autoEnableOrganizationMembers":"ALL","features":[ + {"name":"RUNTIME_MONITORING","autoEnable":"ALL","additionalConfiguration":[ + {"name":"ECS_FARGATE_AGENT_MANAGEMENT","autoEnable":"ALL"}, + {"name":"EC2_AGENT_MANAGEMENT","autoEnable":"ALL"}, + {"name":"EKS_ADDON_MANAGEMENT","autoEnable":"NONE"} + ]} + ]} + """) + .when() + .post("/detector/" + detectorId + "/admin") + .then() + .statusCode(200); + + Response configuration = given() + .header("Authorization", authorization) + .when() + .get("/detector/" + detectorId + "/admin") + .then() + .statusCode(200) + .body("autoEnable", equalTo(true)) + .body("autoEnableOrganizationMembers", equalTo("ALL")) + .extract().response(); + assertEquals( + List.of("ECS_FARGATE_AGENT_MANAGEMENT", "EC2_AGENT_MANAGEMENT", "EKS_ADDON_MANAGEMENT"), + configuration.path("features[0].additionalConfiguration.name")); + } + + @Test + void organizationAdminAccountLifecycle() { + String authorization = auth("000000000204", EAST); + + given() + .contentType("application/json") + .header("Authorization", authorization) + .body("{\"adminAccountId\":\"111111111111\"}") + .when() + .post("/admin/enable") + .then() + .statusCode(200); + + given() + .header("Authorization", authorization) + .when() + .get("/admin") + .then() + .statusCode(200) + .body("adminAccounts[0].adminAccountId", equalTo("111111111111")) + .body("adminAccounts[0].adminStatus", equalTo("ENABLED")); + + given() + .contentType("application/json") + .header("Authorization", authorization) + .body("{\"adminAccountId\":\"111111111111\"}") + .when() + .post("/admin/disable") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", authorization) + .body("{\"adminAccountId\":\"111111111111\"}") + .when() + .post("/admin/disable") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(GuardDutyService.ADMIN_ALREADY_DISABLED_MESSAGE)); + } + + @Test + void detectorsAreIsolatedByAccountAndRegion() { + String eastAccountA = auth("000000000205", EAST); + String eastAccountB = auth("000000000206", EAST); + String westAccountA = auth("000000000205", WEST); + String detectorId = createDetector(eastAccountA, "{\"enable\":true}"); + + given() + .header("Authorization", eastAccountB) + .when() + .get("/detector/" + detectorId) + .then() + .statusCode(400) + .body("message", equalTo(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE)); + + given() + .header("Authorization", westAccountA) + .when() + .get("/detector/" + detectorId) + .then() + .statusCode(400) + .body("message", equalTo(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE)); + + given() + .header("Authorization", eastAccountA) + .when() + .get("/detector/" + detectorId) + .then() + .statusCode(200); + } + + @Test + void secondCreateInSameAccountAndRegionIsRejected() { + String authorization = auth("000000000207", EAST); + createDetector(authorization, "{\"enable\":true}"); + + given() + .contentType("application/json") + .header("Authorization", authorization) + .body("{\"enable\":true}") + .when() + .post("/detector") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + void detectorTagsAreServedThroughTheSharedTagsRoutes() { + String authorization = auth("000000000208", EAST); + String detectorId = createDetector(authorization, "{\"enable\":true,\"tags\":{\"env\":\"test\"}}"); + String arn = "arn:aws:guardduty:" + EAST + ":000000000208:detector/" + detectorId; + + given() + .contentType("application/json") + .header("Authorization", authorization) + .body("{\"tags\":{\"team\":\"security\"}}") + .when() + .post("/tags/" + arn) + .then() + .statusCode(204); + + given() + .header("Authorization", authorization) + .when() + .get("/tags/" + arn) + .then() + .statusCode(200) + .body("tags.env", equalTo("test")) + .body("tags.team", equalTo("security")); + + given() + .header("Authorization", authorization) + .queryParam("tagKeys", "env") + .when() + .delete("/tags/" + arn) + .then() + .statusCode(204); + + given() + .header("Authorization", authorization) + .when() + .get("/tags/" + arn) + .then() + .statusCode(200) + .body("tags.team", equalTo("security")); + } + + private static String auth(String accountId, String region) { + return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260215/" + region + "/guardduty/aws4_request"; + } + + private static String createDetector(String authorization, String body) { + return given() + .contentType("application/json") + .header("Authorization", authorization) + .body(body) + .when() + .post("/detector") + .then() + .statusCode(200) + .body("detectorId", notNullValue()) + .extract().path("detectorId"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java new file mode 100644 index 0000000000..0511dcf3b3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java @@ -0,0 +1,373 @@ +package io.github.hectorvent.floci.services.guardduty; + +import com.fasterxml.jackson.core.type.TypeReference; +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.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.PersistentStorage; +import io.github.hectorvent.floci.services.guardduty.model.AdminAccount; +import io.github.hectorvent.floci.services.guardduty.model.Detector; +import io.github.hectorvent.floci.services.guardduty.model.DetectorAdditionalConfiguration; +import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature; +import io.github.hectorvent.floci.services.guardduty.model.OrganizationAdditionalConfiguration; +import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; +import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GuardDutyServiceTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private final GuardDutyService service = + new GuardDutyService(new InMemoryStorage<>(), new InMemoryStorage<>()); + + @Test + void createDetectorAppliesDefaultsAndGeneratesIdentifiers() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + + assertEquals(32, detector.getId().length()); + assertEquals("ENABLED", detector.getStatus()); + assertEquals("SIX_HOURS", detector.getFindingPublishingFrequency()); + assertEquals( + "arn:aws:iam::" + ACCOUNT + + ":role/aws-service-role/guardduty.amazonaws.com/AWSServiceRoleForAmazonGuardDuty", + detector.getServiceRole()); + assertEquals(detector.getCreatedAt(), detector.getUpdatedAt()); + assertNull(detector.getFeatures()); + } + + @Test + void createDetectorRejectsSecondDetectorInSameRegion() throws Exception { + service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + + AwsException error = assertThrows( + AwsException.class, + () -> service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}"))); + + assertEquals("BadRequestException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals( + "The request is rejected because a detector already exists for the current account.", + error.getMessage()); + } + + @Test + void detectorsAreRegionScoped() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + service.createDetector("us-west-2", ACCOUNT, request("{\"enable\":true}")); + + AwsException error = assertThrows( + AwsException.class, () -> service.getDetector("us-west-2", detector.getId())); + + assertEquals("BadRequestException", error.getErrorCode()); + assertEquals(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE, error.getMessage()); + } + + @Test + void getDetectorRejectsMissingDetectorWithProviderMatchedMessage() { + AwsException error = assertThrows( + AwsException.class, () -> service.getDetector(REGION, "does-not-exist")); + + assertEquals("BadRequestException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE, error.getMessage()); + } + + @Test + void updateDetectorTogglesStatusAndFrequency() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + + service.updateDetector(REGION, detector.getId(), request( + "{\"enable\":false,\"findingPublishingFrequency\":\"ONE_HOUR\"}")); + + Detector updated = service.getDetector(REGION, detector.getId()); + assertEquals("DISABLED", updated.getStatus()); + assertEquals("ONE_HOUR", updated.getFindingPublishingFrequency()); + } + + @Test + void featureAdditionalConfigurationPreservesSubmittedOrder() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request(""" + {"enable":true,"features":[ + {"name":"RUNTIME_MONITORING","status":"ENABLED","additionalConfiguration":[ + {"name":"ECS_FARGATE_AGENT_MANAGEMENT","status":"ENABLED"}, + {"name":"EC2_AGENT_MANAGEMENT","status":"ENABLED"}, + {"name":"EKS_ADDON_MANAGEMENT","status":"DISABLED"} + ]}, + {"name":"S3_DATA_EVENTS","status":"ENABLED"} + ]} + """)); + + List features = service.getDetector(REGION, detector.getId()).getFeatures(); + assertEquals(List.of("RUNTIME_MONITORING", "S3_DATA_EVENTS"), + features.stream().map(DetectorFeature::getName).toList()); + assertEquals( + List.of("ECS_FARGATE_AGENT_MANAGEMENT", "EC2_AGENT_MANAGEMENT", "EKS_ADDON_MANAGEMENT"), + features.get(0).getAdditionalConfiguration().stream() + .map(DetectorAdditionalConfiguration::getName) + .toList()); + } + + @Test + void updateDetectorMergesFeaturesByNameAndAppendsNewOnes() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request(""" + {"enable":true,"features":[ + {"name":"S3_DATA_EVENTS","status":"ENABLED"}, + {"name":"RDS_LOGIN_EVENTS","status":"ENABLED"} + ]} + """)); + + service.updateDetector(REGION, detector.getId(), request(""" + {"features":[ + {"name":"RDS_LOGIN_EVENTS","status":"DISABLED"}, + {"name":"LAMBDA_NETWORK_LOGS","status":"ENABLED"} + ]} + """)); + + List features = service.getDetector(REGION, detector.getId()).getFeatures(); + assertEquals(List.of("S3_DATA_EVENTS", "RDS_LOGIN_EVENTS", "LAMBDA_NETWORK_LOGS"), + features.stream().map(DetectorFeature::getName).toList()); + assertEquals("ENABLED", features.get(0).getStatus()); + assertEquals("DISABLED", features.get(1).getStatus()); + assertEquals("ENABLED", features.get(2).getStatus()); + } + + @Test + void createDetectorRejectsUnknownFeatureName() { + AwsException error = assertThrows( + AwsException.class, + () -> service.createDetector(REGION, ACCOUNT, request( + "{\"enable\":true,\"features\":[{\"name\":\"NOT_A_FEATURE\",\"status\":\"ENABLED\"}]}"))); + + assertEquals("BadRequestException", error.getErrorCode()); + } + + @Test + void createDetectorRejectsInvalidFrequencyAndMissingEnable() { + AwsException frequencyError = assertThrows( + AwsException.class, + () -> service.createDetector(REGION, ACCOUNT, request( + "{\"enable\":true,\"findingPublishingFrequency\":\"NEVER\"}"))); + assertEquals("BadRequestException", frequencyError.getErrorCode()); + + AwsException enableError = assertThrows( + AwsException.class, () -> service.createDetector(REGION, ACCOUNT, request("{}"))); + assertEquals("BadRequestException", enableError.getErrorCode()); + } + + @Test + void deleteDetectorRemovesItAndRejectsSecondDelete() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + + service.deleteDetector(REGION, detector.getId()); + + AwsException error = assertThrows( + AwsException.class, () -> service.deleteDetector(REGION, detector.getId())); + assertEquals(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE, error.getMessage()); + assertTrue(service.listDetectorIds(REGION, null, null).items().isEmpty()); + } + + @Test + void listDetectorIdsReturnsTheRegionalDetector() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + + GuardDutyService.Page page = service.listDetectorIds(REGION, null, null); + + assertEquals(List.of(detector.getId()), page.items()); + assertNull(page.nextToken()); + } + + @Test + void describeOrganizationConfigurationDefaultsToNone() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + + OrganizationConfiguration configuration = + service.describeOrganizationConfiguration(REGION, detector.getId()); + + assertEquals(false, configuration.getAutoEnable()); + assertEquals("NONE", configuration.getAutoEnableOrganizationMembers()); + assertTrue(configuration.getFeatures().isEmpty()); + } + + @Test + void organizationConfigurationEchoesMembersAndDerivesAutoEnable() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + + service.updateOrganizationConfiguration(REGION, detector.getId(), request( + "{\"autoEnableOrganizationMembers\":\"ALL\"}")); + + OrganizationConfiguration configuration = + service.describeOrganizationConfiguration(REGION, detector.getId()); + assertEquals(true, configuration.getAutoEnable()); + assertEquals("ALL", configuration.getAutoEnableOrganizationMembers()); + } + + @Test + void organizationFeatureUpdatesMergeWithoutClobberingOtherFeatures() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + service.updateOrganizationConfiguration(REGION, detector.getId(), request( + "{\"autoEnableOrganizationMembers\":\"ALL\"}")); + + service.updateOrganizationConfiguration(REGION, detector.getId(), request(""" + {"features":[ + {"name":"RUNTIME_MONITORING","autoEnable":"ALL","additionalConfiguration":[ + {"name":"ECS_FARGATE_AGENT_MANAGEMENT","autoEnable":"ALL"}, + {"name":"EC2_AGENT_MANAGEMENT","autoEnable":"ALL"}, + {"name":"EKS_ADDON_MANAGEMENT","autoEnable":"NONE"} + ]} + ]} + """)); + service.updateOrganizationConfiguration(REGION, detector.getId(), request( + "{\"features\":[{\"name\":\"S3_DATA_EVENTS\",\"autoEnable\":\"NEW\"}]}")); + + OrganizationConfiguration configuration = + service.describeOrganizationConfiguration(REGION, detector.getId()); + assertEquals("ALL", configuration.getAutoEnableOrganizationMembers()); + assertEquals(List.of("RUNTIME_MONITORING", "S3_DATA_EVENTS"), + configuration.getFeatures().stream().map(OrganizationFeature::getName).toList()); + assertEquals( + List.of("ECS_FARGATE_AGENT_MANAGEMENT", "EC2_AGENT_MANAGEMENT", "EKS_ADDON_MANAGEMENT"), + configuration.getFeatures().get(0).getAdditionalConfiguration().stream() + .map(OrganizationAdditionalConfiguration::getName) + .toList()); + } + + @Test + void updateOrganizationConfigurationRejectsMissingDetectorAndBadValues() throws Exception { + AwsException notFound = assertThrows( + AwsException.class, + () -> service.updateOrganizationConfiguration(REGION, "missing", request( + "{\"autoEnableOrganizationMembers\":\"ALL\"}"))); + assertEquals(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE, notFound.getMessage()); + + Detector detector = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")); + AwsException badValue = assertThrows( + AwsException.class, + () -> service.updateOrganizationConfiguration(REGION, detector.getId(), request( + "{\"autoEnableOrganizationMembers\":\"SOME\"}"))); + assertEquals("BadRequestException", badValue.getErrorCode()); + } + + @Test + void adminAccountLifecycle() throws Exception { + service.enableOrganizationAdminAccount(REGION, request("{\"adminAccountId\":\"111111111111\"}")); + + GuardDutyService.Page accounts = + service.listOrganizationAdminAccounts(REGION, null, null); + assertEquals(1, accounts.items().size()); + assertEquals("111111111111", accounts.items().get(0).getAdminAccountId()); + assertEquals("ENABLED", accounts.items().get(0).getAdminStatus()); + + AwsException conflict = assertThrows( + AwsException.class, + () -> service.enableOrganizationAdminAccount(REGION, request( + "{\"adminAccountId\":\"222222222222\"}"))); + assertEquals("BadRequestException", conflict.getErrorCode()); + + service.disableOrganizationAdminAccount(REGION, request("{\"adminAccountId\":\"111111111111\"}")); + assertTrue(service.listOrganizationAdminAccounts(REGION, null, null).items().isEmpty()); + + AwsException alreadyDisabled = assertThrows( + AwsException.class, + () -> service.disableOrganizationAdminAccount(REGION, request( + "{\"adminAccountId\":\"111111111111\"}"))); + assertEquals(GuardDutyService.ADMIN_ALREADY_DISABLED_MESSAGE, alreadyDisabled.getMessage()); + } + + @Test + void enableOrganizationAdminAccountRejectsMalformedAccountId() { + AwsException error = assertThrows( + AwsException.class, + () -> service.enableOrganizationAdminAccount(REGION, request( + "{\"adminAccountId\":\"not-an-account\"}"))); + + assertEquals("BadRequestException", error.getErrorCode()); + } + + @Test + void tagOperationsRoundTripThroughTheDetectorArn() throws Exception { + Detector detector = service.createDetector(REGION, ACCOUNT, request( + "{\"enable\":true,\"tags\":{\"env\":\"test\"}}")); + String arn = "arn:aws:guardduty:" + REGION + ":" + ACCOUNT + ":detector/" + detector.getId(); + + service.tagResource(arn, Map.of("team", "security")); + assertEquals(Map.of("env", "test", "team", "security"), service.listTags(arn)); + + service.untagResource(arn, List.of("env")); + assertEquals(Map.of("team", "security"), service.listTags(arn)); + + AwsException error = assertThrows( + AwsException.class, + () -> service.listTags("arn:aws:guardduty:" + REGION + ":" + ACCOUNT + ":detector/missing")); + assertEquals(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE, error.getMessage()); + } + + @Test + void detectorSurvivesPersistentStorageReloadWithOrderIntact(@TempDir Path tempDir) throws Exception { + Path detectorFile = tempDir.resolve("detectors.json"); + Path adminFile = tempDir.resolve("admins.json"); + GuardDutyService firstService = new GuardDutyService( + loadedStore(detectorFile, new TypeReference>() { + }), + loadedStore(adminFile, new TypeReference>() { + })); + Detector created = firstService.createDetector(REGION, ACCOUNT, request(""" + {"enable":true,"tags":{"env":"test"},"features":[ + {"name":"RUNTIME_MONITORING","status":"ENABLED","additionalConfiguration":[ + {"name":"ECS_FARGATE_AGENT_MANAGEMENT","status":"ENABLED"}, + {"name":"EC2_AGENT_MANAGEMENT","status":"ENABLED"}, + {"name":"EKS_ADDON_MANAGEMENT","status":"DISABLED"} + ]} + ]} + """)); + firstService.updateOrganizationConfiguration(REGION, created.getId(), request( + "{\"autoEnableOrganizationMembers\":\"ALL\"}")); + + GuardDutyService reloadedService = new GuardDutyService( + loadedStore(detectorFile, new TypeReference>() { + }), + loadedStore(adminFile, new TypeReference>() { + })); + Detector reloaded = reloadedService.getDetector(REGION, created.getId()); + + assertEquals(created.getId(), reloaded.getId()); + assertEquals(created.getCreatedAt(), reloaded.getCreatedAt()); + assertEquals("test", reloaded.getTags().get("env")); + assertEquals( + List.of("ECS_FARGATE_AGENT_MANAGEMENT", "EC2_AGENT_MANAGEMENT", "EKS_ADDON_MANAGEMENT"), + reloaded.getFeatures().get(0).getAdditionalConfiguration().stream() + .map(DetectorAdditionalConfiguration::getName) + .toList()); + assertEquals("ALL", + reloadedService.describeOrganizationConfiguration(REGION, created.getId()) + .getAutoEnableOrganizationMembers()); + } + + private static PersistentStorage loadedStore( + Path file, TypeReference> type) { + PersistentStorage store = new PersistentStorage<>(file, type); + store.load(); + return store; + } + + private JsonNode request(String json) { + try { + return objectMapper.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index b3c85d7738..962316ab47 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -65,6 +65,8 @@ floci: flush-interval-ms: 60000 rum: flush-interval-ms: 60000 + guardduty: + flush-interval-ms: 60000 auth: validate-signatures: false @@ -307,3 +309,5 @@ floci: cloudhsmv2: rum: enabled: true + guardduty: + enabled: true