Files
floci/docs/services/secrets-manager.md
T
Abhigya 33d17c0146 feat(secretsmanager): add the five missing actions and correct response fidelity (#3711)
* feat(secretsmanager): add the five missing actions and correct response fidelity

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

New actions:

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

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

Response fidelity:

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

Validation, all previously accepted silently:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

SecretsManagerWriteLockTest parks a write mid-flight and asserts the second
caller waits; both cases fail without the fixes.
2026-09-16 15:13:57 -04:00

158 lines
6.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Secrets Manager
**Protocol:** JSON 1.1 (`X-Amz-Target: secretsmanager.*`)
**Endpoint:** `POST http://localhost:4566/`
## Supported Actions
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `CreateSecret` | Create a new secret |
| `GetSecretValue` | Retrieve the current secret value |
| `PutSecretValue` | Update the secret value (new version) |
| `UpdateSecret` | Update secret metadata or value |
| `DescribeSecret` | Get secret metadata and version info |
| `ListSecrets` | List all secrets |
| `DeleteSecret` | Delete a secret (with recovery window) |
| `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 |
| `GetResourcePolicy` | Get the resource policy |
| `GetRandomPassword` | Generate a random password |
| `BatchGetSecretValue` | Retrieve multiple secret values in one call |
| `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
| Variable | Default | Description |
|---|---|---|
| `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
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
# Create a string secret
aws secretsmanager create-secret \
--name /app/database-url \
--secret-string "postgresql://admin:secret@localhost/mydb" \
--endpoint-url $AWS_ENDPOINT_URL
# Create a JSON secret
aws secretsmanager create-secret \
--name /app/api-keys \
--secret-string '{"stripe":"sk_test_xxx","sendgrid":"SG.xxx"}' \
--endpoint-url $AWS_ENDPOINT_URL
# Retrieve a secret
aws secretsmanager get-secret-value \
--secret-id /app/database-url \
--endpoint-url $AWS_ENDPOINT_URL
# Update a secret
aws secretsmanager put-secret-value \
--secret-id /app/database-url \
--secret-string "postgresql://admin:new-password@localhost/mydb" \
--endpoint-url $AWS_ENDPOINT_URL
# List secrets
aws secretsmanager list-secrets --endpoint-url $AWS_ENDPOINT_URL
# Delete (with recovery window)
aws secretsmanager delete-secret \
--secret-id /app/database-url \
--recovery-window-in-days 7 \
--endpoint-url $AWS_ENDPOINT_URL
# Delete immediately (no recovery)
aws secretsmanager delete-secret \
--secret-id /app/database-url \
--force-delete-without-recovery \
--endpoint-url $AWS_ENDPOINT_URL
# Generate a random password
aws secretsmanager get-random-password \
--password-length 24 \
--exclude-punctuation \
--endpoint-url $AWS_ENDPOINT_URL
# Batch-fetch multiple secrets in one call
aws secretsmanager batch-get-secret-value \
--secret-id-list /app/database-url /app/api-keys \
--endpoint-url $AWS_ENDPOINT_URL
# Move the AWSCURRENT label to a different version (e.g. during a rotation)
aws secretsmanager update-secret-version-stage \
--secret-id /app/database-url \
--version-stage AWSCURRENT \
--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.