feat(secretsmanager): add the five missing actions and correct response fidelity (#3711)

* feat(secretsmanager): add the five missing actions and correct response fidelity

Secrets Manager implemented 18 of the 23 actions in the API reference. This
adds the remaining five and corrects a number of response and validation
divergences found by working through each operation's reference page.

New actions:

- CancelRotateSecret turns rotation off and reports the half-built AWSPENDING
  version an interrupted rotation left behind. The staging labels are left
  alone, as AWS leaves them, because that version id is the only handle on a
  stale AWSPENDING - and a stale AWSPENDING that is not also AWSCURRENT makes
  every later RotateSecret fail with "a previous rotation isn't complete".
- ValidateResourcePolicy reports wildcard principals under the same
  REFLEXIVE_PRINCIPAL_CHECK name AWS uses. BlockPublicPolicy on
  PutResourcePolicy now enforces the same check.
- ReplicateSecretToRegions, RemoveRegionsFromReplication and
  StopReplicationToReplica, backed by a replication model on Secret. Replicas
  carry the primary's ARN with the Region swapped, track later writes to the
  primary, and are read-only; a primary that still has replicas cannot be
  deleted.

Scheduled rotation now fires. RotationRules were stored and echoed back but
never acted on, so AutomaticallyAfterDays and ScheduleExpression described a
schedule that could not happen. A background sweep rotates secrets whose
NextRotationDate has passed, reusing the EventBridge Scheduler expression
parser for rate() and cron(). The schedule advances when a rotation is
dispatched rather than when it succeeds, so a failing rotation cannot pin the
sweep on one secret forever.

Response fidelity:

- ListSecrets honours SortBy, SortOrder and IncludePlannedDeletion, and its
  entries carry SecretVersionsToStages, the rotation fields, DeletedDate and
  PrimaryRegion.
- PrimaryRegion and ReplicationStatus appear only on multi-Region secrets,
  matching AWS's "only returns fields that have a value" rule.
- Versions with no staging labels are deprecated: DescribeSecret and
  ListSecretVersionIds omit them unless IncludeDeprecated is set, and an empty
  VersionStages array is omitted rather than sent.
- ListSecretVersionIds gained IncludeDeprecated, LastAccessedDate and paging.

Validation, all previously accepted silently:

- DeleteSecret rejects a recovery window outside 7-30 and the
  ForceDeleteWithoutRecovery/RecoveryWindowInDays combination. A window of 0
  used to fall through to force-delete, turning a request for no recovery
  window into an unrecoverable delete.
- CreateSecret uses ClientRequestToken as the version id and is idempotent on
  retry; UpdateSecret, which AWS documents as not idempotent, rejects a token
  that already names a version.
- RotationRules bounds, secret name charset, SecretString/SecretBinary
  exclusivity, KMS key existence and state, and the documented caps on
  BatchGetSecretValue, Filters, ExcludeCharacters and ResourcePolicy.

Secret values remain stored in the clear; encrypting them with the emulator's
own KMS would protect nothing while making the store unreadable. KmsKeyId is
validated instead, which is the part a caller can observe.

Two deviations are deliberate and recorded in docs/services/secrets-manager.md:
LastRotatedDate is retained after CancelRotateSecret, and RotateSecret with
RotateImmediately=false does not create the throwaway AWSPENDING version.

* test(secretsmanager): create a real KMS key in the sdk-test-java compat test

kmsKeyIdPreservation asserted that floci round-trips whatever KmsKeyId it is
handed, using an ARN that was never created. That passed only because floci
did not check the key; real AWS rejects a key it cannot access, and so does
the new validation.

The test now creates a key through the emulated KMS and round-trips that ARN,
so it still covers KmsKeyId preservation without depending on the missing
check. A second case pins the rejection itself.

* refactor(secretsmanager): import types instead of qualifying them inline

AGENTS.md asks for imports unless a name collision forces qualification.
AwsException and UUID had neither.

* fix(secretsmanager): hold the rotation lock while promoting a replica

StopReplicationToReplica wrote the promoted replica outside the per-secret
lock every other mutation in this file takes. The promotion races the
primary's replica sync, and losing that race writes the replica back over the
copy the call just promoted.

Also imports KmsKey, ConcurrentHashMap and HashMap rather than qualifying
them inline, per the same AGENTS.md rule.

* test(secretsmanager): assert the KMS rejection by exception type, not message text

createSecretWithAnUnknownKmsKeyIsRejected matched "InvalidParameterException"
against the message, but that is the exception type; the message itself reads
"You can't access the KMS key ... in this Region". The assertion now checks
the typed InvalidParameterException and the text it actually carries.

* test(secretsmanager): give the new KMS compat test its own order

createSecretWithAnUnknownKmsKeyIsRejected inherited @Order(13) from the test
it was added next to, so two cases shared a position. JUnit breaks the tie
deterministically, but the duplicate made the sequence misleading; the tail is
renumbered so each case keeps a distinct order.

Also sorts the new KMS imports, which landed between the lambda ones.

* fix(secretsmanager): guard every write to a secret with its owning monitor

UpdateSecret read, mutated and persisted without taking the secret's lock,
unlike every other mutator in the class, so two concurrent calls could drop
one another's field.

StopReplicationToReplica locked the replica's own ARN, but persist() writes a
primary's replica slots while holding only the primary's lock: two monitors
guarding one store slot, so a sync landing after the promotion could overwrite
the promoted copy. The promotion now runs under the primary's monitor, and its
two halves run in one critical section so nothing lands between them.

SecretsManagerWriteLockTest parks a write mid-flight and asserts the second
caller waits; both cases fail without the fixes.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-16 15:13:57 -04:00
1 parent 1831f10105
commit 33d17c0146
14 files changed
+3390 -114

No files matched your search

@@ -0,0 +1,239 @@
package io.github.hectorvent.floci.services.secretsmanager;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* Covers the background sweep that makes a rotation schedule actually fire. Rotation itself runs
* asynchronously, so these assert on the scheduling state the sweep drives - which secret is due
* and where its next rotation lands - rather than on the rotation's outcome.
*/
class SecretRotationSchedulerTest {
private static final String REGION = "us-east-1";
private static final String LAMBDA_ARN = "arn:aws:lambda:us-east-1:000000000000:function:rotate";
private static final String TOKEN = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
private SecretsManagerService service;
private SecretRotationScheduler scheduler;
@BeforeEach
void setUp() {
service = new SecretsManagerService(new InMemoryStorage<>(), 30,
new RegionResolver(REGION, "000000000000"), mock(LambdaService.class), new ObjectMapper());
scheduler = new SecretRotationScheduler(service);
}
private void enableRotation(String name, Secret.RotationRules rules) {
service.createSecret(name, "v1", null, null, null, null, REGION);
service.rotateSecret(name, TOKEN, LAMBDA_ARN, rules, false, REGION);
}
// ─── Next-rotation-date computation ────────────────────────────────────────
@Test
void enablingRotationWithAutomaticallyAfterDaysSchedulesThatManyDaysOut() {
Instant before = Instant.now();
enableRotation("daily", new Secret.RotationRules(14, null, null));
Instant next = service.describeSecret("daily", REGION).getNextRotationDate();
assertNotNull(next, "enabling rotation must schedule the next one");
assertTrue(next.isAfter(before.plus(13, ChronoUnit.DAYS)));
assertTrue(next.isBefore(before.plus(15, ChronoUnit.DAYS)));
}
@Test
void enablingRotationWithARateExpressionSchedulesThatInterval() {
Instant before = Instant.now();
enableRotation("rated", new Secret.RotationRules(null, null, "rate(10 days)"));
Instant next = service.describeSecret("rated", REGION).getNextRotationDate();
assertNotNull(next);
assertTrue(next.isAfter(before.plus(9, ChronoUnit.DAYS)));
assertTrue(next.isBefore(before.plus(11, ChronoUnit.DAYS)));
}
@Test
void enablingRotationWithAnHourlyRateSchedulesInHours() {
Instant before = Instant.now();
enableRotation("hourly", new Secret.RotationRules(null, null, "rate(12 hours)"));
Instant next = service.describeSecret("hourly", REGION).getNextRotationDate();
assertNotNull(next);
assertTrue(next.isAfter(before.plus(11, ChronoUnit.HOURS)));
assertTrue(next.isBefore(before.plus(13, ChronoUnit.HOURS)));
}
@Test
void enablingRotationWithACronExpressionSchedulesTheNextMatchingTime() {
// Every day at 16:00 UTC; the next fire is always within a day.
Instant before = Instant.now();
enableRotation("crony", new Secret.RotationRules(null, null, "cron(0 16 * * ? *)"));
Instant next = service.describeSecret("crony", REGION).getNextRotationDate();
assertNotNull(next);
assertTrue(next.isAfter(before));
assertTrue(next.isBefore(before.plus(25, ChronoUnit.HOURS)));
}
@Test
void anUnparseableScheduleExpressionIsRejected() {
service.createSecret("bad-cron", "v1", null, null, null, null, REGION);
io.github.hectorvent.floci.core.common.AwsException ex =
org.junit.jupiter.api.Assertions.assertThrows(
io.github.hectorvent.floci.core.common.AwsException.class,
() -> service.rotateSecret("bad-cron", TOKEN, LAMBDA_ARN,
new Secret.RotationRules(null, null, "every other tuesday"),
false, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void cancellingRotationClearsTheSchedule() {
enableRotation("cancelled", new Secret.RotationRules(14, null, null));
service.cancelRotateSecret("cancelled", REGION);
assertNull(service.describeSecret("cancelled", REGION).getNextRotationDate());
}
// ─── The sweep ─────────────────────────────────────────────────────────────
/** Drags the schedule into the past so the next tick sees the secret as due. */
private void makeDue(String name) {
Secret secret = service.describeSecret(name, REGION);
secret.setNextRotationDate(Instant.now().minus(1, ChronoUnit.MINUTES));
}
@Test
void tickRotatesASecretWhoseScheduleHasPassed() {
enableRotation("due", new Secret.RotationRules(14, null, null));
makeDue("due");
scheduler.tick(Instant.now());
Instant next = service.describeSecret("due", REGION).getNextRotationDate();
assertTrue(next.isAfter(Instant.now()), "a fired rotation must reschedule into the future");
}
@Test
void tickLeavesASecretThatIsNotDueYet() {
enableRotation("not-due", new Secret.RotationRules(14, null, null));
Instant before = service.describeSecret("not-due", REGION).getNextRotationDate();
scheduler.tick(Instant.now());
assertEquals(before, service.describeSecret("not-due", REGION).getNextRotationDate());
}
@Test
void tickIgnoresSecretsWithRotationTurnedOff() {
service.createSecret("plain", "v1", null, null, null, null, REGION);
scheduler.tick(Instant.now());
assertNull(service.describeSecret("plain", REGION).getNextRotationDate());
}
@Test
void tickIgnoresSecretsManagedByAnotherService() {
// The owning service rotates these itself; floci must not invoke a Lambda for them.
service.createSecret("rds!db-1", "v1", null, null, null, null, "rds", REGION);
service.rotateSecret("rds!db-1", TOKEN, null, new Secret.RotationRules(1, null, null), false, REGION);
makeDue("rds!db-1");
Instant due = service.describeSecret("rds!db-1", REGION).getNextRotationDate();
scheduler.tick(Instant.now());
assertEquals(due, service.describeSecret("rds!db-1", REGION).getNextRotationDate());
}
@Test
void tickIgnoresReplicas() {
enableRotation("replicated", new Secret.RotationRules(14, null, null));
service.replicateSecretToRegions("replicated",
List.of(new SecretsManagerService.ReplicaRegion("eu-west-1", null)), false, REGION);
Secret replica = service.describeSecret("replicated", "eu-west-1");
replica.setNextRotationDate(Instant.now().minus(1, ChronoUnit.MINUTES));
// The replica is due on paper, but rotating it would write to a read-only copy.
scheduler.tick(Instant.now());
assertTrue(service.describeSecret("replicated", "eu-west-1").isReplica());
}
@Test
void tickIgnoresSecretsScheduledForDeletion() {
enableRotation("doomed", new Secret.RotationRules(14, null, null));
makeDue("doomed");
service.deleteSecret("doomed", 7, false, REGION);
Instant due = service.describeSecret("doomed", REGION).getNextRotationDate();
scheduler.tick(Instant.now());
assertEquals(due, service.describeSecret("doomed", REGION).getNextRotationDate());
}
@Test
void tickRotatesASecretOwnedByANonDefaultAccount() {
// The sweep has no request to resolve an account from, so it falls back to the default
// one. Enumerating and writing through that fallback would leave every other account's
// secrets unrotated - and worse, write a phantom copy into the default account.
String foreignAccount = "111122223333";
io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<Secret> store =
io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend.inMemory("000000000000");
SecretsManagerService accountAware = new SecretsManagerService(store, 30,
new RegionResolver(REGION, "000000000000"), mock(LambdaService.class), new ObjectMapper());
SecretRotationScheduler sweep = new SecretRotationScheduler(accountAware);
accountAware.createSecret("foreign", "v1", null, null, null, null, REGION);
accountAware.rotateSecret("foreign", TOKEN, LAMBDA_ARN,
new Secret.RotationRules(14, null, null), false, REGION);
// Re-home the secret into the other account, ARN included, and clear the default copy.
Secret secret = accountAware.describeSecret("foreign", REGION);
secret.setArn(secret.getArn().replace("000000000000", foreignAccount));
secret.setNextRotationDate(Instant.now().minus(1, ChronoUnit.MINUTES));
store.putForAccount(foreignAccount, REGION + "::foreign", secret);
store.deleteForAccount("000000000000", REGION + "::foreign");
sweep.tick(Instant.now());
Secret afterSweep = store.getForAccount(foreignAccount, REGION + "::foreign").orElseThrow();
assertTrue(afterSweep.getNextRotationDate().isAfter(Instant.now()),
"a secret in another account must still be rotated");
assertTrue(store.getForAccount("000000000000", REGION + "::foreign").isEmpty(),
"rotating it must not leave a phantom copy in the default account");
}
@Test
void tickSurvivesASecretThatCannotRotate() {
// An in-flight rotation makes RotateSecret throw; the sweep must carry on to the rest.
enableRotation("blocked", new Secret.RotationRules(14, null, null));
service.putSecretValue("blocked", "half", null,
"b1b2c3d4-e5f6-7890-abcd-ef1234567890", REGION, List.of("AWSPENDING"));
makeDue("blocked");
enableRotation("healthy", new Secret.RotationRules(14, null, null));
makeDue("healthy");
scheduler.tick(Instant.now());
assertTrue(service.describeSecret("healthy", REGION).getNextRotationDate().isAfter(Instant.now()));
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.secretsmanager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
@@ -237,7 +238,7 @@ class SecretsManagerServiceTest {
void listSecretsExcludesDeleted() {
service.createSecret("active", "v1", null, null, null, null, REGION);
service.createSecret("deleted", "v2", null, null, null, null, REGION);
service.deleteSecret("deleted", 0, true, REGION);
service.deleteSecret("deleted", null, true, REGION);
List<Secret> secrets = service.listSecrets(REGION);
assertEquals(1, secrets.size());
@@ -1102,4 +1103,432 @@ class SecretsManagerServiceTest {
assertEquals("InvalidRequestException", ex.getErrorCode());
latch.countDown();
}
// ─── CancelRotateSecret ────────────────────────────────────────────────────
private static final String ROTATION_LAMBDA_ARN =
"arn:aws:lambda:us-east-1:000000000000:function:rotate";
private static final String ROTATION_TOKEN = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
/**
* Turns rotation on without leaving a background rotation racing the assertions: this
* service has no LambdaService, and with no AWSPENDING staged the {@code rotateImmediately
* = false} task only invokes a Lambda that isn't there, so it mutates nothing.
*/
private void enableRotation(String name) {
service.rotateSecret(name, ROTATION_TOKEN, ROTATION_LAMBDA_ARN,
new Secret.RotationRules(14, null, null), false, REGION);
}
@Test
void cancelRotateSecretTurnsRotationOff() {
service.createSecret("rotating", "v1", null, null, null, null, REGION);
enableRotation("rotating");
assertTrue(service.describeSecret("rotating", REGION).isRotationEnabled());
SecretsManagerService.CancelRotationResult result =
service.cancelRotateSecret("rotating", REGION);
assertFalse(result.secret().isRotationEnabled());
assertFalse(service.describeSecret("rotating", REGION).isRotationEnabled());
}
@Test
void cancelRotateSecretReportsNoPendingVersionWhenNoneIsStaged() {
service.createSecret("rotating", "v1", null, null, null, null, REGION);
enableRotation("rotating");
assertNull(service.cancelRotateSecret("rotating", REGION).pendingVersionId());
}
@Test
void cancelRotateSecretReportsTheStagedPendingVersion() {
service.createSecret("rotating", "v1", null, null, null, null, REGION);
service.putSecretValue("rotating", "half-rotated", null,
ROTATION_TOKEN, REGION, List.of("AWSPENDING"));
assertEquals(ROTATION_TOKEN,
service.cancelRotateSecret("rotating", REGION).pendingVersionId());
}
@Test
void cancelRotateSecretLeavesAwsPendingAttachedForTheCallerToCleanUp() {
// AWS explicitly does NOT unstage the version: "You might need to remove the staging
// label AWSPENDING from the partially created version."
service.createSecret("rotating", "v1", null, null, null, null, REGION);
service.putSecretValue("rotating", "half-rotated", null,
ROTATION_TOKEN, REGION, List.of("AWSPENDING"));
service.cancelRotateSecret("rotating", REGION);
SecretVersion pending = service.getSecretValue("rotating", null, "AWSPENDING", REGION);
assertEquals(ROTATION_TOKEN, pending.getVersionId());
}
@Test
void cancelRotateSecretOnASecretMarkedForDeletionThrows() {
service.createSecret("doomed", "v1", null, null, null, null, REGION);
service.deleteSecret("doomed", 7, false, REGION);
AwsException ex = assertThrows(AwsException.class, () ->
service.cancelRotateSecret("doomed", REGION));
assertEquals("InvalidRequestException", ex.getErrorCode());
}
// ─── DeleteSecret recovery-window validation ───────────────────────────────
@Test
void deleteSecretRejectsARecoveryWindowOutsideSevenToThirtyDays() {
service.createSecret("windowed", "v1", null, null, null, null, REGION);
for (int window : new int[] { -1, 0, 6, 31, 365 }) {
AwsException ex = assertThrows(AwsException.class, () ->
service.deleteSecret("windowed", window, false, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode(),
"window " + window + " should be rejected");
}
}
@Test
void deleteSecretAcceptsTheBoundaryRecoveryWindows() {
for (int window : new int[] { 7, 30 }) {
String name = "boundary-" + window;
service.createSecret(name, "v1", null, null, null, null, REGION);
assertNotNull(service.deleteSecret(name, window, false, REGION).getDeletedDate());
}
}
@Test
void deleteSecretRejectsForceDeleteCombinedWithARecoveryWindow() {
service.createSecret("conflicted", "v1", null, null, null, null, REGION);
AwsException ex = assertThrows(AwsException.class, () ->
service.deleteSecret("conflicted", 7, true, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
// ─── CreateSecret ClientRequestToken ───────────────────────────────────────
@Test
void createSecretUsesTheClientRequestTokenAsTheVersionId() {
Secret secret = service.createSecret("tokened", "v1", null, null, null, null,
null, ROTATION_TOKEN, REGION);
assertEquals(ROTATION_TOKEN, secret.getCurrentVersionId());
assertEquals("v1", service.getSecretValue("tokened", ROTATION_TOKEN, null, REGION)
.getSecretString());
}
@Test
void createSecretRejectsAClientRequestTokenOutsideThe32To64Range() {
AwsException ex = assertThrows(AwsException.class, () ->
service.createSecret("bad-token", "v1", null, null, null, null,
null, "too-short", REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
// ─── Service-managed secrets stay manageable by their owning service ───────
@Test
void theOwningServiceCanStillUpdateItsOwnManagedSecret() {
// RDS re-encrypts its managed master user secret in place on ModifyDBCluster by calling
// updateSecret. The "managed by another service" guard belongs on the wire API, which
// outside callers reach; applying it here would break RDS's own rekey path.
service.createSecret("rds!db-1", "v1", null, null, "old-key", null, "rds", REGION);
Secret rekeyed = service.updateSecret("rds!db-1", null, "new-key", REGION);
assertEquals("new-key", rekeyed.getKmsKeyId());
}
@Test
void theOwningServiceCanStillCancelRotationOnItsOwnManagedSecret() {
service.createSecret("rds!db-2", "v1", null, null, null, null, "rds", REGION);
assertFalse(service.cancelRotateSecret("rds!db-2", REGION).secret().isRotationEnabled());
}
@Test
void putSecretValueRejectsBothSecretStringAndSecretBinary() {
// AWS: "Either SecretString or SecretBinary must have a value, but not both."
service.createSecret("both-values", "v1", null, null, null, null, REGION);
AwsException ex = assertThrows(AwsException.class, () ->
service.putSecretValue("both-values", "text", "YmluYXJ5", null, REGION, null));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void putSecretValueStillAcceptsTheEmptyPlaceholderARotationStages() {
// Both null is how a rotation registers its AWSPENDING version before it has a value.
service.createSecret("placeholder", "v1", null, null, null, null, REGION);
SecretVersion staged = service.putSecretValue("placeholder", null, null,
"a1b2c3d4-e5f6-7890-abcd-ef1234567890", REGION, List.of("AWSPENDING"));
assertNull(staged.getSecretString());
assertTrue(staged.getVersionStages().contains("AWSPENDING"));
}
// ─── KMS key validation ────────────────────────────────────────────────────
/**
* KmsService is a cross-service collaborator whose real test constructors are package-private
* to {@code services.kms}, so it is mocked here the same way the rotation tests mock
* LambdaService.
*/
private SecretsManagerService serviceWithKms(io.github.hectorvent.floci.services.kms.KmsService kms) {
return new SecretsManagerService(new InMemoryStorage<>(), 30,
new RegionResolver(REGION, "000000000000"), null, new com.fasterxml.jackson.databind.ObjectMapper(), kms);
}
private static io.github.hectorvent.floci.services.kms.model.KmsKey kmsKey(boolean enabled, String state) {
io.github.hectorvent.floci.services.kms.model.KmsKey key =
new io.github.hectorvent.floci.services.kms.model.KmsKey();
key.setKeyId("abcd1234-ef56-7890-abcd-ef1234567890");
key.setEnabled(enabled);
key.setKeyState(state);
return key;
}
@Test
void createSecretRejectsAKmsKeyThatDoesNotExist() {
io.github.hectorvent.floci.services.kms.KmsService kms =
org.mockito.Mockito.mock(io.github.hectorvent.floci.services.kms.KmsService.class);
org.mockito.Mockito.when(kms.describeKey(org.mockito.ArgumentMatchers.anyString(),
org.mockito.ArgumentMatchers.anyString()))
.thenThrow(new AwsException("NotFoundException", "Key not found", 404));
AwsException ex = assertThrows(AwsException.class, () -> serviceWithKms(kms)
.createSecret("kms-secret", "v1", null, null, "missing-key", null, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void createSecretRejectsADisabledKmsKey() {
io.github.hectorvent.floci.services.kms.KmsService kms =
org.mockito.Mockito.mock(io.github.hectorvent.floci.services.kms.KmsService.class);
org.mockito.Mockito.when(kms.describeKey(org.mockito.ArgumentMatchers.anyString(),
org.mockito.ArgumentMatchers.anyString()))
.thenReturn(kmsKey(false, "Disabled"));
AwsException ex = assertThrows(AwsException.class, () -> serviceWithKms(kms)
.createSecret("kms-secret", "v1", null, null, "disabled-key", null, REGION));
assertEquals("EncryptionFailure", ex.getErrorCode());
}
@Test
void createSecretRejectsAKmsKeyPendingDeletion() {
io.github.hectorvent.floci.services.kms.KmsService kms =
org.mockito.Mockito.mock(io.github.hectorvent.floci.services.kms.KmsService.class);
org.mockito.Mockito.when(kms.describeKey(org.mockito.ArgumentMatchers.anyString(),
org.mockito.ArgumentMatchers.anyString()))
.thenReturn(kmsKey(true, "PendingDeletion"));
AwsException ex = assertThrows(AwsException.class, () -> serviceWithKms(kms)
.createSecret("kms-secret", "v1", null, null, "doomed-key", null, REGION));
assertEquals("EncryptionFailure", ex.getErrorCode());
}
@Test
void createSecretAcceptsAnEnabledKmsKey() {
io.github.hectorvent.floci.services.kms.KmsService kms =
org.mockito.Mockito.mock(io.github.hectorvent.floci.services.kms.KmsService.class);
org.mockito.Mockito.when(kms.describeKey(org.mockito.ArgumentMatchers.anyString(),
org.mockito.ArgumentMatchers.anyString()))
.thenReturn(kmsKey(true, "Enabled"));
Secret secret = serviceWithKms(kms)
.createSecret("kms-secret", "v1", null, null, "good-key", null, REGION);
assertEquals("good-key", secret.getKmsKeyId());
}
@Test
void theAwsManagedDefaultKeyIsNeverLookedUp() {
// AWS creates aws/secretsmanager on demand, so it always resolves. Looking it up would
// fail on a fresh emulator where nobody has created it.
io.github.hectorvent.floci.services.kms.KmsService kms =
org.mockito.Mockito.mock(io.github.hectorvent.floci.services.kms.KmsService.class);
SecretsManagerService kmsAware = serviceWithKms(kms);
kmsAware.createSecret("default-key", "v1", null, null, "alias/aws/secretsmanager", null, REGION);
kmsAware.createSecret("bare-default", "v1", null, null, "aws/secretsmanager", null, REGION);
org.mockito.Mockito.verify(kms, org.mockito.Mockito.never())
.describeKey(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString());
}
@Test
void updateSecretRejectsAKmsKeyThatDoesNotExist() {
io.github.hectorvent.floci.services.kms.KmsService kms =
org.mockito.Mockito.mock(io.github.hectorvent.floci.services.kms.KmsService.class);
SecretsManagerService kmsAware = serviceWithKms(kms);
kmsAware.createSecret("kms-secret", "v1", null, null, null, null, REGION);
org.mockito.Mockito.when(kms.describeKey(org.mockito.ArgumentMatchers.anyString(),
org.mockito.ArgumentMatchers.anyString()))
.thenThrow(new AwsException("NotFoundException", "Key not found", 404));
AwsException ex = assertThrows(AwsException.class, () ->
kmsAware.updateSecret("kms-secret", null, "missing-key", REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void aSecretWithoutAKmsKeyNeedsNoLookup() {
io.github.hectorvent.floci.services.kms.KmsService kms =
org.mockito.Mockito.mock(io.github.hectorvent.floci.services.kms.KmsService.class);
serviceWithKms(kms).createSecret("no-key", "v1", null, null, null, null, REGION);
org.mockito.Mockito.verify(kms, org.mockito.Mockito.never())
.describeKey(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString());
}
// ─── Replication ───────────────────────────────────────────────────────────
private static final String REPLICA_REGION = "eu-west-1";
private Secret replicate(String name, String... regions) {
List<SecretsManagerService.ReplicaRegion> targets = new java.util.ArrayList<>();
for (String r : regions) {
targets.add(new SecretsManagerService.ReplicaRegion(r, null));
}
return service.replicateSecretToRegions(name, targets, false, REGION);
}
@Test
void replicateSecretCopiesTheValueIntoTheReplicaRegion() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
Secret primary = replicate("multi", REPLICA_REGION);
assertEquals(1, primary.getReplicationStatus().size());
assertEquals(REPLICA_REGION, primary.getReplicationStatus().getFirst().region());
assertEquals("InSync", primary.getReplicationStatus().getFirst().status());
assertEquals("v1", service.getSecretValue("multi", null, null, REPLICA_REGION).getSecretString());
}
@Test
void replicaArnMatchesThePrimaryWithTheRegionSwapped() {
// AWS: "The replica ARN is the same as the original primary secret ARN except the Region."
service.createSecret("multi", "v1", null, null, null, null, REGION);
Secret primary = replicate("multi", REPLICA_REGION);
Secret replica = service.describeSecret("multi", REPLICA_REGION);
assertEquals(primary.getArn().replace(REGION, REPLICA_REGION), replica.getArn());
}
@Test
void replicaTracksLaterWritesToThePrimary() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
replicate("multi", REPLICA_REGION);
service.putSecretValue("multi", "v2", null, null, REGION, null);
assertEquals("v2", service.getSecretValue("multi", null, null, REPLICA_REGION).getSecretString());
}
@Test
void replicaReportsThePrimaryRegionAndThePrimaryReportsItsOwn() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
replicate("multi", REPLICA_REGION);
assertEquals(REGION, service.describeSecret("multi", REPLICA_REGION).getPrimaryRegion());
assertNull(service.describeSecret("multi", REGION).getPrimaryRegion());
}
@Test
void replicatingOntoAnExistingNameFailsThatRegionWithoutForce() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
service.createSecret("multi", "squatter", null, null, null, null, REPLICA_REGION);
Secret primary = replicate("multi", REPLICA_REGION);
assertEquals("Failed", primary.getReplicationStatus().getFirst().status());
// The pre-existing secret is left untouched.
assertEquals("squatter", service.getSecretValue("multi", null, null, REPLICA_REGION).getSecretString());
}
@Test
void replicatingOntoAnExistingNameOverwritesItWithForce() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
service.createSecret("multi", "squatter", null, null, null, null, REPLICA_REGION);
Secret primary = service.replicateSecretToRegions("multi",
List.of(new SecretsManagerService.ReplicaRegion(REPLICA_REGION, null)), true, REGION);
assertEquals("InSync", primary.getReplicationStatus().getFirst().status());
assertEquals("v1", service.getSecretValue("multi", null, null, REPLICA_REGION).getSecretString());
}
@Test
void writingToAReplicaIsRejected() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
replicate("multi", REPLICA_REGION);
AwsException ex = assertThrows(AwsException.class, () ->
service.putSecretValue("multi", "sneaky", null, null, REPLICA_REGION, null));
assertEquals("InvalidRequestException", ex.getErrorCode());
}
@Test
void deletingAPrimaryThatStillHasReplicasIsRejected() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
replicate("multi", REPLICA_REGION);
AwsException ex = assertThrows(AwsException.class, () ->
service.deleteSecret("multi", null, false, REGION));
assertEquals("InvalidRequestException", ex.getErrorCode());
}
@Test
void removingARegionDeletesTheReplicaImmediately() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
replicate("multi", REPLICA_REGION);
Secret primary = service.removeRegionsFromReplication("multi", List.of(REPLICA_REGION), REGION);
assertTrue(primary.getReplicationStatus().isEmpty());
assertThrows(AwsException.class, () -> service.describeSecret("multi", REPLICA_REGION));
// With the last replica gone the primary can be deleted again.
assertNotNull(service.deleteSecret("multi", null, false, REGION).getDeletedDate());
}
@Test
void stopReplicationPromotesTheReplicaToAStandalonePrimary() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
replicate("multi", REPLICA_REGION);
Secret promoted = service.stopReplicationToReplica("multi", REPLICA_REGION);
assertNull(promoted.getPrimaryRegion());
// The old primary no longer lists it, and the promoted copy now accepts writes.
assertTrue(service.describeSecret("multi", REGION).getReplicationStatus().isEmpty());
assertEquals("now-mine", service.putSecretValue("multi", "now-mine", null, null,
REPLICA_REGION, null).getSecretString());
// The promotion does not disturb the original primary's value.
assertEquals("v1", service.getSecretValue("multi", null, null, REGION).getSecretString());
}
@Test
void stopReplicationOnAPrimaryIsRejected() {
service.createSecret("multi", "v1", null, null, null, null, REGION);
replicate("multi", REPLICA_REGION);
AwsException ex = assertThrows(AwsException.class, () ->
service.stopReplicationToReplica("multi", REGION));
assertEquals("InvalidRequestException", ex.getErrorCode());
}
// ─── ListSecrets planned deletion ──────────────────────────────────────────
@Test
void listSecretsCanIncludeSecretsPendingDeletion() {
service.createSecret("active", "v1", null, null, null, null, REGION);
service.createSecret("doomed", "v2", null, null, null, null, REGION);
service.deleteSecret("doomed", 7, false, REGION);
assertEquals(1, service.listSecrets(REGION, null, false).size());
assertEquals(2, service.listSecrets(REGION, null, true).size());
}
}
@@ -0,0 +1,164 @@
package io.github.hectorvent.floci.services.secretsmanager;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Every write to a secret goes through the same per-secret monitor, including the writes a primary
* fans out to its replicas. These tests park a write halfway through and assert that a second
* caller aiming at the same secret waits for it, rather than interleaving with it.
*/
class SecretsManagerWriteLockTest {
private static final String REGION = "us-east-1";
private static final String REPLICA_REGION = "us-west-2";
private static final String SECRET_NAME = "shared-secret";
private ParkingStorage storage;
private SecretsManagerService service;
@BeforeEach
void setUp() {
storage = new ParkingStorage();
service = new SecretsManagerService(storage, 30);
service.createSecret(SECRET_NAME, "v1", null, "original", null, null, REGION);
}
@Test
void updateSecretWaitsForAnInFlightUpdate() throws Exception {
storage.parkOn(REGION + "::" + SECRET_NAME);
Watched first = start("first-update", () ->
service.updateSecret(SECRET_NAME, "from-first", null, REGION));
assertTrue(storage.awaitEntered(), "UpdateSecret never reached the store write");
Watched second = start("second-update", () ->
service.updateSecret(SECRET_NAME, null, "alias/second", REGION));
assertTrue(second.awaitBlocked(), "UpdateSecret did not wait for the in-flight UpdateSecret");
storage.release();
first.awaitSuccess();
second.awaitSuccess();
// Serialized, so neither field was dropped: the second update applied on top of the first.
Secret updated = service.describeSecret(SECRET_NAME, REGION);
assertEquals("from-first", updated.getDescription());
assertEquals("alias/second", updated.getKmsKeyId());
}
@Test
void promotingAReplicaWaitsForAnInFlightSyncFromItsPrimary() throws Exception {
service.replicateSecretToRegions(SECRET_NAME,
List.of(new SecretsManagerService.ReplicaRegion(REPLICA_REGION, null)), false, REGION);
// The primary's own write lands first; the copy pushed to the replica is what parks.
storage.parkOn(REPLICA_REGION + "::" + SECRET_NAME);
Watched writer = start("primary-writer", () ->
service.putSecretValue(SECRET_NAME, "v2", null, null, REGION, null));
assertTrue(storage.awaitEntered(), "PutSecretValue never reached the replica sync");
Watched promoter = start("promoter", () ->
service.stopReplicationToReplica(SECRET_NAME, REPLICA_REGION));
assertTrue(promoter.awaitBlocked(),
"StopReplicationToReplica did not wait for the in-flight replica sync");
storage.release();
writer.awaitSuccess();
promoter.awaitSuccess();
// The promotion ran after the sync, so it is the promotion that stands: the replica is a
// standalone secret and the old primary no longer syncs into it.
Secret promoted = service.describeSecret(SECRET_NAME, REPLICA_REGION);
assertNull(promoted.getPrimaryRegion());
assertTrue(service.describeSecret(SECRET_NAME, REGION).getReplicationStatus().isEmpty());
}
private static Watched start(String name, Runnable body) {
Watched watched = new Watched(name, body);
watched.thread.start();
return watched;
}
/** Parks the first write to one chosen key so another thread can race the caller holding it. */
private static final class ParkingStorage extends InMemoryStorage<String, Secret> {
private final CountDownLatch entered = new CountDownLatch(1);
private final CountDownLatch released = new CountDownLatch(1);
private volatile String parkKey;
void parkOn(String key) {
this.parkKey = key;
}
boolean awaitEntered() throws InterruptedException {
return entered.await(5, TimeUnit.SECONDS);
}
void release() {
released.countDown();
}
@Override
public void put(String key, Secret value) {
if (key.equals(parkKey)) {
parkKey = null;
entered.countDown();
try {
released.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
super.put(key, value);
}
}
/** A thread whose failure and whose wait on the secret's monitor the test can assert on. */
private static final class Watched {
private final Thread thread;
private final AtomicReference<Throwable> thrown = new AtomicReference<>();
Watched(String name, Runnable body) {
this.thread = new Thread(() -> {
try {
body.run();
} catch (Throwable t) {
thrown.set(t);
}
}, name);
this.thread.setDaemon(true);
}
/** Waits for the thread to sit on a monitor rather than for a fixed interval to pass. */
boolean awaitBlocked() throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime() < deadline) {
if (thread.getState() == Thread.State.BLOCKED) {
return true;
}
if (!thread.isAlive()) {
return false;
}
Thread.sleep(5);
}
return false;
}
void awaitSuccess() throws InterruptedException {
thread.join(TimeUnit.SECONDS.toMillis(5));
assertTrue(!thread.isAlive(), thread.getName() + " did not finish within the join timeout");
assertNull(thrown.get(), () -> thread.getName() + " failed: " + thrown.get());
}
}
}