mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(secretsmanager): publish secret write events through CloudTrail (#6623)
This commit is contained in:
1 parent
fb1d2d1fdb
commit
57c4a20dde
14 files changed
+1278
-16
No files matched your search
+82
@@ -0,0 +1,82 @@
|
||||
package com.floci.test;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudtrail.CloudTrailClient;
|
||||
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
|
||||
import software.amazon.awssdk.services.eventbridge.model.Target;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
import software.amazon.awssdk.services.sqs.model.Message;
|
||||
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("Secrets Manager API events through CloudTrail and EventBridge")
|
||||
class SecretsManagerEventBridgeTest {
|
||||
@Test
|
||||
@DisplayName("Actual SDK secret writes reach a secret-specific SQS rule without PutEvents fixtures")
|
||||
void secretWritesReachSqsThroughALoggingTrail() throws Exception {
|
||||
String name = TestFixtures.uniqueName("secret-events");
|
||||
try (SecretsManagerClient secrets = TestFixtures.secretsManagerClient();
|
||||
CloudTrailClient trails = TestFixtures.cloudTrailClient();
|
||||
EventBridgeClient events = TestFixtures.eventBridgeClient();
|
||||
SqsClient sqs = TestFixtures.sqsClient();
|
||||
S3Client s3 = TestFixtures.s3Client()) {
|
||||
s3.createBucket(r -> r.bucket(name));
|
||||
String queue = sqs.createQueue(r -> r.queueName(name)).queueUrl();
|
||||
String queueArn = sqs.getQueueAttributes(r -> r.queueUrl(queue)
|
||||
.attributeNames(QueueAttributeName.QUEUE_ARN)).attributes().get(QueueAttributeName.QUEUE_ARN);
|
||||
String secret = secrets.createSecret(r -> r.name(name).secretString("initial-example")).arn();
|
||||
trails.createTrail(r -> r.name(name).s3BucketName(name));
|
||||
events.putRule(r -> r.name(name).eventPattern("{\"source\":[\"aws.secretsmanager\"],"
|
||||
+ "\"detail-type\":[\"AWS API Call via CloudTrail\"],"
|
||||
+ "\"detail\":{\"responseElements\":{\"arn\":[\"" + secret + "\"]}}}"));
|
||||
events.putTargets(r -> r.rule(name).targets(Target.builder().id("queue").arn(queueArn).build()));
|
||||
try {
|
||||
trails.startLogging(r -> r.name(name));
|
||||
secrets.putSecretValue(r -> r.secretId(secret).secretString("sensitive-put-example"));
|
||||
secrets.updateSecret(r -> r.secretId(secret).secretString("sensitive-update-example"));
|
||||
secrets.getSecretValue(r -> r.secretId(secret));
|
||||
|
||||
List<Message> messages = new ArrayList<>();
|
||||
for (int attempt = 0; attempt < 5 && messages.size() < 2; attempt++) {
|
||||
messages.addAll(sqs.receiveMessage(r -> r.queueUrl(queue)
|
||||
.maxNumberOfMessages(10).waitTimeSeconds(1)).messages());
|
||||
}
|
||||
assertThat(messages).hasSize(2);
|
||||
List<String> actions = new ArrayList<>();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
for (Message message : messages) {
|
||||
JsonNode event = mapper.readTree(message.body());
|
||||
assertThat(event.path("source").asText()).isEqualTo("aws.secretsmanager");
|
||||
assertThat(event.path("detail-type").asText()).isEqualTo("AWS API Call via CloudTrail");
|
||||
assertThat(event.path("detail").path("responseElements").path("arn").asText()).isEqualTo(secret);
|
||||
assertThat(event.path("detail").path("managementEvent").asBoolean()).isTrue();
|
||||
assertThat(event.path("detail").path("readOnly").asBoolean()).isFalse();
|
||||
assertThat(message.body()).doesNotContain("sensitive-", "secretString", "secretBinary");
|
||||
actions.add(event.path("detail").path("eventName").asText());
|
||||
sqs.deleteMessage(r -> r.queueUrl(queue).receiptHandle(message.receiptHandle()));
|
||||
}
|
||||
assertThat(actions).containsExactlyInAnyOrder("PutSecretValue", "UpdateSecret");
|
||||
assertThat(sqs.receiveMessage(r -> r.queueUrl(queue).waitTimeSeconds(1)).messages()).isEmpty();
|
||||
} finally {
|
||||
trails.stopLogging(r -> r.name(name));
|
||||
trails.deleteTrail(r -> r.name(name));
|
||||
events.removeTargets(r -> r.rule(name).ids("queue"));
|
||||
events.deleteRule(r -> r.name(name));
|
||||
secrets.deleteSecret(r -> r.secretId(secret).forceDeleteWithoutRecovery(true));
|
||||
sqs.deleteQueue(r -> r.queueUrl(queue));
|
||||
s3.listObjectsV2(r -> r.bucket(name)).contents().forEach(object ->
|
||||
s3.deleteObject(r -> r.bucket(name).key(object.key())));
|
||||
s3.deleteBucket(r -> r.bucket(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@
|
||||
**Protocol:** JSON 1.1 (`X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.*`)
|
||||
**Endpoint:** `POST http://localhost:4566/`
|
||||
|
||||
Floci emulates a CloudTrail trail's full life cycle and emits S3 data
|
||||
events to the trail's destination bucket as gzipped JSON log files at the
|
||||
Floci emulates a CloudTrail trail's full life cycle and emits S3 data events
|
||||
and selected Secrets Manager management writes to the trail's destination bucket as gzipped JSON log files at the
|
||||
AWS-shaped key path:
|
||||
|
||||
```
|
||||
@@ -68,6 +68,23 @@ refused for a permission it needs besides its own, such as
|
||||
operation. A browser `POST` upload, whose credential is in its form fields, is
|
||||
recorded as `PostObject` when IAM refuses it.
|
||||
|
||||
## Management Write Coverage
|
||||
|
||||
Successful Secrets Manager `PutSecretValue` and `UpdateSecret` API calls produce management
|
||||
records when a logging trail selects them. New trails include management events by default.
|
||||
Basic selectors honor `IncludeManagementEvents`, `ReadWriteType`, and source exclusions.
|
||||
Advanced selectors evaluate `eventCategory`, `eventSource`, `eventName`, `readOnly`, `eventType`,
|
||||
and `userIdentity.arn`; unsupported fields do not match these records.
|
||||
|
||||
Records have `eventCategory: Management`, `managementEvent: true`, and `readOnly: false`.
|
||||
Sensitive secret values are omitted. Buffers and background S3 delivery retain the originating
|
||||
account, including when different accounts use the same trail name. Multi-region trails cover
|
||||
regions within their own partition.
|
||||
|
||||
These writes also reach EventBridge's default bus in the request's account and region. See
|
||||
[Secrets Manager event delivery](secrets-manager.md#secret-write-events) for prerequisites,
|
||||
the secret-specific event pattern, and the limits of this coverage.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
@@ -114,6 +114,11 @@ suffix when present. These checks do not verify resource existence or permission
|
||||
|
||||
EventBridge includes a default event bus (`default`) that accepts events from AWS services. Custom buses are for your own application events.
|
||||
|
||||
Secrets Manager `PutSecretValue` and `UpdateSecret` calls publish `AWS API Call via CloudTrail`
|
||||
events here when a logging CloudTrail trail selects management writes. See
|
||||
[secret write events](secrets-manager.md#secret-write-events) for the required trail configuration
|
||||
and a pattern matching `detail.responseElements.arn`.
|
||||
|
||||
```bash
|
||||
# List rules on the default bus
|
||||
aws events list-rules --endpoint-url $AWS_ENDPOINT_URL
|
||||
|
||||
@@ -33,6 +33,63 @@
|
||||
| `StopReplicationToReplica` | Promote a replica to a standalone primary |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
## Secret write events
|
||||
|
||||
Successful `PutSecretValue` and `UpdateSecret` API calls emit an EventBridge event with
|
||||
`source: aws.secretsmanager` and `detail-type: AWS API Call via CloudTrail`. A metadata-only
|
||||
`UpdateSecret` also emits an event. Delivery requires:
|
||||
|
||||
- A CloudTrail trail in the caller's account with logging started. A single-region trail must
|
||||
cover the request's region; a multi-region trail can cover other regions in its partition.
|
||||
- Management writes selected by that trail. New trails select management events by default.
|
||||
Basic selectors must include management events and allow `All` or `WriteOnly`. Advanced
|
||||
selectors must match the management event; data-only and read-only selectors do not qualify.
|
||||
- An enabled rule on the **default event bus**, in the secret's account and region, with an
|
||||
appropriate target. A custom bus receives these events only through an explicit forwarding rule.
|
||||
|
||||
Match a particular secret with this pattern, replacing the example ARN with the ARN returned
|
||||
by `CreateSecret`:
|
||||
|
||||
```json
|
||||
{
|
||||
"source": ["aws.secretsmanager"],
|
||||
"detail-type": ["AWS API Call via CloudTrail"],
|
||||
"detail": {
|
||||
"eventName": ["PutSecretValue", "UpdateSecret"],
|
||||
"responseElements": {
|
||||
"arn": ["arn:aws:secretsmanager:us-east-1:000000000000:secret:example-AbCdEf"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The lowercase `responseElements.arn` follows the current AWS CloudTrail format. Records include
|
||||
the operation, account, region, caller identity, secret name, and version ID when returned.
|
||||
Request metadata is restricted to the secret ID, client request token, version stages, and KMS
|
||||
key ID. Secret strings, binary values, descriptions, and unrecognized request fields are omitted
|
||||
from both EventBridge events and CloudTrail logs.
|
||||
|
||||
One event is published per successful API call even when several trails select it. Matching
|
||||
trails also buffer the same redacted record for their normal S3 log delivery. EventBridge target
|
||||
delivery is asynchronous and does not wait for the CloudTrail S3 flush interval.
|
||||
|
||||
Coverage is limited to these two successful API operations. Reads, failed writes, and internal
|
||||
service writes do not emit these API-call events. Native `Secret Label Updated` events and
|
||||
`RotationSucceeded` service events are separate contracts and are not generated by this hook.
|
||||
Event publication is best effort: a delivery failure does not fail the completed secret write.
|
||||
Publication runs on two background workers with a bounded queue of 256 pending events. Slow
|
||||
targets do not hold the secret-write response open. Each queued delivery restores the originating
|
||||
account and region. Notifications are dropped and logged when the queue is full or publication
|
||||
is paused or stopped. Pending notifications are in memory and are not retained across shutdown.
|
||||
|
||||
An emulator reset discards queued notifications and pauses new notifications. Active deliveries
|
||||
finish before storage is cleared, then publication resumes, including after a failed reset. If
|
||||
active deliveries cannot drain within 30 seconds, or draining is interrupted, reset fails before
|
||||
the storage wipe.
|
||||
|
||||
See AWS's [Secrets Manager event types](https://docs.aws.amazon.com/secretsmanager/latest/userguide/monitoring-eventbridge.html)
|
||||
and [CloudTrail event prerequisites](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-service-event-cloudtrail.html).
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
+81
-10
@@ -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;
|
||||
}
|
||||
|
||||
+180
@@ -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());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -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) {
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package io.github.hectorvent.floci.services.cloudtrail;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedEventSelector;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedFieldSelector;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class CloudTrailManagementEventTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "661100000002";
|
||||
private static final String SOURCE = "secretsmanager.amazonaws.com";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private CloudTrailService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
when(factory.create(anyString(), anyString(), any())).thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
service = new CloudTrailService(factory, new RegionResolver(REGION, ACCOUNT), mock(IamService.class), MAPPER);
|
||||
}
|
||||
|
||||
private void trail(boolean multiRegion) {
|
||||
service.createTrail(REGION, "management-trail", "example-audit-logs", null, null,
|
||||
false, multiRegion, false, false);
|
||||
}
|
||||
|
||||
private CloudTrailService.ManagementEventInput event(String region) {
|
||||
return new CloudTrailService.ManagementEventInput(SOURCE, "PutSecretValue", region, "test",
|
||||
MAPPER.createObjectNode().put("secretId", "example"),
|
||||
MAPPER.createObjectNode().put("arn", "arn:aws:secretsmanager:" + region + ":" + ACCOUNT + ":secret:example"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loggingIsRequiredAndTheDefaultSelectorIncludesManagementWrites() {
|
||||
assertTrue(service.emitManagementEvent(event(REGION)).isEmpty());
|
||||
trail(false);
|
||||
assertTrue(service.emitManagementEvent(event(REGION)).isEmpty());
|
||||
service.startLogging(REGION, "management-trail");
|
||||
ObjectNode record = service.emitManagementEvent(event(REGION)).orElseThrow();
|
||||
assertEquals("Management", record.path("eventCategory").asText());
|
||||
assertEquals("AwsApiCall", record.path("eventType").asText());
|
||||
assertEquals(ACCOUNT, record.path("recipientAccountId").asText());
|
||||
assertTrue(record.path("managementEvent").asBoolean());
|
||||
assertFalse(record.path("readOnly").asBoolean());
|
||||
assertEquals(1, service.pendingRecordCount(new CloudTrailService.TrailKey(REGION, "management-trail", REGION)));
|
||||
service.stopLogging(REGION, "management-trail");
|
||||
assertTrue(service.emitManagementEvent(event(REGION)).isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"All,true,true", "WriteOnly,true,true", "ReadOnly,true,false", "All,false,false"})
|
||||
void basicSelectorsRespectManagementAndWriteFilters(String mode, boolean management, boolean expected) {
|
||||
trail(false);
|
||||
service.startLogging(REGION, "management-trail");
|
||||
service.putEventSelectors(REGION, "management-trail",
|
||||
List.of(new EventSelector(mode, management, List.of(), List.of())));
|
||||
assertEquals(expected, service.emitManagementEvent(event(REGION)).isPresent());
|
||||
}
|
||||
|
||||
private static AdvancedFieldSelector equalsField(String field, String value) {
|
||||
return new AdvancedFieldSelector(field, List.of(value), null, null, null, null, null);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"eventCategory,Management,true", "eventCategory,Data,false", "eventSource,secretsmanager.amazonaws.com,true",
|
||||
"eventSource,kms.amazonaws.com,false", "eventName,PutSecretValue,true", "eventName,UpdateSecret,false",
|
||||
"readOnly,false,true", "readOnly,true,false", "eventType,AwsApiCall,true", "unknown,anything,false"})
|
||||
void advancedSelectorsEvaluateManagementFields(String field, String value, boolean expected) {
|
||||
trail(false);
|
||||
service.startLogging(REGION, "management-trail");
|
||||
service.putAdvancedEventSelectors(REGION, "management-trail", List.of(new AdvancedEventSelector("management",
|
||||
List.of(equalsField("eventCategory", "Management"), equalsField(field, value)))));
|
||||
assertEquals(expected, service.emitManagementEvent(event(REGION)).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void advancedExclusionsAndSourceExclusionsSuppressEvents() {
|
||||
trail(false);
|
||||
service.startLogging(REGION, "management-trail");
|
||||
service.putEventSelectors(REGION, "management-trail", List.of(new EventSelector("All", true, List.of(), List.of(SOURCE))));
|
||||
assertTrue(service.emitManagementEvent(event(REGION)).isEmpty());
|
||||
service.putAdvancedEventSelectors(REGION, "management-trail", List.of(new AdvancedEventSelector("excluded",
|
||||
List.of(equalsField("eventCategory", "Management"), new AdvancedFieldSelector("eventName", null,
|
||||
List.of("PutSecretValue"), null, null, null, null)))));
|
||||
assertTrue(service.emitManagementEvent(event(REGION)).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiRegionTrailsStayWithinTheirPartition() {
|
||||
trail(false);
|
||||
service.startLogging(REGION, "management-trail");
|
||||
assertTrue(service.emitManagementEvent(event("eu-west-1")).isEmpty());
|
||||
service.updateTrail(REGION, "management-trail", null, null, null, null, true, null, null);
|
||||
assertTrue(service.emitManagementEvent(event("eu-west-1")).isPresent());
|
||||
assertTrue(service.emitManagementEvent(event("cn-north-1")).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleTrailsRecordTheSameEventIdAndKeepIndependentCopies() {
|
||||
trail(false);
|
||||
service.createTrail(REGION, "another-trail", "example-audit-logs", null, null, false, false, false, false);
|
||||
service.startLogging(REGION, "management-trail");
|
||||
service.startLogging(REGION, "another-trail");
|
||||
ObjectNode returned = service.emitManagementEvent(event(REGION)).orElseThrow();
|
||||
String id = returned.path("eventID").asText();
|
||||
returned.put("eventName", "changed-by-caller");
|
||||
for (String name : List.of("management-trail", "another-trail")) {
|
||||
ObjectNode queued = service.drainPendingRecords(new CloudTrailService.TrailKey(REGION, name, REGION)).getFirst();
|
||||
assertEquals(id, queued.path("eventID").asText());
|
||||
assertEquals("PutSecretValue", queued.path("eventName").asText());
|
||||
}
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package io.github.hectorvent.floci.services.secretsmanager;
|
||||
|
||||
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.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.lifecycle.EmulatorInfoController;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class SecretsManagerEventPublisherResetTest {
|
||||
private static final String ACCOUNT = "661100000003";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ARN = "arn:aws:secretsmanager:us-east-1:661100000003:secret:example";
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final CloudTrailService trails = mock(CloudTrailService.class);
|
||||
private final EventBridgeService events = mock(EventBridgeService.class);
|
||||
private final StorageFactory storage = mock(StorageFactory.class);
|
||||
private final Deque<Runnable> queued = new ArrayDeque<>();
|
||||
private SecretsManagerEventPublisher publisher;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
publisher = new SecretsManagerEventPublisher(trails, events, new AccountResolver(ACCOUNT), mapper, queued::addLast);
|
||||
when(trails.emitManagementEvent(any())).thenAnswer(call -> {
|
||||
CloudTrailService.ManagementEventInput input = call.getArgument(0);
|
||||
return Optional.of(mapper.createObjectNode().put("recipientAccountId", ACCOUNT).put("awsRegion", REGION)
|
||||
.put("eventID", input.requestParameters().path("clientRequestToken").asText()));
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stop() {
|
||||
publisher.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuedEventsCannotReachRulesCreatedAfterReset() {
|
||||
write("before-reset");
|
||||
Runnable oldDelivery = queued.removeFirst();
|
||||
|
||||
controller().reset();
|
||||
oldDelivery.run();
|
||||
|
||||
verifyNoInteractions(events);
|
||||
write("after-reset");
|
||||
queued.removeFirst().run();
|
||||
verify(events).publishServiceEvent(eq("aws.secretsmanager"), eq("AWS API Call via CloudTrail"),
|
||||
contains("after-reset"), eq(ARN), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetDrainsActiveDeliveriesBeforeWipeDiscardsQueuedEventsAndReusesWorkers() throws Exception {
|
||||
publisher = new SecretsManagerEventPublisher(trails, events, new AccountResolver(ACCOUNT), mapper);
|
||||
CountDownLatch active = new CountDownLatch(2);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
CountDownLatch fresh = new CountDownLatch(1);
|
||||
List<String> stored = new CopyOnWriteArrayList<>();
|
||||
doAnswer(call -> {
|
||||
String id = mapper.readTree((String) call.getArgument(2)).path("eventID").asText();
|
||||
if (id.startsWith("active-")) {
|
||||
active.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS), "blocked targets must be released by the test");
|
||||
}
|
||||
stored.add(id);
|
||||
if ("after-reset".equals(id)) {
|
||||
fresh.countDown();
|
||||
}
|
||||
return null;
|
||||
}).when(events).publishServiceEvent(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
doAnswer(call -> { stored.clear(); return null; }).when(storage).clearAll();
|
||||
ExecutorService resets = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
write("active-first");
|
||||
write("active-second");
|
||||
assertTrue(active.await(5, TimeUnit.SECONDS));
|
||||
write("queued-before-reset");
|
||||
|
||||
Future<?> reset = resets.submit(() -> controller().reset());
|
||||
assertThrows(TimeoutException.class, () -> reset.get(200, TimeUnit.MILLISECONDS),
|
||||
"reset must wait for active target deliveries before wiping storage");
|
||||
verify(storage, never()).clearAll();
|
||||
release.countDown();
|
||||
reset.get(5, TimeUnit.SECONDS);
|
||||
assertTrue(stored.isEmpty(), "active deliveries must finish before their state is wiped");
|
||||
|
||||
write("after-reset");
|
||||
assertTrue(fresh.await(5, TimeUnit.SECONDS), "the same publisher must deliver new events after reset");
|
||||
assertEquals(List.of("after-reset"), stored);
|
||||
verify(events, times(3)).publishServiceEvent(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
} finally {
|
||||
release.countDown();
|
||||
resets.shutdownNow();
|
||||
assertTrue(resets.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void notificationsAreDroppedDuringWipeAndResumeAfterward() throws Exception {
|
||||
CountDownLatch wiping = new CountDownLatch(1);
|
||||
CountDownLatch finishWipe = new CountDownLatch(1);
|
||||
doAnswer(call -> {
|
||||
wiping.countDown();
|
||||
assertTrue(finishWipe.await(5, TimeUnit.SECONDS));
|
||||
return null;
|
||||
}).when(storage).clearAll();
|
||||
ExecutorService resets = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<?> reset = resets.submit(() -> controller().reset());
|
||||
assertTrue(wiping.await(5, TimeUnit.SECONDS));
|
||||
write("during-reset");
|
||||
assertTrue(queued.isEmpty(), "notifications must not enter the queue during the storage wipe");
|
||||
verifyNoInteractions(trails, events);
|
||||
finishWipe.countDown();
|
||||
reset.get(5, TimeUnit.SECONDS);
|
||||
write("after-reset");
|
||||
queued.removeFirst().run();
|
||||
verify(events).publishServiceEvent(anyString(), anyString(), contains("after-reset"), eq(ARN), eq(REGION));
|
||||
} finally {
|
||||
finishWipe.countDown();
|
||||
resets.shutdownNow();
|
||||
assertTrue(resets.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedStorageWipeStillDiscardsOldEventsAndResumesNotifications() {
|
||||
write("before-reset");
|
||||
Runnable oldDelivery = queued.removeFirst();
|
||||
doThrow(new IllegalStateException("example storage failure")).when(storage).clearAll();
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> controller().reset());
|
||||
oldDelivery.run();
|
||||
verifyNoInteractions(events);
|
||||
write("after-failed-reset");
|
||||
queued.removeFirst().run();
|
||||
verify(events).publishServiceEvent(anyString(), anyString(), contains("after-failed-reset"), eq(ARN), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void interruptedDrainRefusesTheWipeAndRestoresPublication() throws Exception {
|
||||
publisher = new SecretsManagerEventPublisher(trails, events, new AccountResolver(ACCOUNT), mapper);
|
||||
CountDownLatch active = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
CountDownLatch fresh = new CountDownLatch(1);
|
||||
doAnswer(call -> {
|
||||
if (((String) call.getArgument(2)).contains("active-before-reset")) {
|
||||
active.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
} else {
|
||||
fresh.countDown();
|
||||
}
|
||||
return null;
|
||||
}).when(events).publishServiceEvent(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
try {
|
||||
write("active-before-reset");
|
||||
assertTrue(active.await(5, TimeUnit.SECONDS));
|
||||
Thread.currentThread().interrupt();
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> controller().reset());
|
||||
assertInstanceOf(InterruptedException.class, failure.getCause());
|
||||
assertTrue(Thread.currentThread().isInterrupted());
|
||||
verify(storage, never()).clearAll();
|
||||
} finally {
|
||||
Thread.interrupted();
|
||||
release.countDown();
|
||||
}
|
||||
write("after-failed-reset");
|
||||
assertTrue(fresh.await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetCannotRestartAShutDownPublisher() {
|
||||
write("before-shutdown");
|
||||
Runnable oldDelivery = queued.removeFirst();
|
||||
publisher.shutdown();
|
||||
controller().reset();
|
||||
oldDelivery.run();
|
||||
write("after-shutdown");
|
||||
assertTrue(queued.isEmpty());
|
||||
verifyNoInteractions(events);
|
||||
}
|
||||
|
||||
private void write(String id) {
|
||||
ObjectNode request = mapper.createObjectNode().put("SecretId", ARN).put("ClientRequestToken", id);
|
||||
publisher.secretWritten("PutSecretValue", request, mapper.createObjectNode().put("ARN", ARN), REGION, null);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private EmulatorInfoController controller() {
|
||||
Instance<Resettable> services = mock(Instance.class);
|
||||
when(services.iterator()).thenAnswer(call -> Resettable.class.isInstance(publisher)
|
||||
? List.of(Resettable.class.cast(publisher)).iterator() : List.<Resettable>of().iterator());
|
||||
Instance<ContainerTeardown> teardowns = mock(Instance.class);
|
||||
when(teardowns.iterator()).thenAnswer(call -> List.<ContainerTeardown>of().iterator());
|
||||
return new EmulatorInfoController(null, null, storage, services, teardowns, null, null, null);
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package io.github.hectorvent.floci.services.secretsmanager;
|
||||
|
||||
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.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class SecretsManagerEventPublisherTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "661100000003";
|
||||
private static final String ARN = "arn:aws:secretsmanager:us-east-1:661100000003:secret:example";
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private CloudTrailService trails;
|
||||
private EventBridgeService events;
|
||||
private SecretsManagerEventPublisher publisher;
|
||||
private Deque<Runnable> deliveries;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
trails = mock(CloudTrailService.class);
|
||||
events = mock(EventBridgeService.class);
|
||||
AccountResolver accounts = mock(AccountResolver.class);
|
||||
when(accounts.extractAccessKeyId("signed-request")).thenReturn("example-access-key");
|
||||
deliveries = new ArrayDeque<>();
|
||||
publisher = new SecretsManagerEventPublisher(trails, events, accounts, mapper, deliveries::addLast);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyAllowlistedMetadataReachesCloudTrailAndEventBridge() throws Exception {
|
||||
ObjectNode request = (ObjectNode) mapper.readTree("""
|
||||
{"SecretId":"example","ClientRequestToken":"example-token","VersionStages":["AWSCURRENT"],
|
||||
"SecretString":"sensitive-string","SecretBinary":"sensitive-binary",
|
||||
"Description":"sensitive-description","unknown":{"password":"sensitive-password"}}
|
||||
""");
|
||||
ObjectNode response = mapper.createObjectNode().put("ARN", ARN).put("Name", "example").put("VersionId", "version");
|
||||
ObjectNode record = record();
|
||||
when(trails.emitManagementEvent(any())).thenReturn(Optional.of(record));
|
||||
|
||||
publisher.secretWritten("PutSecretValue", request, response, REGION, "signed-request");
|
||||
|
||||
ArgumentCaptor<CloudTrailService.ManagementEventInput> capture =
|
||||
ArgumentCaptor.forClass(CloudTrailService.ManagementEventInput.class);
|
||||
verify(trails).emitManagementEvent(capture.capture());
|
||||
CloudTrailService.ManagementEventInput input = capture.getValue();
|
||||
assertEquals("secretsmanager.amazonaws.com", input.eventSource());
|
||||
assertEquals("example-access-key", input.accessKeyId());
|
||||
assertEquals("AWSCURRENT", input.requestParameters().path("versionStages").get(0).asText());
|
||||
assertEquals(3, input.requestParameters().size());
|
||||
assertEquals(ARN, input.responseElements().path("arn").asText());
|
||||
assertFalse(input.requestParameters().toString().contains("sensitive-"));
|
||||
verifyNoInteractions(events);
|
||||
assertEquals(1, deliveries.size());
|
||||
deliveries.removeFirst().run();
|
||||
verify(events).publishServiceEvent("aws.secretsmanager", "AWS API Call via CloudTrail",
|
||||
record.toString(), ARN, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noMatchingLoggingTrailMeansNoEventBridgePublication() {
|
||||
when(trails.emitManagementEvent(any())).thenReturn(Optional.empty());
|
||||
publisher.secretWritten("UpdateSecret", mapper.createObjectNode(),
|
||||
mapper.createObjectNode().put("ARN", ARN), REGION, null);
|
||||
verifyNoInteractions(events);
|
||||
assertTrue(deliveries.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notificationFailureDoesNotFailTheAlreadyCommittedWrite() {
|
||||
when(trails.emitManagementEvent(any())).thenThrow(new IllegalStateException("example failure"));
|
||||
assertDoesNotThrow(() -> publisher.secretWritten("PutSecretValue", mapper.createObjectNode(),
|
||||
mapper.createObjectNode().put("ARN", ARN), REGION, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuedDeliveryUsesSnapshotsInsteadOfMutableRequestObjects() {
|
||||
ObjectNode record = record();
|
||||
String detail = record.toString();
|
||||
ObjectNode response = mapper.createObjectNode().put("ARN", ARN);
|
||||
when(trails.emitManagementEvent(any())).thenReturn(Optional.of(record));
|
||||
publisher.secretWritten("PutSecretValue", mapper.createObjectNode(), response, REGION, null);
|
||||
record.removeAll();
|
||||
response.put("ARN", "changed-after-enqueue");
|
||||
deliveries.removeFirst().run();
|
||||
verify(events).publishServiceEvent("aws.secretsmanager", "AWS API Call via CloudTrail", detail, ARN, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedQueueDoesNotRunDeliveryInTheWriteRequestOrFailTheWrite() {
|
||||
when(trails.emitManagementEvent(any())).thenReturn(Optional.of(record()));
|
||||
publisher = new SecretsManagerEventPublisher(trails, events, new AccountResolver(ACCOUNT), mapper,
|
||||
task -> { throw new RejectedExecutionException("example full queue"); });
|
||||
assertDoesNotThrow(() -> publisher.secretWritten("PutSecretValue", mapper.createObjectNode(),
|
||||
mapper.createObjectNode().put("ARN", ARN), REGION, null));
|
||||
verifyNoInteractions(events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void backgroundDeliveryFailureIsContained() {
|
||||
when(trails.emitManagementEvent(any())).thenReturn(Optional.of(record()));
|
||||
doThrow(new IllegalStateException("example delivery failure")).when(events)
|
||||
.publishServiceEvent(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
publisher.secretWritten("PutSecretValue", mapper.createObjectNode(),
|
||||
mapper.createObjectNode().put("ARN", ARN), REGION, null);
|
||||
assertDoesNotThrow(() -> deliveries.removeFirst().run());
|
||||
}
|
||||
|
||||
private ObjectNode record() {
|
||||
return mapper.createObjectNode().put("eventName", "PutSecretValue")
|
||||
.put("recipientAccountId", ACCOUNT).put("awsRegion", REGION);
|
||||
}
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
package io.github.hectorvent.floci.services.secretsmanager;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Message;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Queue;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
|
||||
import software.amazon.awssdk.services.eventbridge.model.ApiDestinationHttpMethod;
|
||||
import software.amazon.awssdk.services.eventbridge.model.ConnectionAuthorizationType;
|
||||
import software.amazon.awssdk.services.eventbridge.model.Target;
|
||||
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
|
||||
import software.amazon.awssdk.services.secretsmanager.model.ResourceNotFoundException;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
class SecretsManagerEventsIntegrationTest {
|
||||
private static final String ACCOUNT = "661100000001";
|
||||
private static final String REGION = "eu-west-1";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Inject
|
||||
CloudTrailService trails;
|
||||
|
||||
@Inject
|
||||
SqsService sqs;
|
||||
|
||||
private SecretsManagerClient secrets;
|
||||
private EventBridgeClient events;
|
||||
private String name;
|
||||
private String arn;
|
||||
private String queueUrl;
|
||||
|
||||
@BeforeEach
|
||||
void createFixture() {
|
||||
URI endpoint = URI.create("http://localhost:" + RestAssured.port);
|
||||
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create(ACCOUNT, "test"));
|
||||
secrets = SecretsManagerClient.builder().endpointOverride(endpoint).region(Region.of(REGION))
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder()).credentialsProvider(credentials).build();
|
||||
events = EventBridgeClient.builder().endpointOverride(endpoint).region(Region.of(REGION))
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder()).credentialsProvider(credentials).build();
|
||||
name = "secret-events-" + UUID.randomUUID();
|
||||
arn = secrets.createSecret(r -> r.name(name).secretString("initial-example-value")).arn();
|
||||
String queueArn = RequestScopes.callAs(ACCOUNT, REGION, () -> {
|
||||
Queue queue = sqs.createQueue(name, Map.of(), REGION);
|
||||
queueUrl = queue.getQueueUrl();
|
||||
return sqs.getQueueAttributes(queueUrl, List.of("QueueArn"), REGION).get("QueueArn");
|
||||
});
|
||||
events.putRule(r -> r.name(name).eventPattern("{\"source\":[\"aws.secretsmanager\"],"
|
||||
+ "\"detail-type\":[\"AWS API Call via CloudTrail\"],"
|
||||
+ "\"detail\":{\"responseElements\":{\"arn\":[\"" + arn + "\"]}}}"));
|
||||
events.putTargets(r -> r.rule(name).targets(Target.builder().id("queue").arn(queueArn).build()));
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> trails.createTrail(REGION, name, "example-audit-logs",
|
||||
null, null, false, false, false, false));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteFixture() {
|
||||
try {
|
||||
events.removeTargets(r -> r.rule(name).ids("queue"));
|
||||
events.deleteRule(r -> r.name(name));
|
||||
secrets.deleteSecret(r -> r.secretId(arn).forceDeleteWithoutRecovery(true));
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> {
|
||||
trails.deleteTrail(REGION, name);
|
||||
sqs.deleteQueue(queueUrl, REGION);
|
||||
});
|
||||
} finally {
|
||||
events.close();
|
||||
secrets.close();
|
||||
}
|
||||
}
|
||||
|
||||
private List<Message> receive(int waitSeconds) {
|
||||
return RequestScopes.callAs(ACCOUNT, REGION, () -> sqs.receiveMessage(queueUrl, 10, 30, waitSeconds, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkWritesReachTheDefaultBusWithoutInjectedEventsAndExcludeSecretValues() throws Exception {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> trails.startLogging(REGION, name));
|
||||
secrets.putSecretValue(r -> r.secretId(arn).secretString("sensitive-put-example"));
|
||||
secrets.updateSecret(r -> r.secretId(arn).secretString("sensitive-update-example"));
|
||||
List<Message> messages = new ArrayList<>();
|
||||
for (int attempt = 0; attempt < 5 && messages.size() < 2; attempt++) {
|
||||
messages.addAll(receive(1));
|
||||
}
|
||||
assertEquals(2, messages.size(), "both SDK writes must reach the rule through service-originated events");
|
||||
for (Message message : messages) {
|
||||
JsonNode event = MAPPER.readTree(message.getBody());
|
||||
assertEquals("aws.secretsmanager", event.path("source").asText());
|
||||
assertEquals("AWS API Call via CloudTrail", event.path("detail-type").asText());
|
||||
assertEquals(ACCOUNT, event.path("account").asText());
|
||||
assertEquals(REGION, event.path("region").asText());
|
||||
assertEquals(arn, event.path("detail").path("responseElements").path("arn").asText());
|
||||
assertFalse(message.getBody().contains("sensitive-"));
|
||||
assertFalse(message.getBody().contains("SecretString"));
|
||||
assertFalse(message.getBody().contains("secretString"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void metadataOnlyUpdatesPublishButReadsUnrelatedSecretsAndFailedWritesDoNot() throws Exception {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> trails.startLogging(REGION, name));
|
||||
String other = secrets.createSecret(r -> r.name(name + "-other").secretString("other-example")).arn();
|
||||
try {
|
||||
secrets.putSecretValue(r -> r.secretId(other).secretString("unrelated-example"));
|
||||
secrets.getSecretValue(r -> r.secretId(arn));
|
||||
secrets.describeSecret(r -> r.secretId(arn));
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> secrets.putSecretValue(r -> r.secretId(name + "-missing").secretString("failed-example")));
|
||||
assertTrue(receive(0).isEmpty());
|
||||
secrets.updateSecret(r -> r.secretId(arn).description("metadata only"));
|
||||
List<Message> messages = receive(2);
|
||||
assertEquals(1, messages.size());
|
||||
JsonNode detail = MAPPER.readTree(messages.getFirst().getBody()).path("detail");
|
||||
assertEquals("UpdateSecret", detail.path("eventName").asText());
|
||||
assertFalse(detail.path("responseElements").has("versionId"));
|
||||
} finally {
|
||||
secrets.deleteSecret(r -> r.secretId(other).forceDeleteWithoutRecovery(true));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void slowHttpTargetsDoNotDelaySdkWriteResponsesAndKeepRequestScope() throws Exception {
|
||||
CountDownLatch arrived = new CountDownLatch(2);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
List<String> payloads = new CopyOnWriteArrayList<>();
|
||||
ExecutorService httpWorkers = Executors.newVirtualThreadPerTaskExecutor();
|
||||
ExecutorService callers = Executors.newVirtualThreadPerTaskExecutor();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.setExecutor(httpWorkers);
|
||||
server.createContext("/hook", exchange -> {
|
||||
try {
|
||||
payloads.add(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
arrived.countDown();
|
||||
boolean released = release.await(10, TimeUnit.SECONDS);
|
||||
exchange.sendResponseHeaders(released ? 200 : 504, -1);
|
||||
} catch (InterruptedException expected) {
|
||||
// Test teardown interrupts any handler still waiting for release.
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
exchange.close();
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
String connection = events.createConnection(r -> r.name(name)
|
||||
.authorizationType(ConnectionAuthorizationType.API_KEY)
|
||||
.authParameters(p -> p.apiKeyAuthParameters(k -> k.apiKeyName("example-key").apiKeyValue("example-value"))))
|
||||
.connectionArn();
|
||||
String destination = events.createApiDestination(r -> r.name(name).connectionArn(connection)
|
||||
.httpMethod(ApiDestinationHttpMethod.POST).invocationRateLimitPerSecond(100)
|
||||
.invocationEndpoint("http://127.0.0.1:" + server.getAddress().getPort() + "/hook"))
|
||||
.apiDestinationArn();
|
||||
events.putTargets(r -> r.rule(name).targets(Target.builder().id("blocked-http").arn(destination).build()));
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> trails.startLogging(REGION, name));
|
||||
|
||||
Future<?> put = callers.submit(() -> secrets.putSecretValue(r -> r.secretId(arn)
|
||||
.secretString("sensitive-async-put")));
|
||||
Future<?> update = callers.submit(() -> secrets.updateSecret(r -> r.secretId(arn)
|
||||
.secretString("sensitive-async-update")));
|
||||
put.get(2, TimeUnit.SECONDS);
|
||||
update.get(2, TimeUnit.SECONDS);
|
||||
assertTrue(arrived.await(3, TimeUnit.SECONDS), "both target deliveries must run after the SDK writes return");
|
||||
assertEquals(1, release.getCount(), "HTTP targets are still waiting for a response");
|
||||
for (String payload : payloads) {
|
||||
JsonNode event = MAPPER.readTree(payload);
|
||||
assertEquals(ACCOUNT, event.path("account").asText());
|
||||
assertEquals(REGION, event.path("region").asText());
|
||||
assertEquals(arn, event.path("detail").path("responseElements").path("arn").asText());
|
||||
assertFalse(payload.contains("sensitive-"));
|
||||
}
|
||||
} finally {
|
||||
release.countDown();
|
||||
callers.shutdownNow();
|
||||
callers.awaitTermination(5, TimeUnit.SECONDS);
|
||||
server.stop(0);
|
||||
httpWorkers.shutdownNow();
|
||||
events.removeTargets(r -> r.rule(name).ids("blocked-http"));
|
||||
events.deleteApiDestination(r -> r.name(name));
|
||||
events.deleteConnection(r -> r.name(name));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppedTrailsAndReadOnlySelectorsDoNotPublishWrites() {
|
||||
secrets.putSecretValue(r -> r.secretId(arn).secretString("not-logged"));
|
||||
assertTrue(receive(0).isEmpty());
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> {
|
||||
trails.putEventSelectors(REGION, name, List.of(new EventSelector("ReadOnly", true, List.of(), List.of())));
|
||||
trails.startLogging(REGION, name);
|
||||
});
|
||||
secrets.updateSecret(r -> r.secretId(arn).description("metadata only"));
|
||||
assertTrue(receive(0).isEmpty());
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package io.github.hectorvent.floci.services.secretsmanager;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Message;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
|
||||
import software.amazon.awssdk.services.eventbridge.model.ApiDestinationHttpMethod;
|
||||
import software.amazon.awssdk.services.eventbridge.model.ConnectionAuthorizationType;
|
||||
import software.amazon.awssdk.services.eventbridge.model.Target;
|
||||
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
class SecretsManagerEventsResetIntegrationTest {
|
||||
private static final String ACCOUNT = "661100000007";
|
||||
private static final String REGION = "eu-west-1";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String PATTERN = "{\"source\":[\"aws.secretsmanager\"],"
|
||||
+ "\"detail-type\":[\"AWS API Call via CloudTrail\"]}";
|
||||
|
||||
@Inject
|
||||
CloudTrailService trails;
|
||||
|
||||
@Inject
|
||||
SqsService sqs;
|
||||
|
||||
@Test
|
||||
void actualResetDrainsBlockedTargetsDropsOldWritesAndDeliversNewSdkWrites() throws Exception {
|
||||
URI endpoint = URI.create("http://localhost:" + RestAssured.port);
|
||||
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create(ACCOUNT, "test"));
|
||||
CountDownLatch arrived = new CountDownLatch(2);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
ExecutorService httpWorkers = Executors.newVirtualThreadPerTaskExecutor();
|
||||
ExecutorService resets = Executors.newSingleThreadExecutor();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.setExecutor(httpWorkers);
|
||||
server.createContext("/hook", exchange -> {
|
||||
try {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
arrived.countDown();
|
||||
boolean released = release.await(10, TimeUnit.SECONDS);
|
||||
exchange.sendResponseHeaders(released ? 200 : 504, -1);
|
||||
} catch (InterruptedException expected) {
|
||||
// Teardown releases or interrupts every blocked test target.
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
exchange.close();
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
try (SecretsManagerClient secrets = SecretsManagerClient.builder().endpointOverride(endpoint)
|
||||
.region(Region.of(REGION)).httpClientBuilder(UrlConnectionHttpClient.builder())
|
||||
.credentialsProvider(credentials).build();
|
||||
EventBridgeClient events = EventBridgeClient.builder().endpointOverride(endpoint)
|
||||
.region(Region.of(REGION)).httpClientBuilder(UrlConnectionHttpClient.builder())
|
||||
.credentialsProvider(credentials).build()) {
|
||||
String name = "reset-events-" + UUID.randomUUID();
|
||||
String oldArn = secrets.createSecret(r -> r.name(name).secretString("old-example")).arn();
|
||||
String connection = events.createConnection(r -> r.name(name)
|
||||
.authorizationType(ConnectionAuthorizationType.API_KEY)
|
||||
.authParameters(p -> p.apiKeyAuthParameters(k -> k.apiKeyName("example-key").apiKeyValue("example-value"))))
|
||||
.connectionArn();
|
||||
String destination = events.createApiDestination(r -> r.name(name).connectionArn(connection)
|
||||
.httpMethod(ApiDestinationHttpMethod.POST).invocationRateLimitPerSecond(100)
|
||||
.invocationEndpoint("http://127.0.0.1:" + server.getAddress().getPort() + "/hook"))
|
||||
.apiDestinationArn();
|
||||
rule(events, name, destination);
|
||||
startTrail(name);
|
||||
secrets.putSecretValue(r -> r.secretId(oldArn).secretString("old-first"));
|
||||
secrets.updateSecret(r -> r.secretId(oldArn).secretString("old-second"));
|
||||
assertTrue(arrived.await(3, TimeUnit.SECONDS), "both publisher workers must be occupied");
|
||||
secrets.putSecretValue(r -> r.secretId(oldArn).secretString("queued-before-reset"));
|
||||
|
||||
Future<?> reset = resets.submit(() -> given().post("/_floci/state/reset").then().statusCode(200));
|
||||
assertThrows(TimeoutException.class, () -> reset.get(200, TimeUnit.MILLISECONDS),
|
||||
"reset must drain blocked target deliveries before clearing their state");
|
||||
release.countDown();
|
||||
reset.get(15, TimeUnit.SECONDS);
|
||||
|
||||
String freshArn = secrets.createSecret(r -> r.name(name).secretString("fresh-example")).arn();
|
||||
String queueUrl = RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> sqs.createQueue(name, Map.of(), REGION).getQueueUrl());
|
||||
String queueArn = RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> sqs.getQueueAttributes(queueUrl, List.of("QueueArn"), REGION).get("QueueArn"));
|
||||
rule(events, name, queueArn);
|
||||
startTrail(name);
|
||||
secrets.putSecretValue(r -> r.secretId(freshArn).secretString("fresh-write"));
|
||||
List<Message> messages = receive(queueUrl, 2);
|
||||
assertEquals(1, messages.size(), "new rules must receive only writes made after reset");
|
||||
JsonNode event = MAPPER.readTree(messages.getFirst().getBody());
|
||||
assertEquals(freshArn, event.path("detail").path("responseElements").path("arn").asText());
|
||||
assertEquals(ACCOUNT, event.path("account").asText());
|
||||
assertEquals(REGION, event.path("region").asText());
|
||||
assertTrue(receive(queueUrl, 1).isEmpty(),
|
||||
"queued events from deleted secrets must not reach the recreated rule");
|
||||
} finally {
|
||||
release.countDown();
|
||||
resets.shutdownNow();
|
||||
assertTrue(resets.awaitTermination(5, TimeUnit.SECONDS));
|
||||
server.stop(0);
|
||||
httpWorkers.shutdownNow();
|
||||
given().post("/_floci/state/reset").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
private void startTrail(String name) {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> {
|
||||
trails.createTrail(REGION, name, "example-reset-audit-logs", null, null, false, false, false, false);
|
||||
trails.startLogging(REGION, name);
|
||||
});
|
||||
}
|
||||
|
||||
private void rule(EventBridgeClient events, String name, String targetArn) {
|
||||
events.putRule(r -> r.name(name).eventPattern(PATTERN));
|
||||
events.putTargets(r -> r.rule(name).targets(Target.builder().id("target").arn(targetArn).build()));
|
||||
}
|
||||
|
||||
private List<Message> receive(String queueUrl, int waitSeconds) {
|
||||
return RequestScopes.callAs(ACCOUNT, REGION, () -> sqs.receiveMessage(queueUrl, 10, 30, waitSeconds, REGION));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -31,7 +31,8 @@ class SecretsManagerJsonHandlerTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new SecretsManagerService(new InMemoryStorage<>(), 30);
|
||||
handler = new SecretsManagerJsonHandler(service, MAPPER, mock(IamEnforcementFilter.class));
|
||||
handler = new SecretsManagerJsonHandler(service, MAPPER, mock(IamEnforcementFilter.class),
|
||||
mock(SecretsManagerEventPublisher.class));
|
||||
}
|
||||
|
||||
private String getRandomPassword(ObjectNode request) {
|
||||
|
||||
+1
-1
@@ -159,7 +159,7 @@ class SecretsManagerRotationLockTest {
|
||||
// is building DescribeSecret's VersionIdsToStages from the same map. Park the reader one
|
||||
// entry into that iteration, add the version, and let the reader continue.
|
||||
SecretsManagerJsonHandler handler = new SecretsManagerJsonHandler(service, new ObjectMapper(),
|
||||
mock(IamEnforcementFilter.class));
|
||||
mock(IamEnforcementFilter.class), mock(SecretsManagerEventPublisher.class));
|
||||
ParkingIterationVersions versions = new ParkingIterationVersions(secret.getVersions());
|
||||
secret.setVersions(versions);
|
||||
assertTrue(secret.getVersions() instanceof ConcurrentMap,
|
||||
|
||||
Reference in new issue
Block a user