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.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-19 16:45:15 -04:00
1 parent 28799ed352
commit fb390968d5
8 files changed
+654 -1

No files matched your search

@@ -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";
}
}
@@ -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<Map<String, Detector>>() {
}),
loadedStore(adminFile, new TypeReference<Map<String, AdminAccount>>() {
}),
loadedStore(memberFile, new TypeReference<Map<String, MemberAccount>>() {
}),
new InMemoryStorage<>(),
loadedStore(destinationFile, new TypeReference<Map<String, PublishingDestination>>() {
}));
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<Map<String, Detector>>() {
}),
loadedStore(adminFile, new TypeReference<Map<String, AdminAccount>>() {
}),
loadedStore(memberFile, new TypeReference<Map<String, MemberAccount>>() {
}),
new InMemoryStorage<>(),
loadedStore(destinationFile, new TypeReference<Map<String, PublishingDestination>>() {
}));
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<String, PublishingDestination> 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<String, Detector> sharedDetectors = new InMemoryStorage<>();
InMemoryStorage<String, PublishingDestination> 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<String> 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<PublishingDestination> firstPage =
service.listPublishingDestinations(REGION, detectorId, "2", null);
assertEquals(created.subList(0, 2),
firstPage.items().stream().map(PublishingDestination::destinationId).toList());
GuardDutyService.Page<PublishingDestination> 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.<Executable>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 <V> PersistentStorage<String, V> loadedStore(
Path file, TypeReference<Map<String, V>> type) {
PersistentStorage<String, V> store = new PersistentStorage<>(file, type);