From fb390968d5409d88d668b096745ce97c56ba5330 Mon Sep 17 00:00:00 2001 From: Allen Sanborn Date: Mon, 19 Oct 2026 15:45:15 -0500 Subject: [PATCH] feat(guardduty): support publishing destinations (#6016) * feat(guardduty): support publishing destinations Add CreatePublishingDestination, DescribePublishingDestination, UpdatePublishingDestination, DeletePublishingDestination and ListPublishingDestinations under /detector/{detectorId}/publishingDestination. Previously these returned UnknownOperationException, which broke Terraform's aws_guardduty_publishing_destination. Destinations are stored per detector through StorageFactory, so they follow the detector's account and region scoping, survive a persistent-storage reload, and report PUBLISHING on create (the state Terraform's create waiter targets). A missing destination returns BadRequestException with the message the Terraform provider matches for not-found. Deleting a detector removes its destinations. clientToken makes create idempotent and is capped at the model's 64 characters, measured in code points as the model's length constraint is. destinationArn stays optional on create: the GuardDuty model marks DestinationProperties.DestinationArn and KmsKeyArn as not required (botocore guardduty/2017-11-28 service-2.json). The service gains a five-store constructor; the existing three- and four-store (malware protection plan) constructors delegate to it. Closes #4983 * docs(guardduty): update the service matrix operation count * test(guardduty): cover the publishing destination lifecycle through the SDK Create, describe, update, list and delete an S3 publishing destination with the AWS SDK v2 GuardDuty client, asserting the shapes as the SDK reads them, including the required publishingFailureStartTimestamp. --- .../java/com/floci/test/GuardDutyTest.java | 71 ++++++ docs/services/guardduty.md | 10 + docs/services/index.md | 2 +- .../guardduty/GuardDutyController.java | 75 ++++++ .../services/guardduty/GuardDutyService.java | 114 +++++++++ .../model/PublishingDestination.java | 7 + ...yPublishingDestinationIntegrationTest.java | 138 ++++++++++ .../guardduty/GuardDutyServiceTest.java | 238 ++++++++++++++++++ 8 files changed, 654 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/PublishingDestination.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyPublishingDestinationIntegrationTest.java 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 index f631a56f4c..0b632e9e76 100644 --- 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 @@ -9,6 +9,9 @@ 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.DescribePublishingDestinationResponse; +import software.amazon.awssdk.services.guardduty.model.DestinationProperties; +import software.amazon.awssdk.services.guardduty.model.DestinationType; import software.amazon.awssdk.services.guardduty.model.DetectorAdditionalConfiguration; import software.amazon.awssdk.services.guardduty.model.DetectorFeature; import software.amazon.awssdk.services.guardduty.model.DetectorFeatureConfiguration; @@ -23,6 +26,7 @@ import software.amazon.awssdk.services.guardduty.model.OrgFeatureAdditionalConfi 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 software.amazon.awssdk.services.guardduty.model.PublishingStatus; import java.util.List; import java.util.Map; @@ -118,6 +122,73 @@ class GuardDutyTest { } } + @Test + void publishingDestinationLifecycleUsesAwsSdkWireShapes() throws Exception { + String bucketArn = "arn:aws:s3:::compat-findings-bucket"; + String firstKey = "arn:aws:kms:us-east-1:000000000000:key/compat-first"; + String secondKey = "arn:aws:kms:us-east-1:000000000000:key/compat-second"; + + try (GuardDutyClient guardduty = TestFixtures.guardDutyClient()) { + String detectorId = guardduty.createDetector(request -> request.enable(true)).detectorId(); + + try (AutoCloseable deleteDetector = () -> + guardduty.deleteDetector(request -> request.detectorId(detectorId))) { + String destinationId = guardduty.createPublishingDestination(request -> request + .detectorId(detectorId) + .destinationType(DestinationType.S3) + .destinationProperties(DestinationProperties.builder() + .destinationArn(bucketArn) + .kmsKeyArn(firstKey) + .build())) + .destinationId(); + assertThat(destinationId).isNotBlank(); + + DescribePublishingDestinationResponse described = + guardduty.describePublishingDestination(request -> request + .detectorId(detectorId) + .destinationId(destinationId)); + assertThat(described.destinationId()).isEqualTo(destinationId); + assertThat(described.destinationType()).isEqualTo(DestinationType.S3); + assertThat(described.status()).isEqualTo(PublishingStatus.PUBLISHING); + assertThat(described.publishingFailureStartTimestamp()).isNotNull(); + assertThat(described.destinationProperties().destinationArn()).isEqualTo(bucketArn); + assertThat(described.destinationProperties().kmsKeyArn()).isEqualTo(firstKey); + + guardduty.updatePublishingDestination(request -> request + .detectorId(detectorId) + .destinationId(destinationId) + .destinationProperties(DestinationProperties.builder() + .destinationArn(bucketArn) + .kmsKeyArn(secondKey) + .build())); + assertThat(guardduty.describePublishingDestination(request -> request + .detectorId(detectorId) + .destinationId(destinationId)) + .destinationProperties().kmsKeyArn()).isEqualTo(secondKey); + + assertThat(guardduty.listPublishingDestinations(request -> request.detectorId(detectorId)) + .destinations()) + .singleElement() + .satisfies(destination -> { + assertThat(destination.destinationId()).isEqualTo(destinationId); + assertThat(destination.destinationType()).isEqualTo(DestinationType.S3); + assertThat(destination.status()).isEqualTo(PublishingStatus.PUBLISHING); + }); + + guardduty.deletePublishingDestination(request -> request + .detectorId(detectorId) + .destinationId(destinationId)); + assertThat(guardduty.listPublishingDestinations(request -> request.detectorId(detectorId)) + .destinations()).isEmpty(); + assertThatThrownBy(() -> guardduty.describePublishingDestination(request -> request + .detectorId(detectorId) + .destinationId(destinationId))) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("input parameters have invalid values"); + } + } + } + @Test void organizationConfigurationRoundTripsThroughTheSdk() throws Exception { try (GuardDutyClient guardduty = TestFixtures.guardDutyClient()) { diff --git a/docs/services/guardduty.md b/docs/services/guardduty.md index 640155a3e7..c99c64b6af 100644 --- a/docs/services/guardduty.md +++ b/docs/services/guardduty.md @@ -30,6 +30,11 @@ storage mode. | `UpdateMalwareProtectionPlan` | `PATCH /malware-protection-plan/{malwareProtectionPlanId}` | Update a plan's role, object prefixes, and tagging action | | `DeleteMalwareProtectionPlan` | `DELETE /malware-protection-plan/{malwareProtectionPlanId}` | Delete a plan | | `ListMalwareProtectionPlans` | `GET /malware-protection-plan` | List plan ids with pagination | +| `CreatePublishingDestination` | `POST /detector/{detectorId}/publishingDestination` | Create an S3 findings export destination | +| `DescribePublishingDestination` | `GET /detector/{detectorId}/publishingDestination/{destinationId}` | Return the destination's properties and status | +| `UpdatePublishingDestination` | `POST /detector/{detectorId}/publishingDestination/{destinationId}` | Update the destination ARN or KMS key ARN | +| `DeletePublishingDestination` | `DELETE /detector/{detectorId}/publishingDestination/{destinationId}` | Delete the destination | +| `ListPublishingDestinations` | `GET /detector/{detectorId}/publishingDestination` | List destinations with pagination | | `TagResource` | `POST /tags/{resourceArn}` | Add tags to a detector or Malware Protection plan | | `UntagResource` | `DELETE /tags/{resourceArn}` | Remove tags from a detector or Malware Protection plan | | `ListTagsForResource` | `GET /tags/{resourceArn}` | List detector or Malware Protection plan tags | @@ -61,6 +66,11 @@ included. The plan routes are served only to requests signed for `guardduty`, by header or the `X-Amz-Credential` query parameter, so a path-style S3 request for a bucket named `malware-protection-plan` still reaches S3. +## Publishing destinations + +Publishing destinations report `PUBLISHING` as soon as they are created: Floci does not +verify the bucket or key, and no findings are exported to it. + ## Configuration | Variable | Default | Description | diff --git a/docs/services/index.md b/docs/services/index.md index 23c40d15ed..da090da878 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -46,7 +46,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 | +| [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 28 | | [AWS Account Management](account.md) | `/putAlternateContact`, `/getAlternateContact`, `/deleteAlternateContact` | REST JSON | 3 | | [IAM Access Analyzer](access-analyzer.md) | `/analyzer`, `/analyzer/{name}` | REST JSON | 4 | | [IAM Identity Center (SSO Admin)](ssoadmin.md) | `POST /` + `X-Amz-Target: SWBExternalService.*` | JSON 1.1 | 79 | diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java index 20835810f4..e67ccd421d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.guardduty.model.MalwareProtectionPlan import io.github.hectorvent.floci.services.guardduty.model.MemberAccount; import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature; +import io.github.hectorvent.floci.services.guardduty.model.PublishingDestination; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; @@ -181,6 +182,80 @@ public class GuardDutyController { return Response.ok(response).build(); } + @POST + @Path("/detector/{detectorId}/publishingDestination") + public Response createPublishingDestination( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId, String body) { + PublishingDestination destination = service.createPublishingDestination( + regionResolver.resolveRegion(headers), detectorId, parse(body)); + ObjectNode response = objectMapper.createObjectNode(); + response.put("destinationId", destination.destinationId()); + return Response.ok(response).build(); + } + + @GET + @Path("/detector/{detectorId}/publishingDestination") + public Response listPublishingDestinations( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId, + @QueryParam("maxResults") String maxResults, + @QueryParam("nextToken") String nextToken) { + GuardDutyService.Page page = service.listPublishingDestinations( + regionResolver.resolveRegion(headers), detectorId, maxResults, nextToken); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode destinations = response.putArray("destinations"); + for (PublishingDestination destination : page.items()) { + ObjectNode node = destinations.addObject(); + node.put("destinationId", destination.destinationId()); + node.put("destinationType", destination.destinationType()); + node.put("status", destination.status()); + } + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + @GET + @Path("/detector/{detectorId}/publishingDestination/{destinationId}") + public Response describePublishingDestination( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId, + @PathParam("destinationId") String destinationId) { + PublishingDestination destination = service.describePublishingDestination( + regionResolver.resolveRegion(headers), detectorId, destinationId); + ObjectNode response = objectMapper.createObjectNode(); + response.put("destinationId", destination.destinationId()); + response.put("destinationType", destination.destinationType()); + response.put("status", destination.status()); + response.put("publishingFailureStartTimestamp", 0L); + ObjectNode properties = response.putObject("destinationProperties"); + if (destination.destinationArn() != null) { + properties.put("destinationArn", destination.destinationArn()); + } + if (destination.kmsKeyArn() != null) { + properties.put("kmsKeyArn", destination.kmsKeyArn()); + } + return Response.ok(response).build(); + } + + @POST + @Path("/detector/{detectorId}/publishingDestination/{destinationId}") + public Response updatePublishingDestination( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId, + @PathParam("destinationId") String destinationId, String body) { + service.updatePublishingDestination( + regionResolver.resolveRegion(headers), detectorId, destinationId, parse(body)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @DELETE + @Path("/detector/{detectorId}/publishingDestination/{destinationId}") + public Response deletePublishingDestination( + @Context HttpHeaders headers, @PathParam("detectorId") String detectorId, + @PathParam("destinationId") String destinationId) { + service.deletePublishingDestination(regionResolver.resolveRegion(headers), detectorId, destinationId); + return Response.ok(objectMapper.createObjectNode()).build(); + } + @GET @Path("/detector/{detectorId}/admin") public Response describeOrganizationConfiguration( diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java index 6443863730..5536857afb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java @@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.guardduty.model.MemberAccount; import io.github.hectorvent.floci.services.guardduty.model.OrganizationAdditionalConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature; +import io.github.hectorvent.floci.services.guardduty.model.PublishingDestination; import io.github.hectorvent.floci.services.iam.ServiceLinkedRoles; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -96,6 +97,7 @@ public class GuardDutyService { private final StorageBackend adminAccountStore; private final StorageBackend memberStore; private final StorageBackend malwareProtectionPlanStore; + private final StorageBackend destinationStore; @Inject public GuardDutyService(StorageFactory storageFactory) { @@ -118,6 +120,11 @@ public class GuardDutyService { "guardduty", "guardduty-malware-protection-plans.json", new TypeReference>() { + }), + storageFactory.create( + "guardduty", + "guardduty-publishing-destinations.json", + new TypeReference>() { })); } @@ -134,10 +141,20 @@ public class GuardDutyService { StorageBackend adminAccountStore, StorageBackend memberStore, StorageBackend malwareProtectionPlanStore) { + this(detectorStore, adminAccountStore, memberStore, malwareProtectionPlanStore, new InMemoryStorage<>()); + } + + GuardDutyService( + StorageBackend detectorStore, + StorageBackend adminAccountStore, + StorageBackend memberStore, + StorageBackend malwareProtectionPlanStore, + StorageBackend destinationStore) { this.detectorStore = detectorStore; this.adminAccountStore = adminAccountStore; this.memberStore = memberStore; this.malwareProtectionPlanStore = malwareProtectionPlanStore; + this.destinationStore = destinationStore; } public synchronized Detector createDetector(String region, String accountId, JsonNode request) { @@ -194,6 +211,9 @@ public class GuardDutyService { throw detectorNotFound(); } detectorStore.delete(key); + String prefix = destinationKey(region, detectorId, ""); + destinationStore.scan(k -> k.startsWith(prefix)).forEach(d -> + destinationStore.delete(destinationKey(region, detectorId, d.destinationId()))); } public Page listDetectorIds(String region, String accountId, String maxResultsValue, String nextToken) { @@ -337,6 +357,100 @@ public class GuardDutyService { return listMembers(region, detectorId, null, null, null).items(); } + public synchronized PublishingDestination createPublishingDestination( + String region, String detectorId, JsonNode request) { + getDetector(region, detectorId); + if (!"S3".equals(requireText(request, "destinationType"))) { + throw badRequest("destinationType must be S3."); + } + JsonNode properties = request.get("destinationProperties"); + requireObject(properties, "destinationProperties"); + String clientToken = optionalText(request, "clientToken"); + if (clientToken != null && clientToken.codePointCount(0, clientToken.length()) > 64) { + // botocore's ClientToken shape: string, min 0, max 64. + throw badRequest("clientToken must be at most 64 characters."); + } + if (clientToken != null) { + // Idempotent replay: a retried create returns the destination the token already made. + String prefix = destinationKey(region, detectorId, ""); + for (PublishingDestination existing : destinationStore.scan(k -> k.startsWith(prefix))) { + if (clientToken.equals(existing.clientToken())) { + return existing; + } + } + } + PublishingDestination destination = new PublishingDestination( + UUID.randomUUID().toString().replace("-", ""), + "S3", + optionalText(properties, "destinationArn"), + optionalText(properties, "kmsKeyArn"), + "PUBLISHING", + clientToken); + destinationStore.put(destinationKey(region, detectorId, destination.destinationId()), destination); + return destination; + } + + public PublishingDestination describePublishingDestination( + String region, String detectorId, String destinationId) { + getDetector(region, detectorId); + return destinationStore.get(destinationKey(region, detectorId, destinationId)) + .orElseThrow(GuardDutyService::destinationNotFound); + } + + public synchronized void updatePublishingDestination( + String region, String detectorId, String destinationId, JsonNode request) { + PublishingDestination current = describePublishingDestination(region, detectorId, destinationId); + JsonNode properties = request.get("destinationProperties"); + if (properties == null) { + return; + } + requireObject(properties, "destinationProperties"); + destinationStore.put(destinationKey(region, detectorId, destinationId), new PublishingDestination( + destinationId, + current.destinationType(), + properties.has("destinationArn") ? optionalText(properties, "destinationArn") : current.destinationArn(), + properties.has("kmsKeyArn") ? optionalText(properties, "kmsKeyArn") : current.kmsKeyArn(), + current.status(), + current.clientToken())); + } + + public synchronized void deletePublishingDestination(String region, String detectorId, String destinationId) { + describePublishingDestination(region, detectorId, destinationId); + destinationStore.delete(destinationKey(region, detectorId, destinationId)); + } + + public Page listPublishingDestinations( + String region, String detectorId, String maxResults, String nextToken) { + getDetector(region, detectorId); + int limit = parseMaxResults(maxResults); + String prefix = destinationKey(region, detectorId, ""); + List destinations = destinationStore.scan(key -> key.startsWith(prefix)).stream() + .sorted(Comparator.comparing(PublishingDestination::destinationId)).toList(); + int offset = decodeOffset(nextToken, destinations.size()); + int end = Math.min(destinations.size(), offset + limit); + return new Page<>(destinations.subList(offset, end), end < destinations.size() ? encodeOffset(end) : null); + } + + private static String destinationKey(String region, String detectorId, String destinationId) { + return region + "::" + detectorId + "::" + destinationId; + } + + private static String optionalText(JsonNode parent, String field) { + JsonNode value = parent.get(field); + if (value == null || value.isNull()) { + return null; + } + if (!value.isTextual()) { + throw badRequest(field + " must be a string."); + } + return value.textValue(); + } + + /** Matched verbatim by the Terraform AWS provider to detect a deleted publishing destination. */ + private static AwsException destinationNotFound() { + return badRequest("The request is rejected because the one or more input parameters have invalid values."); + } + private static boolean isAssociatedRelationship(String status) { return "Enabled".equals(status) || "Invited".equals(status) || "EmailVerificationInProgress".equals(status); } diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/PublishingDestination.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/PublishingDestination.java new file mode 100644 index 0000000000..4307e04ce3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/PublishingDestination.java @@ -0,0 +1,7 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public record PublishingDestination(String destinationId, String destinationType, String destinationArn, + String kmsKeyArn, String status, String clientToken) {} diff --git a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyPublishingDestinationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyPublishingDestinationIntegrationTest.java new file mode 100644 index 0000000000..8c8e22b1e7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyPublishingDestinationIntegrationTest.java @@ -0,0 +1,138 @@ +package io.github.hectorvent.floci.services.guardduty; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; + +@QuarkusTest +class GuardDutyPublishingDestinationIntegrationTest { + + private static final String ACCOUNT = "818181818181"; + private static final String OTHER_ACCOUNT = "828282828282"; + private static final String BUCKET_ARN = "arn:aws:s3:::findings-bucket"; + private static final String KMS_ARN = "arn:aws:kms:us-east-1:" + ACCOUNT + ":key/first"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void publishingDestinationLifecycle() { + String detectorId = createDetector(ACCOUNT); + String path = "/detector/" + detectorId + "/publishingDestination"; + + String destinationId = given().contentType("application/json") + .header("Authorization", auth(ACCOUNT)) + .body("{\"destinationType\":\"S3\",\"destinationProperties\":" + + "{\"destinationArn\":\"" + BUCKET_ARN + "\",\"kmsKeyArn\":\"" + KMS_ARN + "\"}}") + .post(path) + .then().statusCode(200) + .body("destinationId", notNullValue()) + .extract().path("destinationId"); + + given().header("Authorization", auth(ACCOUNT)) + .get(path + "/" + destinationId) + .then().statusCode(200) + .body("destinationId", equalTo(destinationId)) + .body("destinationType", equalTo("S3")) + .body("status", equalTo("PUBLISHING")) + .body("publishingFailureStartTimestamp", equalTo(0)) + .body("destinationProperties.destinationArn", equalTo(BUCKET_ARN)) + .body("destinationProperties.kmsKeyArn", equalTo(KMS_ARN)); + + given().header("Authorization", auth(ACCOUNT)) + .get(path) + .then().statusCode(200) + .body("destinations", hasSize(1)) + .body("destinations[0].destinationId", equalTo(destinationId)) + .body("destinations[0].destinationType", equalTo("S3")) + .body("destinations[0].status", equalTo("PUBLISHING")); + + String newKms = "arn:aws:kms:us-east-1:" + ACCOUNT + ":key/second"; + given().contentType("application/json") + .header("Authorization", auth(ACCOUNT)) + .body("{\"destinationProperties\":{\"destinationArn\":\"" + BUCKET_ARN + + "\",\"kmsKeyArn\":\"" + newKms + "\"}}") + .post(path + "/" + destinationId) + .then().statusCode(200); + + given().header("Authorization", auth(ACCOUNT)) + .get(path + "/" + destinationId) + .then().statusCode(200) + .body("destinationProperties.kmsKeyArn", equalTo(newKms)); + + given().header("Authorization", auth(ACCOUNT)) + .delete(path + "/" + destinationId) + .then().statusCode(200); + + given().header("Authorization", auth(ACCOUNT)) + .get(path + "/" + destinationId) + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo( + "The request is rejected because the one or more input parameters have invalid values.")); + + given().header("Authorization", auth(ACCOUNT)) + .get(path) + .then().statusCode(200) + .body("destinations", hasSize(0)); + } + + /** + * Another account cannot reach the destination because it cannot reach the owning detector: the + * detector lookup rejects first. Destination storage partitioning itself is pinned in + * GuardDutyServiceTest#publishingDestinationsArePartitionedByAccountEvenForTheSameDetector. + */ + @Test + void anotherAccountCannotReachDestinationThroughAForeignDetector() { + String detectorId = createDetector(OTHER_ACCOUNT); + String path = "/detector/" + detectorId + "/publishingDestination"; + String destinationId = given().contentType("application/json") + .header("Authorization", auth(OTHER_ACCOUNT)) + .body("{\"destinationType\":\"S3\",\"destinationProperties\":" + + "{\"destinationArn\":\"" + BUCKET_ARN + "\",\"kmsKeyArn\":\"" + KMS_ARN + "\"}}") + .post(path) + .then().statusCode(200) + .extract().path("destinationId"); + + given().header("Authorization", auth(ACCOUNT)) + .get(path + "/" + destinationId) + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(GuardDutyService.DETECTOR_NOT_FOUND_MESSAGE)); + } + + @Test + void rejectsUnsupportedDestinationType() { + String detectorId = createDetector("838383838383"); + + given().contentType("application/json") + .header("Authorization", auth("838383838383")) + .body("{\"destinationType\":\"SQS\",\"destinationProperties\":" + + "{\"destinationArn\":\"" + BUCKET_ARN + "\"}}") + .post("/detector/" + detectorId + "/publishingDestination") + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + private static String createDetector(String accountId) { + return given() + .contentType("application/json") + .header("Authorization", auth(accountId)) + .body("{\"enable\":true}") + .post("/detector") + .then().statusCode(200) + .extract().path("detectorId"); + } + + private static String auth(String accountId) { + return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260904/us-east-1/guardduty/aws4_request"; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java index e62015b936..4ee178ef5f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyServiceTest.java @@ -15,14 +15,18 @@ import io.github.hectorvent.floci.services.guardduty.model.MemberAccount; import io.github.hectorvent.floci.services.guardduty.model.OrganizationAdditionalConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature; +import io.github.hectorvent.floci.services.guardduty.model.PublishingDestination; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.api.io.TempDir; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -413,6 +417,240 @@ class GuardDutyServiceTest { .getAutoEnableOrganizationMembers()); } + private static final String DESTINATION_NOT_FOUND = + "The request is rejected because the one or more input parameters have invalid values."; + + @Test + void createPublishingDestinationWithSameClientTokenReturnsOriginal() throws Exception { + String detectorId = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + String body = "{\"destinationType\":\"S3\",\"clientToken\":\"tok-1\"," + + "\"destinationProperties\":{\"destinationArn\":\"arn:aws:s3:::a\"}}"; + String first = service.createPublishingDestination(REGION, detectorId, request(body)).destinationId(); + String retry = service.createPublishingDestination(REGION, detectorId, request(body)).destinationId(); + String other = service.createPublishingDestination(REGION, detectorId, + request(body.replace("tok-1", "tok-2"))).destinationId(); + + assertEquals(first, retry); + assertNotEquals(first, other); + assertEquals(2, service.listPublishingDestinations(REGION, detectorId, null, null).items().size()); + } + + @Test + void createPublishingDestinationRejectsClientTokenOverSixtyFourCharacters() throws Exception { + String detectorId = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + String body = "{\"destinationType\":\"S3\",\"clientToken\":\"%s\"," + + "\"destinationProperties\":{\"destinationArn\":\"arn:aws:s3:::a\"}}"; + + AwsException error = assertThrows(AwsException.class, + () -> service.createPublishingDestination(REGION, detectorId, request(body.formatted("t".repeat(65))))); + assertEquals("BadRequestException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals("clientToken must be at most 64 characters.", error.getMessage()); + assertTrue(service.listPublishingDestinations(REGION, detectorId, null, null).items().isEmpty()); + + service.createPublishingDestination(REGION, detectorId, request(body.formatted("t".repeat(64)))); + assertEquals(1, service.listPublishingDestinations(REGION, detectorId, null, null).items().size()); + } + + /** The model's length constraint counts Unicode code points, not UTF-16 code units. */ + @Test + void createPublishingDestinationMeasuresClientTokenInCodePoints() throws Exception { + String detectorId = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + String body = "{\"destinationType\":\"S3\",\"clientToken\":\"%s\"," + + "\"destinationProperties\":{\"destinationArn\":\"arn:aws:s3:::a\"}}"; + String emoji = "😀"; + + service.createPublishingDestination(REGION, detectorId, request(body.formatted(emoji.repeat(64)))); + assertEquals(1, service.listPublishingDestinations(REGION, detectorId, null, null).items().size()); + + AwsException error = assertThrows(AwsException.class, + () -> service.createPublishingDestination(REGION, detectorId, request(body.formatted(emoji.repeat(65))))); + assertEquals("clientToken must be at most 64 characters.", error.getMessage()); + assertEquals(1, service.listPublishingDestinations(REGION, detectorId, null, null).items().size()); + } + + @Test + void publishingDestinationSurvivesPersistentStorageReloadWithClientToken(@TempDir Path tempDir) + throws Exception { + Path detectorFile = tempDir.resolve("detectors.json"); + Path adminFile = tempDir.resolve("admins.json"); + Path memberFile = tempDir.resolve("members.json"); + Path destinationFile = tempDir.resolve("destinations.json"); + GuardDutyService firstService = new GuardDutyService( + loadedStore(detectorFile, new TypeReference>() { + }), + loadedStore(adminFile, new TypeReference>() { + }), + loadedStore(memberFile, new TypeReference>() { + }), + new InMemoryStorage<>(), + loadedStore(destinationFile, new TypeReference>() { + })); + String detectorId = firstService.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + String body = "{\"destinationType\":\"S3\",\"clientToken\":\"tok-reload\"," + + "\"destinationProperties\":{\"destinationArn\":\"arn:aws:s3:::a\"," + + "\"kmsKeyArn\":\"arn:aws:kms:us-east-1:000000000000:key/k\"}}"; + PublishingDestination created = firstService.createPublishingDestination(REGION, detectorId, request(body)); + + GuardDutyService reloadedService = new GuardDutyService( + loadedStore(detectorFile, new TypeReference>() { + }), + loadedStore(adminFile, new TypeReference>() { + }), + loadedStore(memberFile, new TypeReference>() { + }), + new InMemoryStorage<>(), + loadedStore(destinationFile, new TypeReference>() { + })); + + assertEquals(created, reloadedService.describePublishingDestination( + REGION, detectorId, created.destinationId())); + assertEquals("tok-reload", reloadedService.describePublishingDestination( + REGION, detectorId, created.destinationId()).clientToken()); + PublishingDestination replay = reloadedService.createPublishingDestination(REGION, detectorId, request(body)); + assertEquals(created.destinationId(), replay.destinationId()); + assertEquals(1, reloadedService.listPublishingDestinations(REGION, detectorId, null, null).items().size()); + } + + @Test + void deleteDetectorRemovesItsPublishingDestinations() throws Exception { + InMemoryStorage destinations = new InMemoryStorage<>(); + GuardDutyService svc = new GuardDutyService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), destinations); + String keep = svc.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + String dropRegion = "us-west-2"; + String drop = svc.createDetector(dropRegion, ACCOUNT, request("{\"enable\":true}")).getId(); + String body = "{\"destinationType\":\"S3\",\"destinationProperties\":{\"destinationArn\":\"arn:aws:s3:::a\"}}"; + svc.createPublishingDestination(REGION, keep, request(body)); + svc.createPublishingDestination(dropRegion, drop, request(body)); + + svc.deleteDetector(dropRegion, drop); + + assertEquals(1, destinations.scan(k -> true).size()); + assertEquals(1, svc.listPublishingDestinations(REGION, keep, null, null).items().size()); + } + + @Test + void publishingDestinationsArePartitionedByAccountEvenForTheSameDetector() throws Exception { + // Both services see one detector (plain store), so only the destination store's account + // partitioning can keep the second account away from the first account's destination. + InMemoryStorage sharedDetectors = new InMemoryStorage<>(); + InMemoryStorage sharedDestinations = new InMemoryStorage<>(); + GuardDutyService first = new GuardDutyService(sharedDetectors, new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), + new AccountAwareStorageBackend<>(sharedDestinations, null, "111111111111")); + GuardDutyService second = new GuardDutyService(sharedDetectors, new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), + new AccountAwareStorageBackend<>(sharedDestinations, null, "222222222222")); + String detectorId = first.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + String destinationId = first.createPublishingDestination(REGION, detectorId, request( + "{\"destinationType\":\"S3\",\"destinationProperties\":{\"destinationArn\":\"arn:aws:s3:::a\"}}")) + .destinationId(); + + AwsException hidden = assertThrows(AwsException.class, + () -> second.describePublishingDestination(REGION, detectorId, destinationId)); + assertEquals(DESTINATION_NOT_FOUND, hidden.getMessage()); + assertTrue(second.listPublishingDestinations(REGION, detectorId, null, null).items().isEmpty()); + assertEquals(destinationId, first.describePublishingDestination(REGION, detectorId, destinationId) + .destinationId()); + } + + @Test + void listPublishingDestinationsPagesWithMaxResultsAndRejectsBadTokens() throws Exception { + String detectorId = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + List created = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + created.add(createDestination(detectorId, "arn:aws:s3:::bucket-" + i).destinationId()); + } + created.sort(null); + + GuardDutyService.Page firstPage = + service.listPublishingDestinations(REGION, detectorId, "2", null); + assertEquals(created.subList(0, 2), + firstPage.items().stream().map(PublishingDestination::destinationId).toList()); + GuardDutyService.Page lastPage = + service.listPublishingDestinations(REGION, detectorId, "2", firstPage.nextToken()); + assertEquals(created.subList(2, 3), + lastPage.items().stream().map(PublishingDestination::destinationId).toList()); + assertNull(lastPage.nextToken()); + + service.deletePublishingDestination(REGION, detectorId, created.get(2)); + AwsException stale = assertThrows(AwsException.class, + () -> service.listPublishingDestinations(REGION, detectorId, "2", firstPage.nextToken())); + assertEquals("nextToken is invalid.", stale.getMessage()); + AwsException garbage = assertThrows(AwsException.class, + () -> service.listPublishingDestinations(REGION, detectorId, null, "not-a-token")); + assertEquals("nextToken is invalid.", garbage.getMessage()); + AwsException tooMany = assertThrows(AwsException.class, + () -> service.listPublishingDestinations(REGION, detectorId, "0", null)); + assertEquals("BadRequestException", tooMany.getErrorCode()); + } + + @Test + void updatePublishingDestinationKeepsOmittedFieldsAndValidatesInput() throws Exception { + String detectorId = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + String destinationId = service.createPublishingDestination(REGION, detectorId, request( + "{\"destinationType\":\"S3\",\"destinationProperties\":" + + "{\"destinationArn\":\"arn:aws:s3:::a\",\"kmsKeyArn\":\"arn:aws:kms:k1\"}}")) + .destinationId(); + + service.updatePublishingDestination(REGION, detectorId, destinationId, + request("{\"destinationProperties\":{\"kmsKeyArn\":\"arn:aws:kms:k2\"}}")); + PublishingDestination afterKms = service.describePublishingDestination(REGION, detectorId, destinationId); + assertEquals("arn:aws:s3:::a", afterKms.destinationArn()); + assertEquals("arn:aws:kms:k2", afterKms.kmsKeyArn()); + + service.updatePublishingDestination(REGION, detectorId, destinationId, + request("{\"destinationProperties\":{\"destinationArn\":\"arn:aws:s3:::b\"}}")); + PublishingDestination afterArn = service.describePublishingDestination(REGION, detectorId, destinationId); + assertEquals("arn:aws:s3:::b", afterArn.destinationArn()); + assertEquals("arn:aws:kms:k2", afterArn.kmsKeyArn()); + + service.updatePublishingDestination(REGION, detectorId, destinationId, request("{}")); + assertEquals(afterArn, service.describePublishingDestination(REGION, detectorId, destinationId)); + + AwsException notObject = assertThrows(AwsException.class, + () -> service.updatePublishingDestination(REGION, detectorId, destinationId, + request("{\"destinationProperties\":\"arn:aws:s3:::c\"}"))); + assertEquals("destinationProperties must be a JSON object.", notObject.getMessage()); + AwsException notText = assertThrows(AwsException.class, + () -> service.updatePublishingDestination(REGION, detectorId, destinationId, + request("{\"destinationProperties\":{\"destinationArn\":5}}"))); + assertEquals("destinationArn must be a string.", notText.getMessage()); + assertEquals(afterArn, service.describePublishingDestination(REGION, detectorId, destinationId)); + } + + @Test + void unknownPublishingDestinationIsRejectedWithProviderMatchedMessage() throws Exception { + String detectorId = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + for (Executable call : List.of( + () -> service.describePublishingDestination(REGION, detectorId, "missing"), + () -> service.updatePublishingDestination(REGION, detectorId, "missing", + request("{\"destinationProperties\":{\"destinationArn\":\"arn:aws:s3:::a\"}}")), + () -> service.deletePublishingDestination(REGION, detectorId, "missing"))) { + AwsException error = assertThrows(AwsException.class, call); + assertEquals("BadRequestException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals(DESTINATION_NOT_FOUND, error.getMessage()); + } + } + + @Test + void createPublishingDestinationRequiresDestinationProperties() throws Exception { + String detectorId = service.createDetector(REGION, ACCOUNT, request("{\"enable\":true}")).getId(); + AwsException error = assertThrows(AwsException.class, + () -> service.createPublishingDestination(REGION, detectorId, + request("{\"destinationType\":\"S3\"}"))); + assertEquals("BadRequestException", error.getErrorCode()); + assertEquals("destinationProperties must be a JSON object.", error.getMessage()); + assertTrue(service.listPublishingDestinations(REGION, detectorId, null, null).items().isEmpty()); + } + + private PublishingDestination createDestination(String detectorId, String bucketArn) { + return service.createPublishingDestination(REGION, detectorId, request( + "{\"destinationType\":\"S3\",\"destinationProperties\":{\"destinationArn\":\"" + bucketArn + "\"}}")); + } + private static PersistentStorage loadedStore( Path file, TypeReference> type) { PersistentStorage store = new PersistentStorage<>(file, type);