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

@@ -266,6 +266,7 @@ public interface EmulatorConfig {
TranscribeStorageConfig transcribe();
TaggingStorageConfig tagging();
ElasticBeanstalkStorageConfig elasticbeanstalk();
CloudTrailStorageConfig cloudtrail();
}
interface SsmStorageConfig {
@@ -467,6 +468,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
interface CloudTrailStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface CodeDeployStorageConfig {
Optional<String> mode();
@@ -592,11 +600,6 @@ public interface EmulatorConfig {
boolean enabled();
}
interface CloudTrailServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface LightsailServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -606,7 +609,6 @@ public interface EmulatorConfig {
@WithDefault("true")
boolean enabled();
}
interface S3VectorsServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -647,6 +649,17 @@ public interface EmulatorConfig {
boolean enabled();
}
interface CloudTrailServiceConfig {
@WithDefault("true")
boolean enabled();
/** How often the writer flushes pending records into the destination
* bucket. Real AWS delivers data events with ~5-minute lag; the
* default here is 60s so dev/CI feedback loops stay fast. */
@WithDefault("60")
int flushIntervalSeconds();
}
interface AutoScalingServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -1,12 +1,14 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
import io.github.hectorvent.floci.services.iam.IamActionRegistry;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
@@ -55,6 +57,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private final ResourceArnBuilder arnBuilder;
private final RequestContext requestContext;
private final IamConditionContextResolver conditionContextResolver;
private final CloudTrailService cloudTrailService;
private final CurrentVertxRequest currentVertxRequest;
@Inject
public IamEnforcementFilter(EmulatorConfig config,
@@ -64,7 +68,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
IamActionRegistry actionRegistry,
ResourceArnBuilder arnBuilder,
RequestContext requestContext,
IamConditionContextResolver conditionContextResolver) {
IamConditionContextResolver conditionContextResolver,
CloudTrailService cloudTrailService,
CurrentVertxRequest currentVertxRequest) {
this.config = config;
this.accountResolver = accountResolver;
this.iamService = iamService;
@@ -73,6 +79,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
this.arnBuilder = arnBuilder;
this.requestContext = requestContext;
this.conditionContextResolver = conditionContextResolver;
this.cloudTrailService = cloudTrailService;
this.currentVertxRequest = currentVertxRequest;
}
@Override
@@ -116,10 +124,115 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
Decision decision = evaluator.evaluate(caller, null, action, resource, conditionContext);
if (decision == Decision.DENY) {
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
String denyMessage = "User: arn:aws:iam::" + accountId
+ ":user/" + akid + " is not authorized to perform: " + action
+ " on resource: \"" + resource + "\""
+ " because no identity-based policy allows the " + action + " action";
emitS3DenialIfApplicable(akid, action, resource, ctx, region, denyMessage);
ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType()));
}
}
/**
* Best-effort CloudTrail emission for S3 access denials. Without this hook,
* denied requests get aborted before {@code S3Controller}'s try/catch sees
* them, so denials would never appear in CloudTrail logs — leaving a major
* gap vs. real AWS for downstream audit ingestion. Failures here never
* propagate (the deny response is the load-bearing behavior).
*/
private void emitS3DenialIfApplicable(String akid, String action, String resource,
ContainerRequestContext ctx, String region,
String denyMessage) {
try {
if (action == null || !action.startsWith("s3:")) {
return;
}
String eventName = mapS3ActionToEventName(action, ctx.getMethod());
if (eventName == null) {
return;
}
String[] bk = parseS3Resource(resource);
String bucket = bk[0];
String key = bk[1];
String userAgent = null;
String sourceIp = null;
try {
var rc = currentVertxRequest.getCurrent();
if (rc != null) {
var req = rc.request();
if (req != null) {
userAgent = req.getHeader("User-Agent");
String fwd = req.getHeader("X-Forwarded-For");
if (fwd != null && !fwd.isBlank()) {
int comma = fwd.indexOf(',');
sourceIp = (comma > 0 ? fwd.substring(0, comma) : fwd).trim();
} else if (req.remoteAddress() != null) {
sourceIp = req.remoteAddress().host();
}
}
}
} catch (Exception e) {
LOG.tracev(e, "CloudTrail: could not extract request context for IAM denial {0} on {1}", action, resource);
}
cloudTrailService.emitS3DataEvent(CloudTrailService.S3EventInput.builder()
.region(region)
.eventName(eventName)
.bucketName(bucket)
.key(key)
.accessKeyId(akid)
.sourceIp(sourceIp)
.userAgent(userAgent)
.errorCode("AccessDenied")
.errorMessage(denyMessage)
.eventTimeMillis(System.currentTimeMillis())
.build());
} catch (RuntimeException e) {
LOG.tracev(e, "CloudTrail denial emission failed for {0} on {1}", action, resource);
}
}
// Package-private for unit testing.
static String mapS3ActionToEventName(String action, String httpMethod) {
if (action == null) return null;
// Action set sourced from IamActionRegistry — see that file for any
// additions. HEAD on an object is bucketed under s3:GetObject by the
// registry, so we distinguish via httpMethod.
return switch (action) {
case "s3:GetObject" -> "HEAD".equalsIgnoreCase(httpMethod) ? "HeadObject" : "GetObject";
case "s3:PutObject" -> "PutObject";
case "s3:DeleteObject" -> "DeleteObject";
case "s3:ListBucket" -> "ListObjects";
case "s3:ListAllMyBuckets" -> "ListBuckets";
case "s3:GetObjectAcl" -> "GetObjectAcl";
case "s3:PutObjectAcl" -> "PutObjectAcl";
case "s3:GetObjectTagging" -> "GetObjectTagging";
case "s3:PutObjectTagging" -> "PutObjectTagging";
case "s3:DeleteObjectTagging" -> "DeleteObjectTagging";
default -> null;
};
}
/** Returns [bucket, key] (key may be null if the resource is a bucket-level ARN). */
// Package-private for unit testing.
static String[] parseS3Resource(String resource) {
if (resource == null || !resource.startsWith("arn:aws:s3:::")) {
return new String[] { null, null };
}
String tail = resource.substring("arn:aws:s3:::".length());
if (tail.isEmpty() || "*".equals(tail)) {
return new String[] { null, null };
}
int slash = tail.indexOf('/');
if (slash < 0) {
return new String[] { tail, null };
}
String bucket = tail.substring(0, slash);
String key = tail.substring(slash + 1);
return new String[] { bucket, key.isEmpty() ? null : key };
}
private String extractCredentialScope(String auth) {
Matcher m = SERVICE_PATTERN.matcher(auth);
return m.find() ? m.group(1) : null;
@@ -285,9 +285,11 @@ public class ResolvedServiceCatalog {
protocols(ServiceProtocol.JSON),
Set.of("StarlingDoveService."), Set.of("config"), Set.of(), Set.of()),
descriptor("cloudtrail", "cloudtrail", config.services().cloudtrail().enabled(), true,
"cloudtrail", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
"cloudtrail", storageMode(config.storage().services().cloudtrail().mode(), config.storage().mode()),
config.storage().services().cloudtrail().flushIntervalMs(), null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101."),
Set.of("CloudTrail_20131101.",
"com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101."),
Set.of("cloudtrail"), Set.of(), Set.of()),
descriptor("lightsail", "lightsail", config.services().lightsail().enabled(), true,
"lightsail", storageMode(config.storage().services().lightsail().mode(), config.storage().mode()),
@@ -0,0 +1,41 @@
package io.github.hectorvent.floci.services.cloudtrail;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;
import io.github.hectorvent.floci.services.cloudtrail.model.Trail;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public record CloudTrailEntry(
Trail trail,
List<EventSelector> selectors,
boolean logging,
Long startLoggingTime,
Long stopLoggingTime) {
public CloudTrailEntry withTrail(Trail updated) {
return new CloudTrailEntry(updated, selectors, logging, startLoggingTime, stopLoggingTime);
}
public CloudTrailEntry withSelectors(List<EventSelector> updated, boolean hasCustomSelectors) {
Trail updatedTrail = new Trail(
trail.name(), trail.trailArn(), trail.s3BucketName(), trail.s3KeyPrefix(),
trail.snsTopicArn(), trail.includeGlobalServiceEvents(), trail.isMultiRegionTrail(),
trail.homeRegion(), trail.logFileValidationEnabled(), hasCustomSelectors,
trail.hasInsightSelectors(), trail.isOrganizationTrail());
return new CloudTrailEntry(updatedTrail, updated, logging, startLoggingTime, stopLoggingTime);
}
public CloudTrailEntry startLogging(long time) {
return new CloudTrailEntry(trail, selectors, true, time, stopLoggingTime);
}
public CloudTrailEntry stopLogging(long time) {
return new CloudTrailEntry(trail, selectors, false, startLoggingTime, time);
}
}
@@ -2,20 +2,21 @@ package io.github.hectorvent.floci.services.cloudtrail;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudtrail.model.CloudTrailTrail;
import io.github.hectorvent.floci.services.cloudtrail.model.DataResource;
import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;
import io.github.hectorvent.floci.services.cloudtrail.model.Trail;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class CloudTrailJsonHandler {
private final CloudTrailService service;
private final ObjectMapper mapper;
@@ -25,128 +26,195 @@ public class CloudTrailJsonHandler {
this.mapper = mapper;
}
public Response handle(String action, JsonNode request, String region) {
public Response handle(String action, JsonNode request, String region) throws Exception {
return switch (action) {
case "CreateTrail" -> createTrail(request, region);
case "UpdateTrail" -> updateTrail(request, region);
case "DescribeTrails" -> describeTrails(request, region);
case "DeleteTrail" -> deleteTrail(request, region);
case "UpdateTrail" -> updateTrail(request, region);
case "PutEventSelectors" -> putEventSelectors(request, region);
case "GetEventSelectors" -> getEventSelectors(request, region);
case "StartLogging" -> startLogging(request, region);
case "StopLogging" -> stopLogging(request, region);
case "DeleteTrail" -> deleteTrail(request, region);
case "GetTrailStatus" -> getTrailStatus(request, region);
case "PutEventSelectors" -> putEventSelectors(request, region);
case "LookupEvents" -> lookupEvents(request, region);
default -> throw new AwsException("UnsupportedOperation",
"Operation " + action + " is not supported.", 400);
default -> throw new AwsException(
"InvalidAction", "Could not find operation " + action, 400);
};
}
private Response createTrail(JsonNode request, String region) {
CloudTrailTrail trail = service.createTrail(
region,
request.path("Name").asText(null),
request.path("S3BucketName").asText(null),
request.path("IncludeGlobalServiceEvents").asBoolean(false),
request.path("IsMultiRegionTrail").asBoolean(false),
request.path("IsOrganizationTrail").asBoolean(false),
parseTags(request.path("TagsList")));
return Response.ok(trailNode(trail)).build();
}
private Response createTrail(JsonNode req, String region) {
String name = req.path("Name").asText(null);
String s3BucketName = req.path("S3BucketName").asText(null);
String s3KeyPrefix = req.has("S3KeyPrefix") ? req.path("S3KeyPrefix").asText(null) : null;
String snsTopicArn = req.has("SnsTopicARN") ? req.path("SnsTopicARN").asText(null)
: req.has("SnsTopicName") ? req.path("SnsTopicName").asText(null) : null;
boolean includeGlobal = req.path("IncludeGlobalServiceEvents").asBoolean(true);
boolean isMultiRegion = req.path("IsMultiRegionTrail").asBoolean(false);
boolean enableLogFileValidation = req.path("EnableLogFileValidation").asBoolean(false);
boolean isOrganizationTrail = req.path("IsOrganizationTrail").asBoolean(false);
private Response updateTrail(JsonNode request, String region) {
CloudTrailTrail trail = service.updateTrail(
region,
request.path("Name").asText(null),
request.path("S3BucketName").asText(null),
optionalBoolean(request, "IncludeGlobalServiceEvents"),
optionalBoolean(request, "IsMultiRegionTrail"));
return Response.ok(trailNode(trail)).build();
}
Trail trail = service.createTrail(region, name, s3BucketName, s3KeyPrefix, snsTopicArn,
includeGlobal, isMultiRegion, enableLogFileValidation, isOrganizationTrail);
private Response describeTrails(JsonNode request, String region) {
List<String> names = stringList(request.path("trailNameList"));
ObjectNode response = mapper.createObjectNode();
ArrayNode trails = response.putArray("trailList");
for (CloudTrailTrail trail : service.describeTrails(region, names)) {
trails.add(trailNode(trail));
ObjectNode resp = mapper.createObjectNode();
resp.put("Name", trail.name());
resp.put("S3BucketName", trail.s3BucketName());
if (trail.s3KeyPrefix() != null) resp.put("S3KeyPrefix", trail.s3KeyPrefix());
if (trail.snsTopicArn() != null) {
resp.put("SnsTopicARN", trail.snsTopicArn());
resp.put("SnsTopicName", trail.snsTopicArn());
}
return Response.ok(response).build();
resp.put("IncludeGlobalServiceEvents", trail.includeGlobalServiceEvents());
resp.put("IsMultiRegionTrail", trail.isMultiRegionTrail());
resp.put("TrailARN", trail.trailArn());
resp.put("LogFileValidationEnabled", trail.logFileValidationEnabled());
resp.put("IsOrganizationTrail", trail.isOrganizationTrail());
return Response.ok(resp).build();
}
private Response startLogging(JsonNode request, String region) {
service.startLogging(region, request.path("Name").asText(null));
private Response deleteTrail(JsonNode req, String region) {
String name = req.path("Name").asText(null);
service.deleteTrail(region, name);
return Response.ok(mapper.createObjectNode()).build();
}
private Response stopLogging(JsonNode request, String region) {
service.stopLogging(region, request.path("Name").asText(null));
return Response.ok(mapper.createObjectNode()).build();
}
private Response updateTrail(JsonNode req, String region) {
String name = req.path("Name").asText(null);
String s3BucketName = req.has("S3BucketName") ? req.path("S3BucketName").asText(null) : null;
String s3KeyPrefix = req.has("S3KeyPrefix") ? req.path("S3KeyPrefix").asText(null) : null;
String snsTopicName = req.has("SnsTopicARN") ? req.path("SnsTopicARN").asText(null)
: req.has("SnsTopicName") ? req.path("SnsTopicName").asText(null) : null;
Boolean includeGlobal = req.has("IncludeGlobalServiceEvents")
? req.path("IncludeGlobalServiceEvents").asBoolean() : null;
Boolean isMultiRegion = req.has("IsMultiRegionTrail")
? req.path("IsMultiRegionTrail").asBoolean() : null;
Boolean enableLogFileValidation = req.has("EnableLogFileValidation")
? req.path("EnableLogFileValidation").asBoolean() : null;
Boolean isOrganizationTrail = req.has("IsOrganizationTrail")
? req.path("IsOrganizationTrail").asBoolean() : null;
private Response deleteTrail(JsonNode request, String region) {
service.deleteTrail(region, request.path("Name").asText(null));
return Response.ok(mapper.createObjectNode()).build();
}
Trail trail = service.updateTrail(region, name, s3BucketName, s3KeyPrefix, snsTopicName,
includeGlobal, isMultiRegion, enableLogFileValidation, isOrganizationTrail);
private Response getTrailStatus(JsonNode request, String region) {
CloudTrailTrail trail = service.requireTrail(region, request.path("Name").asText(null));
ObjectNode response = mapper.createObjectNode();
response.put("IsLogging", trail.isLogging());
if (trail.getUpdated() != null) {
response.put("LatestDeliveryTime", trail.getUpdated().toEpochMilli() / 1000.0);
ObjectNode resp = mapper.createObjectNode();
resp.put("Name", trail.name());
resp.put("S3BucketName", trail.s3BucketName());
if (trail.s3KeyPrefix() != null) resp.put("S3KeyPrefix", trail.s3KeyPrefix());
if (trail.snsTopicArn() != null) {
resp.put("SnsTopicARN", trail.snsTopicArn());
resp.put("SnsTopicName", trail.snsTopicArn());
}
return Response.ok(response).build();
resp.put("IncludeGlobalServiceEvents", trail.includeGlobalServiceEvents());
resp.put("IsMultiRegionTrail", trail.isMultiRegionTrail());
resp.put("TrailARN", trail.trailArn());
resp.put("LogFileValidationEnabled", trail.logFileValidationEnabled());
resp.put("IsOrganizationTrail", trail.isOrganizationTrail());
return Response.ok(resp).build();
}
private Response putEventSelectors(JsonNode request, String region) {
service.putEventSelectors(region, request.path("TrailName").asText(null));
private Response describeTrails(JsonNode req, String region) {
List<String> nameList = extractStringList(req, "trailNameList");
List<Trail> trails = service.describeTrails(region, nameList);
ObjectNode resp = mapper.createObjectNode();
resp.set("trailList", mapper.valueToTree(trails));
return Response.ok(resp).build();
}
private Response putEventSelectors(JsonNode req, String region) {
String trailName = req.path("TrailName").asText(null);
List<EventSelector> selectors = parseEventSelectors(req.path("EventSelectors"));
List<EventSelector> stored = service.putEventSelectors(region, trailName, selectors);
ObjectNode resp = mapper.createObjectNode();
Trail trail = firstTrail(service.describeTrails(region, List.of(trailName)));
if (trail != null) {
resp.put("TrailARN", trail.trailArn());
}
resp.set("EventSelectors", mapper.valueToTree(stored));
return Response.ok(resp).build();
}
private Response getEventSelectors(JsonNode req, String region) {
String trailName = req.path("TrailName").asText(null);
List<EventSelector> selectors = service.getEventSelectors(region, trailName);
ObjectNode resp = mapper.createObjectNode();
Trail trail = firstTrail(service.describeTrails(region, List.of(trailName)));
if (trail != null) {
resp.put("TrailARN", trail.trailArn());
}
resp.set("EventSelectors", mapper.valueToTree(selectors));
return Response.ok(resp).build();
}
private Response startLogging(JsonNode req, String region) {
String trailName = req.path("Name").asText(null);
service.startLogging(region, trailName);
return Response.ok(mapper.createObjectNode()).build();
}
private Response lookupEvents(JsonNode request, String region) {
ObjectNode response = mapper.createObjectNode();
response.putArray("Events");
return Response.ok(response).build();
private Response stopLogging(JsonNode req, String region) {
String trailName = req.path("Name").asText(null);
service.stopLogging(region, trailName);
return Response.ok(mapper.createObjectNode()).build();
}
private ObjectNode trailNode(CloudTrailTrail trail) {
ObjectNode node = mapper.createObjectNode();
node.put("Name", trail.getName());
node.put("TrailARN", trail.getTrailArn());
node.put("S3BucketName", trail.getS3BucketName());
node.put("IncludeGlobalServiceEvents", trail.isIncludeGlobalServiceEvents());
node.put("IsMultiRegionTrail", trail.isMultiRegionTrail());
node.put("IsOrganizationTrail", trail.isOrganizationTrail());
node.put("HomeRegion", trail.getHomeRegion());
if (trail.getCreated() != null) {
node.put("CreationDate", trail.getCreated().toEpochMilli() / 1000.0);
private Response getTrailStatus(JsonNode req, String region) {
String trailName = req.path("Name").asText(null);
CloudTrailService.TrailStatus status = service.getTrailStatus(region, trailName);
ObjectNode resp = mapper.createObjectNode();
resp.put("IsLogging", status.logging());
if (status.startLoggingTime() != null) {
resp.put("StartLoggingTime", status.startLoggingTime() / 1000.0);
resp.put("LatestDeliveryTime", status.startLoggingTime() / 1000.0);
}
return node;
if (status.stopLoggingTime() != null) {
resp.put("StopLoggingTime", status.stopLoggingTime() / 1000.0);
}
return Response.ok(resp).build();
}
private static Map<String, String> parseTags(JsonNode tagsNode) {
Map<String, String> tags = new HashMap<>();
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = tag.path("Key").asText(null);
if (key != null) {
tags.put(key, tag.path("Value").asText(""));
private Response lookupEvents(JsonNode req, String region) {
ObjectNode resp = mapper.createObjectNode();
resp.putArray("Events");
return Response.ok(resp).build();
}
// --- Helpers ---
private List<EventSelector> parseEventSelectors(JsonNode selectorsNode) {
List<EventSelector> result = new ArrayList<>();
if (selectorsNode == null || !selectorsNode.isArray()) return result;
for (JsonNode sel : selectorsNode) {
String readWriteType = sel.has("ReadWriteType") ? sel.path("ReadWriteType").asText() : "All";
Boolean includeManagement = sel.has("IncludeManagementEvents")
? sel.path("IncludeManagementEvents").asBoolean() : null;
List<String> excludeManagement = extractStringList(sel, "ExcludeManagementEventSources");
List<DataResource> dataResources = new ArrayList<>();
if (sel.has("DataResources")) {
for (JsonNode dr : sel.path("DataResources")) {
String type = dr.path("Type").asText(null);
List<String> values = extractStringList(dr, "Values");
dataResources.add(new DataResource(type, values));
}
}
result.add(new EventSelector(readWriteType, includeManagement, dataResources,
excludeManagement.isEmpty() ? null : excludeManagement));
}
return tags;
return result;
}
private static List<String> stringList(JsonNode node) {
if (node == null || !node.isArray()) {
return List.of();
}
java.util.ArrayList<String> values = new java.util.ArrayList<>();
node.forEach(value -> values.add(value.asText()));
return values;
private static Trail firstTrail(List<Trail> trails) {
return trails.isEmpty() ? null : trails.get(0);
}
private static Boolean optionalBoolean(JsonNode node, String fieldName) {
return node != null && node.has(fieldName) ? node.path(fieldName).asBoolean() : null;
private List<String> extractStringList(JsonNode req, String fieldName) {
List<String> result = new ArrayList<>();
if (req != null && req.has(fieldName)) {
req.path(fieldName).forEach(n -> result.add(n.asText()));
}
return result;
}
}
@@ -0,0 +1,195 @@
package io.github.hectorvent.floci.services.cloudtrail;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.cloudtrail.model.Trail;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.Startup;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
/**
* Periodically drains queued CloudTrail records from {@link CloudTrailService}
* and writes them as gzipped JSON log files into each trail's destination
* S3 bucket, using AWS's documented key layout:
*
* <pre>{@code
* ${prefix}AWSLogs/${accountId}/CloudTrail/${region}/yyyy/MM/dd/
* ${accountId}_CloudTrail_${region}_${YYYYMMDDTHHMMZ}_${rand12}.json.gz
* }</pre>
*
* Real CloudTrail delivers logs with ~5 minute latency. The flush cadence
* here is configurable so local dev / CI loops stay fast.
*/
@Startup
@ApplicationScoped
public class CloudTrailLogWriter {
private static final Logger LOG = Logger.getLogger(CloudTrailLogWriter.class);
private static final DateTimeFormatter PATH_DATE = DateTimeFormatter.ofPattern("yyyy/MM/dd");
private static final DateTimeFormatter FILE_TS = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmm'Z'");
private static final String FILENAME_RAND_ALPHABET =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private final EmulatorConfig config;
private final CloudTrailService cloudTrailService;
private final S3Service s3Service;
private final RegionResolver regionResolver;
private final ObjectMapper mapper;
private final SecureRandom rng = new SecureRandom();
private ScheduledExecutorService executor;
@Inject
public CloudTrailLogWriter(EmulatorConfig config,
CloudTrailService cloudTrailService,
S3Service s3Service,
RegionResolver regionResolver,
ObjectMapper mapper) {
this.config = config;
this.cloudTrailService = cloudTrailService;
this.s3Service = s3Service;
this.regionResolver = regionResolver;
this.mapper = mapper;
}
@PostConstruct
void start() {
if (!config.services().cloudtrail().enabled()) {
return;
}
int interval = Math.max(1, config.services().cloudtrail().flushIntervalSeconds());
executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "cloudtrail-log-writer");
t.setDaemon(true);
return t;
});
executor.scheduleAtFixedRate(this::flushAll, interval, interval, TimeUnit.SECONDS);
LOG.infov("CloudTrail log writer started (flushIntervalSeconds={0})", interval);
}
void stop(@Observes ShutdownEvent event) {
if (executor != null) {
// Best-effort final flush so shutdown doesn't lose buffered events.
try { flushAll(); } catch (Exception e) { LOG.warnv(e, "CloudTrail final flush on shutdown failed — some records may be lost"); }
executor.shutdownNow();
executor = null;
}
}
/**
* Force an immediate flush. Useful for tests and for deterministic CLI
* verification.
*/
public void flushNow() {
flushAll();
}
private void flushAll() {
try {
for (CloudTrailService.TrailKey key : cloudTrailService.trailsWithPendingRecords()) {
try {
flushTrail(key);
} catch (RuntimeException e) {
LOG.warnv(e, "CloudTrail log flush failed for trail {0} in {1}",
key.trailName(), key.region());
}
}
} catch (RuntimeException outer) {
LOG.errorv(outer, "CloudTrail log writer iteration failed");
}
}
private void flushTrail(CloudTrailService.TrailKey key) {
Trail trail = cloudTrailService.getTrail(key.region(), key.trailName());
if (trail == null) {
// Trail was deleted while records were pending — drop them.
cloudTrailService.drainPendingRecords(key);
return;
}
List<ObjectNode> records = cloudTrailService.drainPendingRecords(key);
if (records.isEmpty()) {
return;
}
try {
byte[] payload = serializeAndGzip(records);
String accountId = regionResolver.getAccountId();
// Use the event region for the S3 delivery path so multi-region trail
// events from us-west-2 land under CloudTrail/us-west-2, not the trail's home region.
String objectKey = buildObjectKey(trail, accountId, key.eventRegion());
s3Service.putObject(trail.s3BucketName(), objectKey, payload,
"application/x-gzip", Map.of());
LOG.debugv("CloudTrail wrote {0} records to s3://{1}/{2}",
records.size(), trail.s3BucketName(), objectKey);
} catch (RuntimeException e) {
// Re-queue so records survive the failed flush and are retried next cycle.
cloudTrailService.requeueRecords(key, records);
LOG.warnv(e, "CloudTrail flush failed for trail {0} ({1} records re-queued)",
key.trailName(), records.size());
throw e;
}
}
private byte[] serializeAndGzip(List<ObjectNode> records) {
ObjectNode envelope = mapper.createObjectNode();
ArrayNode arr = envelope.putArray("Records");
for (ObjectNode r : records) {
arr.add(r);
}
try {
byte[] json = mapper.writeValueAsBytes(envelope);
ByteArrayOutputStream baos = new ByteArrayOutputStream(Math.max(64, json.length / 4));
try (GZIPOutputStream gz = new GZIPOutputStream(baos)) {
gz.write(json);
}
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException("Failed to serialize CloudTrail records", e);
}
}
private String buildObjectKey(Trail trail, String accountId, String region) {
LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
String prefix = trail.s3KeyPrefix() == null || trail.s3KeyPrefix().isEmpty()
? "" : trail.s3KeyPrefix() + (trail.s3KeyPrefix().endsWith("/") ? "" : "/");
String datePath = PATH_DATE.format(now);
String fileTs = FILE_TS.format(now);
String rand = randomFilenameSuffix(16);
return prefix
+ "AWSLogs/" + accountId
+ "/CloudTrail/" + region
+ "/" + datePath + "/"
+ accountId + "_CloudTrail_" + region + "_" + fileTs + "_" + rand + ".json.gz";
}
private String randomFilenameSuffix(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.append(FILENAME_RAND_ALPHABET.charAt(rng.nextInt(FILENAME_RAND_ALPHABET.length())));
}
return sb.toString();
}
}
@@ -1,143 +1,562 @@
package io.github.hectorvent.floci.services.cloudtrail;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudtrail.model.CloudTrailTrail;
import io.github.hectorvent.floci.services.cloudtrail.model.DataResource;
import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;
import io.github.hectorvent.floci.services.cloudtrail.model.Trail;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
@ApplicationScoped
public class CloudTrailService {
private final StorageBackend<String, CloudTrailTrail> trailStore;
private static final Logger LOG = Logger.getLogger(CloudTrailService.class);
private static final String EVENT_VERSION = "1.11";
private static final String S3_EVENT_SOURCE = "s3.amazonaws.com";
private final StorageBackend<String, CloudTrailEntry> store;
private final RegionResolver regionResolver;
private final IamService iamService;
private final ObjectMapper mapper;
/** Per-trail pending record buffers — ephemeral, never persisted. */
private final ConcurrentHashMap<TrailKey, ConcurrentLinkedQueue<ObjectNode>> pendingRecordsByTrail =
new ConcurrentHashMap<>();
@Inject
public CloudTrailService(StorageFactory storageFactory, RegionResolver regionResolver) {
this.trailStore = storageFactory.create("cloudtrail", "cloudtrail-trails.json",
new TypeReference<Map<String, CloudTrailTrail>>() {});
public CloudTrailService(StorageFactory storageFactory, RegionResolver regionResolver,
IamService iamService, ObjectMapper mapper) {
this.store = storageFactory.create("cloudtrail", "cloudtrail-trails.json",
new TypeReference<Map<String, CloudTrailEntry>>() {});
this.regionResolver = regionResolver;
this.iamService = iamService;
this.mapper = mapper;
}
public CloudTrailTrail createTrail(String region, String name, String s3BucketName,
boolean includeGlobalServiceEvents, boolean multiRegionTrail,
boolean organizationTrail, Map<String, String> tags) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidTrailNameException", "Trail name is required", 400);
}
if (trailStore.get(key(region, name)).isPresent()) {
throw new AwsException("TrailAlreadyExistsException", "Trail " + name + " already exists", 400);
}
// --- Control plane ---
CloudTrailTrail trail = new CloudTrailTrail();
Instant now = Instant.now();
trail.setName(name);
trail.setTrailArn(trailArn(region, name));
trail.setS3BucketName(s3BucketName);
trail.setIncludeGlobalServiceEvents(includeGlobalServiceEvents);
trail.setMultiRegionTrail(multiRegionTrail);
trail.setOrganizationTrail(organizationTrail);
trail.setHomeRegion(region);
trail.setCreated(now);
trail.setUpdated(now);
trail.setTags(tags == null ? Map.of() : tags);
trailStore.put(key(region, name), trail);
public Trail createTrail(String region, String name, String s3BucketName, String s3KeyPrefix,
String snsTopicArn, boolean includeGlobalServiceEvents,
boolean isMultiRegionTrail, boolean enableLogFileValidation,
boolean isOrganizationTrail) {
validateTrailName(name);
if (s3BucketName == null || s3BucketName.isEmpty()) {
throw new AwsException("S3BucketDoesNotExistException", "S3 bucket name is required.", 400);
}
String key = regionKey(region, name);
if (store.get(key).isPresent()) {
throw new AwsException("TrailAlreadyExistsException",
"Trail " + name + " already exists.", 400);
}
String arn = AwsArnUtils.Arn.of("cloudtrail", region, regionResolver.getAccountId(),
"trail/" + name).toString();
Trail trail = new Trail(
name, arn, s3BucketName, s3KeyPrefix, snsTopicArn,
includeGlobalServiceEvents, isMultiRegionTrail, region,
enableLogFileValidation, false, false, isOrganizationTrail);
store.put(key, new CloudTrailEntry(trail, List.of(), false, null, null));
return trail;
}
public CloudTrailTrail updateTrail(String region, String nameOrArn, String s3BucketName,
Boolean includeGlobalServiceEvents, Boolean multiRegionTrail) {
CloudTrailTrail trail = requireTrail(region, nameOrArn);
if (s3BucketName != null && !s3BucketName.isBlank()) {
trail.setS3BucketName(s3BucketName);
public void deleteTrail(String region, String trailNameOrArn) {
Trail trail = findTrailOrThrow(region, trailNameOrArn);
store.delete(regionKey(trail.homeRegion(), trail.name()));
pendingRecordsByTrail.keySet().removeIf(k -> k.trailName().equals(trail.name()));
}
public Trail updateTrail(String region, String trailNameOrArn,
String s3BucketName, String s3KeyPrefix, String snsTopicArn,
Boolean includeGlobalServiceEvents, Boolean isMultiRegionTrail,
Boolean enableLogFileValidation, Boolean isOrganizationTrail) {
Trail existing = findTrailOrThrow(region, trailNameOrArn);
Trail updated = new Trail(
existing.name(),
existing.trailArn(),
s3BucketName != null ? s3BucketName : existing.s3BucketName(),
s3KeyPrefix != null ? s3KeyPrefix : existing.s3KeyPrefix(),
snsTopicArn != null ? snsTopicArn : existing.snsTopicArn(),
includeGlobalServiceEvents != null ? includeGlobalServiceEvents : existing.includeGlobalServiceEvents(),
isMultiRegionTrail != null ? isMultiRegionTrail : existing.isMultiRegionTrail(),
existing.homeRegion(),
enableLogFileValidation != null ? enableLogFileValidation : existing.logFileValidationEnabled(),
existing.hasCustomEventSelectors(),
existing.hasInsightSelectors(),
isOrganizationTrail != null ? isOrganizationTrail : existing.isOrganizationTrail());
String key = regionKey(existing.homeRegion(), existing.name());
store.get(key).ifPresent(entry -> store.put(key, entry.withTrail(updated)));
return updated;
}
public List<Trail> describeTrails(String region, List<String> trailNameOrArnList) {
if (trailNameOrArnList == null || trailNameOrArnList.isEmpty()) {
List<Trail> results = new ArrayList<>();
for (String k : store.keys()) {
String trailRegion = regionFromKey(k);
CloudTrailEntry entry = store.get(k).orElse(null);
if (entry == null) continue;
Trail t = entry.trail();
if (trailRegion.equals(region) || t.isMultiRegionTrail()) {
results.add(t);
}
}
return results;
}
if (includeGlobalServiceEvents != null) {
trail.setIncludeGlobalServiceEvents(includeGlobalServiceEvents);
List<Trail> results = new ArrayList<>();
for (String nameOrArn : trailNameOrArnList) {
Trail t = findTrail(region, nameOrArn);
if (t != null) results.add(t);
}
if (multiRegionTrail != null) {
trail.setMultiRegionTrail(multiRegionTrail);
return results;
}
public List<EventSelector> putEventSelectors(String region, String trailNameOrArn, List<EventSelector> selectors) {
Trail trail = findTrailOrThrow(region, trailNameOrArn);
List<EventSelector> normalized = selectors == null ? List.of() : List.copyOf(selectors);
String key = regionKey(trail.homeRegion(), trail.name());
store.get(key).ifPresent(entry -> store.put(key, entry.withSelectors(normalized, true)));
return normalized;
}
public List<EventSelector> getEventSelectors(String region, String trailNameOrArn) {
Trail trail = findTrailOrThrow(region, trailNameOrArn);
return store.get(regionKey(trail.homeRegion(), trail.name()))
.map(e -> e.selectors() != null ? e.selectors() : List.<EventSelector>of())
.orElse(List.of());
}
public void startLogging(String region, String trailNameOrArn) {
Trail trail = findTrailOrThrow(region, trailNameOrArn);
String key = regionKey(trail.homeRegion(), trail.name());
store.get(key).ifPresent(entry -> store.put(key, entry.startLogging(System.currentTimeMillis())));
}
public void stopLogging(String region, String trailNameOrArn) {
Trail trail = findTrailOrThrow(region, trailNameOrArn);
String key = regionKey(trail.homeRegion(), trail.name());
store.get(key).ifPresent(entry -> store.put(key, entry.stopLogging(System.currentTimeMillis())));
}
public TrailStatus getTrailStatus(String region, String trailNameOrArn) {
Trail trail = findTrailOrThrow(region, trailNameOrArn);
return store.get(regionKey(trail.homeRegion(), trail.name()))
.map(e -> new TrailStatus(e.logging(), e.startLoggingTime(), e.stopLoggingTime()))
.orElse(new TrailStatus(false, null, null));
}
// --- Data plane: called by S3 (and other services) when an op happens ---
public void emitS3DataEvent(S3EventInput in) {
try {
String region = in.region() != null ? in.region() : regionResolver.getDefaultRegion();
List<MatchedTrail> matched = trailsMatching(region, in);
if (matched.isEmpty()) {
return;
}
ObjectNode record = buildS3Record(in);
for (MatchedTrail mt : matched) {
ObjectNode copy = record.deepCopy();
copy.put("recipientAccountId", regionResolver.getAccountId());
queueFor(new TrailKey(mt.region(), mt.trail().name(), region)).add(copy);
LOG.tracev("Emitted CloudTrail event {0} for trail {1}", in.eventName(), mt.trail().name());
}
} catch (Exception e) {
// Never let emission take down an S3 op.
LOG.warnv(e, "Failed to emit CloudTrail event for {0} {1}/{2}",
in.eventName(), in.bucketName(), in.key());
}
trail.setUpdated(Instant.now());
trailStore.put(key(trail.getHomeRegion(), trail.getName()), trail);
return trail;
}
public List<CloudTrailTrail> describeTrails(String region, List<String> namesOrArns) {
if (namesOrArns == null || namesOrArns.isEmpty()) {
return trailStore.scan(key -> key.startsWith(region + ":"));
public void requeueRecords(TrailKey key, List<ObjectNode> records) {
if (!records.isEmpty()) {
queueFor(key).addAll(records);
}
return namesOrArns.stream()
.map(nameOrArn -> findTrail(region, nameOrArn))
.flatMap(java.util.Optional::stream)
.toList();
}
public CloudTrailTrail requireTrail(String region, String nameOrArn) {
return findTrail(region, nameOrArn)
.orElseThrow(() -> new AwsException("TrailNotFoundException",
"Trail " + nameOrArn + " does not exist", 400));
}
public void startLogging(String region, String nameOrArn) {
CloudTrailTrail trail = requireTrail(region, nameOrArn);
trail.setLogging(true);
trail.setUpdated(Instant.now());
trailStore.put(key(trail.getHomeRegion(), trail.getName()), trail);
}
public void stopLogging(String region, String nameOrArn) {
CloudTrailTrail trail = requireTrail(region, nameOrArn);
trail.setLogging(false);
trail.setUpdated(Instant.now());
trailStore.put(key(trail.getHomeRegion(), trail.getName()), trail);
}
public void deleteTrail(String region, String nameOrArn) {
CloudTrailTrail trail = requireTrail(region, nameOrArn);
trailStore.delete(key(trail.getHomeRegion(), trail.getName()));
}
public void putEventSelectors(String region, String nameOrArn) {
requireTrail(region, nameOrArn);
}
private java.util.Optional<CloudTrailTrail> findTrail(String region, String nameOrArn) {
String name = nameFromNameOrArn(nameOrArn);
if (name == null || name.isBlank()) {
return java.util.Optional.empty();
public List<ObjectNode> drainPendingRecords(TrailKey key) {
ConcurrentLinkedQueue<ObjectNode> q = pendingRecordsByTrail.get(key);
if (q == null) return List.of();
List<ObjectNode> drained = new ArrayList<>();
ObjectNode r;
while ((r = q.poll()) != null) {
drained.add(r);
}
java.util.Optional<CloudTrailTrail> sameRegion = trailStore.get(key(region, name));
if (sameRegion.isPresent()) {
return sameRegion;
return drained;
}
public List<TrailKey> trailsWithPendingRecords() {
List<TrailKey> result = new ArrayList<>();
for (Map.Entry<TrailKey, ConcurrentLinkedQueue<ObjectNode>> e : pendingRecordsByTrail.entrySet()) {
if (!e.getValue().isEmpty()) {
result.add(e.getKey());
}
}
Predicate<String> candidateKey = nameOrArn.startsWith("arn:")
? ignored -> true
: key -> key.endsWith(":" + name);
return trailStore.scan(candidateKey).stream()
.filter(trail -> name.equals(trail.getName()) || nameOrArn.equals(trail.getTrailArn()))
.findFirst();
return result;
}
private String trailArn(String region, String name) {
return regionResolver.buildArn("cloudtrail", region, "trail/" + name);
public Trail getTrail(String region, String trailName) {
return store.get(regionKey(region, trailName))
.map(CloudTrailEntry::trail)
.orElse(null);
}
private static String key(String region, String name) {
private ConcurrentLinkedQueue<ObjectNode> queueFor(TrailKey key) {
return pendingRecordsByTrail.computeIfAbsent(key, k -> new ConcurrentLinkedQueue<>());
}
/**
* Identifies a pending-records queue.
* {@code region} is the trail's home region (used for trail store lookups).
* {@code eventRegion} is the region where the event occurred (used for the S3 delivery path).
* For single-region trails these are the same; for multi-region trails they differ.
*/
public record TrailKey(String region, String trailName, String eventRegion) {}
// --- Helpers ---
private List<MatchedTrail> trailsMatching(String region, S3EventInput in) {
List<MatchedTrail> result = new ArrayList<>();
for (String k : store.keys()) {
String trailRegion = regionFromKey(k);
boolean sameRegion = trailRegion.equals(region);
CloudTrailEntry entry = store.get(k).orElse(null);
if (entry == null) continue;
Trail trail = entry.trail();
if (!sameRegion && !trail.isMultiRegionTrail()) continue;
if (!entry.logging()) continue;
List<EventSelector> selectors = entry.selectors() != null ? entry.selectors() : List.of();
if (matchesAnySelector(selectors, in)) {
result.add(new MatchedTrail(trail, trailRegion));
}
}
return result;
}
private boolean matchesAnySelector(List<EventSelector> selectors, S3EventInput in) {
if (selectors.isEmpty()) {
return false;
}
boolean isRead = isReadOnlyEvent(in.eventName());
for (EventSelector sel : selectors) {
String rwt = sel.readWriteType() == null ? "All" : sel.readWriteType();
if ("ReadOnly".equalsIgnoreCase(rwt) && !isRead) continue;
if ("WriteOnly".equalsIgnoreCase(rwt) && isRead) continue;
List<DataResource> dataResources = sel.dataResources();
if (dataResources == null || dataResources.isEmpty()) {
continue;
}
for (DataResource dr : dataResources) {
if (!"AWS::S3::Object".equals(dr.type())) continue;
if (dr.values() == null) continue;
for (String v : dr.values()) {
if (matchesS3DataResourceArn(v, in.bucketName(), in.key())) {
return true;
}
}
}
}
return false;
}
// Package-private for unit testing.
static boolean matchesS3DataResourceArn(String configured, String bucketName, String key) {
if (configured == null) return false;
// "arn:aws:s3" (bare, no ":::") is shorthand for all buckets + all objects.
if (configured.equals("arn:aws:s3")) return true;
// Forms accepted:
// arn:aws:s3::: → all buckets, all keys
// arn:aws:s3:::* → all buckets (wildcard)
// arn:aws:s3:::bucket/ → all keys in bucket
// arn:aws:s3:::bucket/prefix → keys with the given prefix in bucket
// arn:aws:s3:::*/* → all objects (wildcard bucket + any key)
String prefix = "arn:aws:s3:::";
if (!configured.startsWith(prefix)) return false;
String tail = configured.substring(prefix.length());
if (tail.isEmpty() || tail.equals("/")) {
return true;
}
int slash = tail.indexOf('/');
if (slash < 0) {
return tail.equals("*") || tail.equals(bucketName);
}
String configBucket = tail.substring(0, slash);
if (!configBucket.equals("*") && !configBucket.equals(bucketName)) return false;
String configKeyPart = tail.substring(slash + 1);
if (configKeyPart.isEmpty()) {
return true;
}
if (configKeyPart.equals("*") || configKeyPart.equals("*/*")) {
return key != null;
}
if (key == null) return false;
return key.startsWith(configKeyPart);
}
// Package-private for unit testing.
static boolean isReadOnlyEvent(String eventName) {
if (eventName == null) return true;
return switch (eventName) {
case "GetObject", "HeadObject", "ListObjects", "ListObjectsV2",
"GetObjectAcl", "GetObjectTagging", "ListMultipartUploads" -> true;
default -> false;
};
}
private ObjectNode buildS3Record(S3EventInput in) {
ObjectNode record = mapper.createObjectNode();
record.put("eventVersion", EVENT_VERSION);
record.set("userIdentity", buildUserIdentity(in.accessKeyId()));
record.put("eventTime", DateTimeFormatter.ISO_INSTANT.format(
Instant.ofEpochMilli((in.eventTimeMillis() == 0L
? System.currentTimeMillis() : in.eventTimeMillis()))
.truncatedTo(java.time.temporal.ChronoUnit.SECONDS)));
record.put("eventSource", S3_EVENT_SOURCE);
record.put("eventName", in.eventName());
record.put("awsRegion", in.region());
record.put("sourceIPAddress", in.sourceIp() == null ? "127.0.0.1" : in.sourceIp());
record.put("userAgent", in.userAgent() == null ? "" : in.userAgent());
if (in.errorCode() != null) {
record.put("errorCode", in.errorCode());
if (in.errorMessage() != null) {
record.put("errorMessage", in.errorMessage());
}
}
ObjectNode reqParams = mapper.createObjectNode();
if (in.bucketName() != null) reqParams.put("bucketName", in.bucketName());
reqParams.put("Host", in.bucketName() == null
? "s3.amazonaws.com"
: in.bucketName() + ".s3.amazonaws.com");
if (in.key() != null) reqParams.put("key", in.key());
record.set("requestParameters", reqParams);
record.set("responseElements", mapper.nullNode());
ObjectNode addl = mapper.createObjectNode();
addl.put("SignatureVersion", "SigV4");
addl.put("CipherSuite", "TLS_AES_128_GCM_SHA256");
addl.put("bytesTransferredIn", in.bytesIn());
addl.put("AuthenticationMethod", "AuthHeader");
addl.put("bytesTransferredOut", in.bytesOut());
record.set("additionalEventData", addl);
record.put("requestID", UUID.randomUUID().toString().replace("-", "").substring(0, 16).toUpperCase());
record.put("eventID", UUID.randomUUID().toString());
record.put("readOnly", isReadOnlyEvent(in.eventName()));
if (in.bucketName() != null) {
ArrayNode resources = mapper.createArrayNode();
ObjectNode bucketRes = mapper.createObjectNode();
bucketRes.put("accountId", regionResolver.getAccountId());
bucketRes.put("type", "AWS::S3::Bucket");
bucketRes.put("ARN", "arn:aws:s3:::" + in.bucketName());
resources.add(bucketRes);
if (in.key() != null) {
ObjectNode objRes = mapper.createObjectNode();
objRes.put("type", "AWS::S3::Object");
objRes.put("ARN", "arn:aws:s3:::" + in.bucketName() + "/" + in.key());
resources.add(objRes);
}
record.set("resources", resources);
}
record.put("eventType", "AwsApiCall");
record.put("managementEvent", false);
record.put("eventCategory", "Data");
ObjectNode tls = mapper.createObjectNode();
tls.put("tlsVersion", "TLSv1.3");
tls.put("cipherSuite", "TLS_AES_128_GCM_SHA256");
tls.put("clientProvidedHostHeader", in.bucketName() == null
? "s3.amazonaws.com"
: in.bucketName() + ".s3.amazonaws.com");
record.set("tlsDetails", tls);
return record;
}
private ObjectNode buildUserIdentity(String accessKeyId) {
ObjectNode identity = mapper.createObjectNode();
String accountId = regionResolver.getAccountId();
if (accessKeyId == null || "test".equals(accessKeyId)) {
identity.put("type", "IAMUser");
identity.put("principalId", "AIDA" + repeat('A', 17));
identity.put("arn", "arn:aws:iam::" + accountId + ":root");
identity.put("accountId", accountId);
identity.put("accessKeyId", accessKeyId == null ? "" : accessKeyId);
identity.put("userName", "root");
return identity;
}
AccessKey key = iamService.findAccessKey(accessKeyId).orElse(null);
if (key != null) {
IamUser user = iamService.findUser(key.getUserName()).orElse(null);
if (user != null) {
identity.put("type", "IAMUser");
identity.put("principalId", user.getUserId());
identity.put("arn", user.getArn());
identity.put("accountId", accountId);
identity.put("accessKeyId", accessKeyId);
identity.put("userName", user.getUserName());
return identity;
}
}
identity.put("type", "IAMUser");
identity.put("principalId", "AIDA" + repeat('A', 17));
identity.put("arn", "arn:aws:iam::" + accountId + ":user/anonymous");
identity.put("accountId", accountId);
identity.put("accessKeyId", accessKeyId);
identity.put("userName", "anonymous");
return identity;
}
private static String repeat(char c, int n) {
char[] arr = new char[n];
java.util.Arrays.fill(arr, c);
return new String(arr);
}
private Trail findTrail(String region, String nameOrArn) {
// ARN → cross-region scan is valid (callers use ARN to target another Region)
if (nameOrArn != null && nameOrArn.startsWith("arn:")) {
for (String k : store.keys()) {
CloudTrailEntry entry = store.get(k).orElse(null);
if (entry == null) continue;
if (nameOrArn.equals(entry.trail().trailArn())) {
return entry.trail();
}
}
return null;
}
// Name → region-scoped only (AWS resolves a name only in the current Region)
return store.get(regionKey(region, nameOrArn))
.map(CloudTrailEntry::trail)
.orElse(null);
}
private Trail findTrailOrThrow(String region, String nameOrArn) {
Trail t = findTrail(region, nameOrArn);
if (t == null) {
throw new AwsException("TrailNotFoundException",
"Unknown trail: " + nameOrArn, 400);
}
return t;
}
private static void validateTrailName(String name) {
if (name == null || name.isEmpty()) {
throw new AwsException("InvalidTrailNameException", "Trail name is required.", 400);
}
if (name.length() < 3) {
throw new AwsException("InvalidTrailNameException",
"Trail name too short. Minimum allowed length: 3 characters.", 400);
}
if (name.length() > 128) {
throw new AwsException("InvalidTrailNameException",
"Trail name too long. Maximum allowed length: 128 characters.", 400);
}
if (!Character.isLetterOrDigit(name.charAt(0))) {
throw new AwsException("InvalidTrailNameException",
"Trail name must starts with a letter or number.", 400);
}
if (!Character.isLetterOrDigit(name.charAt(name.length() - 1))) {
throw new AwsException("InvalidTrailNameException",
"Trail name must end with a letter or number.", 400);
}
for (char c : name.toCharArray()) {
if (!Character.isLetterOrDigit(c) && c != '.' && c != '_' && c != '-') {
throw new AwsException("InvalidTrailNameException",
"Trail name must only contain letters, numbers, periods, underscores, and hyphens.", 400);
}
}
}
private static String regionKey(String region, String name) {
return region + ":" + name;
}
private static String nameFromNameOrArn(String nameOrArn) {
if (nameOrArn == null) {
return null;
private static String regionFromKey(String key) {
int colon = key.indexOf(':');
return colon < 0 ? key : key.substring(0, colon);
}
public record TrailStatus(boolean logging, Long startLoggingTime, Long stopLoggingTime) {}
private record MatchedTrail(Trail trail, String region) {}
/** Input describing a single S3 op for emission. Use the builder for clarity. */
public record S3EventInput(
String region,
String eventName,
String bucketName,
String key,
String accessKeyId,
String sourceIp,
String userAgent,
long bytesIn,
long bytesOut,
String errorCode,
String errorMessage,
long eventTimeMillis) {
public static Builder builder() { return new Builder(); }
public static final class Builder {
private String region;
private String eventName;
private String bucketName;
private String key;
private String accessKeyId;
private String sourceIp;
private String userAgent;
private long bytesIn;
private long bytesOut;
private String errorCode;
private String errorMessage;
private long eventTimeMillis;
public Builder region(String v) { this.region = v; return this; }
public Builder eventName(String v) { this.eventName = v; return this; }
public Builder bucketName(String v) { this.bucketName = v; return this; }
public Builder key(String v) { this.key = v; return this; }
public Builder accessKeyId(String v) { this.accessKeyId = v; return this; }
public Builder sourceIp(String v) { this.sourceIp = v; return this; }
public Builder userAgent(String v) { this.userAgent = v; return this; }
public Builder bytesIn(long v) { this.bytesIn = v; return this; }
public Builder bytesOut(long v) { this.bytesOut = v; return this; }
public Builder errorCode(String v) { this.errorCode = v; return this; }
public Builder errorMessage(String v) { this.errorMessage = v; return this; }
public Builder eventTimeMillis(long v) { this.eventTimeMillis = v; return this; }
public S3EventInput build() {
return new S3EventInput(region, eventName, bucketName, key, accessKeyId,
sourceIp, userAgent, bytesIn, bytesOut,
errorCode, errorMessage, eventTimeMillis);
}
}
int slash = nameOrArn.lastIndexOf('/');
return slash >= 0 ? nameOrArn.substring(slash + 1) : nameOrArn;
}
}
@@ -0,0 +1,16 @@
package io.github.hectorvent.floci.services.cloudtrail.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public record DataResource(
@JsonProperty("Type") String type,
@JsonProperty("Values") List<String> values) {
}
@@ -0,0 +1,18 @@
package io.github.hectorvent.floci.services.cloudtrail.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public record EventSelector(
@JsonProperty("ReadWriteType") String readWriteType,
@JsonProperty("IncludeManagementEvents") Boolean includeManagementEvents,
@JsonProperty("DataResources") List<DataResource> dataResources,
@JsonProperty("ExcludeManagementEventSources") List<String> excludeManagementEventSources) {
}
@@ -0,0 +1,24 @@
package io.github.hectorvent.floci.services.cloudtrail.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public record Trail(
@JsonProperty("Name") String name,
@JsonProperty("TrailARN") String trailArn,
@JsonProperty("S3BucketName") String s3BucketName,
@JsonProperty("S3KeyPrefix") String s3KeyPrefix,
@JsonProperty("SnsTopicARN") String snsTopicArn,
@JsonProperty("IncludeGlobalServiceEvents") boolean includeGlobalServiceEvents,
@JsonProperty("IsMultiRegionTrail") boolean isMultiRegionTrail,
@JsonProperty("HomeRegion") String homeRegion,
@JsonProperty("LogFileValidationEnabled") boolean logFileValidationEnabled,
@JsonProperty("HasCustomEventSelectors") boolean hasCustomEventSelectors,
@JsonProperty("HasInsightSelectors") boolean hasInsightSelectors,
@JsonProperty("IsOrganizationTrail") boolean isOrganizationTrail) {
}
@@ -62,6 +62,10 @@ final class AwsManagedPolicies {
"Allows write permissions to the AWS X-Ray daemon."),
new ManagedPolicyDef("AmazonElasticFileSystemClientFullAccess", "/",
"Provides root client access to an Amazon EFS file system."),
new ManagedPolicyDef("AWSCloudTrail_FullAccess", "/",
"Provides full access to AWS CloudTrail."),
new ManagedPolicyDef("AWSCloudTrail_ReadOnlyAccess", "/",
"Provides read-only access to AWS CloudTrail."),
// Lambda execution role policies
new ManagedPolicyDef("AWSLambdaBasicExecutionRole", "/service-role/",
@@ -134,6 +134,18 @@ public class IamActionRegistry {
String path = ctx.getUriInfo().getPath();
if (!path.startsWith("/")) path = "/" + path;
// S3 sub-resource override: the URL path alone doesn't distinguish
// s3:GetObjectAcl / s3:PutObjectAcl from s3:GetObject / s3:PutObject
// — only the {@code ?acl} query parameter does. Without this hook,
// an actor with s3:GetObject permission could read ACLs that their
// policy intends to forbid.
if ("s3".equals(credentialScope)) {
String s3SubAction = resolveS3SubResourceAction(method, ctx);
if (s3SubAction != null) {
return s3SubAction;
}
}
for (ActionRule rule : RULES) {
if (rule.service().equals(credentialScope)
&& rule.method().equals(method)
@@ -146,6 +158,57 @@ public class IamActionRegistry {
return null;
}
/**
* Resolves S3 sub-resource ops (ACL, tagging, retention, etc.) that
* cannot be distinguished from the parent op by HTTP method + path alone.
* Returns null when no sub-resource is present so the caller falls back
* to the standard rule table.
*/
private static String resolveS3SubResourceAction(String method, ContainerRequestContext ctx) {
var params = ctx.getUriInfo().getQueryParameters();
boolean acl = params.containsKey("acl");
boolean tagging = params.containsKey("tagging");
if (!acl && !tagging) {
return null;
}
// /{bucket}?acl → bucket-level; /{bucket}/{key}?acl → object-level
String path = ctx.getUriInfo().getPath();
// Strip leading slash, then check whether there is a key segment after the bucket.
// A trailing slash is a valid key character, so /bucket/folder/?acl is an object
// request — we cannot use endsWith("/") to infer bucket-level.
String stripped = path.startsWith("/") ? path.substring(1) : path;
int firstSlash = stripped.indexOf('/');
boolean isBucketLevel = firstSlash < 0 || firstSlash == stripped.length() - 1;
if (acl) {
if (isBucketLevel) {
return switch (method) {
case "GET" -> "s3:GetBucketAcl";
case "PUT" -> "s3:PutBucketAcl";
default -> null;
};
}
return switch (method) {
case "GET" -> "s3:GetObjectAcl";
case "PUT" -> "s3:PutObjectAcl";
default -> null;
};
}
if (isBucketLevel) {
return switch (method) {
case "GET" -> "s3:GetBucketTagging";
case "PUT" -> "s3:PutBucketTagging";
case "DELETE" -> "s3:DeleteBucketTagging";
default -> null;
};
}
return switch (method) {
case "GET" -> "s3:GetObjectTagging";
case "PUT" -> "s3:PutObjectTagging";
case "DELETE" -> "s3:DeleteObjectTagging";
default -> null;
};
}
/**
* Reads {@code Action} from a {@code application/x-www-form-urlencoded}
* request body and restores the entity stream so downstream consumers
@@ -965,6 +965,14 @@ public class IamService implements SessionAccountLookup {
return findSessionAnyAccount(accessKeyId).map(SessionCredential::getSecretAccessKey);
}
public Optional<AccessKey> findAccessKey(String accessKeyId) {
return accessKeys.get(accessKeyId);
}
public Optional<IamUser> findUser(String userName) {
return users.get(userName);
}
// =========================================================================
// IAM Enforcement — session tracking and policy collection
// =========================================================================
@@ -2,12 +2,15 @@ package io.github.hectorvent.floci.services.s3;
import static io.github.hectorvent.floci.services.s3.S3RequestParser.hasQueryParam;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
import io.github.hectorvent.floci.services.sns.SnsQueryHandler;
import io.github.hectorvent.floci.services.s3.model.Bucket;
import io.github.hectorvent.floci.services.s3.model.GetObjectAttributesParts;
@@ -93,19 +96,76 @@ public class S3Controller {
private final SnsQueryHandler snsQueryHandler;
private final io.quarkus.vertx.http.runtime.CurrentVertxRequest currentVertxRequest;
private final io.github.hectorvent.floci.services.floci.ui.UiPages uiPages;
private final CloudTrailService cloudTrailService;
private final AccountResolver accountResolver;
private final RequestContext requestContext;
@Inject
public S3Controller(S3Service s3Service, S3SelectService s3SelectService,
RegionResolver regionResolver,
SnsQueryHandler snsQueryHandler,
io.quarkus.vertx.http.runtime.CurrentVertxRequest currentVertxRequest,
io.github.hectorvent.floci.services.floci.ui.UiPages uiPages) {
io.github.hectorvent.floci.services.floci.ui.UiPages uiPages,
CloudTrailService cloudTrailService,
AccountResolver accountResolver,
RequestContext requestContext) {
this.s3Service = s3Service;
this.s3SelectService = s3SelectService;
this.regionResolver = regionResolver;
this.snsQueryHandler = snsQueryHandler;
this.currentVertxRequest = currentVertxRequest;
this.uiPages = uiPages;
this.cloudTrailService = cloudTrailService;
this.accountResolver = accountResolver;
this.requestContext = requestContext;
}
private void emitCloudTrailEvent(String eventName, String bucket, String key,
long bytesIn, long bytesOut,
String errorCode, String errorMessage) {
try {
String authHeader = null;
String userAgent = null;
String sourceIp = null;
try {
var ctx = currentVertxRequest.getCurrent();
if (ctx != null) {
var req = ctx.request();
if (req != null) {
authHeader = req.getHeader("Authorization");
userAgent = req.getHeader("User-Agent");
String fwd = req.getHeader("X-Forwarded-For");
if (fwd != null && !fwd.isBlank()) {
int comma = fwd.indexOf(',');
sourceIp = (comma > 0 ? fwd.substring(0, comma) : fwd).trim();
} else if (req.remoteAddress() != null) {
sourceIp = req.remoteAddress().host();
}
}
}
} catch (Exception e) {
LOG.tracev(e, "CloudTrail: could not extract request context for S3 event {0}/{1}", bucket, key);
}
String akid = accountResolver.extractAccessKeyId(authHeader);
String region = requestContext.getRegion() != null
? requestContext.getRegion() : regionResolver.getDefaultRegion();
cloudTrailService.emitS3DataEvent(CloudTrailService.S3EventInput.builder()
.region(region)
.eventName(eventName)
.bucketName(bucket)
.key(key)
.accessKeyId(akid)
.sourceIp(sourceIp)
.userAgent(userAgent)
.bytesIn(bytesIn)
.bytesOut(bytesOut)
.errorCode(errorCode)
.errorMessage(errorMessage)
.eventTimeMillis(System.currentTimeMillis())
.build());
} catch (Exception e) {
LOG.tracev(e, "CloudTrail event emission failed for {0} {1}/{2}", eventName, bucket, key);
}
}
// --- Bucket operations ---
@@ -516,8 +576,11 @@ public class S3Controller {
}
}
xml.end("ListBucketResult");
return Response.ok(xml.build()).build();
String body = xml.build();
emitCloudTrailEvent("ListObjects", bucket, null, 0L, body.length(), null, null);
return Response.ok(body).build();
} catch (AwsException e) {
emitCloudTrailEvent("ListObjects", bucket, null, 0L, 0L, e.getErrorCode(), e.getMessage());
return xmlErrorResponse(e);
}
}
@@ -634,8 +697,10 @@ public class S3Controller {
resp.header("x-amz-version-id", obj.getVersionId());
}
appendPutObjectResponseHeaders(resp, obj);
emitCloudTrailEvent("PutObject", bucket, key, data == null ? 0 : data.length, 0L, null, null);
return resp.build();
} catch (AwsException e) {
emitCloudTrailEvent("PutObject", bucket, key, 0L, 0L, e.getErrorCode(), e.getMessage());
return xmlErrorResponse(e);
}
}
@@ -690,7 +755,15 @@ public class S3Controller {
}
if (hasQueryParam(uriInfo, "acl")) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAcl", authorization);
return Response.ok(s3Service.getObjectAcl(bucket, key, versionId)).build();
try {
String aclXml = s3Service.getObjectAcl(bucket, key, versionId);
emitCloudTrailEvent("GetObjectAcl", bucket, key, 0L,
aclXml == null ? 0L : aclXml.length(), null, null);
return Response.ok(aclXml).build();
} catch (AwsException e) {
emitCloudTrailEvent("GetObjectAcl", bucket, key, 0L, 0L, e.getErrorCode(), e.getMessage());
return xmlErrorResponse(e);
}
}
if (hasQueryParam(uriInfo, "attributes")) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAttributes", authorization);
@@ -728,8 +801,10 @@ public class S3Controller {
return handleRangeRequest(bucket, key, versionId, obj, rangeHeader, overrides, includeChecksum);
}
emitCloudTrailEvent("GetObject", bucket, key, 0L, obj.getSize(), null, null);
return fullObjectResponse(bucket, key, versionId, obj, overrides, includeChecksum);
} catch (AwsException e) {
emitCloudTrailEvent("GetObject", bucket, key, 0L, 0L, e.getErrorCode(), e.getMessage());
if (isWebsiteErrorDocumentTrigger(e) && isWebsiteRequest(httpHeaders)) {
try {
WebsiteConfiguration webConfig = s3Service.getBucketWebsite(bucket);
@@ -913,8 +988,10 @@ public class S3Controller {
}
boolean includeChecksum = "ENABLED".equalsIgnoreCase(checksumMode);
appendObjectHeaders(resp, obj, overrides, includeChecksum);
emitCloudTrailEvent("HeadObject", bucket, key, 0L, obj.getSize(), null, null);
return resp.build();
} catch (AwsException e) {
emitCloudTrailEvent("HeadObject", bucket, key, 0L, 0L, e.getErrorCode(), e.getMessage());
return xmlErrorResponse(e);
}
}
@@ -1020,8 +1097,10 @@ public class S3Controller {
}
resp.header("x-amz-version-id", result.getVersionId());
}
emitCloudTrailEvent("DeleteObject", bucket, key, 0L, 0L, null, null);
return resp.build();
} catch (AwsException e) {
emitCloudTrailEvent("DeleteObject", bucket, key, 0L, 0L, e.getErrorCode(), e.getMessage());
return xmlErrorResponse(e);
}
}