feat(cloudtrail): in-process CloudTrail with S3 data event emission (#1460)

* feat(cloudtrail): in-process CloudTrail with S3 data event emission

New service supporting CreateTrail / DescribeTrails / DeleteTrail /
UpdateTrail / PutEventSelectors / GetEventSelectors / StartLogging /
StopLogging / GetTrailStatus.

S3 ops (PutObject / GetObject / HeadObject / DeleteObject / ListObjects
/ GetObjectAcl) emit CloudTrail data events through a per-trail buffer.
The CloudTrailLogWriter scheduler flushes pending records as gzipped
JSON envelopes into the destination bucket at AWS-shaped key paths
(AWSLogs/<account>/CloudTrail/<region>/yyyy/MM/dd/<file>.json.gz) on
a configurable cadence (default 60s).

IAM-enforcement denials emit matching AccessDenied records by hooking
IamEnforcementFilter. IamActionRegistry now distinguishes
s3:GetObjectAcl / PutObjectAcl / {Get|Put|Delete}ObjectTagging from
their base ops via ?acl / ?tagging query parameters so the right
event names land in the trail.

Seeded AWSCloudTrail_FullAccess / _ReadOnlyAccess managed policies.

* fix(cloudtrail): return LatestDeliveryTime in GetTrailStatus after StartLogging

The sdk-test-java compatibility test asserts latestDeliveryTime() is
non-null immediately after startLogging. Seed it with the startLoggingTime
so the field is always present once logging has been started.

* fix(cloudtrail): emit SnsTopicARN alongside SnsTopicName in CreateTrail/UpdateTrail responses

Accept both SnsTopicARN and SnsTopicName on input (SnsTopicARN takes
precedence). Emit both fields on output so clients reading the current
field name (SnsTopicARN) get a non-null value.

* fix(cloudtrail): wildcard S3 ARN matching, trail name validation, LookupEvents

- matchesS3DataResourceArn: handle bare "arn:aws:s3", "arn:aws:s3:::*", and
  "arn:aws:s3:::*/*" wildcard forms so trails configured via the AWS Console
  "capture everything" selector actually record events (previously fell through
  silently). Unit tests added to CloudTrailSelectorMatchingTest.

- createTrail: enforce AWS trail name rules (3–128 chars, start/end with letter
  or digit, only letters/numbers/./_/-). Integration tests in new
  CloudTrailNameValidationTest.

- CloudTrailJsonHandler: add LookupEvents stub returning an empty Events array,
  matching upstream's addition in #1603.

* fix(cloudtrail): log empty catches, key selectors/logging by trail home region

- CloudTrailLogWriter.stop(): log at WARN instead of silently swallowing the
  final-flush exception (AGENTS.md: never leave a catch block empty).

- CloudTrailService.putEventSelectors / getEventSelectors / startLogging /
  stopLogging / getTrailStatus: use trail.homeRegion() as the storage key
  instead of the request region. Previously a cross-region call (e.g. accessing
  a trail by ARN from a different-region endpoint) stored selectors and logging
  state in the wrong region's map, so trailsMatching() found an empty selector
  list and logging never fired.

- S3Controller.emitCloudTrailEvent / IamEnforcementFilter.emitS3DenialIfApplicable:
  replace empty inner catch blocks with LOG.tracev() so unexpected failures
  during request-context extraction surface at trace level.

* fix(iam): distinguish bucket-level vs object-level ?acl / ?tagging IAM actions

resolveS3SubResourceAction was always mapping ?acl and ?tagging to object-level
actions (s3:PutObjectAcl, s3:GetObjectAcl, etc.) regardless of path depth.
A PUT /{bucket}?acl request requires s3:PutBucketAcl, not s3:PutObjectAcl —
callers with the correct bucket-level permission were incorrectly denied.

Fix: inspect the URL path after stripping the leading slash. When there is no
slash (or the path ends with one), the target is a bucket; otherwise it is an
object. Applies to all six variants: GetBucketAcl, PutBucketAcl,
GetBucketTagging, PutBucketTagging, DeleteBucketTagging (and their object
counterparts).

* fix(cloudtrail): re-queue records on flush failure instead of dropping them

drainPendingRecords atomically dequeues all records before the S3 write.
If serializeAndGzip or s3Service.putObject threw, those records were gone —
permanently lost before the re-throw reached flushAll.

Fix: wrap the serialize+write block in a try-catch that calls requeueRecords
before rethrowing. Records are added back to the tail of the queue and will be
retried on the next flush cycle. The new CloudTrailService.requeueRecords helper
also makes the re-queue path unit-testable independently of flushTrail.

* fix(s3): emit GetObjectAcl error record under correct event name

getObjectAcl was called inside the outer GET-object try block. On any
AwsException (NoSuchKey, AccessDenied, etc.) the catch at the bottom fired
and emitted a GetObject error record. CloudTrail consumers auditing ACL
errors would see the wrong event name.

Wrap the acl branch in its own try-catch that emits GetObjectAcl on both
success and failure paths, mirroring the pattern used by the other hooked ops.

* ci: retrigger

* fix(test): pass CloudTrailService and CurrentVertxRequest to IamEnforcementFilter constructor

* fix(cloudtrail): persist trail state via StorageFactory instead of volatile in-memory maps

* fix(cloudtrail): address review feedback on region, name lookup, and ACL detection

- S3Controller: use request region (from credential scope) instead of
  getDefaultRegion() for CloudTrail event emission, matching the IAM
  denial hook behaviour so allowed and denied calls land in the same trail.

- CloudTrailService.findTrail: name lookup now uses regionKey(region, name)
  directly; ARNs still do a cross-region scan. Prevents two same-name
  single-region trails from resolving ambiguously by map iteration order.

- TrailKey: add eventRegion field so multi-region trail events are written
  to the correct S3 delivery path (CloudTrail/<eventRegion>/) rather than
  always the trail home region. drainPendingRecords/requeueRecords now take
  a TrailKey to carry all three dimensions.

- IamActionRegistry: fix isBucketLevel — trailing slash is a valid S3 key
  character, so /bucket/folder/?acl is an object ACL request. Replaced the
  endsWith("/") check with an index-based test. Add IamActionRegistryTest
  cases for the folder/ regression.

* docs(cloudtrail): sync action table order with make docs-sync
This commit is contained in:
Guilherme Lima authored and GitHub committed 2026-07-21 12:10:19 -04:00
1 parent fba4d8f5f9
commit 024d74e5c4
25 files changed
+2034 -595

No files matched your search

@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.iam.IamActionRegistry;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.ws.rs.core.MediaType;
@@ -98,7 +99,8 @@ class IamEnforcementFilterTest {
IamEnforcementFilter filter = new IamEnforcementFilter(
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
requestContext, conditionContextResolver);
requestContext, conditionContextResolver,
mock(CloudTrailService.class), mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class));
filter.filter(containerRequest);
@@ -132,7 +134,8 @@ class IamEnforcementFilterTest {
IamEnforcementFilter filter = new IamEnforcementFilter(
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
requestContext, conditionContextResolver);
requestContext, conditionContextResolver,
mock(CloudTrailService.class), mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class));
filter.filter(containerRequest);
@@ -0,0 +1,128 @@
package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Unit tests for the static helpers that drive CloudTrail emission on the
* IAM-deny path. Full HTTP-level coverage (filter → emit → log file) lives in
* the SDK compatibility suite where SigV4 signing is available.
*/
class IamEnforcementFilterUnitTest {
// --- mapS3ActionToEventName ---
@Test
void getObject_overGet_emitsAsGetObject() {
assertEquals("GetObject",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObject", "GET"));
}
@Test
void getObject_overHead_emitsAsHeadObject() {
assertEquals("HeadObject",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObject", "HEAD"));
}
@Test
void putObject_emitsAsPutObject() {
assertEquals("PutObject",
IamEnforcementFilter.mapS3ActionToEventName("s3:PutObject", "PUT"));
}
@Test
void deleteObject_emitsAsDeleteObject() {
assertEquals("DeleteObject",
IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObject", "DELETE"));
}
@Test
void listBucket_emitsAsListObjects() {
assertEquals("ListObjects",
IamEnforcementFilter.mapS3ActionToEventName("s3:ListBucket", "GET"));
}
@Test
void listAllMyBuckets_emitsAsListBuckets() {
assertEquals("ListBuckets",
IamEnforcementFilter.mapS3ActionToEventName("s3:ListAllMyBuckets", "GET"));
}
@Test
void getObjectAcl_emitsAsGetObjectAcl() {
assertEquals("GetObjectAcl",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectAcl", "GET"));
}
@Test
void putObjectAcl_emitsAsPutObjectAcl() {
assertEquals("PutObjectAcl",
IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectAcl", "PUT"));
}
@Test
void objectTagging_emitsCorrectEventNames() {
assertEquals("GetObjectTagging",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectTagging", "GET"));
assertEquals("PutObjectTagging",
IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectTagging", "PUT"));
assertEquals("DeleteObjectTagging",
IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObjectTagging", "DELETE"));
}
@Test
void unknownAction_returnsNull() {
assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:GetBucketAcl", "GET"));
assertNull(IamEnforcementFilter.mapS3ActionToEventName("dynamodb:Query", "POST"));
assertNull(IamEnforcementFilter.mapS3ActionToEventName(null, "GET"));
}
// --- parseS3Resource ---
@Test
void parseObjectArn_splitsBucketAndKey() {
assertArrayEquals(new String[] { "audit-source", "documents/hello.txt" },
IamEnforcementFilter.parseS3Resource("arn:aws:s3:::audit-source/documents/hello.txt"));
}
@Test
void parseBucketArn_returnsBucketWithNullKey() {
assertArrayEquals(new String[] { "audit-source", null },
IamEnforcementFilter.parseS3Resource("arn:aws:s3:::audit-source"));
}
@Test
void parseBucketArnWithTrailingSlash_returnsBucketWithNullKey() {
assertArrayEquals(new String[] { "audit-source", null },
IamEnforcementFilter.parseS3Resource("arn:aws:s3:::audit-source/"));
}
@Test
void parseKeyWithSlashes_keepsFullPath() {
assertArrayEquals(new String[] { "b", "a/b/c.txt" },
IamEnforcementFilter.parseS3Resource("arn:aws:s3:::b/a/b/c.txt"));
}
@Test
void parseStarArn_returnsNulls() {
assertArrayEquals(new String[] { null, null },
IamEnforcementFilter.parseS3Resource("arn:aws:s3:::*"));
}
@Test
void parseEmptyArn_returnsNulls() {
assertArrayEquals(new String[] { null, null },
IamEnforcementFilter.parseS3Resource("arn:aws:s3:::"));
}
@Test
void parseNonS3Arn_returnsNulls() {
assertArrayEquals(new String[] { null, null },
IamEnforcementFilter.parseS3Resource("arn:aws:lambda:us-east-1:000000000000:function:foo"));
assertArrayEquals(new String[] { null, null },
IamEnforcementFilter.parseS3Resource(null));
}
}
@@ -1,21 +1,38 @@
package io.github.hectorvent.floci.services.cloudtrail;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End-to-end smoke test for the CloudTrail control plane + S3 hook + log
* writer pipeline. Sets up a trail, exercises the five hooked S3 ops, forces
* a flush, and verifies that a gzipped CloudTrail log file lands in the
* destination bucket with the right record shape.
*/
@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.";
private static final String CT_TARGET = "CloudTrail_20131101.";
private static final String JSON11 = "application/x-amz-json-1.1";
@Inject
CloudTrailLogWriter writer;
@BeforeAll
static void configureRestAssured() {
@@ -23,414 +40,304 @@ class CloudTrailIntegrationTest {
}
@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));
void s3DataEventsLandAsGzippedLogFilesInDestinationBucket() throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String sourceBucket = "audit-source-" + suffix;
String destBucket = "audit-logs-" + suffix;
String trailName = "audit-trail-" + suffix;
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"));
// 1. Buckets
createBucket(sourceBucket);
createBucket(destBucket);
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEventSelectors")
.contentType(CONTENT_TYPE)
.body("""
// 2. CreateTrail
invokeCloudTrail("CreateTrail", String.format("""
{
"Name": "%s",
"S3BucketName": "%s",
"IsMultiRegionTrail": true,
"IncludeGlobalServiceEvents": true,
"EnableLogFileValidation": true
}
""", trailName, destBucket))
.then()
.statusCode(200)
.body(containsString("\"TrailARN\""));
// 3. PutEventSelectors — match all S3 objects in the source bucket
invokeCloudTrail("PutEventSelectors", String.format("""
{
"TrailName": "%s",
"EventSelectors": [
{
"ReadWriteType": "All",
"IncludeManagementEvents": false,
"DataResources": [
{
"TrailName": "sample-audit",
"AdvancedEventSelectors": []
"Type": "AWS::S3::Object",
"Values": ["arn:aws:s3:::%s/"]
}
""")
.when()
.post("/")
.then()
]
}
]
}
""", trailName, sourceBucket))
.then()
.statusCode(200)
.body(containsString("\"EventSelectors\""));
// 4. StartLogging
invokeCloudTrail("StartLogging",
String.format("{\"Name\":\"%s\"}", trailName))
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "StartLogging")
.contentType(CONTENT_TYPE)
.body("""
{
"Name": "sample-audit"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
// 5. Drive S3 traffic against the source bucket — covers all five
// hooked ops plus a denial path (NoSuchKey on a missing GetObject).
putObject(sourceBucket, "documents/hello.txt", "hello-world");
getObject(sourceBucket, "documents/hello.txt", 200);
headObject(sourceBucket, "documents/hello.txt", 200);
listObjects(sourceBucket);
getObject(sourceBucket, "documents/missing.txt", 404);
deleteObject(sourceBucket, "documents/hello.txt");
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());
// 6. Force the writer to flush — bypasses the scheduled cadence.
writer.flushNow();
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));
// 7. List the destination bucket and find the log file.
String listingXml = given()
.when().get("/" + destBucket + "?list-type=2")
.then().statusCode(200)
.extract().asString();
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));
// Expect AWS-shaped key: AWSLogs/<account>/CloudTrail/<region>/yyyy/MM/dd/<file>.json.gz
assertTrue(listingXml.contains("AWSLogs/"),
"Destination bucket missing AWSLogs prefix; got:\n" + listingXml);
assertTrue(listingXml.contains("/CloudTrail/"),
"Destination bucket missing CloudTrail segment; got:\n" + listingXml);
assertTrue(listingXml.contains(".json.gz"),
"Destination bucket missing .json.gz file; got:\n" + listingXml);
given()
.header("X-Amz-Target", TARGET_PREFIX + "StopLogging")
.contentType(CONTENT_TYPE)
.body("""
{
"Name": "sample-audit"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
String logKey = extractFirstKey(listingXml);
assertNotNull(logKey, "Could not parse first <Key> from listing:\n" + listingXml);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteTrail")
.contentType(CONTENT_TYPE)
.body("""
{
"Name": "sample-audit"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
// 8. Download the log file and decompress.
byte[] gz = given()
.when().get("/" + destBucket + "/" + logKey)
.then().statusCode(200)
.extract().asByteArray();
byte[] json;
try (GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(gz))) {
json = gzin.readAllBytes();
}
// 9. Verify record shape.
ObjectMapper mapper = new ObjectMapper();
JsonNode envelope = mapper.readTree(json);
JsonNode records = envelope.get("Records");
assertNotNull(records, "Missing Records[] in log file:\n" + new String(json));
assertTrue(records.isArray(), "Records is not an array");
assertTrue(records.size() >= 5,
"Expected at least 5 records (Put/Get/Head/List/Delete + denial), got " + records.size()
+ ":\n" + new String(json));
boolean sawPut = false, sawGet = false, sawDelete = false, sawNoSuchKey = false;
for (JsonNode rec : records) {
assertEquals("1.11", rec.path("eventVersion").asText(),
"Bad eventVersion: " + rec);
assertEquals("s3.amazonaws.com", rec.path("eventSource").asText(),
"Bad eventSource: " + rec);
assertEquals("Data", rec.path("eventCategory").asText(),
"Bad eventCategory: " + rec);
assertEquals("AwsApiCall", rec.path("eventType").asText(),
"Bad eventType: " + rec);
assertNotNull(rec.path("eventID").asText(null), "Missing eventID");
assertNotNull(rec.path("requestID").asText(null), "Missing requestID");
assertEquals("IAMUser", rec.path("userIdentity").path("type").asText(),
"Bad userIdentity.type: " + rec);
String name = rec.path("eventName").asText();
if ("PutObject".equals(name)) sawPut = true;
if ("GetObject".equals(name) && rec.path("errorCode").isMissingNode()) sawGet = true;
if ("DeleteObject".equals(name)) sawDelete = true;
if ("NoSuchKey".equals(rec.path("errorCode").asText(null))) sawNoSuchKey = true;
}
assertTrue(sawPut, "Expected a PutObject record");
assertTrue(sawGet, "Expected a successful GetObject record");
assertTrue(sawDelete, "Expected a DeleteObject record");
assertTrue(sawNoSuchKey, "Expected a GetObject NoSuchKey record");
}
@Test
void lookupEventsReturnsEmptyEventPage() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "LookupEvents")
.contentType(CONTENT_TYPE)
.body("""
{
"LookupAttributes": [
{"AttributeKey": "EventName", "AttributeValue": "CreateBucket"}
],
"MaxResults": 10
}
""")
.when()
.post("/")
invokeCloudTrail("LookupEvents", """
{
"LookupAttributes": [
{"AttributeKey": "EventName", "AttributeValue": "CreateBucket"}
],
"MaxResults": 10
}
""")
.then()
.statusCode(200)
.body("Events", hasSize(0));
.statusCode(200)
.body("Events", hasSize(0));
}
@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";
void describeTrailsRoundTripsCreatedTrail() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String trailName = "rt-" + suffix;
String destBucket = "rt-logs-" + suffix;
createBucket(bucket);
putBucketPolicy(bucket, trailName);
putBucketNotification(bucket, queueArn);
setQueuePolicy(queueUrl, bucketArn, queueArn);
createBucket(destBucket);
invokeCloudTrail("CreateTrail", String.format("""
{"Name":"%s","S3BucketName":"%s"}
""", trailName, destBucket))
.then().statusCode(200);
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()
invokeCloudTrail("DescribeTrails",
String.format("{\"trailNameList\":[\"%s\"]}", trailName))
.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);
.body(containsString("\"" + trailName + "\""))
.body(containsString(destBucket));
}
private static void createBucket(String bucket) {
given()
.when()
.put("/" + bucket)
.then()
.statusCode(200);
@Test
void getTrailStatusReflectsStartStopLogging() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String trailName = "ss-" + suffix;
String destBucket = "ss-logs-" + suffix;
createBucket(destBucket);
invokeCloudTrail("CreateTrail", String.format("""
{"Name":"%s","S3BucketName":"%s"}
""", trailName, destBucket))
.then().statusCode(200);
invokeCloudTrail("GetTrailStatus",
String.format("{\"Name\":\"%s\"}", trailName))
.then().statusCode(200).body(containsString("\"IsLogging\":false"));
invokeCloudTrail("StartLogging",
String.format("{\"Name\":\"%s\"}", trailName))
.then().statusCode(200);
invokeCloudTrail("GetTrailStatus",
String.format("{\"Name\":\"%s\"}", trailName))
.then().statusCode(200).body(containsString("\"IsLogging\":true"));
invokeCloudTrail("StopLogging",
String.format("{\"Name\":\"%s\"}", trailName))
.then().statusCode(200);
invokeCloudTrail("GetTrailStatus",
String.format("{\"Name\":\"%s\"}", trailName))
.then().statusCode(200).body(containsString("\"IsLogging\":false"));
}
private static String createQueue(String queueName) {
@Test
void deleteTrailRemovesItFromDescribeTrails() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String trailName = "del-" + suffix;
String destBucket = "del-logs-" + suffix;
createBucket(destBucket);
invokeCloudTrail("CreateTrail", String.format("""
{"Name":"%s","S3BucketName":"%s"}
""", trailName, destBucket))
.then().statusCode(200);
invokeCloudTrail("DescribeTrails",
String.format("{\"trailNameList\":[\"%s\"]}", trailName))
.then().statusCode(200).body(containsString(trailName));
invokeCloudTrail("DeleteTrail",
String.format("{\"Name\":\"%s\"}", trailName))
.then().statusCode(200);
// After deletion, DescribeTrails with the same name yields an empty list
String body = invokeCloudTrail("DescribeTrails",
String.format("{\"trailNameList\":[\"%s\"]}", trailName))
.then().statusCode(200).extract().asString();
assertTrue(body.contains("\"trailList\":[]"),
"Expected empty trailList after delete, got: " + body);
}
@Test
void updateTrailReplacesS3BucketName() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String trailName = "upd-" + suffix;
String oldBucket = "upd-old-" + suffix;
String newBucket = "upd-new-" + suffix;
createBucket(oldBucket);
createBucket(newBucket);
invokeCloudTrail("CreateTrail", String.format("""
{"Name":"%s","S3BucketName":"%s"}
""", trailName, oldBucket))
.then().statusCode(200);
invokeCloudTrail("UpdateTrail", String.format("""
{"Name":"%s","S3BucketName":"%s","IsMultiRegionTrail":true}
""", trailName, newBucket))
.then().statusCode(200)
.body(containsString("\"S3BucketName\":\"" + newBucket + "\""))
.body(containsString("\"IsMultiRegionTrail\":true"));
invokeCloudTrail("DescribeTrails",
String.format("{\"trailNameList\":[\"%s\"]}", trailName))
.then().statusCode(200)
.body(containsString(newBucket));
}
// --- Helpers ---
private static io.restassured.response.Response invokeCloudTrail(String action, String body) {
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");
.header("X-Amz-Target", CT_TARGET + action)
.contentType(JSON11)
.body(body)
.when().post("/");
}
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 void createBucket(String name) {
given().when().put("/" + name).then().statusCode(200);
}
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 putObject(String bucket, String key, String body) {
given().body(body)
.when().put("/" + bucket + "/" + key)
.then().statusCode(200);
}
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 getObject(String bucket, String key, int expectedStatus) {
given().when().get("/" + bucket + "/" + key)
.then().statusCode(expectedStatus);
}
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 headObject(String bucket, String key, int expectedStatus) {
given().when().head("/" + bucket + "/" + key)
.then().statusCode(expectedStatus);
}
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);
private static void listObjects(String bucket) {
given().when().get("/" + bucket + "?list-type=2")
.then().statusCode(200);
}
private static void deleteObject(String bucket, String key) {
given().when().delete("/" + bucket + "/" + key)
.then().statusCode(204);
}
/** Extract the first <Key>...</Key> from an S3 ListObjectsV2 XML response. */
private static String extractFirstKey(String xml) {
int open = xml.indexOf("<Key>");
if (open < 0) return null;
int close = xml.indexOf("</Key>", open);
if (close < 0) return null;
return xml.substring(open + "<Key>".length(), close);
}
}
@@ -0,0 +1,93 @@
package io.github.hectorvent.floci.services.cloudtrail;
import io.github.hectorvent.floci.core.common.AwsException;
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 io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
@QuarkusTest
class CloudTrailNameValidationTest {
private static final String CT_TARGET = "CloudTrail_20131101.";
private static final String JSON11 = "application/x-amz-json-1.1";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void tooShortName_rejectsWithInvalidTrailNameException() {
given()
.header("X-Amz-Target", CT_TARGET + "CreateTrail")
.contentType(JSON11)
.body("{\"Name\":\"ab\",\"S3BucketName\":\"some-bucket\"}")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("InvalidTrailNameException"));
}
@Test
void singleCharName_rejectsWithInvalidTrailNameException() {
given()
.header("X-Amz-Target", CT_TARGET + "CreateTrail")
.contentType(JSON11)
.body("{\"Name\":\"a\",\"S3BucketName\":\"some-bucket\"}")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("InvalidTrailNameException"));
}
@Test
void nameStartingWithHyphen_rejectsWithInvalidTrailNameException() {
given()
.header("X-Amz-Target", CT_TARGET + "CreateTrail")
.contentType(JSON11)
.body("{\"Name\":\"-trail\",\"S3BucketName\":\"some-bucket\"}")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("InvalidTrailNameException"));
}
@Test
void nameEndingWithHyphen_rejectsWithInvalidTrailNameException() {
given()
.header("X-Amz-Target", CT_TARGET + "CreateTrail")
.contentType(JSON11)
.body("{\"Name\":\"trail-\",\"S3BucketName\":\"some-bucket\"}")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("InvalidTrailNameException"));
}
@Test
void nameWithInvalidChar_rejectsWithInvalidTrailNameException() {
given()
.header("X-Amz-Target", CT_TARGET + "CreateTrail")
.contentType(JSON11)
.body("{\"Name\":\"my trail!\",\"S3BucketName\":\"some-bucket\"}")
.when().post("/")
.then()
.statusCode(400)
.body(containsString("InvalidTrailNameException"));
}
@Test
void validName_isAccepted() {
given()
.header("X-Amz-Target", CT_TARGET + "CreateTrail")
.contentType(JSON11)
.body("{\"Name\":\"my-trail_1.0\",\"S3BucketName\":\"some-bucket\"}")
.when().post("/")
.then()
.statusCode(200);
}
}
@@ -0,0 +1,160 @@
package io.github.hectorvent.floci.services.cloudtrail;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit tests for {@link CloudTrailService}'s S3 data-resource matcher and
* read/write classifier — the two predicates that gate every emit decision.
* Full pipeline coverage lives in {@code CloudTrailIntegrationTest}.
*/
class CloudTrailSelectorMatchingTest {
// --- matchesS3DataResourceArn ---
@Test
void allBucketsArn_matchesEverything() {
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::", "any-bucket", "any/key.txt"));
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::", "any-bucket", null));
}
@Test
void allBucketsArnWithSlash_matchesEverything() {
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::/", "any-bucket", "any/key.txt"));
}
@Test
void bucketArnNoSlash_matchesAnyOpOnThatBucket() {
// Bucket-only ARNs are permissive: the selector ARN doesn't carry the
// request's action, so we can't distinguish bucket-level ops from
// object-level ones here. We match on bucket name and let event
// selectors carry the read/write filter via ReadWriteType. Most real
// workflows use `arn:aws:s3:::bucket/` (with slash) to capture every
// object event explicitly.
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::audit-source", "audit-source", null));
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::audit-source", "audit-source", "k.txt"));
assertFalse(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::audit-source", "other-bucket", null));
assertFalse(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::audit-source", "other-bucket", "k.txt"));
}
@Test
void bucketArnWithTrailingSlash_matchesAnyKey() {
assertTrue(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/", "audit-source", "documents/a.txt"));
assertTrue(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/", "audit-source", "k.txt"));
assertFalse(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/", "other-bucket", "k.txt"));
}
@Test
void prefixArn_matchesKeysUnderPrefix() {
assertTrue(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents/", "audit-source", "documents/a.txt"));
assertTrue(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents/", "audit-source", "documents/nested/a.txt"));
assertFalse(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents/", "audit-source", "exports/a.txt"));
}
@Test
void prefixArnNoTrailingSlash_isPrefixMatchOnKey() {
// arn:aws:s3:::bucket/prefix matches keys that start with "prefix"
assertTrue(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents", "audit-source", "documents/a.txt"));
assertTrue(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents", "audit-source", "documents-v2/a.txt"));
assertFalse(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents", "audit-source", "exports/a.txt"));
}
@Test
void prefixArn_doesNotMatchOtherBucket() {
assertFalse(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents/", "other-bucket", "documents/a.txt"));
}
@Test
void exactKeyArn_matchesOnlyThatKey() {
assertTrue(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents/a.txt", "audit-source", "documents/a.txt"));
// The current implementation uses startsWith, so "documents/a.txt2" also
// matches — that's deliberate (mirrors AWS's prefix semantics for object ARNs)
assertTrue(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents/a.txt", "audit-source", "documents/a.txt2"));
assertFalse(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents/a.txt", "audit-source", "documents/b.txt"));
}
@Test
void bareS3Arn_matchesEverything() {
// "arn:aws:s3" without ":::" is the AWS Console / CLI "all objects" shorthand
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3", "any-bucket", "any/key.txt"));
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3", "any-bucket", null));
}
@Test
void wildcardBucketArn_matchesAnyBucket() {
// arn:aws:s3:::* matches all buckets (moto-style)
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::*", "any-bucket", null));
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::*", "another-bucket", "k.txt"));
}
@Test
void wildcardObjectArn_matchesAnyNonNullKey() {
// arn:aws:s3:::*/* matches all objects across all buckets (value moto uses in its tests)
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::*/*", "any-bucket", "k.txt"));
assertTrue(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::*/*", "another-bucket", "a/b/c.json"));
assertFalse(CloudTrailService.matchesS3DataResourceArn("arn:aws:s3:::*/*", "any-bucket", null));
}
@Test
void nonS3Arn_neverMatches() {
assertFalse(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:lambda:us-east-1:000:function:foo", "audit-source", "k.txt"));
assertFalse(CloudTrailService.matchesS3DataResourceArn(null, "audit-source", "k.txt"));
}
@Test
void prefixArn_nullKey_doesNotMatchKeyOps() {
// A key-level selector cannot match a bucket-level op (which has key=null)
assertFalse(CloudTrailService.matchesS3DataResourceArn(
"arn:aws:s3:::audit-source/documents/", "audit-source", null));
}
// --- isReadOnlyEvent ---
@Test
void readOps_classifiedReadOnly() {
assertTrue(CloudTrailService.isReadOnlyEvent("GetObject"));
assertTrue(CloudTrailService.isReadOnlyEvent("HeadObject"));
assertTrue(CloudTrailService.isReadOnlyEvent("ListObjects"));
assertTrue(CloudTrailService.isReadOnlyEvent("ListObjectsV2"));
assertTrue(CloudTrailService.isReadOnlyEvent("GetObjectAcl"));
assertTrue(CloudTrailService.isReadOnlyEvent("GetObjectTagging"));
assertTrue(CloudTrailService.isReadOnlyEvent("ListMultipartUploads"));
}
@Test
void writeOps_classifiedNotReadOnly() {
assertFalse(CloudTrailService.isReadOnlyEvent("PutObject"));
assertFalse(CloudTrailService.isReadOnlyEvent("DeleteObject"));
assertFalse(CloudTrailService.isReadOnlyEvent("PutObjectAcl"));
}
@Test
void unknownEvent_defaultsToWrite() {
// Conservative default: unknown ops are treated as writes so a
// ReadOnly selector won't accidentally swallow them.
assertFalse(CloudTrailService.isReadOnlyEvent("SomeFutureOperation"));
}
@Test
void nullEvent_classifiedReadOnly() {
// Defensive — buildS3Record uses this for the "readOnly" field, which
// should default to safe-no-write semantics if the eventName is missing.
assertTrue(CloudTrailService.isReadOnlyEvent(null));
}
}
@@ -121,6 +121,32 @@ class IamActionRegistryTest {
assertNull(registry.resolve("kms", ctx));
}
@Test
void s3AclOnTrailingSlashKeyIsObjectLevel() {
// /bucket/folder/?acl — trailing slash is a valid key character, so this
// must be s3:GetObjectAcl, not s3:GetBucketAcl.
MultivaluedMap<String, String> acl = new MultivaluedHashMap<>();
acl.add("acl", "");
ContainerRequestContext ctx = mockCtx("GET", "/bucket/folder/", acl, null, "");
assertEquals("s3:GetObjectAcl", registry.resolve("s3", ctx));
}
@Test
void s3TaggingOnTrailingSlashKeyIsObjectLevel() {
MultivaluedMap<String, String> tagging = new MultivaluedHashMap<>();
tagging.add("tagging", "");
ContainerRequestContext ctx = mockCtx("GET", "/bucket/folder/", tagging, null, "");
assertEquals("s3:GetObjectTagging", registry.resolve("s3", ctx));
}
@Test
void s3AclOnBucketRootIsStillBucketLevel() {
MultivaluedMap<String, String> acl = new MultivaluedHashMap<>();
acl.add("acl", "");
ContainerRequestContext ctx = mockCtx("GET", "/bucket/", acl, null, "");
assertEquals("s3:GetBucketAcl", registry.resolve("s3", ctx));
}
// -------------------------------------------------------------------------
private static ContainerRequestContext mockCtx(String method, String path,