Skip to content

armgit / floci

Public Imported from GitHub
0

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

Add CloudTrail trail lifecycle support (#1256)

Jason van Zyl9a244a696464
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index f1c286f96d..7c884febf2 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -171,6 +171,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>servicediscovery</artifactId>
</dependency>
+ <!-- CloudTrail client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>cloudtrail</artifactId>
+ </dependency>
<!-- Kinesis client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index a78c4ba553..60b478dda7 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
@@ -4,6 +4,7 @@ import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
+import software.amazon.awssdk.services.cloudtrail.CloudTrailClient;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
@@ -477,6 +478,14 @@ public final class TestFixtures {
.build();
}
+ public static CloudTrailClient cloudTrailClient() {
+ return CloudTrailClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static SfnClient sfnClient() {
return SfnClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudTrailTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudTrailTest.java
new file mode 100644
index 0000000000..38fb0156b7
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudTrailTest.java
@@ -0,0 +1,112 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.*;
+import software.amazon.awssdk.services.cloudtrail.CloudTrailClient;
+import software.amazon.awssdk.services.cloudtrail.model.CreateTrailResponse;
+import software.amazon.awssdk.services.cloudtrail.model.DescribeTrailsResponse;
+import software.amazon.awssdk.services.cloudtrail.model.GetTrailStatusResponse;
+import software.amazon.awssdk.services.cloudtrail.model.Trail;
+import software.amazon.awssdk.services.cloudtrail.model.TrailNotFoundException;
+import software.amazon.awssdk.services.cloudtrail.model.UpdateTrailResponse;
+
+import static org.assertj.core.api.Assertions.*;
+
+@DisplayName("CloudTrail")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class CloudTrailTest {
+
+ private static CloudTrailClient cloudTrail;
+ private static String trailName;
+ private static String bucketName;
+ private static String updatedBucketName;
+
+ @BeforeAll
+ static void setup() {
+ cloudTrail = TestFixtures.cloudTrailClient();
+ trailName = TestFixtures.uniqueName("ct-sdk");
+ bucketName = TestFixtures.uniqueName("ct-bucket");
+ updatedBucketName = TestFixtures.uniqueName("ct-bucket-updated");
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (cloudTrail != null) {
+ try {
+ cloudTrail.deleteTrail(r -> r.name(trailName));
+ } catch (Exception ignored) {
+ }
+ cloudTrail.close();
+ }
+ }
+
+ @Test
+ @Order(1)
+ void createTrail() {
+ CreateTrailResponse response = cloudTrail.createTrail(r -> r
+ .name(trailName)
+ .s3BucketName(bucketName)
+ .includeGlobalServiceEvents(true)
+ .isMultiRegionTrail(true));
+
+ assertThat(response.name()).isEqualTo(trailName);
+ assertThat(response.s3BucketName()).isEqualTo(bucketName);
+ assertThat(response.trailARN()).contains(":cloudtrail:").endsWith(":trail/" + trailName);
+ assertThat(response.includeGlobalServiceEvents()).isTrue();
+ assertThat(response.isMultiRegionTrail()).isTrue();
+ }
+
+ @Test
+ @Order(2)
+ void describeTrailsByName() {
+ DescribeTrailsResponse response = cloudTrail.describeTrails(r -> r.trailNameList(trailName));
+
+ assertThat(response.trailList()).hasSize(1);
+ Trail trail = response.trailList().get(0);
+ assertThat(trail.name()).isEqualTo(trailName);
+ assertThat(trail.homeRegion()).isEqualTo("us-east-1");
+ assertThat(trail.s3BucketName()).isEqualTo(bucketName);
+ }
+
+ @Test
+ @Order(3)
+ void updateTrail() {
+ UpdateTrailResponse response = cloudTrail.updateTrail(r -> r
+ .name(trailName)
+ .s3BucketName(updatedBucketName)
+ .includeGlobalServiceEvents(false));
+
+ assertThat(response.name()).isEqualTo(trailName);
+ assertThat(response.s3BucketName()).isEqualTo(updatedBucketName);
+ assertThat(response.includeGlobalServiceEvents()).isFalse();
+ }
+
+ @Test
+ @Order(4)
+ void startAndStopLogging() {
+ cloudTrail.startLogging(r -> r.name(trailName));
+
+ GetTrailStatusResponse started = cloudTrail.getTrailStatus(r -> r.name(trailName));
+ assertThat(started.isLogging()).isTrue();
+ assertThat(started.latestDeliveryTime()).isNotNull();
+
+ cloudTrail.stopLogging(r -> r.name(trailName));
+
+ GetTrailStatusResponse stopped = cloudTrail.getTrailStatus(r -> r.name(trailName));
+ assertThat(stopped.isLogging()).isFalse();
+ }
+
+ @Test
+ @Order(5)
+ void putEventSelectorsAcceptsTrailName() {
+ cloudTrail.putEventSelectors(r -> r.trailName(trailName));
+ }
+
+ @Test
+ @Order(6)
+ void deleteTrail() {
+ cloudTrail.deleteTrail(r -> r.name(trailName));
+
+ assertThatThrownBy(() -> cloudTrail.getTrailStatus(r -> r.name(trailName)))
+ .isInstanceOf(TrailNotFoundException.class);
+ }
+}
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 13db3ed8ff..545620e240 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -364,10 +364,16 @@ public interface EmulatorConfig {
CurServiceConfig cur();
BcmDataExportsServiceConfig bcmDataExports();
ConfigServiceConfig configservice();
+ CloudTrailServiceConfig cloudtrail();
CloudFrontServiceConfig cloudfront();
AppSyncServiceConfig appsync();
}
+ interface CloudTrailServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface TransferServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
index cdd72ee890..bc117df033 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.glue.GlueJsonHandler;
import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingJsonHandler;
import io.github.hectorvent.floci.services.bcmdataexports.BcmDataExportsJsonHandler;
import io.github.hectorvent.floci.services.ce.CostExplorerJsonHandler;
+import io.github.hectorvent.floci.services.cloudtrail.CloudTrailJsonHandler;
import io.github.hectorvent.floci.services.configservice.ConfigServiceJsonHandler;
import io.github.hectorvent.floci.services.cur.CurJsonHandler;
import io.github.hectorvent.floci.services.pricing.PricingJsonHandler;
@@ -80,6 +81,7 @@ public class AwsJson11Controller {
private final CurJsonHandler curJsonHandler;
private final BcmDataExportsJsonHandler bcmDataExportsJsonHandler;
private final ConfigServiceJsonHandler configServiceJsonHandler;
+ private final CloudTrailJsonHandler cloudTrailJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -106,7 +108,8 @@ public class AwsJson11Controller {
CostExplorerJsonHandler costExplorerJsonHandler,
CurJsonHandler curJsonHandler,
BcmDataExportsJsonHandler bcmDataExportsJsonHandler,
- ConfigServiceJsonHandler configServiceJsonHandler) {
+ ConfigServiceJsonHandler configServiceJsonHandler,
+ CloudTrailJsonHandler cloudTrailJsonHandler) {
this.objectMapper = objectMapper;
this.catalog = catalog;
this.regionResolver = regionResolver;
@@ -137,6 +140,7 @@ public class AwsJson11Controller {
this.curJsonHandler = curJsonHandler;
this.bcmDataExportsJsonHandler = bcmDataExportsJsonHandler;
this.configServiceJsonHandler = configServiceJsonHandler;
+ this.cloudTrailJsonHandler = cloudTrailJsonHandler;
}
@POST
@@ -192,6 +196,7 @@ public class AwsJson11Controller {
case "cur" -> curJsonHandler.handle(action, request, region);
case "bcm-data-exports" -> bcmDataExportsJsonHandler.handle(action, request, region);
case "config" -> configServiceJsonHandler.handle(action, request, region);
+ case "cloudtrail" -> cloudTrailJsonHandler.handle(action, request, region);
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
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 41fc672ded..76d911ba1f 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
@@ -234,6 +234,11 @@ public class ResolvedServiceCatalog {
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("StarlingDoveService."), Set.of("config"), Set.of(), Set.of()),
+ descriptor("cloudtrail", "cloudtrail", config.services().cloudtrail().enabled(), true,
+ "cloudtrail", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
+ protocols(ServiceProtocol.JSON),
+ Set.of("com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101."),
+ Set.of("cloudtrail"), Set.of(), Set.of()),
descriptor("autoscaling", "autoscaling", config.services().autoscaling().enabled(), true,
"autoscaling", config.storage().mode(), 5000L, AwsNamespaces.AUTOSCALING, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java
new file mode 100644
index 0000000000..f6375cbf2e
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java
@@ -0,0 +1,145 @@
+package io.github.hectorvent.floci.services.cloudtrail;
+
+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.services.cloudtrail.model.CloudTrailTrail;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@ApplicationScoped
+public class CloudTrailJsonHandler {
+ private final CloudTrailService service;
+ private final ObjectMapper mapper;
+
+ @Inject
+ public CloudTrailJsonHandler(CloudTrailService service, ObjectMapper mapper) {
+ this.service = service;
+ this.mapper = mapper;
+ }
+
+ public Response handle(String action, JsonNode request, String region) {
+ return switch (action) {
+ case "CreateTrail" -> createTrail(request, region);
+ case "UpdateTrail" -> updateTrail(request, region);
+ case "DescribeTrails" -> describeTrails(request, region);
+ case "StartLogging" -> startLogging(request, region);
+ case "StopLogging" -> stopLogging(request, region);
+ case "DeleteTrail" -> deleteTrail(request, region);
+ case "GetTrailStatus" -> getTrailStatus(request, region);
+ case "PutEventSelectors" -> putEventSelectors(request, region);
+ default -> throw new AwsException("UnsupportedOperation",
+ "Operation " + action + " is not supported.", 400);
+ };
+ }
+
+ private Response createTrail(JsonNode request, String region) {
+ CloudTrailTrail trail = service.createTrail(
+ region,
+ request.path("Name").asText(null),
+ request.path("S3BucketName").asText(null),
+ request.path("IncludeGlobalServiceEvents").asBoolean(false),
+ request.path("IsMultiRegionTrail").asBoolean(false),
+ request.path("IsOrganizationTrail").asBoolean(false),
+ parseTags(request.path("TagsList")));
+ return Response.ok(trailNode(trail)).build();
+ }
+
+ private Response updateTrail(JsonNode request, String region) {
+ CloudTrailTrail trail = service.updateTrail(
+ region,
+ request.path("Name").asText(null),
+ request.path("S3BucketName").asText(null),
+ optionalBoolean(request, "IncludeGlobalServiceEvents"),
+ optionalBoolean(request, "IsMultiRegionTrail"));
+ return Response.ok(trailNode(trail)).build();
+ }
+
+ private Response describeTrails(JsonNode request, String region) {
+ List<String> names = stringList(request.path("trailNameList"));
+ ObjectNode response = mapper.createObjectNode();
+ ArrayNode trails = response.putArray("trailList");
+ for (CloudTrailTrail trail : service.describeTrails(region, names)) {
+ trails.add(trailNode(trail));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response startLogging(JsonNode request, String region) {
+ service.startLogging(region, request.path("Name").asText(null));
+ return Response.ok(mapper.createObjectNode()).build();
+ }
+
+ private Response stopLogging(JsonNode request, String region) {
+ service.stopLogging(region, request.path("Name").asText(null));
+ return Response.ok(mapper.createObjectNode()).build();
+ }
+
+ private Response deleteTrail(JsonNode request, String region) {
+ service.deleteTrail(region, request.path("Name").asText(null));
+ return Response.ok(mapper.createObjectNode()).build();
+ }
+
+ private Response getTrailStatus(JsonNode request, String region) {
+ CloudTrailTrail trail = service.requireTrail(region, request.path("Name").asText(null));
+ ObjectNode response = mapper.createObjectNode();
+ response.put("IsLogging", trail.isLogging());
+ if (trail.getUpdated() != null) {
+ response.put("LatestDeliveryTime", trail.getUpdated().toEpochMilli() / 1000.0);
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response putEventSelectors(JsonNode request, String region) {
+ service.putEventSelectors(region, request.path("TrailName").asText(null));
+ return Response.ok(mapper.createObjectNode()).build();
+ }
+
+ private ObjectNode trailNode(CloudTrailTrail trail) {
+ ObjectNode node = mapper.createObjectNode();
+ node.put("Name", trail.getName());
+ node.put("TrailARN", trail.getTrailArn());
+ node.put("S3BucketName", trail.getS3BucketName());
+ node.put("IncludeGlobalServiceEvents", trail.isIncludeGlobalServiceEvents());
+ node.put("IsMultiRegionTrail", trail.isMultiRegionTrail());
+ node.put("IsOrganizationTrail", trail.isOrganizationTrail());
+ node.put("HomeRegion", trail.getHomeRegion());
+ if (trail.getCreated() != null) {
+ node.put("CreationDate", trail.getCreated().toEpochMilli() / 1000.0);
+ }
+ return node;
+ }
+
+ private static Map<String, String> parseTags(JsonNode tagsNode) {
+ Map<String, String> tags = new HashMap<>();
+ if (tagsNode != null && tagsNode.isArray()) {
+ for (JsonNode tag : tagsNode) {
+ String key = tag.path("Key").asText(null);
+ if (key != null) {
+ tags.put(key, tag.path("Value").asText(""));
+ }
+ }
+ }
+ return tags;
+ }
+
+ private static List<String> stringList(JsonNode node) {
+ if (node == null || !node.isArray()) {
+ return List.of();
+ }
+ java.util.ArrayList<String> values = new java.util.ArrayList<>();
+ node.forEach(value -> values.add(value.asText()));
+ return values;
+ }
+
+ private static Boolean optionalBoolean(JsonNode node, String fieldName) {
+ return node != null && node.has(fieldName) ? node.path(fieldName).asBoolean() : null;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java
new file mode 100644
index 0000000000..105aee20e4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java
@@ -0,0 +1,143 @@
+package io.github.hectorvent.floci.services.cloudtrail;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.cloudtrail.model.CloudTrailTrail;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Predicate;
+
+@ApplicationScoped
+public class CloudTrailService {
+ private final StorageBackend<String, CloudTrailTrail> trailStore;
+ private final RegionResolver regionResolver;
+
+ @Inject
+ public CloudTrailService(StorageFactory storageFactory, RegionResolver regionResolver) {
+ this.trailStore = storageFactory.create("cloudtrail", "cloudtrail-trails.json",
+ new TypeReference<Map<String, CloudTrailTrail>>() {});
+ this.regionResolver = regionResolver;
+ }
+
+ public CloudTrailTrail createTrail(String region, String name, String s3BucketName,
+ boolean includeGlobalServiceEvents, boolean multiRegionTrail,
+ boolean organizationTrail, Map<String, String> tags) {
+ if (name == null || name.isBlank()) {
+ throw new AwsException("InvalidTrailNameException", "Trail name is required", 400);
+ }
+ if (trailStore.get(key(region, name)).isPresent()) {
+ throw new AwsException("TrailAlreadyExistsException", "Trail " + name + " already exists", 400);
+ }
+
+ CloudTrailTrail trail = new CloudTrailTrail();
+ Instant now = Instant.now();
+ trail.setName(name);
+ trail.setTrailArn(trailArn(region, name));
+ trail.setS3BucketName(s3BucketName);
+ trail.setIncludeGlobalServiceEvents(includeGlobalServiceEvents);
+ trail.setMultiRegionTrail(multiRegionTrail);
+ trail.setOrganizationTrail(organizationTrail);
+ trail.setHomeRegion(region);
+ trail.setCreated(now);
+ trail.setUpdated(now);
+ trail.setTags(tags == null ? Map.of() : tags);
+ trailStore.put(key(region, name), trail);
+ return trail;
+ }
+
+ public CloudTrailTrail updateTrail(String region, String nameOrArn, String s3BucketName,
+ Boolean includeGlobalServiceEvents, Boolean multiRegionTrail) {
+ CloudTrailTrail trail = requireTrail(region, nameOrArn);
+ if (s3BucketName != null && !s3BucketName.isBlank()) {
+ trail.setS3BucketName(s3BucketName);
+ }
+ if (includeGlobalServiceEvents != null) {
+ trail.setIncludeGlobalServiceEvents(includeGlobalServiceEvents);
+ }
+ if (multiRegionTrail != null) {
+ trail.setMultiRegionTrail(multiRegionTrail);
+ }
+ trail.setUpdated(Instant.now());
+ trailStore.put(key(trail.getHomeRegion(), trail.getName()), trail);
+ return trail;
+ }
+
+ public List<CloudTrailTrail> describeTrails(String region, List<String> namesOrArns) {
+ if (namesOrArns == null || namesOrArns.isEmpty()) {
+ return trailStore.scan(key -> key.startsWith(region + ":"));
+ }
+ return namesOrArns.stream()
+ .map(nameOrArn -> findTrail(region, nameOrArn))
+ .flatMap(java.util.Optional::stream)
+ .toList();
+ }
+
+ public CloudTrailTrail requireTrail(String region, String nameOrArn) {
+ return findTrail(region, nameOrArn)
+ .orElseThrow(() -> new AwsException("TrailNotFoundException",
+ "Trail " + nameOrArn + " does not exist", 400));
+ }
+
+ public void startLogging(String region, String nameOrArn) {
+ CloudTrailTrail trail = requireTrail(region, nameOrArn);
+ trail.setLogging(true);
+ trail.setUpdated(Instant.now());
+ trailStore.put(key(trail.getHomeRegion(), trail.getName()), trail);
+ }
+
+ public void stopLogging(String region, String nameOrArn) {
+ CloudTrailTrail trail = requireTrail(region, nameOrArn);
+ trail.setLogging(false);
+ trail.setUpdated(Instant.now());
+ trailStore.put(key(trail.getHomeRegion(), trail.getName()), trail);
+ }
+
+ public void deleteTrail(String region, String nameOrArn) {
+ CloudTrailTrail trail = requireTrail(region, nameOrArn);
+ trailStore.delete(key(trail.getHomeRegion(), trail.getName()));
+ }
+
+ public void putEventSelectors(String region, String nameOrArn) {
+ requireTrail(region, nameOrArn);
+ }
+
+ private java.util.Optional<CloudTrailTrail> findTrail(String region, String nameOrArn) {
+ String name = nameFromNameOrArn(nameOrArn);
+ if (name == null || name.isBlank()) {
+ return java.util.Optional.empty();
+ }
+ java.util.Optional<CloudTrailTrail> sameRegion = trailStore.get(key(region, name));
+ if (sameRegion.isPresent()) {
+ return sameRegion;
+ }
+ Predicate<String> candidateKey = nameOrArn.startsWith("arn:")
+ ? ignored -> true
+ : key -> key.endsWith(":" + name);
+ return trailStore.scan(candidateKey).stream()
+ .filter(trail -> name.equals(trail.getName()) || nameOrArn.equals(trail.getTrailArn()))
+ .findFirst();
+ }
+
+ private String trailArn(String region, String name) {
+ return regionResolver.buildArn("cloudtrail", region, "trail/" + name);
+ }
+
+ private static String key(String region, String name) {
+ return region + ":" + name;
+ }
+
+ private static String nameFromNameOrArn(String nameOrArn) {
+ if (nameOrArn == null) {
+ return null;
+ }
+ int slash = nameOrArn.lastIndexOf('/');
+ return slash >= 0 ? nameOrArn.substring(slash + 1) : nameOrArn;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/CloudTrailTrail.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/CloudTrailTrail.java
new file mode 100644
index 0000000000..682320d5c9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/CloudTrailTrail.java
@@ -0,0 +1,118 @@
+package io.github.hectorvent.floci.services.cloudtrail.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.Map;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class CloudTrailTrail {
+ private String name;
+ private String trailArn;
+ private String s3BucketName;
+ private boolean includeGlobalServiceEvents;
+ private boolean multiRegionTrail;
+ private boolean organizationTrail;
+ private boolean logging;
+ private String homeRegion;
+ private Instant created;
+ private Instant updated;
+ private Map<String, String> tags;
+
+ public CloudTrailTrail() {
+ this.tags = new HashMap<>();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getTrailArn() {
+ return trailArn;
+ }
+
+ public void setTrailArn(String trailArn) {
+ this.trailArn = trailArn;
+ }
+
+ public String getS3BucketName() {
+ return s3BucketName;
+ }
+
+ public void setS3BucketName(String s3BucketName) {
+ this.s3BucketName = s3BucketName;
+ }
+
+ public boolean isIncludeGlobalServiceEvents() {
+ return includeGlobalServiceEvents;
+ }
+
+ public void setIncludeGlobalServiceEvents(boolean includeGlobalServiceEvents) {
+ this.includeGlobalServiceEvents = includeGlobalServiceEvents;
+ }
+
+ public boolean isMultiRegionTrail() {
+ return multiRegionTrail;
+ }
+
+ public void setMultiRegionTrail(boolean multiRegionTrail) {
+ this.multiRegionTrail = multiRegionTrail;
+ }
+
+ public boolean isOrganizationTrail() {
+ return organizationTrail;
+ }
+
+ public void setOrganizationTrail(boolean organizationTrail) {
+ this.organizationTrail = organizationTrail;
+ }
+
+ public boolean isLogging() {
+ return logging;
+ }
+
+ public void setLogging(boolean logging) {
+ this.logging = logging;
+ }
+
+ public String getHomeRegion() {
+ return homeRegion;
+ }
+
+ public void setHomeRegion(String homeRegion) {
+ this.homeRegion = homeRegion;
+ }
+
+ public Instant getCreated() {
+ return created;
+ }
+
+ public void setCreated(Instant created) {
+ this.created = created;
+ }
+
+ public Instant getUpdated() {
+ return updated;
+ }
+
+ public void setUpdated(Instant updated) {
+ this.updated = updated;
+ }
+
+ public Map<String, String> getTags() {
+ return tags;
+ }
+
+ public void setTags(Map<String, String> tags) {
+ this.tags = tags == null ? new HashMap<>() : new HashMap<>(tags);
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index e9359daebb..d2f61e4f7f 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -310,6 +310,8 @@ floci:
bcm-data-exports:
enabled: true
emit-mode: synchronous
+ cloudtrail:
+ enabled: true
cloudfront:
enabled: true
appsync:
diff --git a/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java b/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java
new file mode 100644
index 0000000000..097bd1a0ee
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java
@@ -0,0 +1,29 @@
+package io.github.hectorvent.floci.config;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ApplicationDefaultsTest {
+
+ @Test
+ void productionConfigEnablesCloudTrailByDefault() throws IOException {
+ try (InputStream configStream = getClass().getClassLoader().getResourceAsStream("application.yml")) {
+ assertNotNull(configStream, "application.yml should be available on the test classpath");
+ JsonNode config = new YAMLMapper().readTree(configStream);
+
+ assertTrue(config.path("floci")
+ .path("services")
+ .path("cloudtrail")
+ .path("enabled")
+ .asBoolean(false),
+ "application.yml should enable CloudTrail by default");
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailIntegrationTest.java
new file mode 100644
index 0000000000..795d0eb0e8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailIntegrationTest.java
@@ -0,0 +1,416 @@
+package io.github.hectorvent.floci.services.cloudtrail;
+
+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.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.startsWith;
+
+@QuarkusTest
+class CloudTrailIntegrationTest {
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String TARGET_PREFIX = "com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void trailLifecycleRoundTripsThroughJsonHandler() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeTrails")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "trailNameList": ["sample-audit"]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("trailList", hasSize(0));
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateTrail")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "sample-audit",
+ "S3BucketName": "sample-audit-bucket",
+ "IncludeGlobalServiceEvents": true,
+ "IsMultiRegionTrail": true,
+ "IsOrganizationTrail": false,
+ "TagsList": [
+ {"Key": "example:component", "Value": "audit"}
+ ]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Name", equalTo("sample-audit"))
+ .body("TrailARN", startsWith("arn:aws:cloudtrail:"))
+ .body("S3BucketName", equalTo("sample-audit-bucket"));
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "PutEventSelectors")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "TrailName": "sample-audit",
+ "AdvancedEventSelectors": []
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "StartLogging")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "sample-audit"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetTrailStatus")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "sample-audit"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("IsLogging", equalTo(true))
+ .body("LatestDeliveryTime", notNullValue());
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "UpdateTrail")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "sample-audit",
+ "S3BucketName": "sample-audit-bucket-2"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("S3BucketName", equalTo("sample-audit-bucket-2"))
+ .body("IncludeGlobalServiceEvents", equalTo(true))
+ .body("IsMultiRegionTrail", equalTo(true));
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeTrails")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "trailNameList": ["sample-audit"]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("trailList", hasSize(1))
+ .body("trailList[0].Name", equalTo("sample-audit"))
+ .body("trailList[0].S3BucketName", equalTo("sample-audit-bucket-2"))
+ .body("trailList[0].IncludeGlobalServiceEvents", equalTo(true))
+ .body("trailList[0].IsMultiRegionTrail", equalTo(true));
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "StopLogging")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "sample-audit"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteTrail")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "sample-audit"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ void trailProvisioningLifecycleWorksWithBucketNotificationsAndQueuePolicy() {
+ String bucket = "cloudtrail-audit-feed-bucket";
+ String bucket2 = "cloudtrail-audit-feed-bucket-2";
+ String queueName = "cloudtrail-audit-feed-events";
+ String queueUrl = createQueue(queueName);
+ String queueArn = getQueueArn(queueUrl);
+ String bucketArn = "arn:aws:s3:::" + bucket;
+ String trailName = "cloudtrail-audit-feed";
+
+ createBucket(bucket);
+ putBucketPolicy(bucket, trailName);
+ putBucketNotification(bucket, queueArn);
+ setQueuePolicy(queueUrl, bucketArn, queueArn);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "CreateTrail")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "%s",
+ "S3BucketName": "%s",
+ "IncludeGlobalServiceEvents": true,
+ "IsMultiRegionTrail": false,
+ "IsOrganizationTrail": false,
+ "TagsList": [
+ {"Key": "example:component", "Value": "cloudAudit"}
+ ]
+ }
+ """.formatted(trailName, bucket))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Name", equalTo(trailName))
+ .body("TrailARN", startsWith("arn:aws:cloudtrail:"))
+ .body("S3BucketName", equalTo(bucket));
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "PutEventSelectors")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "TrailName": "%s",
+ "AdvancedEventSelectors": [
+ {
+ "Name": "Management events",
+ "FieldSelectors": [
+ {"Field": "eventCategory", "Equals": ["Management"]}
+ ]
+ }
+ ]
+ }
+ """.formatted(trailName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "StartLogging")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "%s"
+ }
+ """.formatted(trailName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetTrailStatus")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "%s"
+ }
+ """.formatted(trailName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("IsLogging", equalTo(true));
+
+ given()
+ .when()
+ .get("/" + bucket + "?notification")
+ .then()
+ .statusCode(200)
+ .body(containsString("<Queue>" + queueArn + "</Queue>"))
+ .body(containsString("<Event>s3:ObjectCreated:*</Event>"));
+
+ getQueuePolicy(queueUrl)
+ .statusCode(200)
+ .body(containsString(bucketArn));
+
+ createBucket(bucket2);
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "UpdateTrail")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "%s",
+ "S3BucketName": "%s",
+ "IncludeGlobalServiceEvents": true,
+ "IsMultiRegionTrail": false
+ }
+ """.formatted(trailName, bucket2))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("S3BucketName", equalTo(bucket2));
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DescribeTrails")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "trailNameList": ["%s"]
+ }
+ """.formatted(trailName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("trailList", hasSize(1))
+ .body("trailList[0].S3BucketName", equalTo(bucket2));
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "StopLogging")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "%s"
+ }
+ """.formatted(trailName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "DeleteTrail")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "Name": "%s"
+ }
+ """.formatted(trailName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void createBucket(String bucket) {
+ given()
+ .when()
+ .put("/" + bucket)
+ .then()
+ .statusCode(200);
+ }
+
+ private static String createQueue(String queueName) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateQueue")
+ .formParam("QueueName", queueName)
+ .formParam("Attribute.1.Name", "VisibilityTimeout")
+ .formParam("Attribute.1.Value", "30")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
+ }
+
+ private static String getQueueArn(String queueUrl) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueAttributes")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("AttributeName.1", "QueueArn")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath().getString("GetQueueAttributesResponse.GetQueueAttributesResult.Attribute.Value");
+ }
+
+ private static io.restassured.response.ValidatableResponse getQueuePolicy(String queueUrl) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueAttributes")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("AttributeName.1", "Policy")
+ .when()
+ .post("/")
+ .then();
+ }
+
+ private static void setQueuePolicy(String queueUrl, String bucketArn, String queueArn) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "SetQueueAttributes")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("Attribute.1.Name", "Policy")
+ .formParam("Attribute.1.Value", """
+ {"Version":"2012-10-17","Statement":[{"Sid":"AllowS3Notifications","Effect":"Allow","Principal":{"Service":"s3.amazonaws.com"},"Action":"sqs:SendMessage","Resource":"%s","Condition":{"ArnEquals":{"aws:SourceArn":"%s"}}}]}
+ """.formatted(queueArn, bucketArn))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void putBucketPolicy(String bucket, String trailName) {
+ given()
+ .contentType("application/json")
+ .body("""
+ {"Version":"2012-10-17","Statement":[{"Sid":"AllowCloudTrail","Effect":"Allow","Principal":{"Service":"cloudtrail.amazonaws.com"},"Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/AWSLogs/*","Condition":{"StringEquals":{"aws:SourceArn":"arn:aws:cloudtrail:us-east-1:000000000000:trail/%s"}}}]}
+ """.formatted(bucket, trailName))
+ .when()
+ .put("/" + bucket + "?policy")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void putBucketNotification(String bucket, String queueArn) {
+ given()
+ .contentType("application/xml")
+ .body("""
+ <NotificationConfiguration>
+ <QueueConfiguration>
+ <Id>cloudtrail-to-sqs</Id>
+ <Queue>%s</Queue>
+ <Event>s3:ObjectCreated:*</Event>
+ </QueueConfiguration>
+ </NotificationConfiguration>
+ """.formatted(queueArn))
+ .when()
+ .put("/" + bucket + "?notification")
+ .then()
+ .statusCode(200);
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 8b990f38cc..735f8e1a61 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -197,6 +197,8 @@ floci:
bcm-data-exports:
enabled: true
emit-mode: off
+ cloudtrail:
+ enabled: true
cloudfront:
enabled: true
appsync: