diff --git a/docs/services/cloudtrail.md b/docs/services/cloudtrail.md index 726cf12b35..d9a380fc40 100644 --- a/docs/services/cloudtrail.md +++ b/docs/services/cloudtrail.md @@ -25,7 +25,7 @@ ${prefix}AWSLogs/${accountId}/CloudTrail/${region}/yyyy/MM/dd/${accountId}_Cloud | `StartLogging` | Starts logging for a trail | | `StopLogging` | Stops logging for a trail | | `GetTrailStatus` | Returns the logging status of a trail | -| `LookupEvents` | - | +| `LookupEvents` | Returns the management events in the account's event history, newest first | | `ListTrails` | - | | `AddTags` | Adds or overwrites tags on a trail, identified by ARN | | `RemoveTags` | Removes the given tag keys from a trail, identified by ARN | @@ -85,6 +85,20 @@ These writes also reach EventBridge's default bus in the request's account and r [Secrets Manager event delivery](secrets-manager.md#secret-write-events) for prerequisites, the secret-specific event pattern, and the limits of this coverage. +## Event History + +`LookupEvents` reads the event history: every management event Floci records, in the caller's +account and region, whether or not a trail is logging, as on AWS. Today those are the Secrets Manager +`PutSecretValue` and `UpdateSecret` writes above. Events come back newest first, at most 50 a page +with a `NextToken` for the rest (as on AWS, the token is accepted only with the same parameters), and can be narrowed by `StartTime`, `EndTime` and one +`LookupAttributes` entry (`EventId`, `EventName`, `EventSource`, `ReadOnly`, `Username` or +`AccessKeyId`). Each event carries `CloudTrailEvent`, the full record as a trail delivers it. + +The history keeps 90 days and at most 10,000 events per account and region, in memory: it does not +survive a restart, and an emulator reset empties it. Records name no resources, so `Resources` is empty and a `ResourceType` or +`ResourceName` attribute matches nothing. Floci records no Insights events, so `EventCategory: insight` +returns an empty page; any other category is refused with `InvalidEventCategoryException`. + ## Configuration | Variable | Default | Description | diff --git a/pom.xml b/pom.xml index 2f7b701da0..d5afe27ebf 100644 --- a/pom.xml +++ b/pom.xml @@ -572,6 +572,12 @@ ${aws.sdk.version} test + + software.amazon.awssdk + cloudtrail + ${aws.sdk.version} + test + software.amazon.awssdk appsync diff --git a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailEventHistory.java b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailEventHistory.java new file mode 100644 index 0000000000..ae44bccf93 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailEventHistory.java @@ -0,0 +1,101 @@ +package io.floci.aws.services.cloudtrail; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +/** + * CloudTrail's event history: the management events of each account and region, kept without a + * trail, as {@code LookupEvents} reads them. AWS keeps 90 days; this keeps that window and at most + * {@link #MAX_EVENTS_PER_REGION} events per account and region, in memory only. + */ +final class CloudTrailEventHistory { + + static final int MAX_EVENTS_PER_REGION = 10_000; + static final Duration RETENTION = Duration.ofDays(90); + + /** The lookup attribute keys AWS accepts. */ + static final Set LOOKUP_ATTRIBUTE_KEYS = Set.of("EventId", "EventName", "ReadOnly", "Username", + "ResourceType", "ResourceName", "EventSource", "AccessKeyId"); + + /** One recorded event; {@code sequence} orders events recorded within the same instant. */ + record HistoryEvent(long sequence, Instant eventTime, ObjectNode record) {} + + /** The one lookup attribute a request may name: its key as AWS spells it, and the value to match. */ + record LookupAttribute(String key, String value) {} + + private final Map> eventsByAccountAndRegion = new ConcurrentHashMap<>(); + private final AtomicLong sequence = new AtomicLong(); + + void record(String accountId, String region, Instant eventTime, ObjectNode record) { + ObjectNode copy = record.deepCopy(); + eventsByAccountAndRegion.compute(key(accountId, region), (ignored, events) -> { + Deque updated = events == null ? new ArrayDeque<>() : events; + // Numbered under the region's lock, so the deque, the sequence and the page order agree. + updated.addLast(new HistoryEvent(sequence.incrementAndGet(), eventTime, copy)); + while (updated.size() > MAX_EVENTS_PER_REGION) { + updated.removeFirst(); + } + return updated; + }); + } + + /** The events of an account and region inside the retention window that match, newest first. */ + List lookup(String accountId, String region, LookupAttribute attribute, + Instant startTime, Instant endTime, Instant now) { + Instant oldest = now.minus(RETENTION); + List matching = new ArrayList<>(); + eventsByAccountAndRegion.computeIfPresent(key(accountId, region), (ignored, events) -> { + // Event times are taken before the lock, so two concurrent writes can land out of time order. + events.removeIf(event -> event.eventTime().isBefore(oldest)); + events.descendingIterator().forEachRemaining(event -> { + if (inRange(event.eventTime(), startTime, endTime) && matches(event.record(), attribute)) { + matching.add(event); + } + }); + return events.isEmpty() ? null : events; + }); + return matching; + } + + private static boolean inRange(Instant eventTime, Instant startTime, Instant endTime) { + return (startTime == null || !eventTime.isBefore(startTime)) && (endTime == null || !eventTime.isAfter(endTime)); + } + + private static boolean matches(ObjectNode record, LookupAttribute attribute) { + if (attribute == null) { + return true; + } + JsonNode identity = record.path("userIdentity"); + String actual = switch (attribute.key()) { + case "EventId" -> record.path("eventID").asText(null); + case "EventName" -> record.path("eventName").asText(null); + case "EventSource" -> record.path("eventSource").asText(null); + case "ReadOnly" -> record.path("readOnly").asText(null); + case "Username" -> identity.path("userName").asText(null); + case "AccessKeyId" -> identity.path("accessKeyId").asText(null); + // The recorded events name no resources, so a resource attribute matches none of them. + case "ResourceType", "ResourceName" -> null; + default -> throw new IllegalArgumentException("Not a lookup attribute key: " + attribute.key()); + }; + return attribute.value().equals(actual); + } + + void clear() { + eventsByAccountAndRegion.clear(); + } + + private static String key(String accountId, String region) { + return accountId + "::" + region; + } +} diff --git a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailJsonHandler.java b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailJsonHandler.java index cdcbe87601..b2bf6f5c98 100644 --- a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailJsonHandler.java +++ b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailJsonHandler.java @@ -5,8 +5,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.AwsJsonTimestamp; import io.floci.aws.core.common.EpochSeconds; import io.floci.aws.core.common.JsonNumberCoercion; +import io.floci.aws.core.common.PaginatedResult; +import io.floci.aws.core.common.Pagination; import io.floci.aws.services.cloudtrail.model.AdvancedEventSelector; import io.floci.aws.services.cloudtrail.model.DataResource; import io.floci.aws.services.cloudtrail.model.EventSelector; @@ -15,14 +18,21 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; +import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Set; @ApplicationScoped public class CloudTrailJsonHandler { + /** {@code LookupEvents} returns at most 50 events a page, whatever {@code MaxResults} asks for. */ + private static final int MAX_LOOKUP_EVENTS = 50; + private static final Set READ_ONLY_VALUES = Set.of("true", "false"); + private final CloudTrailService service; private final ObjectMapper mapper; @@ -243,33 +253,124 @@ public class CloudTrailJsonHandler { } private Response lookupEvents(JsonNode req, String region) { - validateMaxResults(req.path("MaxResults")); + Integer maxResults = validateMaxResults(req.path("MaxResults")); + CloudTrailEventHistory.LookupAttribute attribute = lookupAttribute(req.path("LookupAttributes")); + Instant startTime = AwsJsonTimestamp.epochSeconds(req, "StartTime", "SerializationException"); + Instant endTime = AwsJsonTimestamp.epochSeconds(req, "EndTime", "SerializationException"); + if (startTime != null && endTime != null && startTime.isAfter(endTime)) { + throw new AwsException("InvalidTimeRangeException", "The start time precedes the end time.", 400); + } + boolean insights = insightCategory(req.path("EventCategory")); + // Floci records no Insights events, so the insight category always holds none. + PaginatedResult page = Pagination.paginate( + insights ? List.of() : service.lookupEvents(region, attribute, startTime, endTime), + event -> String.format("%019d", Long.MAX_VALUE - event.sequence()), + maxResults == null ? MAX_LOOKUP_EVENTS : Math.min(maxResults, MAX_LOOKUP_EVENTS), + textOrNull(req, "NextToken"), lookupNamespace(region, attribute, startTime, endTime, insights), + token -> new AwsException("InvalidNextTokenException", "Can't decrypt marker", 400)); ObjectNode resp = mapper.createObjectNode(); - resp.putArray("Events"); + ArrayNode events = resp.putArray("Events"); + for (CloudTrailEventHistory.HistoryEvent event : page.items()) { + ObjectNode record = event.record(); + ObjectNode out = events.addObject(); + out.put("EventId", record.path("eventID").asText()); + out.put("EventName", record.path("eventName").asText()); + out.put("ReadOnly", record.path("readOnly").asText()); + out.put("AccessKeyId", record.path("userIdentity").path("accessKeyId").asText()); + out.put("EventTime", EpochSeconds.fromMillis(event.eventTime().toEpochMilli())); + out.put("EventSource", record.path("eventSource").asText()); + out.put("Username", record.path("userIdentity").path("userName").asText()); + out.putArray("Resources"); + out.put("CloudTrailEvent", record.toString()); + } + if (page.nextToken() != null) { + resp.put("NextToken", page.nextToken()); + } return Response.ok(resp).build(); } + /** + * A token pages only the lookup that issued it: AWS requires the same parameters with it, and + * a token reused for another filter, time range or region is refused rather than read as a + * position in a different list. + */ + private static String lookupNamespace(String region, CloudTrailEventHistory.LookupAttribute attribute, + Instant startTime, Instant endTime, boolean insights) { + return "lookup-events:" + Integer.toHexString(Objects.hash(region, attribute, startTime, endTime, insights)); + } + + /** {@code EventCategory} has one value, {@code insight}; omitted, the lookup reads management events. */ + private static boolean insightCategory(JsonNode category) { + if (category.isMissingNode() || category.isNull()) { + return false; + } + if (!category.isTextual()) { + throw notConvertible(category, "a String"); + } + if (!"insight".equals(category.asText())) { + throw new AwsException("InvalidEventCategoryException", "Invalid event category specified.", 400); + } + return true; + } + + /** AWS takes at most one lookup attribute, keyed by one of the documented names. */ + private static CloudTrailEventHistory.LookupAttribute lookupAttribute(JsonNode attributes) { + if (attributes.isMissingNode() || attributes.isNull()) { + return null; + } + if (!attributes.isArray()) { + throw notConvertible(attributes, "a list"); + } + if (attributes.isEmpty()) { + return null; + } + if (attributes.size() > 1) { + throw new AwsException("InvalidLookupAttributesException", + "You cannot specify more than one lookup attribute.", 400); + } + JsonNode attribute = attributes.get(0); + if (!attribute.isObject()) { + throw notConvertible(attribute, "a structure"); + } + JsonNode key = attribute.path("AttributeKey"); + JsonNode value = attribute.path("AttributeValue"); + if (!key.isTextual() || !CloudTrailEventHistory.LOOKUP_ATTRIBUTE_KEYS.contains(key.asText())) { + throw new AwsException("InvalidLookupAttributesException", + "Lookup attribute key cannot be null or empty.", 400); + } + if (!value.isTextual() || value.asText().isEmpty() + || "ReadOnly".equals(key.asText()) && !READ_ONLY_VALUES.contains(value.asText())) { + throw new AwsException("InvalidLookupAttributesException", "Lookup attribute key is invalid", 400); + } + return new CloudTrailEventHistory.LookupAttribute(key.asText(), value.asText()); + } + + /** The {@code SerializationException} AWS answers for a member of the wrong JSON type. */ + private static AwsException notConvertible(JsonNode node, String target) { + if (node.isObject()) { + return serialization("Start of structure or map found where not expected."); + } + if (node.isArray()) { + return serialization("Start of list found where not expected"); + } + String kind = node.isTextual() ? "STRING_VALUE" : node.isBoolean() + ? (node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE") : "NUMBER_VALUE"; + return serialization(kind + " can not be converted to " + target); + } + /** An omitted or null {@code MaxResults} is optional and takes the service default. */ - private static void validateMaxResults(JsonNode maxResults) { + private static Integer validateMaxResults(JsonNode maxResults) { if (maxResults.isMissingNode() || maxResults.isNull()) { - return; + return null; } - int value; - if (maxResults.isNumber()) { - value = JsonNumberCoercion.truncateAndClampToInt(maxResults); - } else if (maxResults.isTextual()) { - throw serialization("STRING_VALUE can not be converted to an Integer"); - } else if (maxResults.isArray()) { - throw serialization("Start of list found where not expected"); - } else if (maxResults.isObject()) { - throw serialization("Start of structure or map found where not expected."); - } else { - throw serialization((maxResults.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE") - + " can not be converted to an Integer"); + if (!maxResults.isNumber()) { + throw notConvertible(maxResults, "an Integer"); } + int value = JsonNumberCoercion.truncateAndClampToInt(maxResults); if (value < 1) { throw invalidMaxResults(value); } + return value; } private static AwsException invalidMaxResults(int value) { diff --git a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java index 66f987ba66..8ac8d3ed64 100644 --- a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java +++ b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java @@ -10,6 +10,7 @@ import io.floci.aws.core.common.AwsEndpoints; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.Resettable; import io.floci.aws.core.common.ServicePrincipals; import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.storage.AccountAwareStorageBackend; @@ -48,7 +49,7 @@ import java.util.regex.Pattern; import static io.floci.aws.core.common.auth.SigV4RequestValidator.LEGACY_ACCESS_KEY_ID; @ApplicationScoped -public class CloudTrailService implements StoredResourceArns { +public class CloudTrailService implements StoredResourceArns, Resettable { private static final Logger LOG = Logger.getLogger(CloudTrailService.class); @@ -77,6 +78,8 @@ public class CloudTrailService implements StoredResourceArns { */ private final ConcurrentHashMap trailLocks = new ConcurrentHashMap<>(); + private final CloudTrailEventHistory eventHistory = new CloudTrailEventHistory(); + @Inject public CloudTrailService(StorageFactory storageFactory, RegionResolver regionResolver, IamService iamService, ObjectMapper mapper) { @@ -487,13 +490,17 @@ public class CloudTrailService implements StoredResourceArns { public record ManagementEventInput(String eventSource, String eventName, String region, String accessKeyId, ObjectNode requestParameters, ObjectNode responseElements) {} - /** Records one management write and returns the event only when a logging trail selects it. */ + /** + * Records one management write in the account's event history and returns the event only when + * a logging trail also selects it. + */ public Optional emitManagementEvent(ManagementEventInput in) { try { String region = in.region() != null ? in.region() : regionResolver.getDefaultRegion(); + Instant eventTime = Instant.now(); ObjectNode record = mapper.createObjectNode(); record.put("eventVersion", EVENT_VERSION); - record.put("eventTime", Instant.now().toString()); + record.put("eventTime", eventTime.toString()); record.put("eventSource", in.eventSource()); record.put("eventName", in.eventName()); record.put("awsRegion", region); @@ -507,6 +514,7 @@ public class CloudTrailService implements StoredResourceArns { record.set("userIdentity", buildUserIdentity(in.accessKeyId())); record.set("requestParameters", in.requestParameters().deepCopy()); record.set("responseElements", in.responseElements().deepCopy()); + eventHistory.record(regionResolver.getAccountId(), region, eventTime, record); List matched = trailsMatching(region, entry -> matchesManagementEvent(entry, record)); if (matched.isEmpty()) { return Optional.empty(); @@ -521,6 +529,22 @@ public class CloudTrailService implements StoredResourceArns { } } + /** + * The current account's management events in {@code region}, newest first, as event history + * holds them: no trail is needed. A null attribute or bound does not filter. + */ + public List lookupEvents(String region, + CloudTrailEventHistory.LookupAttribute attribute, + Instant startTime, Instant endTime) { + return eventHistory.lookup(regionResolver.getAccountId(), region, attribute, startTime, endTime, Instant.now()); + } + + /** Trails live in storage, which reset wipes; the event history is held here. */ + @Override + public void clear() { + eventHistory.clear(); + } + /** Whether the current account has a trail, so a caller can skip building an event. */ public boolean hasTrails() { return !store.isEmpty(); diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailEventHistoryTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailEventHistoryTest.java new file mode 100644 index 0000000000..c57d26f350 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailEventHistoryTest.java @@ -0,0 +1,63 @@ +package io.floci.aws.services.cloudtrail; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CloudTrailEventHistoryTest { + + private static final String ACCOUNT = "111122223333"; + private static final String REGION = "us-east-1"; + private static final Instant NOW = Instant.parse("2026-11-21T12:00:00Z"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final CloudTrailEventHistory history = new CloudTrailEventHistory(); + + @Test + void eventsOlderThanNinetyDaysAreNotReturned() { + history.record(ACCOUNT, REGION, NOW.minus(Duration.ofDays(90)).minusSeconds(1), event("expired")); + history.record(ACCOUNT, REGION, NOW.minus(Duration.ofDays(90)), event("oldest-kept")); + + List events = history.lookup(ACCOUNT, REGION, null, null, null, NOW); + + assertEquals(List.of("oldest-kept"), names(events)); + } + + @Test + void anAccountAndRegionKeepsItsTenThousandNewestEvents() { + for (int i = 0; i <= 10_000; i++) { + history.record(ACCOUNT, REGION, NOW, event("event-" + i)); + } + + List events = history.lookup(ACCOUNT, REGION, null, null, null, NOW); + + assertEquals(10_000, events.size()); + assertEquals("event-10000", events.getFirst().record().path("eventName").asText()); + assertEquals("event-1", events.getLast().record().path("eventName").asText()); + } + + @Test + void historyIsKeptPerAccountAndRegion() { + history.record(ACCOUNT, REGION, NOW, event("here")); + history.record("444455556666", REGION, NOW, event("other-account")); + history.record(ACCOUNT, "eu-west-1", NOW, event("other-region")); + + assertEquals(List.of("here"), names(history.lookup(ACCOUNT, REGION, null, null, null, NOW))); + } + + private static ObjectNode event(String name) { + ObjectNode record = MAPPER.createObjectNode(); + record.put("eventName", name); + return record; + } + + private static List names(List events) { + return events.stream().map(event -> event.record().path("eventName").asText()).toList(); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailIntegrationTest.java index 06bdbc501f..f6e25463df 100644 --- a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailIntegrationTest.java @@ -32,6 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class CloudTrailIntegrationTest { private static final String CT_TARGET = "CloudTrail_20131101."; + private static final String EMPTY_HISTORY_ACCOUNT = "246813579024"; private static final String JSON11 = "application/x-amz-json-1.1"; @Inject @@ -194,6 +195,49 @@ class CloudTrailIntegrationTest { assertTrue(sawHeadInvalidRange, "Expected a HeadObject InvalidRange record"); } + @Test + void lookupEventsRefusesMalformedTimeBoundsAndLookupAttributes() { + invokeCloudTrail("LookupEvents", "{\"StartTime\":\"2026-01-01\"}") + .then().statusCode(400).body(containsString("SerializationException")); + invokeCloudTrail("LookupEvents", "{\"EndTime\":true}") + .then().statusCode(400).body(containsString("SerializationException")); + invokeCloudTrail("LookupEvents", "{\"LookupAttributes\":{}}") + .then().statusCode(400).body(containsString("SerializationException")); + invokeCloudTrail("LookupEvents", "{\"LookupAttributes\":[\"EventName\"]}") + .then().statusCode(400).body(containsString("SerializationException")); + invokeCloudTrail("LookupEvents", + "{\"LookupAttributes\":[{\"AttributeKey\":\"EventName\",\"AttributeValue\":\"\"}]}") + .then().statusCode(400) + .body("__type", containsString("InvalidLookupAttributesException")) + .body("message", equalTo("Lookup attribute key is invalid")); + } + + @Test + void lookupEventsAnswersAwsFixedRejectionMessages() { + invokeCloudTrail("LookupEvents", "{\"StartTime\":1790000000,\"EndTime\":1780000000}") + .then().statusCode(400) + .body("__type", containsString("InvalidTimeRangeException")) + .body("message", equalTo("The start time precedes the end time.")); + invokeCloudTrail("LookupEvents", "{\"NextToken\":\"not-a-real-token\"}") + .then().statusCode(400) + .body("__type", containsString("InvalidNextTokenException")) + .body("message", equalTo("Can't decrypt marker")); + invokeCloudTrail("LookupEvents", "{\"EventCategory\":\"not-a-category\"}") + .then().statusCode(400) + .body("__type", containsString("InvalidEventCategoryException")) + .body("message", equalTo("Invalid event category specified.")); + invokeCloudTrail("LookupEvents", + "{\"LookupAttributes\":[{\"AttributeKey\":\"NotARealAttributeKey\",\"AttributeValue\":\"x\"}]}") + .then().statusCode(400) + .body("__type", containsString("InvalidLookupAttributesException")) + .body("message", equalTo("Lookup attribute key cannot be null or empty.")); + invokeCloudTrail("LookupEvents", + "{\"LookupAttributes\":[{\"AttributeKey\":\"ReadOnly\",\"AttributeValue\":\"maybe\"}]}") + .then().statusCode(400) + .body("__type", containsString("InvalidLookupAttributesException")) + .body("message", equalTo("Lookup attribute key is invalid")); + } + @Test void lookupEventsReturnsEmptyEventPage() { invokeCloudTrail("LookupEvents", """ @@ -211,47 +255,47 @@ class CloudTrailIntegrationTest { @Test void lookupEventsAcceptsOmittedAndPositiveMaxResults() { - invokeCloudTrail("LookupEvents", "{}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":null}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":null}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":1}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":1}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":50}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":50}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":51}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":51}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":1000}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":1000}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":1001}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":1001}") .then().statusCode(200).body("Events", hasSize(0)); } @Test void lookupEventsCoercesFractionalMaxResultsLikeTheSdkParser() { - invokeCloudTrail("LookupEvents", "{\"MaxResults\":0.5}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":0.5}") .then().statusCode(400) .body(containsString("InvalidMaxResultsException")) .body(containsString("A max results value of 0 is invalid.")); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":-0.5}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":-0.5}") .then().statusCode(400) .body(containsString("InvalidMaxResultsException")) .body(containsString("A max results value of 0 is invalid.")); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":1.5}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":1.5}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":50.9}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":50.9}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":1000.5}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":1000.5}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":2147483648}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":2147483648}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":-2147483649}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":-2147483649}") .then().statusCode(400) .body(containsString("InvalidMaxResultsException")) .body(containsString("A max results value of -2147483648 is invalid.")); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":1e309}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":1e309}") .then().statusCode(200).body("Events", hasSize(0)); - invokeCloudTrail("LookupEvents", "{\"MaxResults\":-1e309}") + invokeCloudTrailInAnEmptyAccount("LookupEvents", "{\"MaxResults\":-1e309}") .then().statusCode(400) .body(containsString("InvalidMaxResultsException")) .body(containsString("A max results value of -2147483648 is invalid.")); @@ -565,6 +609,17 @@ class CloudTrailIntegrationTest { // --- Helpers --- + /** The MaxResults checks run in an account no test writes to, so its history stays empty. */ + private static Response invokeCloudTrailInAnEmptyAccount(String action, String body) { + return given() + .header("X-Amz-Target", CT_TARGET + action) + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + EMPTY_HISTORY_ACCOUNT + + "/20260101/us-east-1/cloudtrail/aws4_request, SignedHeaders=host, Signature=0") + .contentType(JSON11) + .body(body) + .when().post("/"); + } + private static Response invokeCloudTrail(String action, String body) { return given() .header("X-Amz-Target", CT_TARGET + action) diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLookupEventsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLookupEventsIntegrationTest.java new file mode 100644 index 0000000000..4a3fc37cf6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailLookupEventsIntegrationTest.java @@ -0,0 +1,183 @@ +package io.floci.aws.services.cloudtrail; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; +import software.amazon.awssdk.services.cloudtrail.model.Event; +import software.amazon.awssdk.services.cloudtrail.model.EventCategory; +import software.amazon.awssdk.services.cloudtrail.model.InvalidLookupAttributesException; +import software.amazon.awssdk.services.cloudtrail.model.InvalidNextTokenException; +import software.amazon.awssdk.services.cloudtrail.model.LookupAttributeKey; +import software.amazon.awssdk.services.cloudtrail.model.LookupEventsResponse; +import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; + +import java.net.URI; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Event history: {@code LookupEvents} returns the management events of the caller's account and + * region, newest first, with no trail needed, filtered by one lookup attribute and a time range. + * Each test runs in its own account so it sees only the events it caused. + */ +@QuarkusTest +class CloudTrailLookupEventsIntegrationTest { + + private static final String SECRETS_MANAGER = "secretsmanager.amazonaws.com"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @TestHTTPResource("/") + URI endpoint; + + @Test + void aManagementWriteIsInTheEventHistoryWithoutATrail() throws Exception { + String account = newAccount(); + String secret = putSecretValues(account, 1); + + List events = lookup(account, LookupAttributeKey.EVENT_SOURCE, SECRETS_MANAGER, null).events(); + + assertEquals(1, events.size()); + Event event = events.getFirst(); + assertEquals("PutSecretValue", event.eventName()); + assertEquals(SECRETS_MANAGER, event.eventSource()); + assertEquals("false", event.readOnly()); + assertNotNull(event.eventTime()); + JsonNode record = MAPPER.readTree(event.cloudTrailEvent()); + assertEquals(event.eventId(), record.path("eventID").asText()); + assertEquals("PutSecretValue", record.path("eventName").asText()); + assertEquals(account, record.path("recipientAccountId").asText()); + assertEquals(record.path("userIdentity").path("userName").asText(), event.username()); + assertTrue(record.path("requestParameters").path("secretId").asText().contains(secret)); + } + + @Test + void aLookupAttributeSelectsOnlyMatchingEvents() { + String account = newAccount(); + putSecretValues(account, 1); + + assertEquals(0, lookup(account, LookupAttributeKey.EVENT_NAME, "UpdateSecret", null).events().size()); + assertEquals(1, lookup(account, LookupAttributeKey.EVENT_NAME, "PutSecretValue", null).events().size()); + assertEquals(0, lookup(account, LookupAttributeKey.EVENT_SOURCE, "s3.amazonaws.com", null).events().size()); + } + + @Test + void aTimeRangeSelectsOnlyEventsInsideIt() { + String account = newAccount(); + Instant before = Instant.now().minusSeconds(60); + putSecretValues(account, 1); + Instant after = Instant.now().plusSeconds(60); + + try (CloudTrailClient cloudTrail = cloudTrail(account)) { + assertEquals(1, cloudTrail.lookupEvents(r -> r.startTime(before).endTime(after)).events().size()); + assertEquals(0, cloudTrail.lookupEvents(r -> r.startTime(after)).events().size()); + assertEquals(0, cloudTrail.lookupEvents(r -> r.endTime(before)).events().size()); + } + } + + @Test + void eventsArePagedNewestFirst() { + String account = newAccount(); + putSecretValues(account, 3); + + LookupEventsResponse first = lookup(account, LookupAttributeKey.EVENT_SOURCE, SECRETS_MANAGER, 2); + assertEquals(2, first.events().size()); + assertNotNull(first.nextToken()); + assertTrue(!first.events().get(0).eventTime().isBefore(first.events().get(1).eventTime())); + + try (CloudTrailClient cloudTrail = cloudTrail(account)) { + LookupEventsResponse second = cloudTrail.lookupEvents(r -> r.maxResults(2).nextToken(first.nextToken()) + .lookupAttributes(a -> a.attributeKey(LookupAttributeKey.EVENT_SOURCE).attributeValue(SECRETS_MANAGER))); + assertEquals(1, second.events().size()); + assertNull(second.nextToken()); + assertTrue(!first.events().get(1).eventTime().isBefore(second.events().getFirst().eventTime())); + } + } + + @Test + void theInsightCategoryHoldsNoManagementEvents() { + String account = newAccount(); + putSecretValues(account, 1); + + try (CloudTrailClient cloudTrail = cloudTrail(account)) { + assertEquals(1, cloudTrail.lookupEvents(r -> r.maxResults(50)).events().size()); + LookupEventsResponse insights = cloudTrail.lookupEvents(r -> r.eventCategory(EventCategory.INSIGHT)); + assertEquals(0, insights.events().size()); + assertNull(insights.nextToken()); + } + } + + @Test + void aPageHoldsAtMostFiftyEventsWhateverMaxResultsAsks() { + String account = newAccount(); + putSecretValues(account, 51); + + LookupEventsResponse page = lookup(account, LookupAttributeKey.EVENT_SOURCE, SECRETS_MANAGER, 1000); + + assertEquals(50, page.events().size()); + assertNotNull(page.nextToken()); + } + + @Test + void aNextTokenIsRefusedForADifferentLookup() { + String account = newAccount(); + putSecretValues(account, 2); + String token = lookup(account, LookupAttributeKey.EVENT_SOURCE, SECRETS_MANAGER, 1).nextToken(); + assertNotNull(token); + + try (CloudTrailClient cloudTrail = cloudTrail(account)) { + assertThrows(InvalidNextTokenException.class, () -> cloudTrail.lookupEvents(r -> r.maxResults(1) + .nextToken(token) + .lookupAttributes(a -> a.attributeKey(LookupAttributeKey.EVENT_NAME).attributeValue("PutSecretValue")))); + } + } + + @Test + void moreThanOneLookupAttributeIsRefused() { + try (CloudTrailClient cloudTrail = cloudTrail(newAccount())) { + assertThrows(InvalidLookupAttributesException.class, () -> cloudTrail.lookupEvents(r -> r.lookupAttributes( + a -> a.attributeKey(LookupAttributeKey.EVENT_NAME).attributeValue("PutSecretValue"), + a -> a.attributeKey(LookupAttributeKey.EVENT_SOURCE).attributeValue(SECRETS_MANAGER)))); + } + } + + private String putSecretValues(String account, int writes) { + String name = "history-" + UUID.randomUUID(); + try (SecretsManagerClient secrets = AwsTestClients.create(SecretsManagerClient.builder(), account, + Region.US_EAST_1, endpoint)) { + secrets.createSecret(r -> r.name(name).secretString("v0")); + for (int i = 1; i <= writes; i++) { + String value = "v" + i; + secrets.putSecretValue(r -> r.secretId(name).secretString(value)); + } + } + return name; + } + + private LookupEventsResponse lookup(String account, LookupAttributeKey key, String value, Integer maxResults) { + try (CloudTrailClient cloudTrail = cloudTrail(account)) { + return cloudTrail.lookupEvents(r -> r.maxResults(maxResults) + .lookupAttributes(a -> a.attributeKey(key).attributeValue(value))); + } + } + + private CloudTrailClient cloudTrail(String account) { + return AwsTestClients.create(CloudTrailClient.builder(), account, Region.US_EAST_1, endpoint); + } + + private static String newAccount() { + return String.valueOf(ThreadLocalRandom.current().nextLong(100_000_000_000L, 1_000_000_000_000L)); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java index cdbd55ed4e..eb7f587709 100644 --- a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java @@ -34,6 +34,18 @@ class CloudTrailServiceTest { private CloudTrailService service; + @Test + void resetEmptiesTheEventHistory() { + ObjectMapper mapper = new ObjectMapper(); + service.emitManagementEvent(new CloudTrailService.ManagementEventInput("secretsmanager.amazonaws.com", + "PutSecretValue", REGION, null, mapper.createObjectNode(), mapper.createObjectNode())); + assertEquals(1, service.lookupEvents(REGION, null, null, null).size()); + + service.clear(); + + assertEquals(0, service.lookupEvents(REGION, null, null, null).size()); + } + @BeforeEach void setUp() { StorageFactory storageFactory = mock(StorageFactory.class);