feat(cloudtrail): return recorded management events from LookupEvents (#9157)

This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-22 07:55:01 -04:00
1 parent c0e1728d99
commit 15d142819b
9 files changed
+595 -36

No files matched your search

@@ -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<String> 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<String, Deque<HistoryEvent>> 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<HistoryEvent> 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<HistoryEvent> lookup(String accountId, String region, LookupAttribute attribute,
Instant startTime, Instant endTime, Instant now) {
Instant oldest = now.minus(RETENTION);
List<HistoryEvent> 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;
}
}
@@ -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<String> 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<CloudTrailEventHistory.HistoryEvent> 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) {
@@ -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<String, Object> 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<ObjectNode> 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<MatchedTrail> 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<CloudTrailEventHistory.HistoryEvent> 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();