mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(secretsmanager): add the five missing actions and correct response fidelity (#3711)
* feat(secretsmanager): add the five missing actions and correct response fidelity Secrets Manager implemented 18 of the 23 actions in the API reference. This adds the remaining five and corrects a number of response and validation divergences found by working through each operation's reference page. New actions: - CancelRotateSecret turns rotation off and reports the half-built AWSPENDING version an interrupted rotation left behind. The staging labels are left alone, as AWS leaves them, because that version id is the only handle on a stale AWSPENDING - and a stale AWSPENDING that is not also AWSCURRENT makes every later RotateSecret fail with "a previous rotation isn't complete". - ValidateResourcePolicy reports wildcard principals under the same REFLEXIVE_PRINCIPAL_CHECK name AWS uses. BlockPublicPolicy on PutResourcePolicy now enforces the same check. - ReplicateSecretToRegions, RemoveRegionsFromReplication and StopReplicationToReplica, backed by a replication model on Secret. Replicas carry the primary's ARN with the Region swapped, track later writes to the primary, and are read-only; a primary that still has replicas cannot be deleted. Scheduled rotation now fires. RotationRules were stored and echoed back but never acted on, so AutomaticallyAfterDays and ScheduleExpression described a schedule that could not happen. A background sweep rotates secrets whose NextRotationDate has passed, reusing the EventBridge Scheduler expression parser for rate() and cron(). The schedule advances when a rotation is dispatched rather than when it succeeds, so a failing rotation cannot pin the sweep on one secret forever. Response fidelity: - ListSecrets honours SortBy, SortOrder and IncludePlannedDeletion, and its entries carry SecretVersionsToStages, the rotation fields, DeletedDate and PrimaryRegion. - PrimaryRegion and ReplicationStatus appear only on multi-Region secrets, matching AWS's "only returns fields that have a value" rule. - Versions with no staging labels are deprecated: DescribeSecret and ListSecretVersionIds omit them unless IncludeDeprecated is set, and an empty VersionStages array is omitted rather than sent. - ListSecretVersionIds gained IncludeDeprecated, LastAccessedDate and paging. Validation, all previously accepted silently: - DeleteSecret rejects a recovery window outside 7-30 and the ForceDeleteWithoutRecovery/RecoveryWindowInDays combination. A window of 0 used to fall through to force-delete, turning a request for no recovery window into an unrecoverable delete. - CreateSecret uses ClientRequestToken as the version id and is idempotent on retry; UpdateSecret, which AWS documents as not idempotent, rejects a token that already names a version. - RotationRules bounds, secret name charset, SecretString/SecretBinary exclusivity, KMS key existence and state, and the documented caps on BatchGetSecretValue, Filters, ExcludeCharacters and ResourcePolicy. Secret values remain stored in the clear; encrypting them with the emulator's own KMS would protect nothing while making the store unreadable. KmsKeyId is validated instead, which is the part a caller can observe. Two deviations are deliberate and recorded in docs/services/secrets-manager.md: LastRotatedDate is retained after CancelRotateSecret, and RotateSecret with RotateImmediately=false does not create the throwaway AWSPENDING version. * test(secretsmanager): create a real KMS key in the sdk-test-java compat test kmsKeyIdPreservation asserted that floci round-trips whatever KmsKeyId it is handed, using an ARN that was never created. That passed only because floci did not check the key; real AWS rejects a key it cannot access, and so does the new validation. The test now creates a key through the emulated KMS and round-trips that ARN, so it still covers KmsKeyId preservation without depending on the missing check. A second case pins the rejection itself. * refactor(secretsmanager): import types instead of qualifying them inline AGENTS.md asks for imports unless a name collision forces qualification. AwsException and UUID had neither. * fix(secretsmanager): hold the rotation lock while promoting a replica StopReplicationToReplica wrote the promoted replica outside the per-secret lock every other mutation in this file takes. The promotion races the primary's replica sync, and losing that race writes the replica back over the copy the call just promoted. Also imports KmsKey, ConcurrentHashMap and HashMap rather than qualifying them inline, per the same AGENTS.md rule. * test(secretsmanager): assert the KMS rejection by exception type, not message text createSecretWithAnUnknownKmsKeyIsRejected matched "InvalidParameterException" against the message, but that is the exception type; the message itself reads "You can't access the KMS key ... in this Region". The assertion now checks the typed InvalidParameterException and the text it actually carries. * test(secretsmanager): give the new KMS compat test its own order createSecretWithAnUnknownKmsKeyIsRejected inherited @Order(13) from the test it was added next to, so two cases shared a position. JUnit breaks the tie deterministically, but the duplicate made the sequence misleading; the tail is renumbered so each case keeps a distinct order. Also sorts the new KMS imports, which landed between the lambda ones. * fix(secretsmanager): guard every write to a secret with its owning monitor UpdateSecret read, mutated and persisted without taking the secret's lock, unlike every other mutator in the class, so two concurrent calls could drop one another's field. StopReplicationToReplica locked the replica's own ARN, but persist() writes a primary's replica slots while holding only the primary's lock: two monitors guarding one store slot, so a sync landing after the promotion could overwrite the promoted copy. The promotion now runs under the primary's monitor, and its two halves run in one critical section so nothing lands between them. SecretsManagerWriteLockTest parks a write mid-flight and asserts the second caller waits; both cases fail without the fixes.
This commit is contained in:
1 parent
1831f10105
commit
33d17c0146
14 files changed
+3390
-114
No files matched your search
@@ -1600,6 +1600,12 @@ public interface EmulatorConfig {
|
||||
|
||||
@WithDefault("30")
|
||||
int defaultRecoveryWindowDays();
|
||||
|
||||
@WithDefault("true")
|
||||
boolean scheduledRotationEnabled();
|
||||
|
||||
@WithDefault("60")
|
||||
long rotationTickSeconds();
|
||||
}
|
||||
|
||||
interface ApiGatewayV2ServiceConfig {
|
||||
|
||||
+3
@@ -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())
|
||||
|
||||
+103
@@ -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;
|
||||
}
|
||||
}
|
||||
+117
@@ -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);
|
||||
}
|
||||
}
|
||||
+458
-66
@@ -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;
|
||||
|
||||
@ApplicationScoped
|
||||
public 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);
|
||||
|
||||
+646
-36
@@ -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;
|
||||
|
||||
@ApplicationScoped
|
||||
public 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 {
|
||||
|
||||
@Inject
|
||||
public 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);
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user