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,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<CloudTrailEventHistory.HistoryEvent> 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<CloudTrailEventHistory.HistoryEvent> 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<String> names(List<CloudTrailEventHistory.HistoryEvent> events) {
return events.stream().map(event -> event.record().path("eventName").asText()).toList();
}
}
@@ -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)
@@ -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<Event> 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));
}
}
@@ -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);