Light, fluffy, and always free - The AWS Local Emulator alternative
feat(secretsmanager): add the five missing actions and correct response fidelity (#3711)
Abhigya33d17c0146ca
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SecretsManagerTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SecretsManagerTest.javaindex f7eedaa2ef..95f194edd3 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SecretsManagerTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SecretsManagerTest.java@@ -9,6 +9,8 @@ import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;import software.amazon.awssdk.core.SdkBytes;+import software.amazon.awssdk.services.kms.KmsClient;+import software.amazon.awssdk.services.kms.model.CreateKeyRequest;import software.amazon.awssdk.services.lambda.LambdaClient;import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;@@ -30,6 +32,7 @@ import software.amazon.awssdk.services.secretsmanager.model.GetResourcePolicyReqimport software.amazon.awssdk.services.secretsmanager.model.GetResourcePolicyResponse;import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;+import software.amazon.awssdk.services.secretsmanager.model.InvalidParameterException;import software.amazon.awssdk.services.secretsmanager.model.ListSecretVersionIdsRequest;import software.amazon.awssdk.services.secretsmanager.model.ListSecretVersionIdsResponse;import software.amazon.awssdk.services.secretsmanager.model.ListSecretsRequest;@@ -276,8 +279,16 @@ class SecretsManagerTest {@Test@Order(13)void kmsKeyIdPreservation() {- String kmsKeyId = "arn:aws:kms:us-east-1:000000000000:key/my-key";+ // The key has to exist: Secrets Manager checks it before accepting the secret, so a+ // made-up ARN is rejected here the same way AWS rejects one.String kmsSecretName = "sdk-test-kms-secret-" + System.currentTimeMillis();+ String kmsKeyId;+ try (KmsClient kms = TestFixtures.kmsClient()) {+ kmsKeyId = kms.createKey(CreateKeyRequest.builder()+ .description("sdk-test secrets manager key")+ .build())+ .keyMetadata().arn();+ }try {sm.createSecret(CreateSecretRequest.builder()@@ -303,6 +314,20 @@ class SecretsManagerTest {@Test@Order(14)+ void createSecretWithAnUnknownKmsKeyIsRejected() {+ String kmsSecretName = "sdk-test-bad-kms-secret-" + System.currentTimeMillis();++ assertThatThrownBy(() -> sm.createSecret(CreateSecretRequest.builder()+ .name(kmsSecretName)+ .secretString("kms-value")+ .kmsKeyId("arn:aws:kms:us-east-1:000000000000:key/does-not-exist")+ .build()))+ .isInstanceOf(InvalidParameterException.class)+ .hasMessageContaining("You can't access the KMS key");+ }++ @Test+ @Order(15)void createSecretDuplicateThrows400() {String dupName = "sdk-test-dup-secret-" + System.currentTimeMillis();@@ -330,7 +355,7 @@ class SecretsManagerTest {}@Test- @Order(15)+ @Order(16)void getRandomPassword() {GetRandomPasswordResponse response = sm.getRandomPassword(GetRandomPasswordRequest.builder().passwordLength(32L)@@ -341,7 +366,7 @@ class SecretsManagerTest {}@Test- @Order(16)+ @Order(17)void getSecretValueNonExistentThrows400() {assertThatThrownBy(() -> sm.getSecretValue(GetSecretValueRequest.builder().secretId("non-existent-secret-" + System.currentTimeMillis())@@ -356,7 +381,7 @@ class SecretsManagerTest {// ─────────────────────────────────────────────────────────────────────────@Test- @Order(17)+ @Order(18)@DisplayName("#340 getSecretValue resolves partial ARN (without random suffix)")void getSecretValueByPartialArn() {Assumptions.assumeTrue(secretArn != null, "CreateSecret must succeed first");@@ -374,7 +399,7 @@ class SecretsManagerTest {}@Test- @Order(18)+ @Order(19)@DisplayName("#340 getSecretValue resolves partial ARN for secret with slashes in name")void getSecretValueByPartialArnWithSlashesInName() {String slashName = "compat-340/dev/database-" + System.currentTimeMillis();@@ -404,7 +429,7 @@ class SecretsManagerTest {}@Test- @Order(19)+ @Order(20)void batchGetSecretValue() {String s1 = "batch-secret-1-" + System.currentTimeMillis();String s2 = "batch-secret-2-" + System.currentTimeMillis();@@ -429,7 +454,7 @@ class SecretsManagerTest {}@Test- @Order(20)+ @Order(21)@DisplayName("batchGetSecretValue returns partial Errors list for missing secrets without throwing")void batchGetSecretValuePartialErrors() {String exists = "batch-exists-" + UUID.randomUUID();@@ -472,7 +497,7 @@ class SecretsManagerTest {// ─────────────────────────────────────────────────────────────────────────@Test- @Order(21)+ @Order(22)@DisplayName("resource policy round trip: put returns ARN/Name, get returns the policy, delete clears it")void resourcePolicyRoundTrip() {Assumptions.assumeTrue(secretArn != null, "CreateSecret must succeed first");diff --git a/docs/services/secrets-manager.md b/docs/services/secrets-manager.mdindex 4cb1d29881..b661fc9445 100644--- a/docs/services/secrets-manager.md+++ b/docs/services/secrets-manager.md@@ -15,8 +15,9 @@| `DescribeSecret` | Get secret metadata and version info || `ListSecrets` | List all secrets || `DeleteSecret` | Delete a secret (with recovery window) |-| `RestoreSecret` | - |+| `RestoreSecret` | Cancel a scheduled deletion and restore the secret || `RotateSecret` | Trigger secret rotation, via a Lambda or by the owning service |+| `CancelRotateSecret` | Turn off automatic rotation and report any half-staged `AWSPENDING` version || `TagResource` | Tag a secret || `UntagResource` | Remove tags || `ListSecretVersionIds` | List all versions of a secret |@@ -26,6 +27,10 @@| `DeleteResourcePolicy` | Remove the resource policy || `PutResourcePolicy` | Attach a resource policy || `UpdateSecretVersionStage` | Move a staging label between versions |+| `ValidateResourcePolicy` | Check a resource policy for overly broad principals |+| `ReplicateSecretToRegions` | Replicate a secret into other regions |+| `RemoveRegionsFromReplication` | Delete replicas from the given regions |+| `StopReplicationToReplica` | Promote a replica to a standalone primary |<!-- floci:actions:end -->## Configuration@@ -34,6 +39,8 @@|---|---|---|| `FLOCI_SERVICES_SECRETSMANAGER_ENABLED` | `true` | Enable or disable the service || `FLOCI_SERVICES_SECRETSMANAGER_DEFAULT_RECOVERY_WINDOW_DAYS` | `30` | Days before a deleted secret is permanently purged |+| `FLOCI_SERVICES_SECRETSMANAGER_SCHEDULED_ROTATION_ENABLED` | `true` | Run the background sweep that fires rotations when a schedule comes due |+| `FLOCI_SERVICES_SECRETSMANAGER_ROTATION_TICK_SECONDS` | `60` | How often that sweep looks for due rotations |## Examples@@ -96,4 +103,55 @@ aws secretsmanager update-secret-version-stage \--move-to-version-id <new-version-id> \--remove-from-version-id <old-version-id> \--endpoint-url $AWS_ENDPOINT_URL++# Turn on scheduled rotation, then turn it back off+aws secretsmanager rotate-secret \+ --secret-id /app/database-url \+ --rotation-lambda-arn arn:aws:lambda:us-east-1:000000000000:function:my-rotator \+ --rotation-rules '{"ScheduleExpression":"rate(10 days)"}' \+ --endpoint-url $AWS_ENDPOINT_URL++aws secretsmanager cancel-rotate-secret \+ --secret-id /app/database-url \+ --endpoint-url $AWS_ENDPOINT_URL++# Replicate to another region, then promote the replica to its own primary+aws secretsmanager replicate-secret-to-regions \+ --secret-id /app/database-url \+ --add-replica-regions Region=eu-west-1 \+ --endpoint-url $AWS_ENDPOINT_URL++aws secretsmanager stop-replication-to-replica \+ --secret-id /app/database-url \+ --region eu-west-1 \+ --endpoint-url $AWS_ENDPOINT_URL++# Check a resource policy before attaching it+aws secretsmanager validate-resource-policy \+ --secret-id /app/database-url \+ --resource-policy file://policy.json \+ --endpoint-url $AWS_ENDPOINT_URL```++## Behaviour notes++- **Rotation schedules fire.** A background sweep (see the config table) rotates any secret whose+ `NextRotationDate` has passed. `AutomaticallyAfterDays`, `rate()` and `cron()` are all honoured.+- **Replication is synchronous.** Real AWS reports `InProgress` first; floci copies the secret+ immediately, so a replica is `InSync` by the time the call returns. Replicas are read-only and+ track later writes to the primary.+- **Secret values are stored in the clear.** `KmsKeyId` is validated — a missing key is rejected,+ and a disabled or pending-deletion key raises `EncryptionFailure` — but values are not actually+ encrypted, since encrypting with the emulator's own KMS would protect nothing.+- **`ValidateResourcePolicy` and `BlockPublicPolicy` check for wildcard principals only.** AWS runs+ the policy through Zelkova; a pass here is weaker than a pass on AWS. `PutResourcePolicy` with+ `BlockPublicPolicy` raises `PublicPolicyException` for a wildcard principal, and — as on AWS —+ leaves such a policy alone when the flag is absent.+- **`PrimaryRegion` and `ReplicationStatus` appear only on multi-region secrets**, matching AWS's+ "only returns fields that have a value" rule — a standalone secret carries neither.+- **Rotation schedule limits are enforced**: `AutomaticallyAfterDays` 1–1000, `Duration` as `Nh`,+ and `rate()` in hours or days no faster than every four hours.+- **Known deviation:** `RotateSecret` with `RotateImmediately: false` invokes the rotation+ function's `testSecret` step but does not first create the throwaway `AWSPENDING` version that+ AWS creates and removes, so a rotation function whose `testSecret` reads that version by id+ will not find it.diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 0a620ef263..1638382004 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -1600,6 +1600,12 @@ public interface EmulatorConfig {@WithDefault("30")int defaultRecoveryWindowDays();++ @WithDefault("true")+ boolean scheduledRotationEnabled();++ @WithDefault("60")+ long rotationTickSeconds();}interface ApiGatewayV2ServiceConfig {diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/RandomPasswordGenerator.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/RandomPasswordGenerator.javaindex 3cff47ae52..7fe0760639 100644--- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/RandomPasswordGenerator.java+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/RandomPasswordGenerator.java@@ -42,6 +42,9 @@ public final class RandomPasswordGenerator {boolean excludePunctuation = boolField(node, "ExcludePunctuation");boolean includeSpace = boolField(node, "IncludeSpace");String excludeChars = stringField(node, "ExcludeCharacters");+ if (excludeChars != null && excludeChars.length() > 4096) {+ throw new IllegalArgumentException("ExcludeCharacters must be at most 4096 characters.");+ }JsonNode passwordLengthNode = node == null ? null : node.get("PasswordLength");int length = (passwordLengthNode != null && !passwordLengthNode.isNull())diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/ResourcePolicyValidator.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/ResourcePolicyValidator.javanew file mode 100644index 0000000000..fbdec82145--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/ResourcePolicyValidator.java@@ -0,0 +1,103 @@+package io.github.hectorvent.floci.services.secretsmanager;++import com.fasterxml.jackson.databind.JsonNode;++import java.util.ArrayList;+import java.util.List;++/**+ * Checks a Secrets Manager resource policy for principals broad enough that the policy would hand+ * the secret to anyone.+ *+ * <p>Real AWS runs the policy through Zelkova, an automated reasoning engine, and reports each+ * finding under a check name. Floci does not carry a reasoning engine, so it implements the one+ * check that catches the mistake the API exists to catch - a wildcard principal - and reports it+ * under the same {@code REFLEXIVE_PRINCIPAL_CHECK} name real AWS uses, so a caller keying off the+ * check name behaves identically. Narrower Zelkova findings (a policy that grants broad access by+ * way of conditions, say) are not detected, so a pass here is weaker than a pass on AWS.+ *+ * @see <a href="https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_ValidateResourcePolicy.html">+ * AWS Secrets Manager - ValidateResourcePolicy</a>+ */+public final class ResourcePolicyValidator {++ /** The name AWS reports a broad-principal finding under. */+ public static final String REFLEXIVE_PRINCIPAL_CHECK = "REFLEXIVE_PRINCIPAL_CHECK";++ private static final String WILDCARD = "*";++ /** A single finding: the check that failed and what it found. */+ public record ValidationError(String checkName, String errorMessage) {+ }++ private ResourcePolicyValidator() {+ }++ /**+ * Returns the findings for {@code policy}, empty when the policy passes. The document is+ * assumed to already be syntactically valid JSON; callers raise+ * MalformedPolicyDocumentException before reaching here.+ */+ public static List<ValidationError> validate(JsonNode policy) {+ List<ValidationError> errors = new ArrayList<>();+ JsonNode statements = policy.path("Statement");++ // A lone statement object is as valid as an array of them.+ if (statements.isObject()) {+ checkStatement(statements, errors);+ } else if (statements.isArray()) {+ for (JsonNode statement : statements) {+ checkStatement(statement, errors);+ }+ }+ return errors;+ }++ private static void checkStatement(JsonNode statement, List<ValidationError> errors) {+ // Only Allow statements can widen access; a wildcard principal on a Deny is a deny-all,+ // which is restrictive rather than dangerous.+ if (!"Allow".equalsIgnoreCase(statement.path("Effect").asText())) {+ return;+ }+ if (isWildcardPrincipal(statement.path("Principal"))) {+ errors.add(new ValidationError(REFLEXIVE_PRINCIPAL_CHECK,+ "The resource policy grants broad access to your secret. "+ + "Amend the policy so that it does not use a wildcard principal."));+ }+ }++ /**+ * A principal is wildcard either as the bare string {@code "*"} or as a keyed form whose value+ * is {@code "*"} - {@code {"AWS": "*"}} and {@code {"AWS": ["*"]}} both grant everyone.+ */+ private static boolean isWildcardPrincipal(JsonNode principal) {+ if (principal.isMissingNode() || principal.isNull()) {+ return false;+ }+ if (principal.isTextual()) {+ return WILDCARD.equals(principal.asText());+ }+ if (principal.isObject()) {+ for (JsonNode value : principal) {+ if (containsWildcard(value)) {+ return true;+ }+ }+ }+ return false;+ }++ private static boolean containsWildcard(JsonNode value) {+ if (value.isTextual()) {+ return WILDCARD.equals(value.asText());+ }+ if (value.isArray()) {+ for (JsonNode entry : value) {+ if (entry.isTextual() && WILDCARD.equals(entry.asText())) {+ return true;+ }+ }+ }+ return false;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretRotationScheduler.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretRotationScheduler.javanew file mode 100644index 0000000000..d6857afd0d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretRotationScheduler.java@@ -0,0 +1,117 @@+package io.github.hectorvent.floci.services.secretsmanager;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.secretsmanager.model.Secret;+import io.quarkus.runtime.ShutdownEvent;+import io.quarkus.runtime.StartupEvent;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.event.Observes;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.UUID;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;++/**+ * Fires rotations when a secret's rotation schedule comes due.+ *+ * <p>Without this, {@code RotationRules} were stored and echoed back but never acted on: only an+ * explicit RotateSecret call ever rotated anything, so {@code AutomaticallyAfterDays} and+ * {@code ScheduleExpression} described a schedule that could not happen.+ *+ * <p>A single background thread ticks on a fixed interval and rotates every secret whose+ * {@code NextRotationDate} has passed. {@link SecretsManagerService#rotateSecret} advances that+ * date as it dispatches, so a secret is claimed on the tick that picks it up and the rotation's+ * own success or failure does not decide whether the sweep retries it immediately.+ */+@ApplicationScoped+public class SecretRotationScheduler {++ private static final Logger LOG = Logger.getLogger(SecretRotationScheduler.class);++ private final SecretsManagerService service;+ private final long tickIntervalSeconds;+ private final boolean enabled;+ private final ScheduledExecutorService executor;++ @Inject+ public SecretRotationScheduler(SecretsManagerService service, EmulatorConfig config) {+ this.service = service;+ this.tickIntervalSeconds = config.services().secretsmanager().rotationTickSeconds();+ this.enabled = config.services().secretsmanager().enabled()+ && config.services().secretsmanager().scheduledRotationEnabled();+ this.executor = Executors.newSingleThreadScheduledExecutor(r -> {+ Thread t = new Thread(r, "secretsmanager-rotation-scheduler");+ t.setDaemon(true);+ return t;+ });+ }++ /** Test seam: a scheduler that never starts its thread, so {@link #tick} drives it directly. */+ SecretRotationScheduler(SecretsManagerService service) {+ this.service = service;+ this.tickIntervalSeconds = 60;+ this.enabled = false;+ this.executor = null;+ }++ void onStart(@Observes StartupEvent ignored) {+ if (!enabled) {+ LOG.debug("Secrets Manager scheduled rotation disabled by configuration");+ return;+ }+ executor.scheduleAtFixedRate(this::tickSafely, tickIntervalSeconds, tickIntervalSeconds,+ TimeUnit.SECONDS);+ LOG.infov("Secrets Manager rotation scheduler started (tick every {0}s)", tickIntervalSeconds);+ }++ void onStop(@Observes ShutdownEvent ignored) {+ if (executor != null) {+ executor.shutdownNow();+ }+ }++ void tickSafely() {+ try {+ tick(Instant.now());+ } catch (Throwable t) {+ LOG.warnv("Secrets Manager rotation sweep failed: {0}", t.getMessage());+ }+ }++ void tick(Instant now) {+ for (SecretsManagerService.RegionalSecret entry : service.listAllSecrets()) {+ if (!isDue(entry.secret(), now)) {+ continue;+ }+ try {+ // Addressed by ARN, not name: the ARN names the owning account, and this thread+ // has no request to resolve one from. A null Lambda ARN reuses the one already+ // configured on the secret.+ service.rotateSecret(entry.secret().getArn(), UUID.randomUUID().toString(),+ null, null, true, entry.region());+ LOG.infov("Triggered scheduled rotation for secret {0} in {1}",+ entry.secret().getName(), entry.region());+ } catch (Exception e) {+ // One secret mid-rotation, or missing its Lambda, must not stop the sweep.+ LOG.debugv("Skipping scheduled rotation for {0}: {1}",+ entry.secret().getName(), e.getMessage());+ }+ }+ }++ private boolean isDue(Secret secret, Instant now) {+ if (!secret.isRotationEnabled() || secret.getNextRotationDate() == null) {+ return false;+ }+ // A replica is read-only, a deleted secret is not rotatable, and a secret another AWS+ // service owns is rotated by that service rather than through a rotation Lambda.+ if (secret.isReplica() || secret.getDeletedDate() != null || secret.getOwningService() != null) {+ return false;+ }+ return !secret.getNextRotationDate().isAfter(now);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.javaindex 29d2d69de1..4ef88ac6d9 100644--- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.secretsmanager;import io.github.hectorvent.floci.core.common.AwsErrorResponse;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.secretsmanager.model.Secret;import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;import com.fasterxml.jackson.core.JsonProcessingException;@@ -15,14 +16,21 @@ import jakarta.ws.rs.core.Response;import java.time.Instant;import java.util.ArrayList;import java.util.Comparator;-import java.util.HashMap;import java.util.List;import java.util.Map;+import java.util.UUID;import java.util.stream.StreamSupport;@ApplicationScopedpublic class SecretsManagerJsonHandler {+ private static final int MAX_FILTERS = 10;+ private static final int MAX_BATCH_SECRET_IDS = 20;+ private static final int MAX_RESOURCE_POLICY_LENGTH = 20480;+ private static final String SORT_BY_CREATED_DATE = "created-date";+ private static final List<String> SORT_BY_VALUES =+ List.of(SORT_BY_CREATED_DATE, "last-accessed-date", "last-changed-date", "name");+private final SecretsManagerService service;private final ObjectMapper objectMapper;@@ -43,6 +51,7 @@ public class SecretsManagerJsonHandler {case "DeleteSecret" -> handleDeleteSecret(request, region);case "RestoreSecret" -> handleRestoreSecret(request, region);case "RotateSecret" -> handleRotateSecret(request, region);+ case "CancelRotateSecret" -> handleCancelRotateSecret(request, region);case "TagResource" -> handleTagResource(request, region);case "UntagResource" -> handleUntagResource(request, region);case "ListSecretVersionIds" -> handleListSecretVersionIds(request, region);@@ -52,6 +61,10 @@ public class SecretsManagerJsonHandler {case "DeleteResourcePolicy" -> handleDeleteResourcePolicy(request, region);case "PutResourcePolicy" -> handlePutResourcePolicy(request, region);case "UpdateSecretVersionStage" -> handleUpdateSecretVersionStage(request, region);+ case "ValidateResourcePolicy" -> handleValidateResourcePolicy(request, region);+ case "ReplicateSecretToRegions" -> handleReplicateSecretToRegions(request, region);+ case "RemoveRegionsFromReplication" -> handleRemoveRegionsFromReplication(request, region);+ case "StopReplicationToReplica" -> handleStopReplicationToReplica(request, region);default -> Response.status(400).entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported.")).build();@@ -78,6 +91,12 @@ public class SecretsManagerJsonHandler {if (request.has("SecretIdList")) {List<String> secretIdList = new ArrayList<>();request.path("SecretIdList").forEach(id -> secretIdList.add(id.asText()));+ if (secretIdList.size() > MAX_BATCH_SECRET_IDS) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "SecretIdList can contain at most " + MAX_BATCH_SECRET_IDS + " items."))+ .build();+ }SecretsManagerService.BatchGetSecretValueResult result =service.batchGetSecretValue(secretIdList, region);values = result.values();@@ -105,8 +124,16 @@ public class SecretsManagerJsonHandler {}}+ List<SecretsManagerService.Filter> filters = parseFilters(request);+ if (filters.size() > MAX_FILTERS) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "Filters can contain at most " + MAX_FILTERS + " items."))+ .build();+ }+List<SecretsManagerService.BatchSecretValue> allFilteredValues =- service.batchGetSecretValueByFilters(parseFilters(request), region);+ service.batchGetSecretValueByFilters(filters, region);if (startIndex > allFilteredValues.size()) {values = List.of();@@ -135,11 +162,7 @@ public class SecretsManagerJsonHandler {if (value.createdDate() != null) {node.put("CreatedDate", value.createdDate().toEpochMilli() / 1000.0);}- ArrayNode stages = objectMapper.createArrayNode();- if (value.versionStages() != null) {- value.versionStages().forEach(stages::add);- }- node.set("VersionStages", stages);+ putVersionStages(node, value.versionStages());secretValues.add(node);}response.set("SecretValues", secretValues);@@ -162,18 +185,33 @@ public class SecretsManagerJsonHandler {private Response handleCreateSecret(JsonNode request, String region) {String name = request.path("Name").asText();+ SecretsManagerService.validateSecretName(name);String secretString = request.has("SecretString") ? request.path("SecretString").asText() : null;String secretBinary = request.has("SecretBinary") ? request.path("SecretBinary").asText() : null;String description = request.has("Description") ? request.path("Description").asText() : null;String kmsKeyId = request.has("KmsKeyId") ? request.path("KmsKeyId").asText() : null;+ String clientRequestToken = request.hasNonNull("ClientRequestToken")+ ? request.path("ClientRequestToken").asText() : null;List<Secret.Tag> tags = parseTags(request);- Secret secret = service.createSecret(name, secretString, secretBinary, description, kmsKeyId, tags, region);+ Secret secret = service.createSecret(name, secretString, secretBinary, description, kmsKeyId,+ tags, null, clientRequestToken, region);++ // AddReplicaRegions is the same work ReplicateSecretToRegions does, so the secret is+ // created first and then replicated, exactly as AWS documents the combined call.+ List<SecretsManagerService.ReplicaRegion> replicaRegions = parseReplicaRegions(request);+ if (!replicaRegions.isEmpty()) {+ secret = service.replicateSecretToRegions(secret.getArn(), replicaRegions,+ request.path("ForceOverwriteReplicaSecret").asBoolean(false), region);+ }ObjectNode response = objectMapper.createObjectNode();response.put("ARN", secret.getArn());response.put("Name", secret.getName());response.put("VersionId", secret.getCurrentVersionId());+ if (!replicaRegions.isEmpty()) {+ response.set("ReplicationStatus", replicationStatusNode(secret));+ }return Response.ok(response).build();}@@ -198,11 +236,7 @@ public class SecretsManagerJsonHandler {if (version.getCreatedDate() != null) {response.put("CreatedDate", version.getCreatedDate().toEpochMilli() / 1000.0);}- ArrayNode stages = objectMapper.createArrayNode();- if (version.getVersionStages() != null) {- version.getVersionStages().forEach(stages::add);- }- response.set("VersionStages", stages);+ putVersionStages(response, version.getVersionStages());return Response.ok(response).build();}@@ -212,6 +246,14 @@ public class SecretsManagerJsonHandler {String secretBinary = request.has("SecretBinary") ? request.path("SecretBinary").asText() : null;String clientRequestToken = request.has("ClientRequestToken") ? request.path("ClientRequestToken").asText() : null;+ // AWS: "You must include SecretBinary or SecretString, but not both." The service allows+ // neither, because that is how a rotation stages an empty AWSPENDING placeholder+ // internally, so the wire API is where a valueless request has to be refused.+ if (secretString == null && secretBinary == null) {+ throw new AwsException("InvalidParameterException",+ "You must specify either SecretString or SecretBinary.", 400);+ }+List<String> versionStages = request.has("VersionStages") && request.path("VersionStages").isArray()? StreamSupport.stream(request.path("VersionStages").spliterator(), false).map(JsonNode::asText).toList(): null;@@ -223,11 +265,7 @@ public class SecretsManagerJsonHandler {response.put("ARN", secret.getArn());response.put("Name", secret.getName());response.put("VersionId", version.getVersionId());- ArrayNode stages = objectMapper.createArrayNode();- if (version.getVersionStages() != null) {- version.getVersionStages().forEach(stages::add);- }- response.set("VersionStages", stages);+ putVersionStages(response, version.getVersionStages());return Response.ok(response).build();}@@ -237,13 +275,34 @@ public class SecretsManagerJsonHandler {String kmsKeyId = request.has("KmsKeyId") ? request.path("KmsKeyId").asText() : null;String secretString = request.has("SecretString") ? request.path("SecretString").asText() : null;String secretBinary = request.has("SecretBinary") ? request.path("SecretBinary").asText() : null;+ if (secretString != null && secretBinary != null) {+ throw new AwsException("InvalidParameterException",+ "You can't specify both SecretString and SecretBinary in the same request.", 400);+ }++ Secret existing = service.describeSecret(secretId, region);+ SecretsManagerService.throwIfServiceManaged(existing);++ // UpdateSecret, unlike PutSecretValue and CreateSecret, is NOT idempotent: AWS errors+ // when the token names a version that already exists, because an existing version can+ // never be modified. PutSecretValue below would happily treat it as a no-op retry.+ String clientRequestToken = request.hasNonNull("ClientRequestToken")+ ? request.path("ClientRequestToken").asText() : null;+ if (clientRequestToken != null && existing.getVersions() != null+ && existing.getVersions().containsKey(clientRequestToken)) {+ throw new AwsException("ResourceExistsException",+ "The ClientRequestToken " + clientRequestToken+ + " already names a version of this secret. You can't modify an existing "+ + "version, only create a new one.", 400);+ }Secret secret = service.updateSecret(secretId, description, kmsKeyId, region);String versionId = null;if (secretString != null || secretBinary != null) {- String clientRequestToken = request.has("ClientRequestToken") ? request.path("ClientRequestToken").asText() : java.util.UUID.randomUUID().toString();- SecretVersion version = service.putSecretValue(secretId, secretString, secretBinary, clientRequestToken, region, null);+ SecretVersion version = service.putSecretValue(secretId, secretString, secretBinary,+ clientRequestToken != null ? clientRequestToken : UUID.randomUUID().toString(),+ region, null);versionId = version.getVersionId();}@@ -274,23 +333,13 @@ public class SecretsManagerJsonHandler {response.put("RotationLambdaARN", secret.getRotationLambdaArn());}if (secret.getRotationRules() != null) {- ObjectNode rulesNode = objectMapper.createObjectNode();- if (secret.getRotationRules().automaticallyAfterDays() != null) rulesNode.put("AutomaticallyAfterDays", secret.getRotationRules().automaticallyAfterDays());- if (secret.getRotationRules().duration() != null) rulesNode.put("Duration", secret.getRotationRules().duration());- if (secret.getRotationRules().scheduleExpression() != null) rulesNode.put("ScheduleExpression", secret.getRotationRules().scheduleExpression());- response.set("RotationRules", rulesNode);+ response.set("RotationRules", rotationRulesNode(secret.getRotationRules()));}if (secret.getLastRotatedDate() != null) {response.put("LastRotatedDate", secret.getLastRotatedDate().toEpochMilli() / 1000.0);}-- Instant nextRotationDate = secret.getNextRotationDate();- if (nextRotationDate == null && secret.isRotationEnabled() && secret.getRotationRules() != null && secret.getRotationRules().automaticallyAfterDays() != null) {- Instant lastRotated = secret.getLastRotatedDate() != null ? secret.getLastRotatedDate() : secret.getCreatedDate();- if (lastRotated != null) {- nextRotationDate = lastRotated.plusSeconds((long) secret.getRotationRules().automaticallyAfterDays() * 86400);- }- }++ Instant nextRotationDate = nextRotationDate(secret);if (nextRotationDate != null) {response.put("NextRotationDate", nextRotationDate.toEpochMilli() / 1000.0);}@@ -307,6 +356,66 @@ public class SecretsManagerJsonHandler {response.put("OwningService", secret.getOwningService());}+ // PrimaryRegion is a multi-region-only field: AWS returns only fields "that have a+ // value", and a standalone secret carries none. A replica points back at its primary's+ // region; a primary that has replicas reports its own.+ if (secret.isReplica()) {+ response.put("PrimaryRegion", secret.getPrimaryRegion());+ } else if (isReplicated(secret)) {+ response.put("PrimaryRegion", region);+ response.set("ReplicationStatus", replicationStatusNode(secret));+ }+ response.set("Tags", tagsNode(secret));+ response.set("VersionIdsToStages", versionStagesNode(secret));+ return Response.ok(response).build();+ }++ private static Comparator<Secret> sortComparator(String sortBy) {+ Comparator<Secret> comparator = switch (sortBy) {+ case "name" -> Comparator.comparing(Secret::getName, Comparator.nullsLast(Comparator.naturalOrder()));+ case "last-accessed-date" -> Comparator.comparing(Secret::getLastAccessedDate,+ Comparator.nullsLast(Comparator.naturalOrder()));+ case "last-changed-date" -> Comparator.comparing(Secret::getLastChangedDate,+ Comparator.nullsLast(Comparator.naturalOrder()));+ default -> Comparator.comparing(Secret::getCreatedDate,+ Comparator.nullsLast(Comparator.naturalOrder()));+ };+ return comparator.thenComparing(Secret::getName, Comparator.nullsLast(Comparator.naturalOrder()));+ }++ /**+ * The rotation date AWS reports: the one explicitly stored, otherwise the one implied by+ * {@code AutomaticallyAfterDays}. Null when rotation is off, which is what AWS returns.+ */+ private static Instant nextRotationDate(Secret secret) {+ if (secret.getNextRotationDate() != null) {+ return secret.getNextRotationDate();+ }+ if (!secret.isRotationEnabled() || secret.getRotationRules() == null+ || secret.getRotationRules().automaticallyAfterDays() == null) {+ return null;+ }+ Instant lastRotated = secret.getLastRotatedDate() != null+ ? secret.getLastRotatedDate() : secret.getCreatedDate();+ return lastRotated == null ? null+ : lastRotated.plusSeconds((long) secret.getRotationRules().automaticallyAfterDays() * 86400);+ }++ private ObjectNode rotationRulesNode(Secret.RotationRules rules) {+ ObjectNode node = objectMapper.createObjectNode();+ if (rules.automaticallyAfterDays() != null) {+ node.put("AutomaticallyAfterDays", rules.automaticallyAfterDays());+ }+ if (rules.duration() != null) {+ node.put("Duration", rules.duration());+ }+ if (rules.scheduleExpression() != null) {+ node.put("ScheduleExpression", rules.scheduleExpression());+ }+ return node;+ }++ private ArrayNode tagsNode(Secret secret) {ArrayNode tagsArray = objectMapper.createArrayNode();if (secret.getTags() != null) {for (Secret.Tag tag : secret.getTags()) {@@ -316,21 +425,29 @@ public class SecretsManagerJsonHandler {tagsArray.add(tagNode);}}- response.set("Tags", tagsArray);+ return tagsArray;+ }+ /**+ * The version-id to staging-label map. DescribeSecret calls it {@code VersionIdsToStages} and+ * ListSecrets calls it {@code SecretVersionsToStages}; the shape is identical.+ */+ private ObjectNode versionStagesNode(Secret secret) {ObjectNode versionIdsToStages = objectMapper.createObjectNode();if (secret.getVersions() != null) {- for (Map.Entry<String, SecretVersion> entry- : secret.getVersions().entrySet()) {- ArrayNode stagesArray = objectMapper.createArrayNode();- if (entry.getValue().getVersionStages() != null) {- entry.getValue().getVersionStages().forEach(stagesArray::add);+ for (Map.Entry<String, SecretVersion> entry : secret.getVersions().entrySet()) {+ List<String> stages = entry.getValue().getVersionStages();+ // A version with every staging label stripped is deprecated - AWS lists only+ // versions "that have staging labels attached" and never an empty array.+ if (stages == null || stages.isEmpty()) {+ continue;}+ ArrayNode stagesArray = objectMapper.createArrayNode();+ stages.forEach(stagesArray::add);versionIdsToStages.set(entry.getKey(), stagesArray);}}- response.set("VersionIdsToStages", versionIdsToStages);- return Response.ok(response).build();+ return versionIdsToStages;}/** Parses the request's {@code Filters} array, shared by BatchGetSecretValue and ListSecrets. */@@ -349,11 +466,37 @@ public class SecretsManagerJsonHandler {}private Response handleListSecrets(JsonNode request, String region) {- List<Secret> secrets = new ArrayList<>(service.listSecrets(region, parseFilters(request)));- // AWS lists secrets by CreatedDate when SortBy is absent; sort on it (name as a- // tiebreaker) for AWS-matching, stable pagination across calls.- secrets.sort(Comparator.comparing(Secret::getCreatedDate, Comparator.nullsLast(Comparator.naturalOrder()))- .thenComparing(Secret::getName));+ List<SecretsManagerService.Filter> filters = parseFilters(request);+ if (filters.size() > MAX_FILTERS) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "Filters can contain at most " + MAX_FILTERS + " items."))+ .build();+ }++ String sortBy = request.hasNonNull("SortBy") ? request.path("SortBy").asText() : SORT_BY_CREATED_DATE;+ if (!SORT_BY_VALUES.contains(sortBy)) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "Invalid SortBy value, must be one of " + String.join(" | ", SORT_BY_VALUES)))+ .build();+ }++ String sortOrder = request.hasNonNull("SortOrder") ? request.path("SortOrder").asText() : "asc";+ if (!"asc".equals(sortOrder) && !"desc".equals(sortOrder)) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "Invalid SortOrder value, must be asc or desc"))+ .build();+ }++ boolean includePlannedDeletion = request.path("IncludePlannedDeletion").asBoolean(false);+ List<Secret> secrets = new ArrayList<>(service.listSecrets(region, filters, includePlannedDeletion));++ // AWS lists secrets by CreatedDate when SortBy is absent. Whatever the key, name breaks+ // ties so offset-based pagination stays stable across calls.+ Comparator<Secret> comparator = sortComparator(sortBy);+ secrets.sort("desc".equals(sortOrder) ? comparator.reversed() : comparator);// MaxResults is constrained to 1-100; when absent the full result set is returned.int maxResults = secrets.size();@@ -398,6 +541,19 @@ public class SecretsManagerJsonHandler {node.put("KmsKeyId", secret.getKmsKeyId());}node.put("RotationEnabled", secret.isRotationEnabled());+ if (secret.getRotationLambdaArn() != null) {+ node.put("RotationLambdaARN", secret.getRotationLambdaArn());+ }+ if (secret.getRotationRules() != null) {+ node.set("RotationRules", rotationRulesNode(secret.getRotationRules()));+ }+ if (secret.getLastRotatedDate() != null) {+ node.put("LastRotatedDate", secret.getLastRotatedDate().toEpochMilli() / 1000.0);+ }+ Instant nextRotation = nextRotationDate(secret);+ if (nextRotation != null) {+ node.put("NextRotationDate", nextRotation.toEpochMilli() / 1000.0);+ }if (secret.getCreatedDate() != null) {node.put("CreatedDate", secret.getCreatedDate().toEpochMilli() / 1000.0);}@@ -407,19 +563,20 @@ public class SecretsManagerJsonHandler {if (secret.getLastAccessedDate() != null) {node.put("LastAccessedDate", secret.getLastAccessedDate().toEpochMilli() / 1000.0);}+ if (secret.getDeletedDate() != null) {+ node.put("DeletedDate", secret.getDeletedDate().toEpochMilli() / 1000.0);+ }if (secret.getOwningService() != null) {node.put("OwningService", secret.getOwningService());}- ArrayNode tagsArray = objectMapper.createArrayNode();- if (secret.getTags() != null) {- for (Secret.Tag tag : secret.getTags()) {- ObjectNode tagNode = objectMapper.createObjectNode();- tagNode.put("Key", tag.key());- tagNode.put("Value", tag.value());- tagsArray.add(tagNode);- }+ if (secret.isReplica()) {+ node.put("PrimaryRegion", secret.getPrimaryRegion());+ } else if (isReplicated(secret)) {+ node.put("PrimaryRegion", region);+ node.set("ReplicationStatus", replicationStatusNode(secret));}- node.set("Tags", tagsArray);+ node.set("Tags", tagsNode(secret));+ node.set("SecretVersionsToStages", versionStagesNode(secret));secretList.add(node);}response.set("SecretList", secretList);@@ -432,7 +589,7 @@ public class SecretsManagerJsonHandler {private Response handleDeleteSecret(JsonNode request, String region) {String secretId = request.path("SecretId").asText();boolean forceDelete = request.path("ForceDeleteWithoutRecovery").asBoolean(false);- Integer recoveryWindowInDays = request.has("RecoveryWindowInDays")+ Integer recoveryWindowInDays = request.hasNonNull("RecoveryWindowInDays")? request.path("RecoveryWindowInDays").asInt() : null;Secret secret = service.deleteSecret(secretId, recoveryWindowInDays, forceDelete, region);@@ -458,7 +615,7 @@ public class SecretsManagerJsonHandler {private Response handleRotateSecret(JsonNode request, String region) {String secretId = request.path("SecretId").asText();- String clientRequestToken = request.has("ClientRequestToken") ? request.path("ClientRequestToken").asText() : java.util.UUID.randomUUID().toString();+ String clientRequestToken = request.has("ClientRequestToken") ? request.path("ClientRequestToken").asText() : UUID.randomUUID().toString();String lambdaArn = request.has("RotationLambdaARN") ? request.path("RotationLambdaARN").asText() : null;@@ -494,8 +651,32 @@ public class SecretsManagerJsonHandler {return Response.ok(response).build();}+ private Response handleCancelRotateSecret(JsonNode request, String region) {+ String secretId = request.path("SecretId").asText();+ // A service-managed secret is rotated by its owning service, so rotation can't be turned+ // off from outside - the same guard RotateSecret applies.+ SecretsManagerService.throwIfServiceManaged(service.describeSecret(secretId, region));+ SecretsManagerService.CancelRotationResult result = service.cancelRotateSecret(secretId, region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("ARN", result.secret().getArn());+ response.put("Name", result.secret().getName());+ // AWS omits VersionId when no rotation was in flight, as in its own example response.+ if (result.pendingVersionId() != null) {+ response.put("VersionId", result.pendingVersionId());+ }+ return Response.ok(response).build();+ }+private Response handleTagResource(JsonNode request, String region) {String secretId = request.path("SecretId").asText();+ // Tags is a required parameter; an absent list used to parse to empty and no-op.+ if (!request.path("Tags").isArray() || request.path("Tags").isEmpty()) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "Tags must contain at least one tag."))+ .build();+ }List<Secret.Tag> tags = parseTags(request);service.tagResource(secretId, tags, region);return Response.ok(objectMapper.createObjectNode()).build();@@ -503,6 +684,13 @@ public class SecretsManagerJsonHandler {private Response handleUntagResource(JsonNode request, String region) {String secretId = request.path("SecretId").asText();+ // TagKeys is a required parameter; an absent list used to parse to empty and no-op.+ if (!request.path("TagKeys").isArray() || request.path("TagKeys").isEmpty()) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "TagKeys must contain at least one key."))+ .build();+ }List<String> tagKeys = new ArrayList<>();request.path("TagKeys").forEach(k -> tagKeys.add(k.asText()));service.untagResource(secretId, tagKeys, region);@@ -511,32 +699,86 @@ public class SecretsManagerJsonHandler {private Response handleListSecretVersionIds(JsonNode request, String region) {String secretId = request.path("SecretId").asText();+ // A version with no staging labels is deprecated and AWS hides it unless asked.+ boolean includeDeprecated = request.path("IncludeDeprecated").asBoolean(false);++ int maxResults = 100;+ if (request.hasNonNull("MaxResults")) {+ maxResults = request.path("MaxResults").asInt();+ if (maxResults < 1 || maxResults > 100) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "Invalid MaxResults value, must be between 1 and 100"))+ .build();+ }+ }++ int offset = 0;+ if (request.hasNonNull("NextToken")) {+ try {+ offset = Integer.parseInt(request.path("NextToken").asText());+ if (offset < 0) {+ throw new NumberFormatException();+ }+ } catch (NumberFormatException e) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidNextTokenException", "Invalid NextToken"))+ .build();+ }+ }+Secret secret = service.describeSecret(secretId, region);Map<String, List<String>> versionMap = service.listSecretVersionIds(secretId, region);+ // Sorted by creation so offset-based pagination is stable across calls.+ List<String> versionIds = new ArrayList<>(versionMap.keySet());+ versionIds.removeIf(id -> {+ List<String> stages = versionMap.get(id);+ return !includeDeprecated && (stages == null || stages.isEmpty());+ });+ versionIds.sort(Comparator.comparing(+ id -> versionCreatedDate(secret, id), Comparator.nullsLast(Comparator.naturalOrder())));+ObjectNode response = objectMapper.createObjectNode();response.put("ARN", secret.getArn());response.put("Name", secret.getName());+ offset = Math.min(offset, versionIds.size());+ int end = Math.min(versionIds.size(), offset + maxResults);+ArrayNode versions = objectMapper.createArrayNode();- for (Map.Entry<String, List<String>> entry : versionMap.entrySet()) {+ for (String versionId : versionIds.subList(offset, end)) {ObjectNode versionNode = objectMapper.createObjectNode();- versionNode.put("VersionId", entry.getKey());- ArrayNode stagesArray = objectMapper.createArrayNode();- if (entry.getValue() != null) {- entry.getValue().forEach(stagesArray::add);+ versionNode.put("VersionId", versionId);+ List<String> stages = versionMap.get(versionId);+ // AWS's own example omits VersionStages entirely for a deprecated version rather+ // than returning an empty array.+ if (stages != null && !stages.isEmpty()) {+ ArrayNode stagesArray = objectMapper.createArrayNode();+ stages.forEach(stagesArray::add);+ versionNode.set("VersionStages", stagesArray);}- versionNode.set("VersionStages", stagesArray);- SecretVersion sv = secret.getVersions() != null ? secret.getVersions().get(entry.getKey()) : null;+ SecretVersion sv = secret.getVersions() != null ? secret.getVersions().get(versionId) : null;if (sv != null && sv.getCreatedDate() != null) {versionNode.put("CreatedDate", sv.getCreatedDate().toEpochMilli() / 1000.0);}+ if (sv != null && sv.getLastAccessedDate() != null) {+ versionNode.put("LastAccessedDate", sv.getLastAccessedDate().toEpochMilli() / 1000.0);+ }versions.add(versionNode);}response.set("Versions", versions);+ if (end < versionIds.size()) {+ response.put("NextToken", String.valueOf(end));+ }return Response.ok(response).build();}+ private static Instant versionCreatedDate(Secret secret, String versionId) {+ SecretVersion version = secret.getVersions() != null ? secret.getVersions().get(versionId) : null;+ return version != null ? version.getCreatedDate() : null;+ }+private Response handleGetResourcePolicy(JsonNode request, String region) {String secretId = request.path("SecretId").asText();Secret secret = service.getResourcePolicy(secretId, region);@@ -551,8 +793,6 @@ public class SecretsManagerJsonHandler {return Response.ok(response).build();}- // BlockPublicPolicy is accepted but not enforced: the emulator does no public-policy- // analysis, so PublicPolicyException is never raised.private Response handlePutResourcePolicy(JsonNode request, String region) {String secretId = request.path("SecretId").asText();String resourcePolicy = request.hasNonNull("ResourcePolicy") ? request.get("ResourcePolicy").asText() : null;@@ -562,6 +802,12 @@ public class SecretsManagerJsonHandler {"Invalid parameter: ResourcePolicy must not be null or empty.")).build();}+ if (resourcePolicy.length() > MAX_RESOURCE_POLICY_LENGTH) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "ResourcePolicy must be at most " + MAX_RESOURCE_POLICY_LENGTH + " characters."))+ .build();+ }JsonNode parsedPolicy;try {@@ -576,6 +822,17 @@ public class SecretsManagerJsonHandler {.build();}+ // BlockPublicPolicy refuses a policy that hands the secret to everyone. AWS leaves it off+ // by default, so an unguarded call still accepts a wildcard principal.+ if (request.path("BlockPublicPolicy").asBoolean(false)+ && !ResourcePolicyValidator.validate(parsedPolicy).isEmpty()) {+ return Response.status(400)+ .entity(new AwsErrorResponse("PublicPolicyException",+ "The BlockPublicPolicy parameter is set to true, and the resource policy "+ + "did not prevent broad access to the secret."))+ .build();+ }+Secret secret = service.putResourcePolicy(secretId, resourcePolicy, region);ObjectNode response = objectMapper.createObjectNode();// The terraform provider uses the returned ARN as the aws_secretsmanager_secret_policy@@ -585,6 +842,141 @@ public class SecretsManagerJsonHandler {return Response.ok(response).build();}+ /** Parses an {@code AddReplicaRegions} array into replication targets. */+ private List<SecretsManagerService.ReplicaRegion> parseReplicaRegions(JsonNode request) {+ List<SecretsManagerService.ReplicaRegion> targets = new ArrayList<>();+ JsonNode node = request.path("AddReplicaRegions");+ if (node.isArray()) {+ for (JsonNode entry : node) {+ targets.add(new SecretsManagerService.ReplicaRegion(+ entry.path("Region").asText(null),+ entry.hasNonNull("KmsKeyId") ? entry.path("KmsKeyId").asText() : null));+ }+ }+ return targets;+ }++ /**+ * Attaches {@code VersionStages} only when the version actually carries labels. AWS models+ * the array with a one-item minimum, so a deprecated version omits the field rather than+ * sending an empty array.+ */+ private void putVersionStages(ObjectNode node, List<String> stages) {+ if (stages == null || stages.isEmpty()) {+ return;+ }+ ArrayNode array = objectMapper.createArrayNode();+ stages.forEach(array::add);+ node.set("VersionStages", array);+ }++ /** True when this primary has at least one replica. */+ private static boolean isReplicated(Secret secret) {+ return secret.getReplicationStatus() != null && !secret.getReplicationStatus().isEmpty();+ }++ private ArrayNode replicationStatusNode(Secret secret) {+ ArrayNode statuses = objectMapper.createArrayNode();+ if (secret.getReplicationStatus() == null) {+ return statuses;+ }+ for (Secret.ReplicaStatus status : secret.getReplicationStatus()) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Region", status.region());+ if (status.kmsKeyId() != null) {+ node.put("KmsKeyId", status.kmsKeyId());+ }+ node.put("Status", status.status());+ if (status.statusMessage() != null) {+ node.put("StatusMessage", status.statusMessage());+ }+ if (status.lastAccessedDate() != null) {+ node.put("LastAccessedDate", status.lastAccessedDate().toEpochMilli() / 1000.0);+ }+ statuses.add(node);+ }+ return statuses;+ }++ private Response handleReplicateSecretToRegions(JsonNode request, String region) {+ String secretId = request.path("SecretId").asText();+ boolean force = request.path("ForceOverwriteReplicaSecret").asBoolean(false);+ Secret primary = service.replicateSecretToRegions(+ secretId, parseReplicaRegions(request), force, region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("ARN", primary.getArn());+ response.set("ReplicationStatus", replicationStatusNode(primary));+ return Response.ok(response).build();+ }++ private Response handleRemoveRegionsFromReplication(JsonNode request, String region) {+ String secretId = request.path("SecretId").asText();+ List<String> regionsToRemove = new ArrayList<>();+ request.path("RemoveReplicaRegions").forEach(r -> regionsToRemove.add(r.asText()));++ Secret primary = service.removeRegionsFromReplication(secretId, regionsToRemove, region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("ARN", primary.getArn());+ response.set("ReplicationStatus", replicationStatusNode(primary));+ return Response.ok(response).build();+ }++ private Response handleStopReplicationToReplica(JsonNode request, String region) {+ String secretId = request.path("SecretId").asText();+ Secret promoted = service.stopReplicationToReplica(secretId, region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("ARN", promoted.getArn());+ return Response.ok(response).build();+ }++ private Response handleValidateResourcePolicy(JsonNode request, String region) {+ String resourcePolicy = request.hasNonNull("ResourcePolicy")+ ? request.get("ResourcePolicy").asText() : null;+ if (resourcePolicy == null || resourcePolicy.isBlank()) {+ return Response.status(400)+ .entity(new AwsErrorResponse("InvalidParameterException",+ "Invalid parameter: ResourcePolicy must not be null or empty."))+ .build();+ }++ // SecretId is optional on this operation, but a caller that names a secret expects the+ // usual not-found handling rather than a silent pass.+ if (request.hasNonNull("SecretId")) {+ service.describeSecret(request.path("SecretId").asText(), region);+ }++ JsonNode parsedPolicy;+ try {+ parsedPolicy = objectMapper.readTree(resourcePolicy);+ } catch (JsonProcessingException e) {+ parsedPolicy = null;+ }+ if (parsedPolicy == null || !parsedPolicy.isObject()) {+ return Response.status(400)+ .entity(new AwsErrorResponse("MalformedPolicyDocumentException",+ "The resource policy is not a valid JSON policy document."))+ .build();+ }++ List<ResourcePolicyValidator.ValidationError> errors =+ ResourcePolicyValidator.validate(parsedPolicy);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("PolicyValidationPassed", errors.isEmpty());+ ArrayNode errorNodes = objectMapper.createArrayNode();+ for (ResourcePolicyValidator.ValidationError error : errors) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("CheckName", error.checkName());+ node.put("ErrorMessage", error.errorMessage());+ errorNodes.add(node);+ }+ response.set("ValidationErrors", errorNodes);+ return Response.ok(response).build();+ }+private Response handleDeleteResourcePolicy(JsonNode request, String region) {String secretId = request.path("SecretId").asText();Secret secret = service.deleteResourcePolicy(secretId, region);diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.javaindex ec4a7eae4d..eb5e719602 100644--- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java@@ -14,13 +14,17 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.services.lambda.LambdaService;import io.github.hectorvent.floci.services.lambda.model.InvocationType;+import io.github.hectorvent.floci.services.kms.KmsService;+import io.github.hectorvent.floci.services.kms.model.KmsKey;import io.github.hectorvent.floci.services.lambda.model.InvokeResult;+import io.github.hectorvent.floci.services.scheduler.SchedulerExpressionParser;import jakarta.annotation.PreDestroy;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;import java.util.Collections;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -39,6 +43,7 @@ import io.github.hectorvent.floci.core.resource.ResourceProvider;import io.github.hectorvent.floci.core.resource.SupportedResourceType;import java.util.LinkedHashMap;import java.util.Set;+import java.util.regex.Pattern;@ApplicationScopedpublic class SecretsManagerService implements ResourceProvider {@@ -48,14 +53,18 @@ public class SecretsManagerService implements ResourceProvider {private static final String AWSCURRENT = "AWSCURRENT";private static final String AWSPREVIOUS = "AWSPREVIOUS";private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";+ private static final String AWS_MANAGED_KEY = "aws/secretsmanager";+ private static final String PENDING_DELETION_STATE = "PendingDeletion";+ private static final Pattern SECRET_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9/_+=.@-]+");private final StorageBackend<String, Secret> store;private final int defaultRecoveryWindowDays;private final RegionResolver regionResolver;private final LambdaService lambdaService;private final ObjectMapper objectMapper;+ private final KmsService kmsService;private final ExecutorService rotationExecutor = Executors.newCachedThreadPool();- private final java.util.concurrent.ConcurrentHashMap<String, Object> rotationLocks = new java.util.concurrent.ConcurrentHashMap<>();+ private final ConcurrentHashMap<String, Object> rotationLocks = new ConcurrentHashMap<>();private Object lockFor(String secretArn) {return rotationLocks.computeIfAbsent(secretArn, k -> new Object());@@ -63,24 +72,33 @@ public class SecretsManagerService implements ResourceProvider {@Injectpublic SecretsManagerService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,- LambdaService lambdaService, ObjectMapper objectMapper) {+ LambdaService lambdaService, ObjectMapper objectMapper,+ KmsService kmsService) {this(factory.create("secretsmanager", "secretsmanager-secrets.json",new TypeReference<Map<String, Secret>>() {}),config.services().secretsmanager().defaultRecoveryWindowDays(),- regionResolver, lambdaService, objectMapper);+ regionResolver, lambdaService, objectMapper, kmsService);}SecretsManagerService(StorageBackend<String, Secret> store, int defaultRecoveryWindowDays) {- this(store, defaultRecoveryWindowDays, new RegionResolver("us-east-1", "000000000000"), null, new ObjectMapper());+ this(store, defaultRecoveryWindowDays, new RegionResolver("us-east-1", "000000000000"), null,+ new ObjectMapper(), null);}SecretsManagerService(StorageBackend<String, Secret> store, int defaultRecoveryWindowDays,RegionResolver regionResolver, LambdaService lambdaService, ObjectMapper objectMapper) {+ this(store, defaultRecoveryWindowDays, regionResolver, lambdaService, objectMapper, null);+ }++ SecretsManagerService(StorageBackend<String, Secret> store, int defaultRecoveryWindowDays,+ RegionResolver regionResolver, LambdaService lambdaService,+ ObjectMapper objectMapper, KmsService kmsService) {this.store = store;this.defaultRecoveryWindowDays = defaultRecoveryWindowDays;this.regionResolver = regionResolver;this.lambdaService = lambdaService;this.objectMapper = objectMapper;+ this.kmsService = kmsService;}@PreDestroy@@ -90,7 +108,7 @@ public class SecretsManagerService implements ResourceProvider {public Secret createSecret(String name, String secretString, String secretBinary,String description, String kmsKeyId, List<Secret.Tag> tags, String region) {- return createSecret(name, secretString, secretBinary, description, kmsKeyId, tags, null, region);+ return createSecret(name, secretString, secretBinary, description, kmsKeyId, tags, null, null, region);}/**@@ -101,6 +119,28 @@ public class SecretsManagerService implements ResourceProvider {public Secret createSecret(String name, String secretString, String secretBinary,String description, String kmsKeyId, List<Secret.Tag> tags,String owningService, String region) {+ return createSecret(name, secretString, secretBinary, description, kmsKeyId, tags,+ owningService, null, region);+ }++ /**+ * Creates a secret whose initial version carries {@code clientRequestToken} as its version id.+ * AWS documents that token as becoming the {@code VersionId} of the new version, which is what+ * makes CreateSecret idempotent and lets a caller address the version it just wrote without+ * a follow-up DescribeSecret. A {@code null} token falls back to a generated UUID, matching+ * what the SDKs do on the client side.+ */+ public Secret createSecret(String name, String secretString, String secretBinary,+ String description, String kmsKeyId, List<Secret.Tag> tags,+ String owningService, String clientRequestToken, String region) {+ if (clientRequestToken != null+ && (clientRequestToken.length() < 32 || clientRequestToken.length() > 64)) {+ throw new AwsException("InvalidParameterException",+ "ClientRequestToken must be between 32 and 64 characters long.", 400);+ }+ throwIfBothSecretValues(secretString, secretBinary);+ validateKmsKey(kmsKeyId, region);+String storageKey = regionKey(region, name);Secret existing = store.get(storageKey).orElse(null);@@ -111,6 +151,18 @@ public class SecretsManagerService implements ResourceProvider {// key AND clear its deletedDate, so the original value became unrecoverable and// RestoreSecret then reported "was not deleted" - silent data loss.throwIfPendingDeletion(existing);++ // ClientRequestToken makes CreateSecret idempotent: AWS ignores a repeat that names+ // the same version and carries the same value, so a client retrying after a dropped+ // response gets the original secret back rather than ResourceExistsException.+ SecretVersion tokenVersion = clientRequestToken != null && existing.getVersions() != null+ ? existing.getVersions().get(clientRequestToken) : null;+ if (tokenVersion != null+ && Objects.equals(tokenVersion.getSecretString(), secretString)+ && Objects.equals(tokenVersion.getSecretBinary(), secretBinary)) {+ return existing;+ }+throw new AwsException("ResourceExistsException","A secret with the name " + name + " already exists.", 400);}@@ -118,7 +170,7 @@ public class SecretsManagerService implements ResourceProvider {String arn = buildSecretArn(region, name);Instant now = Instant.now();- String versionId = UUID.randomUUID().toString();+ String versionId = clientRequestToken != null ? clientRequestToken : UUID.randomUUID().toString();SecretVersion version = new SecretVersion();version.setVersionId(versionId);version.setSecretString(secretString);@@ -176,7 +228,10 @@ public class SecretsManagerService implements ResourceProvider {version.setLastAccessedDate(Instant.now());secret.setLastAccessedDate(Instant.now());- store.put(regionKey(region, secret.getName()), secret);+ // Deliberately not persist(): reading a secret is not a change to replicate, and pushing+ // the primary out to every replica on each read would rebuild them constantly and+ // clobber each replica's own last-accessed bookkeeping.+ putSecret(region, secret);return version;}@@ -186,6 +241,8 @@ public class SecretsManagerService implements ResourceProvider {List<String> versionStages) {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);+ throwIfReplica(secret);+ throwIfBothSecretValues(secretString, secretBinary);if (clientRequestToken != null && (clientRequestToken.length() < 32 || clientRequestToken.length() > 64)) {throw new AwsException("InvalidParameterException", "ClientRequestToken must be between 32 and 64 characters long.", 400);@@ -285,7 +342,7 @@ public class SecretsManagerService implements ResourceProvider {}secret.setLastChangedDate(now);- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);LOG.infov("Put secret value for: {0}", secret.getName());return newVersion;}@@ -294,18 +351,25 @@ public class SecretsManagerService implements ResourceProvider {public Secret updateSecret(String secretId, String description, String kmsKeyId, String region) {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);+ throwIfReplica(secret);- if (description != null) {- secret.setDescription(description);- }- if (kmsKeyId != null) {- secret.setKmsKeyId(kmsKeyId);- }- secret.setLastChangedDate(Instant.now());+ validateKmsKey(kmsKeyId, region);- store.put(regionKey(region, secret.getName()), secret);- LOG.infov("Updated secret metadata: {0}", secret.getName());- return secret;+ synchronized (lockFor(secret.getArn())) {+ if (description != null) {+ secret.setDescription(description);+ }+ if (kmsKeyId != null) {+ // AWS: "If you set this to an empty string, Secrets Manager uses the AWS managed key+ // aws/secretsmanager" - which DescribeSecret reports by omitting KmsKeyId entirely.+ secret.setKmsKeyId(kmsKeyId.isEmpty() ? null : kmsKeyId);+ }+ secret.setLastChangedDate(Instant.now());++ persist(secret, region);+ LOG.infov("Updated secret metadata: {0}", secret.getName());+ return secret;+ }}public Secret describeSecret(String secretId, String region) {@@ -386,7 +450,7 @@ public class SecretsManagerService implements ResourceProvider {}secret.setTargetAttachmentOwner(attachmentOwner);- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);return true;}}@@ -436,19 +500,28 @@ public class SecretsManagerService implements ResourceProvider {return;}secret.setTargetAttachmentOwner(null);- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);}}public List<Secret> listSecrets(String region) {- String prefix = region + "::";- return store.scan(key -> key.startsWith(prefix) && store.get(key)- .map(s -> s.getDeletedDate() == null)- .orElse(false));+ return listSecrets(region, null, false);}public List<Secret> listSecrets(String region, List<Filter> filters) {- List<Secret> allSecrets = listSecrets(region);+ return listSecrets(region, filters, false);+ }++ /**+ * Lists the region's secrets, by default hiding the ones inside their recovery window the way+ * AWS does. {@code includePlannedDeletion} surfaces those too, carrying their DeletedDate so a+ * caller can tell them apart.+ */+ public List<Secret> listSecrets(String region, List<Filter> filters, boolean includePlannedDeletion) {+ String prefix = region + "::";+ List<Secret> allSecrets = store.scan(key -> key.startsWith(prefix) && store.get(key)+ .map(s -> includePlannedDeletion || s.getDeletedDate() == null)+ .orElse(false));if (filters == null || filters.isEmpty()) {return allSecrets;}@@ -550,10 +623,33 @@ public class SecretsManagerService implements ResourceProvider {public record Filter(String key, List<String> values) {}public Secret deleteSecret(String secretId, Integer recoveryWindowInDays, boolean forceDelete, String region) {+ // Parameters are checked before the secret is resolved, the way AWS orders it: an invalid+ // window is reported as such even when the secret does not exist.+ if (forceDelete && recoveryWindowInDays != null) {+ throw new AwsException("InvalidParameterException",+ "You can't use ForceDeleteWithoutRecovery in conjunction with RecoveryWindowInDays.", 400);+ }+ // AWS accepts 7-30 only. Zero used to fall through to the force-delete branch below, which+ // silently turned "delete with no recovery window" into an unrecoverable delete; a negative+ // value produced a DeletionDate already in the past.+ if (recoveryWindowInDays != null && (recoveryWindowInDays < 7 || recoveryWindowInDays > 30)) {+ throw new AwsException("InvalidParameterException",+ "The RecoveryWindowInDays value must be between 7 and 30 days, inclusive.", 400);+ }+Secret secret = resolveSecret(secretId, region);+ throwIfReplica(secret);+ // AWS: "You can't delete a primary secret that is replicated to other Regions. You must+ // first delete the replicas." Deleting it here would strand every replica with no primary+ // to sync from and no way to remove them.+ if (secret.getReplicationStatus() != null && !secret.getReplicationStatus().isEmpty()) {+ throw new AwsException("InvalidRequestException",+ "You can't delete a secret that is replicated to other Regions. "+ + "Remove the replicas with RemoveRegionsFromReplication first.", 400);+ }String storageKey = regionKey(region, secret.getName());- if (forceDelete || (recoveryWindowInDays != null && recoveryWindowInDays == 0)) {+ if (forceDelete) {store.delete(storageKey);LOG.infov("Force-deleted secret: {0}", secret.getName());secret.setDeletedDate(Instant.now());@@ -575,6 +671,375 @@ public class SecretsManagerService implements ResourceProvider {return secret;}+ // ─── Multi-region replication ──────────────────────────────────────────────++ private static final String STATUS_IN_SYNC = "InSync";+ private static final String STATUS_FAILED = "Failed";++ /**+ * When the next rotation is due, given the rules and a starting point.+ *+ * <p>{@code ScheduleExpression} wins over {@code AutomaticallyAfterDays} because RotateSecret+ * refuses a rules object carrying both. Returns null when the rules schedule nothing, which is+ * how a rotation-enabled secret with no schedule stays manual-only.+ *+ * @throws AwsException if the expression is not a form AWS accepts+ */+ /** {@code Duration} is a whole number of hours, "3h" style, 2-3 characters long. */+ private static final Pattern DURATION_PATTERN = Pattern.compile("[0-9]{1,2}h");++ /**+ * Secrets Manager accepts a narrower {@code rate()} than EventBridge Scheduler does: hours or+ * days only, where the scheduler also takes minutes and weeks.+ */+ private static final Pattern ROTATION_RATE_PATTERN =+ Pattern.compile("^rate\\(\\s*\\d+\\s+(hours?|days?)\\s*\\)$",+ Pattern.CASE_INSENSITIVE);++ /** AWS: "You can rotate a secret as often as every four hours." */+ private static final long MIN_ROTATION_INTERVAL_MILLIS = 4 * 3_600_000L;++ /** Enforces the documented bounds on a RotationRules structure. */+ public static void validateRotationRules(Secret.RotationRules rules) {+ if (rules == null) {+ return;+ }+ Integer days = rules.automaticallyAfterDays();+ if (days != null && (days < 1 || days > 1000)) {+ throw new AwsException("InvalidParameterException",+ "AutomaticallyAfterDays must be between 1 and 1000.", 400);+ }+ String duration = rules.duration();+ if (duration != null && !DURATION_PATTERN.matcher(duration).matches()) {+ throw new AwsException("InvalidParameterException",+ "Duration must be a number of hours, for example 3h.", 400);+ }+ String expression = rules.scheduleExpression();+ if (expression != null) {+ if (expression.isEmpty() || expression.length() > 256) {+ throw new AwsException("InvalidParameterException",+ "ScheduleExpression must be between 1 and 256 characters.", 400);+ }+ validateScheduleExpression(expression);+ }+ }++ private static void validateScheduleExpression(String expression) {+ SchedulerExpressionParser.Kind kind;+ try {+ kind = SchedulerExpressionParser.classify(expression);+ } catch (IllegalArgumentException e) {+ throw new AwsException("InvalidParameterException",+ "Invalid ScheduleExpression: " + e.getMessage(), 400);+ }+ if (kind == SchedulerExpressionParser.Kind.AT) {+ throw new AwsException("InvalidParameterException",+ "Secrets Manager rotation supports only rate() and cron() expressions.", 400);+ }+ if (kind != SchedulerExpressionParser.Kind.RATE) {+ return;+ }+ if (!ROTATION_RATE_PATTERN.matcher(expression.trim()).matches()) {+ throw new AwsException("InvalidParameterException",+ "Secrets Manager rate() expressions must be in hours or days, "+ + "for example rate(12 hours) or rate(10 days).", 400);+ }+ if (SchedulerExpressionParser.parseRateMillis(expression) < MIN_ROTATION_INTERVAL_MILLIS) {+ throw new AwsException("InvalidParameterException",+ "You can rotate a secret as often as every four hours, but no more frequently.", 400);+ }+ }++ public static Instant computeNextRotationDate(Secret.RotationRules rules, Instant from) {+ if (rules == null) {+ return null;+ }+ String expression = rules.scheduleExpression();+ if (expression != null && !expression.isBlank()) {+ try {+ return switch (SchedulerExpressionParser.classify(expression)) {+ case RATE -> from.plusMillis(SchedulerExpressionParser.parseRateMillis(expression));+ case CRON -> SchedulerExpressionParser.nextCronFire(expression, from, null);+ // at() is an EventBridge Scheduler form; Secrets Manager accepts only+ // rate() and cron(), so it is rejected rather than silently honoured.+ case AT -> throw new IllegalArgumentException(+ "Secrets Manager rotation supports only rate() and cron() expressions.");+ };+ } catch (IllegalArgumentException | IllegalStateException e) {+ throw new AwsException("InvalidParameterException",+ "Invalid ScheduleExpression: " + e.getMessage(), 400);+ }+ }+ if (rules.automaticallyAfterDays() != null) {+ return from.plusSeconds((long) rules.automaticallyAfterDays() * 86400);+ }+ return null;+ }++ /** A secret paired with the region whose store holds it, for background sweeps. */+ public record RegionalSecret(String region, Secret secret) {+ }++ /**+ * Every stored secret with its region, across every account.+ *+ * <p>Used by {@link SecretRotationScheduler}, which runs on a background thread. That matters+ * for the account: {@code store.keys()} resolves the account from the in-flight request, and+ * a sweep has none, so it would silently see only the default account's secrets and never+ * rotate anyone else's. {@code scanAllAccountEntries} is the explicit-account form built for+ * exactly this.+ */+ public List<RegionalSecret> listAllSecrets() {+ List<RegionalSecret> all = new ArrayList<>();+ if (store instanceof AccountAwareStorageBackend<Secret> aware) {+ for (AccountAwareStorageBackend.AccountEntry<Secret> entry+ : aware.scanAllAccountEntries(k -> k.contains("::"))) {+ String keyRegion = entry.key().substring(0, entry.key().indexOf("::"));+ all.add(new RegionalSecret(keyRegion, entry.value()));+ }+ return all;+ }+ for (String key : store.keys()) {+ int separator = key.indexOf("::");+ if (separator < 0) {+ continue;+ }+ String keyRegion = key.substring(0, separator);+ store.get(key).ifPresent(secret -> all.add(new RegionalSecret(keyRegion, secret)));+ }+ return all;+ }++ /** A replication target: the region to copy into, and optionally the KMS key to record. */+ public record ReplicaRegion(String region, String kmsKeyId) {+ }++ /**+ * Copies the secret into each target region and records the outcome per region.+ *+ * <p>Real AWS replicates asynchronously and reports {@code InProgress} first; floci copies+ * synchronously, so a region is {@code InSync} by the time this returns. A region whose name+ * is already taken comes back {@code Failed} rather than throwing, because AWS reports+ * per-region outcomes and the other regions in the same call still succeed.+ */+ public Secret replicateSecretToRegions(String secretId, List<ReplicaRegion> targets,+ boolean forceOverwrite, String region) {+ if (targets == null || targets.isEmpty()) {+ throw new AwsException("InvalidParameterException",+ "AddReplicaRegions must contain at least one Region.", 400);+ }++ Secret primary = resolveSecret(secretId, region);+ throwIfPendingDeletion(primary);+ throwIfReplica(primary);++ synchronized (lockFor(primary.getArn())) {+ List<Secret.ReplicaStatus> statuses = primary.getReplicationStatus() != null+ ? new ArrayList<>(primary.getReplicationStatus()) : new ArrayList<>();++ for (ReplicaRegion target : targets) {+ if (target.region() == null || target.region().equals(region)) {+ throw new AwsException("InvalidParameterException",+ "You can't replicate a secret into its own Region.", 400);+ }+ statuses.removeIf(s -> s.region().equals(target.region()));+ statuses.add(replicateInto(primary, target, forceOverwrite, region));+ }++ primary.setReplicationStatus(statuses);+ primary.setLastChangedDate(Instant.now());+ putSecret(region, primary);+ return primary;+ }+ }++ /** Writes one replica, or reports why it could not be written. */+ private Secret.ReplicaStatus replicateInto(Secret primary, ReplicaRegion target,+ boolean forceOverwrite, String primaryRegionName) {+ String replicaKey = regionKey(target.region(), primary.getName());+ Secret existing = store.get(replicaKey).orElse(null);+ // An unrelated secret already holding the name is only replaced when the caller asks;+ // overwriting it silently would destroy a secret this call never mentioned.+ if (existing != null && !existing.isReplica() && !forceOverwrite) {+ return new Secret.ReplicaStatus(target.region(), target.kmsKeyId(), STATUS_FAILED,+ "A secret with this name already exists in this region.", null);+ }++ putSecret(target.region(), buildReplica(primary, target, primaryRegionName));+ LOG.infov("Replicated secret {0} to region {1}", primary.getName(), target.region());+ return new Secret.ReplicaStatus(target.region(), target.kmsKeyId(), STATUS_IN_SYNC,+ "Replication succeeded.", null);+ }++ /**+ * Builds the replica copy. The ARN is the primary's with the region swapped, which is the+ * identity AWS gives a replica and what StopReplicationToReplica promises to return.+ */+ private Secret buildReplica(Secret primary, ReplicaRegion target, String primaryRegionName) {+ Secret replica = new Secret();+ replica.setName(primary.getName());+ replica.setArn(replicaArn(primary.getArn(), target.region()));+ replica.setDescription(primary.getDescription());+ replica.setKmsKeyId(target.kmsKeyId() != null ? target.kmsKeyId() : primary.getKmsKeyId());+ replica.setCreatedDate(primary.getCreatedDate());+ replica.setLastChangedDate(primary.getLastChangedDate());+ replica.setLastRotatedDate(primary.getLastRotatedDate());+ replica.setRotationEnabled(primary.isRotationEnabled());+ replica.setRotationLambdaArn(primary.getRotationLambdaArn());+ replica.setRotationRules(primary.getRotationRules());+ replica.setNextRotationDate(primary.getNextRotationDate());+ replica.setOwningService(primary.getOwningService());+ replica.setTags(primary.getTags() != null ? new ArrayList<>(primary.getTags()) : null);+ replica.setCurrentVersionId(primary.getCurrentVersionId());+ replica.setPrimaryRegion(primaryRegionName);++ Map<String, SecretVersion> versions = new HashMap<>();+ if (primary.getVersions() != null) {+ primary.getVersions().forEach((id, version) -> versions.put(id, copyVersion(version)));+ }+ replica.setVersions(versions);+ return replica;+ }++ private static SecretVersion copyVersion(SecretVersion source) {+ SecretVersion copy = new SecretVersion();+ copy.setVersionId(source.getVersionId());+ copy.setSecretString(source.getSecretString());+ copy.setSecretBinary(source.getSecretBinary());+ copy.setCreatedDate(source.getCreatedDate());+ copy.setVersionStages(source.getVersionStages() != null+ ? new ArrayList<>(source.getVersionStages()) : null);+ return copy;+ }++ /** The primary ARN with only the region replaced, preserving the random name suffix. */+ private String replicaArn(String primaryArn, String replicaRegion) {+ AwsArnUtils.Arn parsed = parseOrNull(primaryArn);+ if (parsed == null) {+ return primaryArn;+ }+ return regionResolver.buildArn("secretsmanager", replicaRegion, parsed.resource());+ }++ /** Deletes the named replicas outright, as AWS does, and drops them from the primary. */+ public Secret removeRegionsFromReplication(String secretId, List<String> regionsToRemove, String region) {+ if (regionsToRemove == null || regionsToRemove.isEmpty()) {+ throw new AwsException("InvalidParameterException",+ "RemoveReplicaRegions must contain at least one Region.", 400);+ }++ Secret primary = resolveSecret(secretId, region);+ throwIfReplica(primary);++ synchronized (lockFor(primary.getArn())) {+ List<Secret.ReplicaStatus> statuses = primary.getReplicationStatus() != null+ ? new ArrayList<>(primary.getReplicationStatus()) : new ArrayList<>();++ for (String target : regionsToRemove) {+ Secret replica = store.get(regionKey(target, primary.getName())).orElse(null);+ // Only a replica of THIS secret is removed; an unrelated secret that happens to+ // share the name in that region is left alone.+ if (replica != null && region.equals(replica.getPrimaryRegion())) {+ store.delete(regionKey(target, primary.getName()));+ LOG.infov("Removed replica of {0} from region {1}", primary.getName(), target);+ }+ statuses.removeIf(s -> s.region().equals(target));+ }++ primary.setReplicationStatus(statuses);+ primary.setLastChangedDate(Instant.now());+ putSecret(region, primary);+ return primary;+ }+ }++ /**+ * Promotes the replica in {@code region} to a standalone primary, which is why this must be+ * called in the replica's own region rather than the primary's.+ */+ public Secret stopReplicationToReplica(String secretId, String region) {+ Secret replica = resolveSecret(secretId, region);+ if (!replica.isReplica()) {+ throw new AwsException("InvalidRequestException",+ "You must call StopReplicationToReplica from the Region of the replica "+ + "you want to promote.", 400);+ }++ String primaryRegionName = replica.getPrimaryRegion();+ Secret primary = store.get(regionKey(primaryRegionName, replica.getName())).orElse(null);++ // The primary's monitor, not the replica's: persist() writes a primary's replica slots+ // while holding only the primary's lock, so guarding the promotion with the replica's own+ // ARN would leave the two paths writing the same slot under different monitors. Both+ // halves of the promotion run inside one critical section for the same reason: a sync+ // landing between them would write the replica back over the copy just promoted.+ synchronized (lockFor(primary != null ? primary.getArn() : replica.getArn())) {+ replica.setPrimaryRegion(null);+ replica.setLastChangedDate(Instant.now());+ putSecret(region, replica);++ // Detach from the old primary too, so it stops syncing over the promoted copy and can+ // itself be deleted once no replicas remain.+ if (primary != null && primary.getReplicationStatus() != null) {+ List<Secret.ReplicaStatus> statuses = new ArrayList<>(primary.getReplicationStatus());+ statuses.removeIf(s -> s.region().equals(region));+ primary.setReplicationStatus(statuses);+ putSecret(primaryRegionName, primary);+ }+ }++ LOG.infov("Promoted replica of {0} in region {1} to a standalone secret",+ replica.getName(), region);+ return replica;+ }++ /**+ * Persists a primary and pushes the change out to its replicas, so a replica never serves a+ * value the primary has moved past.+ */+ private void persist(Secret updated, String updatedRegion) {+ putSecret(updatedRegion, updated);++ List<Secret.ReplicaStatus> statuses = updated.getReplicationStatus();+ if (statuses == null || statuses.isEmpty() || updated.isReplica()) {+ return;+ }+ for (Secret.ReplicaStatus status : statuses) {+ if (!STATUS_IN_SYNC.equals(status.status())) {+ continue;+ }+ putSecret(status.region(),+ buildReplica(updated, new ReplicaRegion(status.region(), status.kmsKeyId()), updatedRegion));+ }+ }++ /**+ * Writes a secret under the account its own ARN names rather than the ambient one.+ *+ * <p>In a request these are the same account, so this changes nothing there. On a background+ * thread they are not: the ambient account falls back to the default, so a plain+ * {@code store.put} would write a foreign account's secret into the default account's+ * namespace - a phantom copy, and the real secret left unrotated.+ */+ private void putSecret(String region, Secret secret) {+ String key = regionKey(region, secret.getName());+ AwsArnUtils.Arn arn = parseOrNull(secret.getArn());+ if (arn != null && store instanceof AccountAwareStorageBackend<Secret> aware) {+ aware.putForAccount(arn.accountId(), key, secret);+ } else {+ store.put(key, secret);+ }+ }++ /** A replica is read-only; AWS directs the caller to the primary's region instead. */+ private static void throwIfReplica(Secret secret) {+ if (secret.isReplica()) {+ throw new AwsException("InvalidRequestException",+ "You can't modify a replica secret. Make the change in the primary secret's "+ + "Region " + secret.getPrimaryRegion() + ".", 400);+ }+ }+public Secret restoreSecret(String secretId, String region) {Secret secret = resolveSecret(secretId, region);String storageKey = regionKey(region, secret.getName());@@ -594,6 +1059,7 @@ public class SecretsManagerService implements ResourceProvider {boolean rotateImmediately, String region) {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);+ throwIfReplica(secret);if (clientRequestToken != null && (clientRequestToken.length() < 32 || clientRequestToken.length() > 64)) {throw new AwsException("InvalidParameterException", "ClientRequestToken must be between 32 and 64 characters long.", 400);@@ -603,6 +1069,7 @@ public class SecretsManagerService implements ResourceProvider {throw new AwsException("InvalidParameterException","RotationRules can't include both AutomaticallyAfterDays and ScheduleExpression.", 400);}+ validateRotationRules(rotationRules);// A service-managed secret is rotated by its owning service, so it has no rotation Lambda:// AWS rejects one here, and does not require one to enable rotation.@@ -649,12 +1116,16 @@ public class SecretsManagerService implements ResourceProvider {}secret.setRotationEnabled(true);secret.setLastChangedDate(Instant.now());+ // Scheduled from now rather than from the rotation's completion on purpose: the+ // rotation itself runs asynchronously and may fail, and a schedule that only advanced+ // on success would leave the background sweep retrying it on every tick forever.+ secret.setNextRotationDate(computeNextRotationDate(secret.getRotationRules(), Instant.now()));// A service-managed secret is rotated by its owning service, which floci does not// emulate: the master password is not re-issued here, so nothing sets LastRotatedDate.// Reporting a rotation that did not happen would leave GetSecretValue and the database// holding a credential the secret claims to have replaced.- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);}if (serviceManaged) {@@ -679,6 +1150,54 @@ public class SecretsManagerService implements ResourceProvider {}+ /**+ * The outcome of {@link #cancelRotateSecret}: the secret with rotation turned off, plus the id+ * of the version a cancelled rotation left behind, or {@code null} when no rotation was in+ * flight.+ */+ public record CancelRotationResult(Secret secret, String pendingVersionId) {+ }++ /**+ * Turns automatic rotation off and reports the half-built version an in-flight rotation left+ * staged as AWSPENDING.+ *+ * <p>The staging labels are deliberately left alone, as AWS leaves them: rolling forward or+ * back is the caller's decision, made with UpdateSecretVersionStage. The returned version id+ * is the only handle on that version, and it matters - a stale AWSPENDING that is not also+ * AWSCURRENT makes every later {@link #rotateSecret} fail with "a previous rotation isn't+ * complete", so a caller that cannot find it can never rotate the secret again.+ *+ * <p>{@code RotationRules} and the Lambda ARN are kept so rotation can be switched back on+ * with a bare RotateSecret, which is what DescribeSecret's "previously had rotation turned on"+ * contract promises.+ */+ public CancelRotationResult cancelRotateSecret(String secretId, String region) {+ Secret secret = resolveSecret(secretId, region);+ throwIfPendingDeletion(secret);+ throwIfReplica(secret);++ synchronized (lockFor(secret.getArn())) {+ secret.setRotationEnabled(false);+ // The schedule goes with the rotation; leaving it set would keep the background sweep+ // firing a rotation the caller just turned off.+ secret.setNextRotationDate(null);+ secret.setLastChangedDate(Instant.now());+ persist(secret, region);++ // AWSPENDING sitting on the AWSCURRENT version is the signature of a rotation that+ // finished, not one that was interrupted, so there is nothing partial to report.+ SecretVersion pending = findVersionByStage(secret, "AWSPENDING");+ SecretVersion current = findVersionByStage(secret, AWSCURRENT);+ String pendingVersionId = pending != null+ && (current == null || !pending.getVersionId().equals(current.getVersionId()))+ ? pending.getVersionId() : null;++ LOG.infov("Cancelled rotation for secret: {0}", secret.getName());+ return new CancelRotationResult(secret, pendingVersionId);+ }+ }+private void executeRotationLifecycle(String secretArn, String clientRequestToken, String lambdaArn, boolean rotateImmediately, boolean isExistingVersion, String region) {if (!rotateImmediately) {invokeRotationLambda(secretArn, clientRequestToken, lambdaArn, "testSecret", region);@@ -690,7 +1209,7 @@ public class SecretsManagerService implements ResourceProvider {List<String> stages = new ArrayList<>(pending.getVersionStages());stages.remove("AWSPENDING");pending.setVersionStages(stages);- store.put(regionKey(region, refreshed.getName()), refreshed);+ persist(refreshed, region);}}return;@@ -708,10 +1227,10 @@ public class SecretsManagerService implements ResourceProvider {pendingVersion.setVersionStages(List.of("AWSPENDING"));pendingVersion.setCreatedDate(Instant.now());if (secret.getVersions() == null) {- secret.setVersions(new java.util.HashMap<>());+ secret.setVersions(new HashMap<>());}secret.getVersions().put(clientRequestToken, pendingVersion);- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);}}}@@ -724,7 +1243,7 @@ public class SecretsManagerService implements ResourceProvider {Secret refreshed = resolveSecret(secretArn, region);refreshed.setLastRotatedDate(Instant.now());- store.put(regionKey(region, refreshed.getName()), refreshed);+ persist(refreshed, region);} catch (Exception e) {LOG.errorv(e, "Error during rotation steps for secret {0}", secretArn);throw e;@@ -760,6 +1279,7 @@ public class SecretsManagerService implements ResourceProvider {public void tagResource(String secretId, List<Secret.Tag> tags, String region) {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);+ throwIfReplica(secret);List<Secret.Tag> existing = secret.getTags() != null ? new ArrayList<>(secret.getTags()) : new ArrayList<>();for (Secret.Tag newTag : tags) {@@ -767,24 +1287,26 @@ public class SecretsManagerService implements ResourceProvider {existing.add(newTag);}secret.setTags(existing);- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);}public void untagResource(String secretId, List<String> tagKeys, String region) {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);+ throwIfReplica(secret);List<Secret.Tag> existing = secret.getTags() != null ? new ArrayList<>(secret.getTags()) : new ArrayList<>();existing.removeIf(t -> tagKeys.contains(t.key()));secret.setTags(existing);- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);}public Secret putResourcePolicy(String secretId, String resourcePolicy, String region) {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);+ throwIfReplica(secret);secret.setResourcePolicy(resourcePolicy);- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);LOG.infov("Put resource policy on secret: {0}", secret.getName());return secret;}@@ -801,8 +1323,9 @@ public class SecretsManagerService implements ResourceProvider {public Secret deleteResourcePolicy(String secretId, String region) {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);+ throwIfReplica(secret);secret.setResourcePolicy(null);- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);LOG.infov("Deleted resource policy on secret: {0}", secret.getName());return secret;}@@ -874,6 +1397,7 @@ public class SecretsManagerService implements ResourceProvider {Secret secret = resolveSecret(secretId, region);throwIfPendingDeletion(secret);+ throwIfReplica(secret);synchronized (lockFor(secret.getArn())) {SecretVersion versionByStage = findVersionByStage(secret, versionStage);@@ -936,7 +1460,7 @@ public class SecretsManagerService implements ResourceProvider {}}- store.put(regionKey(region, secret.getName()), secret);+ persist(secret, region);return secret;}@@ -978,6 +1502,82 @@ public class SecretsManagerService implements ResourceProvider {* recoverable case is InvalidRequestException, matching what {@code batchGetSecretValue}* already does correctly - the other call sites threw ResourceNotFoundException instead.*/+ /**+ * AWS accepts ASCII letters, numbers and {@code /_+=.@-} in a secret name, up to 512 chars.+ *+ * <p>Enforced at the wire layer rather than here on purpose. The service API is also floci's+ * internal one: RDS creates {@code rds!db-...} secrets, whose {@code !} the public constraint+ * forbids, and the ARN resolver deliberately supports names containing colons for secrets+ * persisted by earlier versions. Validating here would make those unrepresentable.+ */+ public static void validateSecretName(String name) {+ if (name == null || name.isEmpty() || name.length() > 512) {+ throw new AwsException("InvalidParameterException",+ "Invalid name. Must be a minimum of 1 and a maximum of 512 characters.", 400);+ }+ if (!SECRET_NAME_PATTERN.matcher(name).matches()) {+ throw new AwsException("InvalidParameterException",+ "Invalid name. Must be a valid name containing alphanumeric characters, "+ + "or any of the following: -/_+=.@", 400);+ }+ }++ /**+ * Checks that a caller-supplied KMS key exists and can actually encrypt.+ *+ * <p>Floci stores secret values in the clear - encrypting them with the emulator's own KMS+ * would protect nothing while making the store unreadable for debugging - so this validates+ * the key rather than using it. That covers the behaviour a caller can observe: AWS rejects a+ * key that is missing, disabled, or on its way out, and code under test should see the same+ * rejection here.+ *+ * <p>The AWS-managed {@code aws/secretsmanager} key is exempt: AWS creates it on demand, so+ * looking it up would fail on an emulator where nobody has created it.+ */+ private void validateKmsKey(String kmsKeyId, String region) {+ if (kmsService == null || kmsKeyId == null || kmsKeyId.isBlank()+ || AWS_MANAGED_KEY.equals(kmsKeyId) || ("alias/" + AWS_MANAGED_KEY).equals(kmsKeyId)) {+ return;+ }++ KmsKey key;+ try {+ key = kmsService.describeKey(kmsKeyId, region);+ } catch (AwsException e) {+ throw new AwsException("InvalidParameterException",+ "You can't access the KMS key " + kmsKeyId + " in this Region.", 400);+ }+ if (key != null && (!key.isEnabled() || PENDING_DELETION_STATE.equals(key.getKeyState()))) {+ throw new AwsException("EncryptionFailure",+ "Secrets Manager can't encrypt the protected secret text using the provided KMS key. "+ + "Check that the KMS key is available, enabled, and not in an invalid state.", 400);+ }+ }++ /** AWS: "Either SecretString or SecretBinary must have a value, but not both." */+ private static void throwIfBothSecretValues(String secretString, String secretBinary) {+ if (secretString != null && secretBinary != null) {+ throw new AwsException("InvalidParameterException",+ "You can't specify both SecretString and SecretBinary in the same request.", 400);+ }+ }++ /**+ * A secret another AWS service owns is managed through that service, so the public API refuses+ * to change it.+ *+ * <p>Applied at the wire layer, not here, for the same reason as {@link #validateSecretName}:+ * this service API is also floci's internal one, and the owning service has to keep managing+ * its own secret. RDS re-encrypts its managed master user secret in place on ModifyDBCluster+ * by calling {@link #updateSecret}; enforcing this here would break that.+ */+ public static void throwIfServiceManaged(Secret secret) {+ if (secret.getOwningService() != null) {+ throw new AwsException("InvalidRequestException",+ "The secret is managed by another service, and you must use that service to update it.", 400);+ }+ }+private void throwIfPendingDeletion(Secret secret) {if (secret.getDeletedDate() != null) {throw new AwsException("InvalidRequestException",@@ -1016,6 +1616,16 @@ public class SecretsManagerService implements ResourceProvider {}}+ // 3. The scans above resolve the account from the in-flight request, so a background+ // worker looking up a full ARN would miss a secret that is not in the default+ // account. The ARN names its own account, so address that one directly.+ if (parsedArn != null) {+ Secret inOwningAccount = findByArnInAccount(secretId, parsedArn);+ if (inOwningAccount != null) {+ return inOwningAccount;+ }+ }+throw new AwsException("ResourceNotFoundException","Secrets Manager can't find the specified secret.", 400);}diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/model/Secret.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/model/Secret.javaindex 7c4fa48d8e..5307c53fff 100644--- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/model/Secret.java+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/model/Secret.java@@ -33,6 +33,24 @@ public class Secret {private String owningService;/** Resource-based policy JSON attached via PutResourcePolicy, or null when none is attached. */private String resourcePolicy;+ /** Replicas of this secret in other regions. Only a primary carries these. */+ private List<ReplicaStatus> replicationStatus;+ /**+ * The region holding the primary this secret replicates, or null when this secret IS the+ * primary. Doubles as the "am I a replica?" flag, so a replica can never be mistaken for a+ * standalone secret and silently accept writes.+ */+ private String primaryRegion;++ /** One replica's location and health, as reported in {@code ReplicationStatus}. */+ @RegisterForReflection+ public record ReplicaStatus(+ @JsonProperty("Region") String region,+ @JsonProperty("KmsKeyId") String kmsKeyId,+ @JsonProperty("Status") String status,+ @JsonProperty("StatusMessage") String statusMessage,+ @JsonProperty("LastAccessedDate") Instant lastAccessedDate) {+ }@RegisterForReflectionpublic record RotationRules(@@ -201,4 +219,24 @@ public class Secret {public void setResourcePolicy(String resourcePolicy) {this.resourcePolicy = resourcePolicy;}++ public List<ReplicaStatus> getReplicationStatus() {+ return replicationStatus;+ }++ public void setReplicationStatus(List<ReplicaStatus> replicationStatus) {+ this.replicationStatus = replicationStatus;+ }++ public String getPrimaryRegion() {+ return primaryRegion;+ }++ public void setPrimaryRegion(String primaryRegion) {+ this.primaryRegion = primaryRegion;+ }++ public boolean isReplica() {+ return primaryRegion != null;+ }}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex df3532e8ab..a2c2666122 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -435,6 +435,8 @@ floci:secretsmanager:enabled: truedefault-recovery-window-days: 30+ scheduled-rotation-enabled: true+ rotation-tick-seconds: 60kinesis:enabled: truefirehose:diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretRotationSchedulerTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretRotationSchedulerTest.javanew file mode 100644index 0000000000..f5aa4ced3a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretRotationSchedulerTest.java@@ -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()));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.javaindex 4282244c8b..c05d034e5b 100644--- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.secretsmanager;import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.core.common.AwsErrorResponse;@@ -648,9 +649,11 @@ class SecretsManagerJsonHandlerTest {// SecretId, and uses the ARN echoed back by PutResourcePolicy as the resource id.String arn = createSecretReturningArn("policy-secret");+ // A scoped principal, because BlockPublicPolicy is now enforced: the terraform provider+ // sends block_public_policy, and a wildcard principal under it is refused.ObjectNode put = MAPPER.createObjectNode();put.put("SecretId", arn);- put.put("ResourcePolicy", RESOURCE_POLICY);+ put.put("ResourcePolicy", SCOPED_RESOURCE_POLICY);put.put("BlockPublicPolicy", true);Response putResponse = handler.handle("PutResourcePolicy", put, REGION);assertThat(putResponse.getStatus(), is(200));@@ -665,7 +668,7 @@ class SecretsManagerJsonHandlerTest {ObjectNode getBody = (ObjectNode) getResponse.getEntity();assertThat(getBody.get("ARN").asText(), is(arn));assertThat(getBody.get("Name").asText(), is("policy-secret"));- assertThat(getBody.get("ResourcePolicy").asText(), is(RESOURCE_POLICY));+ assertThat(getBody.get("ResourcePolicy").asText(), is(SCOPED_RESOURCE_POLICY));}@Test@@ -793,4 +796,1091 @@ class SecretsManagerJsonHandlerTest {assertThat(ex.getErrorCode(), is("InvalidRequestException"));assertThat(ex.getMessage(), containsString("marked for deletion"));}++ // ─── CancelRotateSecret ────────────────────────────────────────────────────++ private static final String LAMBDA_ARN =+ "arn:aws:lambda:us-east-1:000000000000:function:rotate";++ /**+ * Turns rotation on without starting one: with no rotation Lambda wired into the service+ * under test and no AWSPENDING version staged, the {@code RotateImmediately: false} path+ * runs its background task as a no-op, so the stored state is settled when this returns.+ */+ private void enableRotation(String secretName) {+ ObjectNode rotate = MAPPER.createObjectNode();+ rotate.put("SecretId", secretName);+ rotate.put("RotationLambdaARN", LAMBDA_ARN);+ rotate.put("RotateImmediately", false);+ ObjectNode rules = rotate.putObject("RotationRules");+ rules.put("AutomaticallyAfterDays", 14);+ assertThat(handler.handle("RotateSecret", rotate, REGION).getStatus(), is(200));+ }++ private ObjectNode describe(String secretName) {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", secretName);+ return (ObjectNode) handler.handle("DescribeSecret", req, REGION).getEntity();+ }++ @Test+ void cancelRotateSecretTurnsRotationOffAndReturnsArnAndName() {+ createSecret("cancel-me");+ enableRotation("cancel-me");+ assertThat(describe("cancel-me").get("RotationEnabled").asBoolean(), is(true));++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "cancel-me");+ Response response = handler.handle("CancelRotateSecret", req, REGION);++ assertThat(response.getStatus(), is(200));+ ObjectNode body = (ObjectNode) response.getEntity();+ assertThat(body.get("Name").asText(), is("cancel-me"));+ assertThat(body.get("ARN").asText(), startsWith("arn:aws:secretsmanager:"));+ assertThat(describe("cancel-me").get("RotationEnabled").asBoolean(), is(false));+ }++ @Test+ void cancelRotateSecretKeepsTheRotationRulesForLaterReEnabling() {+ // AWS: "If the secret previously had rotation turned on, but it is now turned off, this+ // field shows the previous rotation schedule and rotation function."+ createSecret("cancel-keeps-rules");+ enableRotation("cancel-keeps-rules");++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "cancel-keeps-rules");+ handler.handle("CancelRotateSecret", req, REGION);++ ObjectNode described = describe("cancel-keeps-rules");+ assertThat(described.get("RotationEnabled").asBoolean(), is(false));+ assertThat(described.get("RotationLambdaARN").asText(), is(LAMBDA_ARN));+ assertThat(described.get("RotationRules").get("AutomaticallyAfterDays").asInt(), is(14));+ }++ @Test+ void cancelRotateSecretOmitsVersionIdWhenNoRotationIsInProgress() {+ createSecret("cancel-no-pending");+ enableRotation("cancel-no-pending");++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "cancel-no-pending");+ ObjectNode body = (ObjectNode) handler.handle("CancelRotateSecret", req, REGION).getEntity();++ assertThat(body.has("VersionId"), is(false));+ }++ @Test+ void cancelRotateSecretReportsThePartiallyCreatedPendingVersion() {+ // AWS returns the id of the version the cancelled rotation created so the caller can+ // strip AWSPENDING from it; a stale AWSPENDING blocks every future rotation.+ createSecret("cancel-with-pending");+ String pendingToken = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ service.putSecretValue("cancel-with-pending", "half-rotated", null,+ pendingToken, REGION, java.util.List.of("AWSPENDING"));++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "cancel-with-pending");+ ObjectNode body = (ObjectNode) handler.handle("CancelRotateSecret", req, REGION).getEntity();++ assertThat(body.get("VersionId").asText(), is(pendingToken));+ }++ @Test+ void cancelRotateSecretOnAServiceManagedSecretThrows() {+ // Outside callers can't turn off rotation the owning service performs. Enforced on the+ // wire rather than in the service, so RDS can still manage its own secret internally.+ service.createSecret("rds!db-managed", "value", null, null, null, null, "rds", REGION);++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "rds!db-managed");+ assertThat(expectAwsException("CancelRotateSecret", req).getErrorCode(),+ is("InvalidRequestException"));+ }++ @Test+ void cancelRotateSecretOnUnknownSecretThrowsResourceNotFound() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "nope");+ io.github.hectorvent.floci.core.common.AwsException ex =+ org.junit.jupiter.api.Assertions.assertThrows(+ io.github.hectorvent.floci.core.common.AwsException.class,+ () -> handler.handle("CancelRotateSecret", req, REGION));+ assertThat(ex.getErrorCode(), is("ResourceNotFoundException"));+ }++ // ─── DeleteSecret recovery-window validation ───────────────────────────────++ private void assertDeleteSecretRejected(ObjectNode request) {+ io.github.hectorvent.floci.core.common.AwsException ex =+ org.junit.jupiter.api.Assertions.assertThrows(+ io.github.hectorvent.floci.core.common.AwsException.class,+ () -> handler.handle("DeleteSecret", request, REGION));+ assertThat(ex.getErrorCode(), is("InvalidParameterException"));+ }++ @Test+ void deleteSecretRejectsRecoveryWindowBelowSevenDays() {+ createSecret("short-window");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "short-window");+ req.put("RecoveryWindowInDays", 6);+ assertDeleteSecretRejected(req);+ }++ @Test+ void deleteSecretRejectsRecoveryWindowAboveThirtyDays() {+ createSecret("long-window");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "long-window");+ req.put("RecoveryWindowInDays", 31);+ assertDeleteSecretRejected(req);+ }++ @Test+ void deleteSecretRejectsRecoveryWindowOfZero() {+ // Zero used to be accepted as a synonym for ForceDeleteWithoutRecovery; AWS rejects it.+ createSecret("zero-window");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "zero-window");+ req.put("RecoveryWindowInDays", 0);+ assertDeleteSecretRejected(req);+ }++ @Test+ void deleteSecretRejectsForceDeleteCombinedWithRecoveryWindow() {+ createSecret("both-params");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "both-params");+ req.put("RecoveryWindowInDays", 7);+ req.put("ForceDeleteWithoutRecovery", true);+ assertDeleteSecretRejected(req);+ }++ @Test+ void deleteSecretAcceptsTheBoundaryRecoveryWindows() {+ for (int window : new int[] { 7, 30 }) {+ String name = "boundary-" + window;+ createSecret(name);+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", name);+ req.put("RecoveryWindowInDays", window);+ Response response = handler.handle("DeleteSecret", req, REGION);+ assertThat(response.getStatus(), is(200));+ assertThat(((ObjectNode) response.getEntity()).has("DeletionDate"), is(true));+ }+ }++ @Test+ void deleteSecretStillForceDeletesWithoutARecoveryWindow() {+ createSecret("force-me");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "force-me");+ req.put("ForceDeleteWithoutRecovery", true);+ assertThat(handler.handle("DeleteSecret", req, REGION).getStatus(), is(200));++ ObjectNode list = (ObjectNode) handler.handle("ListSecrets", MAPPER.createObjectNode(), REGION).getEntity();+ assertThat(list.get("SecretList").size(), is(0));+ }++ // ─── ListSecrets fidelity ──────────────────────────────────────────────────++ private ObjectNode listSecrets(ObjectNode request) {+ Response response = handler.handle("ListSecrets", request, REGION);+ assertThat(response.getStatus(), is(200));+ return (ObjectNode) response.getEntity();+ }++ @Test+ void listSecretsIncludesVersionStagesAndRotationFields() {+ createSecret("rich-entry");+ enableRotation("rich-entry");++ ObjectNode entry = (ObjectNode) listSecrets(MAPPER.createObjectNode()).get("SecretList").get(0);++ assertThat(entry.get("RotationLambdaARN").asText(), is(LAMBDA_ARN));+ assertThat(entry.get("RotationRules").get("AutomaticallyAfterDays").asInt(), is(14));+ // SecretVersionsToStages appears in AWS's own ListSecrets example response.+ ObjectNode stages = (ObjectNode) entry.get("SecretVersionsToStages");+ assertThat(stages.size(), is(1));+ assertThat(stages.elements().next().get(0).asText(), is("AWSCURRENT"));+ assertThat(entry.has("NextRotationDate"), is(true));+ }++ @Test+ void listSecretsOmitsSecretsPendingDeletionByDefault() {+ createSecret("staying");+ createSecret("going");+ ObjectNode delete = MAPPER.createObjectNode();+ delete.put("SecretId", "going");+ handler.handle("DeleteSecret", delete, REGION);++ ObjectNode list = listSecrets(MAPPER.createObjectNode());+ assertThat(list.get("SecretList").size(), is(1));+ assertThat(list.get("SecretList").get(0).get("Name").asText(), is("staying"));+ }++ @Test+ void listSecretsIncludesPlannedDeletionWhenAsked() {+ createSecret("staying");+ createSecret("going");+ ObjectNode delete = MAPPER.createObjectNode();+ delete.put("SecretId", "going");+ handler.handle("DeleteSecret", delete, REGION);++ ObjectNode req = MAPPER.createObjectNode();+ req.put("IncludePlannedDeletion", true);+ ObjectNode list = listSecrets(req);++ assertThat(list.get("SecretList").size(), is(2));+ ObjectNode deleted = null;+ for (com.fasterxml.jackson.databind.JsonNode node : list.get("SecretList")) {+ if ("going".equals(node.get("Name").asText())) {+ deleted = (ObjectNode) node;+ }+ }+ assertThat(deleted, is(notNullValue()));+ assertThat(deleted.has("DeletedDate"), is(true));+ }++ @Test+ void listSecretsSortsByNameDescending() {+ createSecret("secret-a");+ createSecret("secret-b");+ createSecret("secret-c");++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SortBy", "name");+ req.put("SortOrder", "desc");+ ObjectNode list = listSecrets(req);++ assertThat(list.get("SecretList").get(0).get("Name").asText(), is("secret-c"));+ assertThat(list.get("SecretList").get(1).get("Name").asText(), is("secret-b"));+ assertThat(list.get("SecretList").get(2).get("Name").asText(), is("secret-a"));+ }++ @Test+ void listSecretsSortsByNameAscending() {+ createSecret("secret-c");+ createSecret("secret-a");+ createSecret("secret-b");++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SortBy", "name");+ ObjectNode list = listSecrets(req);++ assertThat(list.get("SecretList").get(0).get("Name").asText(), is("secret-a"));+ assertThat(list.get("SecretList").get(2).get("Name").asText(), is("secret-c"));+ }++ @Test+ void listSecretsRejectsUnknownSortBy() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SortBy", "sideways");+ Response response = handler.handle("ListSecrets", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ @Test+ void listSecretsRejectsUnknownSortOrder() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SortOrder", "sideways");+ Response response = handler.handle("ListSecrets", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ @Test+ void listSecretsRejectsMoreThanTenFilters() {+ ObjectNode req = MAPPER.createObjectNode();+ ArrayNodeBuilder filters = new ArrayNodeBuilder(req.putArray("Filters"));+ for (int i = 0; i < 11; i++) {+ filters.addNameFilter("secret-" + i);+ }+ Response response = handler.handle("ListSecrets", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ /** Small helper so the filter-cap test stays readable. */+ private static final class ArrayNodeBuilder {+ private final com.fasterxml.jackson.databind.node.ArrayNode array;++ ArrayNodeBuilder(com.fasterxml.jackson.databind.node.ArrayNode array) {+ this.array = array;+ }++ void addNameFilter(String value) {+ ObjectNode filter = array.addObject();+ filter.put("Key", "name");+ filter.putArray("Values").add(value);+ }+ }++ // ─── CreateSecret ClientRequestToken ───────────────────────────────────────++ @Test+ void createSecretUsesClientRequestTokenAsTheVersionId() {+ // AWS: "This value becomes the VersionId of the new version."+ String token = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "tokened");+ req.put("SecretString", "value");+ req.put("ClientRequestToken", token);++ ObjectNode body = (ObjectNode) handler.handle("CreateSecret", req, REGION).getEntity();+ assertThat(body.get("VersionId").asText(), is(token));++ // The version is addressable by that id, which is what a rotation Lambda relies on.+ ObjectNode get = MAPPER.createObjectNode();+ get.put("SecretId", "tokened");+ get.put("VersionId", token);+ ObjectNode value = (ObjectNode) handler.handle("GetSecretValue", get, REGION).getEntity();+ assertThat(value.get("SecretString").asText(), is("value"));+ }++ @Test+ void createSecretWithoutClientRequestTokenStillGetsAGeneratedVersionId() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "untokened");+ req.put("SecretString", "value");++ ObjectNode body = (ObjectNode) handler.handle("CreateSecret", req, REGION).getEntity();+ assertThat(body.get("VersionId").asText(), is(not(emptyString())));+ }++ // ─── CreateSecret / UpdateSecret validation ────────────────────────────────++ private io.github.hectorvent.floci.core.common.AwsException expectAwsException(+ String action, ObjectNode request) {+ return org.junit.jupiter.api.Assertions.assertThrows(+ io.github.hectorvent.floci.core.common.AwsException.class,+ () -> handler.handle(action, request, REGION));+ }++ @Test+ void createSecretRejectsBothSecretStringAndSecretBinary() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "both-values");+ req.put("SecretString", "value");+ req.put("SecretBinary", "dmFsdWU=");+ assertThat(expectAwsException("CreateSecret", req).getErrorCode(), is("InvalidParameterException"));+ }++ @Test+ void createSecretRejectsNamesWithCharactersAwsDoesNotAllow() {+ // AWS allows ASCII letters, numbers and /_+=.@- only.+ for (String name : new String[] { "bad name", "bad#name", "bad$name", "bad:name" }) {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", name);+ req.put("SecretString", "value");+ assertThat("name " + name + " should be rejected",+ expectAwsException("CreateSecret", req).getErrorCode(), is("InvalidParameterException"));+ }+ }++ @Test+ void createSecretAcceptsEveryCharacterClassAwsAllows() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "path/to_my+secret=v1.0@prod-1");+ req.put("SecretString", "value");+ assertThat(handler.handle("CreateSecret", req, REGION).getStatus(), is(200));+ }++ @Test+ void createSecretRejectsANameLongerThan512Characters() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "a".repeat(513));+ req.put("SecretString", "value");+ assertThat(expectAwsException("CreateSecret", req).getErrorCode(), is("InvalidParameterException"));+ }++ @Test+ void updateSecretOnAServiceManagedSecretThrows() {+ // AWS: "The secret is managed by another service, and you must use that service to+ // update it." RotateSecret already guarded this; UpdateSecret did not.+ service.createSecret("rds!db-managed", "value", null, null, null, null, "rds", REGION);++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "rds!db-managed");+ req.put("Description", "hijacked");+ assertThat(expectAwsException("UpdateSecret", req).getErrorCode(), is("InvalidRequestException"));+ }++ @Test+ void updateSecretRejectsBothSecretStringAndSecretBinary() {+ createSecret("update-both");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "update-both");+ req.put("SecretString", "value");+ req.put("SecretBinary", "dmFsdWU=");+ assertThat(expectAwsException("UpdateSecret", req).getErrorCode(), is("InvalidParameterException"));+ }++ @Test+ void describeSecretOmitsVersionsThatNoLongerCarryStagingLabels() {+ // AWS: "A list of the versions of the secret that have staging labels attached.+ // Versions that don't have staging labels are considered deprecated."+ createSecret("deprecating");+ String pendingToken = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ service.putSecretValue("deprecating", "pending", null, pendingToken, REGION,+ java.util.List.of("AWSPENDING"));+ service.updateSecretVersionStage("deprecating", null, pendingToken, "AWSPENDING", REGION);++ ObjectNode stages = (ObjectNode) describe("deprecating").get("VersionIdsToStages");+ assertThat(stages.has(pendingToken), is(false));+ assertThat(stages.size(), is(1));+ }++ // ─── Replication over the wire ─────────────────────────────────────────────++ private static final String REPLICA_REGION = "eu-west-1";++ private ObjectNode replicateOverWire(String name, String targetRegion, boolean force) {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", name);+ ObjectNode target = req.putArray("AddReplicaRegions").addObject();+ target.put("Region", targetRegion);+ if (force) {+ req.put("ForceOverwriteReplicaSecret", true);+ }+ Response response = handler.handle("ReplicateSecretToRegions", req, REGION);+ assertThat(response.getStatus(), is(200));+ return (ObjectNode) response.getEntity();+ }++ @Test+ void replicateSecretToRegionsReturnsPrimaryArnAndReplicationStatus() {+ createSecret("wire-multi");+ ObjectNode body = replicateOverWire("wire-multi", REPLICA_REGION, false);++ assertThat(body.get("ARN").asText(), containsString(REGION));+ assertThat(body.get("ReplicationStatus").size(), is(1));+ ObjectNode status = (ObjectNode) body.get("ReplicationStatus").get(0);+ assertThat(status.get("Region").asText(), is(REPLICA_REGION));+ assertThat(status.get("Status").asText(), is("InSync"));+ assertThat(status.has("StatusMessage"), is(true));+ }++ @Test+ void describeSecretReportsReplicationStatusAndPrimaryRegion() {+ createSecret("wire-multi");+ replicateOverWire("wire-multi", REPLICA_REGION, false);++ ObjectNode primary = describe("wire-multi");+ assertThat(primary.get("PrimaryRegion").asText(), is(REGION));+ assertThat(primary.get("ReplicationStatus").size(), is(1));++ ObjectNode replicaReq = MAPPER.createObjectNode();+ replicaReq.put("SecretId", "wire-multi");+ ObjectNode replica = (ObjectNode) handler.handle("DescribeSecret", replicaReq, REPLICA_REGION).getEntity();+ // Seen from the replica, PrimaryRegion points back at the primary.+ assertThat(replica.get("PrimaryRegion").asText(), is(REGION));+ assertThat(replica.has("ReplicationStatus"), is(false));+ }++ @Test+ void createSecretReplicatesWhenAddReplicaRegionsIsGiven() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "born-replicated");+ req.put("SecretString", "value");+ req.putArray("AddReplicaRegions").addObject().put("Region", REPLICA_REGION);++ ObjectNode body = (ObjectNode) handler.handle("CreateSecret", req, REGION).getEntity();+ assertThat(body.get("ReplicationStatus").size(), is(1));+ assertThat(body.get("ReplicationStatus").get(0).get("Status").asText(), is("InSync"));++ ObjectNode get = MAPPER.createObjectNode();+ get.put("SecretId", "born-replicated");+ ObjectNode value = (ObjectNode) handler.handle("GetSecretValue", get, REPLICA_REGION).getEntity();+ assertThat(value.get("SecretString").asText(), is("value"));+ }++ @Test+ void createSecretWithoutReplicasOmitsReplicationStatus() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "solo");+ req.put("SecretString", "value");+ ObjectNode body = (ObjectNode) handler.handle("CreateSecret", req, REGION).getEntity();+ assertThat(body.has("ReplicationStatus"), is(false));+ }++ @Test+ void removeRegionsFromReplicationReturnsTheRemainingReplicas() {+ createSecret("wire-multi");+ replicateOverWire("wire-multi", REPLICA_REGION, false);++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "wire-multi");+ req.putArray("RemoveReplicaRegions").add(REPLICA_REGION);+ ObjectNode body = (ObjectNode) handler.handle("RemoveRegionsFromReplication", req, REGION).getEntity();++ assertThat(body.get("ReplicationStatus").size(), is(0));+ assertThat(body.get("ARN").asText(), containsString(REGION));+ }++ @Test+ void stopReplicationToReplicaReturnsThePromotedReplicaArn() {+ createSecret("wire-multi");+ replicateOverWire("wire-multi", REPLICA_REGION, false);++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "wire-multi");+ Response response = handler.handle("StopReplicationToReplica", req, REPLICA_REGION);++ assertThat(response.getStatus(), is(200));+ ObjectNode body = (ObjectNode) response.getEntity();+ assertThat(body.get("ARN").asText(), containsString(REPLICA_REGION));+ }++ @Test+ void listSecretsReportsTheReplicationStatusOfAPrimary() {+ createSecret("wire-multi");+ replicateOverWire("wire-multi", REPLICA_REGION, false);++ ObjectNode entry = (ObjectNode) listSecrets(MAPPER.createObjectNode()).get("SecretList").get(0);+ assertThat(entry.get("ReplicationStatus").size(), is(1));+ assertThat(entry.get("PrimaryRegion").asText(), is(REGION));+ }++ @Test+ void replicateSecretToRegionsRequiresAtLeastOneRegion() {+ createSecret("wire-multi");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "wire-multi");+ assertThat(expectAwsException("ReplicateSecretToRegions", req).getErrorCode(),+ is("InvalidParameterException"));+ }++ // ─── Required parameters that were silently no-ops ─────────────────────────++ @Test+ void tagResourceRequiresTags() {+ createSecret("tagless");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "tagless");+ Response response = handler.handle("TagResource", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ @Test+ void untagResourceRequiresTagKeys() {+ createSecret("keyless");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "keyless");+ Response response = handler.handle("UntagResource", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ // ─── BlockPublicPolicy ─────────────────────────────────────────────────────++ private Response putResourcePolicy(String secretName, String policy, Boolean blockPublic) {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", secretName);+ req.put("ResourcePolicy", policy);+ if (blockPublic != null) {+ req.put("BlockPublicPolicy", blockPublic);+ }+ return handler.handle("PutResourcePolicy", req, REGION);+ }++ @Test+ void putResourcePolicyBlocksAWildcardPrincipalWhenBlockPublicPolicyIsSet() {+ createSecret("blocked-policy");+ Response response = putResourcePolicy("blocked-policy", RESOURCE_POLICY, true);++ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("PublicPolicyException"));+ }++ @Test+ void putResourcePolicyAllowsAWildcardPrincipalByDefault() {+ // AWS: "By default, public policies aren't blocked."+ createSecret("open-policy");+ assertThat(putResourcePolicy("open-policy", RESOURCE_POLICY, null).getStatus(), is(200));+ assertThat(putResourcePolicy("open-policy", RESOURCE_POLICY, false).getStatus(), is(200));+ }++ @Test+ void putResourcePolicyAcceptsAScopedPolicyWithBlockPublicPolicySet() {+ createSecret("scoped-policy");+ assertThat(putResourcePolicy("scoped-policy", SCOPED_RESOURCE_POLICY, true).getStatus(), is(200));+ }++ @Test+ void putResourcePolicyRejectsAPolicyLongerThan20480Characters() {+ createSecret("huge-policy");+ String huge = "{\"Version\":\"2012-10-17\",\"Statement\":[],\"Pad\":\"" + "a".repeat(20480) + "\"}";+ Response response = putResourcePolicy("huge-policy", huge, null);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ // ─── Empty VersionStages is omitted, not sent as [] ────────────────────────++ @Test+ void getSecretValueOmitsVersionStagesForADeprecatedVersion() {+ // AWS models VersionStages with "Array Members: Minimum number of 1 item", so an empty+ // array is not a shape it ever emits - the field is simply absent.+ createSecret("deprecated-read");+ String token = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ service.putSecretValue("deprecated-read", "pending", null, token, REGION,+ java.util.List.of("AWSPENDING"));+ service.updateSecretVersionStage("deprecated-read", null, token, "AWSPENDING", REGION);++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "deprecated-read");+ req.put("VersionId", token);+ ObjectNode body = (ObjectNode) handler.handle("GetSecretValue", req, REGION).getEntity();++ assertThat(body.get("SecretString").asText(), is("pending"));+ assertThat(body.has("VersionStages"), is(false));+ }++ @Test+ void getSecretValueStillReportsStagesForACurrentVersion() {+ createSecret("current-read");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "current-read");+ ObjectNode body = (ObjectNode) handler.handle("GetSecretValue", req, REGION).getEntity();++ assertThat(body.get("VersionStages").get(0).asText(), is("AWSCURRENT"));+ }++ // ─── GetRandomPassword input caps ──────────────────────────────────────────++ @Test+ void getRandomPasswordRejectsExcludeCharactersLongerThan4096() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("ExcludeCharacters", "a".repeat(4097));+ Response response = handler.handle("GetRandomPassword", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ // ─── BatchGetSecretValue caps ──────────────────────────────────────────────++ @Test+ void batchGetSecretValueRejectsMoreThanTwentySecretIds() {+ // AWS caps SecretIdList at 20. Returning 25 results here would let code pass against+ // floci and then fail against AWS, which is the one outcome an emulator must avoid.+ ObjectNode req = MAPPER.createObjectNode();+ ArrayNode ids = req.putArray("SecretIdList");+ for (int i = 0; i < 21; i++) {+ ids.add("secret-" + i);+ }+ Response response = handler.handle("BatchGetSecretValue", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ @Test+ void batchGetSecretValueAcceptsExactlyTwentySecretIds() {+ ObjectNode req = MAPPER.createObjectNode();+ ArrayNode ids = req.putArray("SecretIdList");+ for (int i = 0; i < 20; i++) {+ ids.add("secret-" + i);+ }+ assertThat(handler.handle("BatchGetSecretValue", req, REGION).getStatus(), is(200));+ }++ @Test+ void batchGetSecretValueRejectsMoreThanTenFilters() {+ ObjectNode req = MAPPER.createObjectNode();+ ArrayNodeBuilder filters = new ArrayNodeBuilder(req.putArray("Filters"));+ for (int i = 0; i < 11; i++) {+ filters.addNameFilter("secret-" + i);+ }+ Response response = handler.handle("BatchGetSecretValue", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ // ─── PutSecretValue / UpdateSecret value rules ─────────────────────────────++ @Test+ void putSecretValueRequiresOneOfSecretStringOrSecretBinary() {+ // AWS: "You must include SecretBinary or SecretString, but not both." Neither is as+ // invalid as both - it would otherwise store a valueless version.+ createSecret("needs-a-value");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "needs-a-value");+ assertThat(expectAwsException("PutSecretValue", req).getErrorCode(),+ is("InvalidParameterException"));+ }++ @Test+ void putSecretValueRejectsBothValueForms() {+ createSecret("not-both");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "not-both");+ req.put("SecretString", "text");+ req.put("SecretBinary", "YmluYXJ5");+ assertThat(expectAwsException("PutSecretValue", req).getErrorCode(),+ is("InvalidParameterException"));+ }++ @Test+ void updateSecretRejectsAClientRequestTokenThatAlreadyNamesAVersion() {+ // Unlike PutSecretValue and CreateSecret, UpdateSecret is NOT idempotent. AWS: "If you+ // call this operation with a ClientRequestToken that matches an existing version's+ // VersionId, the operation results in an error."+ String token = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ ObjectNode create = MAPPER.createObjectNode();+ create.put("Name", "update-token");+ create.put("SecretString", "v1");+ create.put("ClientRequestToken", token);+ handler.handle("CreateSecret", create, REGION);++ ObjectNode update = MAPPER.createObjectNode();+ update.put("SecretId", "update-token");+ update.put("SecretString", "v1");+ update.put("ClientRequestToken", token);+ assertThat(expectAwsException("UpdateSecret", update).getErrorCode(),+ is("ResourceExistsException"));+ }++ @Test+ void updateSecretWithAFreshClientRequestTokenCreatesThatVersion() {+ String token = "b1b2c3d4-e5f6-7890-abcd-ef1234567890";+ createSecret("update-fresh");++ ObjectNode update = MAPPER.createObjectNode();+ update.put("SecretId", "update-fresh");+ update.put("SecretString", "v2");+ update.put("ClientRequestToken", token);+ ObjectNode body = (ObjectNode) handler.handle("UpdateSecret", update, REGION).getEntity();++ assertThat(body.get("VersionId").asText(), is(token));+ }++ @Test+ void updateSecretWithAnEmptyKmsKeyIdFallsBackToTheAwsManagedKey() {+ // AWS: "If you set this to an empty string, Secrets Manager uses the AWS managed key+ // aws/secretsmanager" - and DescribeSecret omits KmsKeyId for the managed key.+ ObjectNode create = MAPPER.createObjectNode();+ create.put("Name", "kms-cleared");+ create.put("SecretString", "v1");+ create.put("KmsKeyId", "some-key");+ handler.handle("CreateSecret", create, REGION);++ ObjectNode update = MAPPER.createObjectNode();+ update.put("SecretId", "kms-cleared");+ update.put("KmsKeyId", "");+ handler.handle("UpdateSecret", update, REGION);++ assertThat(describe("kms-cleared").has("KmsKeyId"), is(false));+ }++ // ─── PrimaryRegion is a multi-region-only field ────────────────────────────++ @Test+ void describeSecretOmitsPrimaryRegionForASecretThatIsNotReplicated() {+ // AWS "only returns fields that have a value", and its DescribeSecret example - a plain+ // secret with rotation configured - carries no PrimaryRegion. The field shows up only+ // once a secret is part of a multi-region set.+ createSecret("standalone");+ assertThat(describe("standalone").has("PrimaryRegion"), is(false));+ }++ @Test+ void listSecretsOmitsPrimaryRegionForASecretThatIsNotReplicated() {+ createSecret("standalone");+ ObjectNode entry = (ObjectNode) listSecrets(MAPPER.createObjectNode()).get("SecretList").get(0);+ assertThat(entry.has("PrimaryRegion"), is(false));+ }++ // ─── RotationRules validation ──────────────────────────────────────────────++ private ObjectNode rotateRequest(String secretId, java.util.function.Consumer<ObjectNode> rules) {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", secretId);+ req.put("RotationLambdaARN", LAMBDA_ARN);+ req.put("RotateImmediately", false);+ rules.accept(req.putObject("RotationRules"));+ return req;+ }++ @Test+ void rotateSecretRejectsAutomaticallyAfterDaysOutsideOneToAThousand() {+ createSecret("rot-days");+ for (int days : new int[] { 0, -1, 1001 }) {+ ObjectNode req = rotateRequest("rot-days", r -> r.put("AutomaticallyAfterDays", days));+ assertThat("days " + days, expectAwsException("RotateSecret", req).getErrorCode(),+ is("InvalidParameterException"));+ }+ }++ @Test+ void rotateSecretAcceptsTheAutomaticallyAfterDaysBoundaries() {+ for (int days : new int[] { 1, 1000 }) {+ String name = "rot-bound-" + days;+ createSecret(name);+ ObjectNode req = rotateRequest(name, r -> r.put("AutomaticallyAfterDays", days));+ assertThat(handler.handle("RotateSecret", req, REGION).getStatus(), is(200));+ }+ }++ @Test+ void rotateSecretRejectsADurationThatIsNotHours() {+ createSecret("rot-duration");+ for (String duration : new String[] { "3", "3d", "300h", "h" }) {+ ObjectNode req = rotateRequest("rot-duration", r -> {+ r.put("AutomaticallyAfterDays", 7);+ r.put("Duration", duration);+ });+ assertThat("duration " + duration,+ expectAwsException("RotateSecret", req).getErrorCode(), is("InvalidParameterException"));+ }+ }++ @Test+ void rotateSecretAcceptsAnHoursDuration() {+ createSecret("rot-duration-ok");+ ObjectNode req = rotateRequest("rot-duration-ok", r -> {+ r.put("AutomaticallyAfterDays", 7);+ r.put("Duration", "3h");+ });+ assertThat(handler.handle("RotateSecret", req, REGION).getStatus(), is(200));+ }++ @Test+ void rotateSecretRejectsARateFasterThanFourHours() {+ // AWS: "You can rotate a secret as often as every four hours."+ createSecret("rot-fast");+ ObjectNode req = rotateRequest("rot-fast", r -> r.put("ScheduleExpression", "rate(1 hours)"));+ assertThat(expectAwsException("RotateSecret", req).getErrorCode(), is("InvalidParameterException"));+ }++ @Test+ void rotateSecretRejectsRateUnitsSecretsManagerDoesNotSupport() {+ // Secrets Manager rate() is hours or days only, unlike EventBridge Scheduler.+ createSecret("rot-units");+ for (String expression : new String[] { "rate(30 minutes)", "rate(2 weeks)" }) {+ ObjectNode req = rotateRequest("rot-units", r -> r.put("ScheduleExpression", expression));+ assertThat("expression " + expression,+ expectAwsException("RotateSecret", req).getErrorCode(), is("InvalidParameterException"));+ }+ }++ @Test+ void rotateSecretAcceptsAFourHourRate() {+ createSecret("rot-four");+ ObjectNode req = rotateRequest("rot-four", r -> r.put("ScheduleExpression", "rate(4 hours)"));+ assertThat(handler.handle("RotateSecret", req, REGION).getStatus(), is(200));+ }++ // ─── CreateSecret idempotency ──────────────────────────────────────────────++ @Test+ void repeatingCreateSecretWithTheSameTokenAndValueIsIgnored() {+ // AWS: "If a version with this value already exists and the version SecretString and+ // SecretBinary values are the same as those in the request, then the request is ignored."+ String token = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "idempotent");+ req.put("SecretString", "value");+ req.put("ClientRequestToken", token);++ ObjectNode first = (ObjectNode) handler.handle("CreateSecret", req, REGION).getEntity();+ ObjectNode second = (ObjectNode) handler.handle("CreateSecret", req, REGION).getEntity();++ assertThat(second.get("ARN").asText(), is(first.get("ARN").asText()));+ assertThat(second.get("VersionId").asText(), is(token));+ }++ @Test+ void repeatingCreateSecretWithTheSameTokenButADifferentValueFails() {+ String token = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ ObjectNode first = MAPPER.createObjectNode();+ first.put("Name", "idempotent-conflict");+ first.put("SecretString", "value");+ first.put("ClientRequestToken", token);+ handler.handle("CreateSecret", first, REGION);++ ObjectNode second = first.deepCopy();+ second.put("SecretString", "different");+ assertThat(expectAwsException("CreateSecret", second).getErrorCode(), is("ResourceExistsException"));+ }++ @Test+ void recreatingAnExistingNameWithoutATokenStillFails() {+ createSecret("taken");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "taken");+ req.put("SecretString", "value");+ assertThat(expectAwsException("CreateSecret", req).getErrorCode(), is("ResourceExistsException"));+ }++ // ─── ListSecretVersionIds ──────────────────────────────────────────────────++ /** Leaves {@code deprecated} staged nowhere, alongside the AWSCURRENT version. */+ private String stageThenDeprecate(String secretName) {+ String token = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ service.putSecretValue(secretName, "pending", null, token, REGION,+ java.util.List.of("AWSPENDING"));+ service.updateSecretVersionStage(secretName, null, token, "AWSPENDING", REGION);+ return token;+ }++ @Test+ void listSecretVersionIdsExcludesDeprecatedVersionsByDefault() {+ // AWS: "By default, versions without staging labels aren't included."+ createSecret("versioned");+ String deprecated = stageThenDeprecate("versioned");++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "versioned");+ ObjectNode body = (ObjectNode) handler.handle("ListSecretVersionIds", req, REGION).getEntity();++ assertThat(body.get("Versions").size(), is(1));+ assertThat(body.get("Versions").get(0).get("VersionId").asText(), is(not(deprecated)));+ }++ @Test+ void listSecretVersionIdsIncludesDeprecatedVersionsWhenAsked() {+ createSecret("versioned");+ String deprecated = stageThenDeprecate("versioned");++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "versioned");+ req.put("IncludeDeprecated", true);+ ObjectNode body = (ObjectNode) handler.handle("ListSecretVersionIds", req, REGION).getEntity();++ assertThat(body.get("Versions").size(), is(2));+ ObjectNode deprecatedEntry = null;+ for (com.fasterxml.jackson.databind.JsonNode node : body.get("Versions")) {+ if (deprecated.equals(node.get("VersionId").asText())) {+ deprecatedEntry = (ObjectNode) node;+ }+ }+ assertThat(deprecatedEntry, is(notNullValue()));+ // AWS's example omits VersionStages entirely for a version that has none.+ assertThat(deprecatedEntry.has("VersionStages"), is(false));+ }++ @Test+ void listSecretVersionIdsPaginates() {+ createSecret("versioned");+ for (int i = 1; i <= 3; i++) {+ service.putSecretValue("versioned", "v" + i, null, null, REGION,+ java.util.List.of("stage-" + i));+ }++ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "versioned");+ req.put("MaxResults", 2);+ ObjectNode page1 = (ObjectNode) handler.handle("ListSecretVersionIds", req, REGION).getEntity();+ assertThat(page1.get("Versions").size(), is(2));+ assertThat(page1.has("NextToken"), is(true));++ ObjectNode next = MAPPER.createObjectNode();+ next.put("SecretId", "versioned");+ next.put("MaxResults", 2);+ next.put("NextToken", page1.get("NextToken").asText());+ ObjectNode page2 = (ObjectNode) handler.handle("ListSecretVersionIds", next, REGION).getEntity();+ assertThat(page2.get("Versions").size(), is(2));+ assertThat(page2.has("NextToken"), is(false));+ }++ @Test+ void listSecretVersionIdsRejectsMaxResultsOutOfRange() {+ createSecret("versioned");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "versioned");+ req.put("MaxResults", 101);+ Response response = handler.handle("ListSecretVersionIds", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ // ─── ValidateResourcePolicy ────────────────────────────────────────────────++ /** Named principal, unlike {@code RESOURCE_POLICY}, which deliberately uses a wildcard. */+ private static final String SCOPED_RESOURCE_POLICY = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",\+ "Principal":{"AWS":"arn:aws:iam::123456789012:root"},\+ "Action":"secretsmanager:GetSecretValue","Resource":"*"}]}""";++ @Test+ void validateResourcePolicyPassesAScopedPolicy() {+ createSecret("policy-target");+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "policy-target");+ req.put("ResourcePolicy", SCOPED_RESOURCE_POLICY);++ Response response = handler.handle("ValidateResourcePolicy", req, REGION);+ assertThat(response.getStatus(), is(200));+ ObjectNode body = (ObjectNode) response.getEntity();+ assertThat(body.get("PolicyValidationPassed").asBoolean(), is(true));+ assertThat(body.get("ValidationErrors").size(), is(0));+ }++ @Test+ void validateResourcePolicyFailsAWildcardPrincipal() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("ResourcePolicy", """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",\+ "Principal":"*","Action":"secretsmanager:GetSecretValue","Resource":"*"}]}""");++ ObjectNode body = (ObjectNode) handler.handle("ValidateResourcePolicy", req, REGION).getEntity();+ assertThat(body.get("PolicyValidationPassed").asBoolean(), is(false));+ assertThat(body.get("ValidationErrors").size(), greaterThan(0));+ assertThat(body.get("ValidationErrors").get(0).get("CheckName").asText(),+ is("REFLEXIVE_PRINCIPAL_CHECK"));+ }++ @Test+ void validateResourcePolicyFailsAWildcardAwsPrincipal() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("ResourcePolicy", """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",\+ "Principal":{"AWS":"*"},"Action":"secretsmanager:GetSecretValue","Resource":"*"}]}""");++ ObjectNode body = (ObjectNode) handler.handle("ValidateResourcePolicy", req, REGION).getEntity();+ assertThat(body.get("PolicyValidationPassed").asBoolean(), is(false));+ }++ @Test+ void validateResourcePolicyRejectsMalformedJson() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("ResourcePolicy", "not json at all");+ Response response = handler.handle("ValidateResourcePolicy", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("MalformedPolicyDocumentException"));+ }++ @Test+ void validateResourcePolicyRequiresAPolicy() {+ ObjectNode req = MAPPER.createObjectNode();+ Response response = handler.handle("ValidateResourcePolicy", req, REGION);+ assertThat(response.getStatus(), is(400));+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("InvalidParameterException"));+ }++ @Test+ void validateResourcePolicyOnAnUnknownSecretThrowsResourceNotFound() {+ // SecretId is optional, but when given it must resolve.+ ObjectNode req = MAPPER.createObjectNode();+ req.put("SecretId", "nope");+ req.put("ResourcePolicy", SCOPED_RESOURCE_POLICY);+ assertThat(expectAwsException("ValidateResourcePolicy", req).getErrorCode(),+ is("ResourceNotFoundException"));+ }++ @Test+ void createSecretRejectsAClientRequestTokenOutsideThe32To64Range() {+ ObjectNode req = MAPPER.createObjectNode();+ req.put("Name", "bad-token");+ req.put("SecretString", "value");+ req.put("ClientRequestToken", "too-short");++ io.github.hectorvent.floci.core.common.AwsException ex =+ org.junit.jupiter.api.Assertions.assertThrows(+ io.github.hectorvent.floci.core.common.AwsException.class,+ () -> handler.handle("CreateSecret", req, REGION));+ assertThat(ex.getErrorCode(), is("InvalidParameterException"));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.javaindex a8df6fa728..84fc4e1652 100644--- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java@@ -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());+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.javanew file mode 100644index 0000000000..8ef20da538--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerWriteLockTest.java@@ -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());+ }+ }+}