feat(secretsmanager): publish secret write events through CloudTrail (#6623)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-30 07:27:51 -04:00
1 parent fb1d2d1fdb
commit 57c4a20dde
14 files changed
+1278 -16

No files matched your search

@@ -33,9 +33,11 @@ import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
@@ -407,6 +409,43 @@ public class CloudTrailService {
// --- Data plane: called by S3 (and other services) when an op happens ---
public record ManagementEventInput(String eventSource, String eventName, String region, String accessKeyId,
ObjectNode requestParameters, ObjectNode responseElements) {}
/** Records one management write and returns the event only when a logging trail selects it. */
public Optional<ObjectNode> emitManagementEvent(ManagementEventInput in) {
try {
String region = in.region() != null ? in.region() : regionResolver.getDefaultRegion();
ObjectNode record = mapper.createObjectNode();
record.put("eventVersion", EVENT_VERSION);
record.put("eventTime", Instant.now().toString());
record.put("eventSource", in.eventSource());
record.put("eventName", in.eventName());
record.put("awsRegion", region);
record.put("recipientAccountId", regionResolver.getAccountId());
record.put("eventType", "AwsApiCall");
record.put("eventCategory", "Management");
record.put("managementEvent", true);
record.put("readOnly", false);
record.put("eventID", UUID.randomUUID().toString());
record.put("requestID", UUID.randomUUID().toString());
record.set("userIdentity", buildUserIdentity(in.accessKeyId()));
record.set("requestParameters", in.requestParameters().deepCopy());
record.set("responseElements", in.responseElements().deepCopy());
List<MatchedTrail> matched = trailsMatching(region, entry -> matchesManagementEvent(entry, record));
if (matched.isEmpty()) {
return Optional.empty();
}
for (MatchedTrail trail : matched) {
append(new TrailKey(trail.region(), trail.trail().name(), region), record.deepCopy());
}
return Optional.of(record);
} catch (RuntimeException e) {
LOG.warnv(e, "Failed to record CloudTrail management event {0}", in.eventName());
return Optional.empty();
}
}
public void emitS3DataEvent(S3EventInput in) {
try {
String region = in.region() != null ? in.region() : regionResolver.getDefaultRegion();
@@ -680,6 +719,15 @@ public class CloudTrailService {
// --- Helpers ---
private List<MatchedTrail> trailsMatching(String region, S3EventInput in) {
return trailsMatching(region, entry -> {
List<AdvancedEventSelector> advanced = entry.advancedSelectors();
return advanced != null && !advanced.isEmpty()
? matchesAnyAdvancedSelector(advanced, in)
: matchesAnySelector(entry.selectors() != null ? entry.selectors() : List.of(), in);
});
}
private List<MatchedTrail> trailsMatching(String region, Predicate<CloudTrailEntry> matches) {
List<MatchedTrail> result = new ArrayList<>();
for (String k : store.keys()) {
String trailRegion = regionFromKey(k);
@@ -698,22 +746,41 @@ public class CloudTrailService {
if (!entry.logging()) {
continue;
}
List<AdvancedEventSelector> advancedSelectors =
entry.advancedSelectors() != null ? entry.advancedSelectors() : List.of();
boolean matched;
if (!advancedSelectors.isEmpty()) {
matched = matchesAnyAdvancedSelector(advancedSelectors, in);
} else {
List<EventSelector> selectors = entry.selectors() != null ? entry.selectors() : List.of();
matched = matchesAnySelector(selectors, in);
}
if (matched) {
if (matches.test(entry)) {
result.add(new MatchedTrail(trail, trailRegion));
}
}
return result;
}
private boolean matchesManagementEvent(CloudTrailEntry entry, ObjectNode record) {
List<AdvancedEventSelector> advanced = entry.advancedSelectors();
if (advanced != null && !advanced.isEmpty()) {
return advanced.stream().anyMatch(selector -> selector.fieldSelectors() != null
&& !selector.fieldSelectors().isEmpty()
&& selector.fieldSelectors().stream().allMatch(field -> matchesManagementField(field, record)));
}
List<EventSelector> selectors = entry.selectors();
if (selectors == null || selectors.isEmpty()) {
return !entry.trail().hasCustomEventSelectors();
}
return selectors.stream().anyMatch(selector -> !Boolean.FALSE.equals(selector.includeManagementEvents())
&& (selector.readWriteType() == null || "All".equalsIgnoreCase(selector.readWriteType())
|| "WriteOnly".equalsIgnoreCase(selector.readWriteType()))
&& (selector.excludeManagementEventSources() == null
|| !selector.excludeManagementEventSources().contains(record.path("eventSource").asText())));
}
private static boolean matchesManagementField(AdvancedFieldSelector field, ObjectNode record) {
String value = switch (field.field()) {
case "eventCategory", "eventSource", "eventName", "readOnly", "eventType" ->
record.path(field.field()).asText();
case "userIdentity.arn" -> record.path("userIdentity").path("arn").asText();
default -> null;
};
return matchesFieldValue(field, value);
}
private boolean matchesAnySelector(List<EventSelector> selectors, S3EventInput in) {
if (selectors.isEmpty()) {
return false;
@@ -777,6 +844,10 @@ public class CloudTrailService {
case "resources.ARN" -> s3ObjectArn;
default -> null;
};
return matchesFieldValue(fs, value);
}
private static boolean matchesFieldValue(AdvancedFieldSelector fs, String value) {
if (value == null) {
return false;
}
@@ -0,0 +1,180 @@
package io.github.hectorvent.floci.services.secretsmanager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/** Emits successful secret API writes, without copying credential-bearing request bodies. */
@ApplicationScoped
public class SecretsManagerEventPublisher implements Resettable {
private static final Logger LOG = Logger.getLogger(SecretsManagerEventPublisher.class);
private static final long RESET_DRAIN_TIMEOUT_SECONDS = 30;
private final CloudTrailService cloudTrail;
private final EventBridgeService eventBridge;
private final AccountResolver accounts;
private final ObjectMapper mapper;
private final Executor deliveries;
private final Object deliveryLock = new Object();
private long generation;
private int activeDeliveries;
private boolean paused;
private boolean stopped;
@Inject
public SecretsManagerEventPublisher(CloudTrailService cloudTrail, EventBridgeService eventBridge,
AccountResolver accounts, ObjectMapper mapper) {
this(cloudTrail, eventBridge, accounts, mapper, new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(256),
Thread.ofPlatform().daemon().name("secret-event-publisher-", 0).factory(),
new ThreadPoolExecutor.AbortPolicy()));
}
SecretsManagerEventPublisher(CloudTrailService cloudTrail, EventBridgeService eventBridge,
AccountResolver accounts, ObjectMapper mapper, Executor deliveries) {
this.cloudTrail = cloudTrail;
this.eventBridge = eventBridge;
this.accounts = accounts;
this.mapper = mapper;
this.deliveries = deliveries;
}
@PreDestroy
void shutdown() {
synchronized (deliveryLock) {
stopped = true;
paused = true;
discardPending();
}
if (deliveries instanceof ExecutorService executorService) {
executorService.shutdownNow();
}
}
@Override
public void beforeReset() {
synchronized (deliveryLock) {
paused = true;
discardPending();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(RESET_DRAIN_TIMEOUT_SECONDS);
while (activeDeliveries > 0) {
long remaining = deadline - System.nanoTime();
if (remaining <= 0) {
throw new IllegalStateException("Secrets Manager event deliveries did not drain before reset");
}
try {
TimeUnit.NANOSECONDS.timedWait(deliveryLock, remaining);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while draining Secrets Manager events before reset", e);
}
}
}
}
@Override
public void clear() {
synchronized (deliveryLock) {
discardPending();
}
}
@Override
public void afterReset() {
synchronized (deliveryLock) {
if (!stopped) {
paused = false;
}
}
}
private void discardPending() {
generation++;
if (deliveries instanceof ThreadPoolExecutor executor) {
executor.getQueue().clear();
}
}
public void secretWritten(String action, JsonNode request, JsonNode response, String region, String authorization) {
synchronized (deliveryLock) {
if (paused || stopped) {
LOG.warnv("Dropped Secrets Manager {0} event while publisher is {1}",
action, stopped ? "stopped" : "resetting");
return;
}
try {
ObjectNode parameters = mapper.createObjectNode();
copy(request, parameters, "SecretId", "secretId");
copy(request, parameters, "ClientRequestToken", "clientRequestToken");
copy(request, parameters, "VersionStages", "versionStages");
copy(request, parameters, "KmsKeyId", "kmsKeyId");
ObjectNode result = mapper.createObjectNode();
copy(response, result, "ARN", "arn");
copy(response, result, "Name", "name");
copy(response, result, "VersionId", "versionId");
cloudTrail.emitManagementEvent(new CloudTrailService.ManagementEventInput(
ServicePrincipals.of("secretsmanager"), action, region,
accounts.extractAccessKeyId(authorization), parameters, result)).ifPresent(record ->
queueEvent(action, record, result.path("arn").asText()));
} catch (RuntimeException e) {
// The API write is already committed. Notification failures must not turn it into a failed write.
LOG.warnv(e, "Failed to publish Secrets Manager {0} event", action);
}
}
}
private void queueEvent(String action, ObjectNode record, String secretArn) {
String accountId = record.path("recipientAccountId").asText();
String region = record.path("awsRegion").asText();
String detail = record.toString();
long eventGeneration = generation;
deliveries.execute(() -> {
synchronized (deliveryLock) {
if (paused || stopped || eventGeneration != generation) {
return;
}
activeDeliveries++;
}
try {
RequestScopes.runAs(accountId, region, () -> eventBridge.publishServiceEvent(
"aws.secretsmanager", "AWS API Call via CloudTrail", detail, secretArn, region));
} catch (RuntimeException e) {
LOG.warnv(e, "Failed to deliver Secrets Manager {0} event", action);
} finally {
synchronized (deliveryLock) {
activeDeliveries--;
deliveryLock.notifyAll();
}
}
});
}
private static void copy(JsonNode source, ObjectNode target, String from, String to) {
JsonNode value = source.path(from);
if (value.isTextual()) {
target.put(to, value.asText());
} else if ("VersionStages".equals(from) && value.isArray()) {
value.forEach(stage -> {
if (stage.isTextual()) {
target.withArray(to).add(stage.asText());
}
});
}
}
}
@@ -35,13 +35,16 @@ public class SecretsManagerJsonHandler {
private final SecretsManagerService service;
private final ObjectMapper objectMapper;
private final IamEnforcementFilter iamEnforcementFilter;
private final SecretsManagerEventPublisher eventPublisher;
@Inject
public SecretsManagerJsonHandler(SecretsManagerService service, ObjectMapper objectMapper,
IamEnforcementFilter iamEnforcementFilter) {
IamEnforcementFilter iamEnforcementFilter,
SecretsManagerEventPublisher eventPublisher) {
this.service = service;
this.objectMapper = objectMapper;
this.iamEnforcementFilter = iamEnforcementFilter;
this.eventPublisher = eventPublisher;
}
/**
@@ -59,7 +62,7 @@ public class SecretsManagerJsonHandler {
* resource
*/
public Response handle(String action, JsonNode request, String region, String authorization) {
return switch (action) {
Response response = switch (action) {
case "CreateSecret" -> handleCreateSecret(request, region);
case "GetSecretValue" -> handleGetSecretValue(request, region);
case "PutSecretValue" -> handlePutSecretValue(request, region);
@@ -87,6 +90,10 @@ public class SecretsManagerJsonHandler {
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
.build();
};
if (response.getStatus() == 200 && ("PutSecretValue".equals(action) || "UpdateSecret".equals(action))) {
eventPublisher.secretWritten(action, request, (JsonNode) response.getEntity(), region, authorization);
}
return response;
}
private Response handleBatchGetSecretValue(JsonNode request, String region) {