mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(redshift): rotate managed master passwords (#6505)
* feat(redshift): rotate managed master passwords * fix(redshift): serialize managed secret rotation * fix(redshift): address managed secret rotation review * fix(redshift): keep concurrent rotation retries idempotent * fix: defer managed secret guard until rotation reservation succeeds * fix: preserve secret versions saved during rotation reservation * fix: guarantee required character types in serverless passwords * revert: defer serverless password character types fix to dedicated PR * test(secretsmanager): extract blocking reserve helper across rotators
This commit is contained in:
1 parent
ec21cf38c7
commit
ce0933be9b
8 files changed
+820
-33
No files matched your search
@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.redshift.model.Snapshot;
|
||||
import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant;
|
||||
import io.github.hectorvent.floci.services.redshift.model.SnapshotSchedule;
|
||||
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.ManagedSecretRotator;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.RandomPasswordGenerator;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
|
||||
@@ -59,7 +60,7 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftService {
|
||||
public class RedshiftService implements ManagedSecretRotator {
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftService.class);
|
||||
|
||||
// The group every cluster starts on until one is named.
|
||||
@@ -95,6 +96,7 @@ public class RedshiftService {
|
||||
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
private final ConcurrentHashMap<ResourceKey, ResourceLock> resourceLocks = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, ResourceKey> managedRotationReservations = new ConcurrentHashMap<>();
|
||||
|
||||
private record ResourceKey(String accountId, String kind, String identifier) { }
|
||||
|
||||
@@ -104,7 +106,11 @@ public class RedshiftService {
|
||||
}
|
||||
|
||||
private <T> T withResourceLock(String kind, String identifier, Supplier<T> work) {
|
||||
ResourceKey key = new ResourceKey(clusters.accountId(), kind, identifier);
|
||||
return withResourceLock(clusters.accountId(), kind, identifier, work);
|
||||
}
|
||||
|
||||
private <T> T withResourceLock(String accountId, String kind, String identifier, Supplier<T> work) {
|
||||
ResourceKey key = new ResourceKey(accountId, kind, identifier);
|
||||
ResourceLock scoped = resourceLocks.compute(key, (ignored, existing) -> {
|
||||
ResourceLock selected = existing == null ? new ResourceLock() : existing;
|
||||
selected.users++;
|
||||
@@ -121,7 +127,18 @@ public class RedshiftService {
|
||||
|
||||
// Acquire resource locks before the service monitor; snapshot I/O never takes the monitor.
|
||||
private <T> T mutateCluster(String identifier, Supplier<T> mutation) {
|
||||
return withResourceLock("cluster", identifier, () -> mutate(mutation));
|
||||
return withResourceLock("cluster", identifier, () -> {
|
||||
ensureNoManagedRotation(clusters.accountId(), identifier);
|
||||
return mutate(mutation);
|
||||
});
|
||||
}
|
||||
|
||||
private void ensureNoManagedRotation(String accountId, String identifier) {
|
||||
ResourceKey key = new ResourceKey(accountId, "cluster", identifier);
|
||||
if (managedRotationReservations.containsValue(key)) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"The cluster's managed master password is being rotated. Try again after rotation completes.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized <T> T mutate(Supplier<T> mutation) {
|
||||
@@ -699,6 +716,7 @@ public class RedshiftService {
|
||||
public Cluster deleteCluster(String identifier, Boolean skipFinalClusterSnapshot,
|
||||
String finalSnapshotIdentifier, Integer finalSnapshotRetentionPeriod) {
|
||||
return withResourceLock("cluster", identifier, () -> {
|
||||
ensureNoManagedRotation(clusters.accountId(), identifier);
|
||||
Supplier<Cluster> deletion = () -> deleteClusterWithFinalSnapshot(identifier, skipFinalClusterSnapshot,
|
||||
finalSnapshotIdentifier, finalSnapshotRetentionPeriod);
|
||||
return Boolean.TRUE.equals(skipFinalClusterSnapshot) ? deletion.get()
|
||||
@@ -911,6 +929,98 @@ public class RedshiftService {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String secretArn, String region) {
|
||||
if (!AwsArnUtils.isArn(secretArn) || !region.equals(AwsArnUtils.parse(secretArn).region())) {
|
||||
return false;
|
||||
}
|
||||
return clusters.scanAllAccountEntries(key -> true).stream()
|
||||
.anyMatch(entry -> secretArn.equals(entry.value().getMasterPasswordSecretArn()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rotate(String secretArn, String region, ManagedSecretRotator.Rotation rotation) {
|
||||
AccountAwareStorageBackend.AccountEntry<Cluster> entry = clusters.scanAllAccountEntries(key -> true).stream()
|
||||
.filter(candidate -> secretArn.equals(candidate.value().getMasterPasswordSecretArn()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The Redshift cluster for this managed secret no longer exists.", 400));
|
||||
withResourceLock(entry.accountId(), "cluster", entry.key(), () -> mutate(() -> {
|
||||
Cluster cluster = clusters.getForAccount(entry.accountId(), entry.key())
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The Redshift cluster for this managed secret no longer exists.", 400));
|
||||
if (!secretArn.equals(cluster.getMasterPasswordSecretArn())) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The Redshift cluster for this managed secret no longer exists.", 400);
|
||||
}
|
||||
if (!"available".equals(cluster.getClusterStatus())) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"The Redshift cluster must be available to rotate its master password.", 400);
|
||||
}
|
||||
String oldPassword = cluster.getMasterPassword();
|
||||
String newPassword = RandomPasswordGenerator.generate(objectMapper.createObjectNode()
|
||||
.put("ExcludeCharacters", "'\"/@\\"));
|
||||
rotation.commit(() -> {
|
||||
containerManager.alterUserPassword(entry.accountId(), cluster.getClusterIdentifier(),
|
||||
cluster.getMasterUsername(), newPassword);
|
||||
proxyManager.updateMasterPassword(
|
||||
relayKey(entry.accountId(), cluster.getClusterIdentifier()), newPassword);
|
||||
cluster.setMasterPassword(newPassword);
|
||||
clusters.putForAccount(entry.accountId(), cluster.getClusterIdentifier(), cluster);
|
||||
clusters.flush();
|
||||
return managedMasterSecret(cluster, newPassword);
|
||||
}, () -> {
|
||||
containerManager.alterUserPassword(entry.accountId(), cluster.getClusterIdentifier(),
|
||||
cluster.getMasterUsername(), oldPassword);
|
||||
proxyManager.updateMasterPassword(
|
||||
relayKey(entry.accountId(), cluster.getClusterIdentifier()), oldPassword);
|
||||
cluster.setMasterPassword(oldPassword);
|
||||
clusters.putForAccount(entry.accountId(), cluster.getClusterIdentifier(), cluster);
|
||||
clusters.flush();
|
||||
});
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reserve(String secretArn, String region) {
|
||||
AccountAwareStorageBackend.AccountEntry<Cluster> entry = clusters.scanAllAccountEntries(key -> true).stream()
|
||||
.filter(candidate -> secretArn.equals(candidate.value().getMasterPasswordSecretArn()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The Redshift cluster for this managed secret no longer exists.", 400));
|
||||
ResourceKey key = new ResourceKey(entry.accountId(), "cluster", entry.key());
|
||||
withResourceLock(entry.accountId(), "cluster", entry.key(), () -> {
|
||||
Cluster cluster = clusters.getForAccount(entry.accountId(), entry.key())
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The Redshift cluster for this managed secret no longer exists.", 400));
|
||||
if (!secretArn.equals(cluster.getMasterPasswordSecretArn())) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The Redshift cluster for this managed secret no longer exists.", 400);
|
||||
}
|
||||
if (!"available".equals(cluster.getClusterStatus())) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"The Redshift cluster must be available to rotate its master password.", 400);
|
||||
}
|
||||
if (managedRotationReservations.putIfAbsent(secretArn, key) != null) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"The cluster's managed master password is already being rotated.", 400);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(String secretArn, String region) {
|
||||
ResourceKey key = managedRotationReservations.get(secretArn);
|
||||
if (key != null) {
|
||||
withResourceLock(key.accountId(), key.kind(), key.identifier(), () -> {
|
||||
managedRotationReservations.remove(secretArn, key);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public Cluster describeLoggingStatus(String clusterIdentifier) {
|
||||
return clusters.get(clusterIdentifier)
|
||||
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
|
||||
@@ -1236,8 +1346,11 @@ public class RedshiftService {
|
||||
}
|
||||
|
||||
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier, String nodeType) {
|
||||
return withResourceLock("cluster", clusterIdentifier, () -> withResourceLock("snapshot", snapshotIdentifier,
|
||||
() -> mutate(() -> restoreSnapshot(clusterIdentifier, snapshotIdentifier, nodeType))));
|
||||
return withResourceLock("cluster", clusterIdentifier, () -> {
|
||||
ensureNoManagedRotation(clusters.accountId(), clusterIdentifier);
|
||||
return withResourceLock("snapshot", snapshotIdentifier,
|
||||
() -> mutate(() -> restoreSnapshot(clusterIdentifier, snapshotIdentifier, nodeType)));
|
||||
});
|
||||
}
|
||||
|
||||
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier, String nodeType,
|
||||
@@ -1248,6 +1361,7 @@ public class RedshiftService {
|
||||
}
|
||||
return withResourceLock("cluster", clusterIdentifier, () -> withResourceLock("snapshot", snapshotIdentifier,
|
||||
() -> {
|
||||
ensureNoManagedRotation(clusters.accountId(), clusterIdentifier);
|
||||
Cluster cluster = restoreSnapshot(clusterIdentifier, snapshotIdentifier, nodeType);
|
||||
try {
|
||||
cluster.setClusterSubnetGroupName(clusterSubnetGroupName);
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package io.github.hectorvent.floci.services.secretsmanager;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Supplies the backend credential change for a service-owned secret rotation. */
|
||||
public interface ManagedSecretRotator {
|
||||
|
||||
boolean supports(String secretArn, String region);
|
||||
|
||||
default void reserve(String secretArn, String region) { }
|
||||
|
||||
default void release(String secretArn, String region) { }
|
||||
|
||||
void rotate(String secretArn, String region, Rotation rotation);
|
||||
|
||||
/** Commits a backend password change and its corresponding secret value as one rotation. */
|
||||
interface Rotation {
|
||||
void commit(Supplier<String> changeBackend, Runnable rollbackBackend);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -84,7 +84,9 @@ public class SecretRotationScheduler {
|
||||
|
||||
void tick(Instant now) {
|
||||
for (SecretsManagerService.RegionalSecret entry : service.listAllSecrets()) {
|
||||
if (!isDue(entry.secret(), now)) {
|
||||
if (!isDue(entry.secret(), now)
|
||||
|| (entry.secret().getOwningService() != null
|
||||
&& !service.supportsManagedRotation(entry.secret().getArn(), entry.region()))) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
@@ -109,7 +111,7 @@ public class SecretRotationScheduler {
|
||||
}
|
||||
// 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) {
|
||||
if (secret.isReplica() || secret.getDeletedDate() != null) {
|
||||
return false;
|
||||
}
|
||||
return !secret.getNextRotationDate().isAfter(now);
|
||||
|
||||
+205
-24
@@ -25,6 +25,7 @@ import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -48,6 +49,7 @@ import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -71,6 +73,7 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
private final LambdaService lambdaService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final KmsService kmsService;
|
||||
private final List<ManagedSecretRotator> managedSecretRotators;
|
||||
|
||||
// Fixed threads with an unbounded queue: a burst of rotations is queued, not rejected,
|
||||
// because RotateSecret documents no overload error.
|
||||
@@ -87,6 +90,7 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
private final Object[] nameLockStripes = newLockStripes(NAME_LOCK_STRIPE_COUNT);
|
||||
// Entries exist only while a service owner changes backend credentials outside the stripe.
|
||||
private final Set<String> managedReleases = ConcurrentHashMap.newKeySet();
|
||||
private final Map<String, String> managedRotationTokens = new ConcurrentHashMap<>();
|
||||
|
||||
private static Object[] newLockStripes(int count) {
|
||||
Object[] stripes = new Object[count];
|
||||
@@ -124,11 +128,26 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
@Inject
|
||||
public SecretsManagerService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
LambdaService lambdaService, ObjectMapper objectMapper,
|
||||
KmsService kmsService) {
|
||||
KmsService kmsService, Instance<ManagedSecretRotator> managedSecretRotators) {
|
||||
this(factory.create("secretsmanager", "secretsmanager-secrets.json",
|
||||
new TypeReference<Map<String, Secret>>() {}),
|
||||
config.services().secretsmanager().defaultRecoveryWindowDays(),
|
||||
regionResolver, lambdaService, objectMapper, kmsService);
|
||||
regionResolver, lambdaService, objectMapper, kmsService, managedSecretRotators.stream().toList());
|
||||
}
|
||||
|
||||
public SecretsManagerService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
LambdaService lambdaService, ObjectMapper objectMapper,
|
||||
KmsService kmsService) {
|
||||
this(factory, config, regionResolver, lambdaService, objectMapper, kmsService, List.of());
|
||||
}
|
||||
|
||||
private SecretsManagerService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
LambdaService lambdaService, ObjectMapper objectMapper,
|
||||
KmsService kmsService, List<ManagedSecretRotator> managedSecretRotators) {
|
||||
this(factory.create("secretsmanager", "secretsmanager-secrets.json",
|
||||
new TypeReference<Map<String, Secret>>() {}),
|
||||
config.services().secretsmanager().defaultRecoveryWindowDays(),
|
||||
regionResolver, lambdaService, objectMapper, kmsService, managedSecretRotators);
|
||||
}
|
||||
|
||||
SecretsManagerService(StorageBackend<String, Secret> store, int defaultRecoveryWindowDays) {
|
||||
@@ -144,12 +163,20 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
SecretsManagerService(StorageBackend<String, Secret> store, int defaultRecoveryWindowDays,
|
||||
RegionResolver regionResolver, LambdaService lambdaService,
|
||||
ObjectMapper objectMapper, KmsService kmsService) {
|
||||
this(store, defaultRecoveryWindowDays, regionResolver, lambdaService, objectMapper, kmsService, List.of());
|
||||
}
|
||||
|
||||
SecretsManagerService(StorageBackend<String, Secret> store, int defaultRecoveryWindowDays,
|
||||
RegionResolver regionResolver, LambdaService lambdaService,
|
||||
ObjectMapper objectMapper, KmsService kmsService,
|
||||
List<ManagedSecretRotator> managedSecretRotators) {
|
||||
this.store = store;
|
||||
this.defaultRecoveryWindowDays = defaultRecoveryWindowDays;
|
||||
this.regionResolver = regionResolver;
|
||||
this.lambdaService = lambdaService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.kmsService = kmsService;
|
||||
this.managedSecretRotators = List.copyOf(managedSecretRotators);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@@ -311,6 +338,7 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
}
|
||||
|
||||
synchronized (lockFor(secret.getArn())) {
|
||||
throwIfManagedRelease(secret.getArn());
|
||||
if (clientRequestToken != null && secret.getVersions() != null && secret.getVersions().containsKey(clientRequestToken)) {
|
||||
SecretVersion existingVersion = secret.getVersions().get(clientRequestToken);
|
||||
boolean isPendingPlaceholder = existingVersion.getSecretString() == null
|
||||
@@ -418,6 +446,7 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
validateKmsKey(kmsKeyId, region);
|
||||
|
||||
synchronized (lockFor(secret.getArn())) {
|
||||
throwIfManagedRelease(secret.getArn());
|
||||
if (description != null) {
|
||||
secret.setDescription(description);
|
||||
}
|
||||
@@ -963,6 +992,10 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
return all;
|
||||
}
|
||||
|
||||
public boolean supportsManagedRotation(String secretArn, String region) {
|
||||
return managedSecretRotators.stream().anyMatch(rotator -> rotator.supports(secretArn, region));
|
||||
}
|
||||
|
||||
/** A replication target: the region to copy into, and optionally the KMS key to record. */
|
||||
public record ReplicaRegion(String region, String kmsKeyId) {
|
||||
}
|
||||
@@ -1275,7 +1308,12 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
|
||||
// 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.
|
||||
String secretArn = secret.getArn();
|
||||
boolean serviceManaged = secret.getOwningService() != null;
|
||||
ManagedSecretRotator managedRotator = serviceManaged ? managedSecretRotators.stream()
|
||||
.filter(candidate -> candidate.supports(secretArn, region))
|
||||
.findFirst()
|
||||
.orElse(null) : null;
|
||||
if (serviceManaged && rotationLambdaArn != null) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"Rotation Lambda ARN is not supported for a service-managed secret.", 400);
|
||||
@@ -1316,38 +1354,97 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
synchronized (lockFor(secret.getArn())) {
|
||||
SecretVersion pendingVersion = findVersionByStage(secret, "AWSPENDING");
|
||||
if (pendingVersion != null) {
|
||||
SecretVersion currentVersion = findVersionByStage(secret, "AWSCURRENT");
|
||||
if (currentVersion == null || !pendingVersion.getVersionId().equals(currentVersion.getVersionId())) {
|
||||
String managedToken = serviceManaged && rotateImmediately
|
||||
? clientRequestToken != null && !clientRequestToken.isEmpty()
|
||||
? clientRequestToken : UUID.randomUUID().toString() : null;
|
||||
|
||||
if (managedToken != null && managedRotator != null) {
|
||||
synchronized (lockFor(secret.getArn())) {
|
||||
Secret latest = resolveSecret(secret.getArn(), region);
|
||||
SecretVersion existing = latest.getVersions() == null ? null : latest.getVersions().get(managedToken);
|
||||
if (existing != null) {
|
||||
return latest;
|
||||
}
|
||||
String activeToken = managedRotationTokens.get(secret.getArn());
|
||||
if (activeToken != null) {
|
||||
if (activeToken.equals(managedToken)) {
|
||||
return latest;
|
||||
}
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"A previous rotation isn't complete. That rotation will be reattempted.", 400);
|
||||
}
|
||||
throwIfManagedRelease(secret.getArn());
|
||||
managedRotationTokens.put(secret.getArn(), managedToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (rotationLambdaArn != null) {
|
||||
secret.setRotationLambdaArn(rotationLambdaArn);
|
||||
boolean managedReservationAcquired = false;
|
||||
boolean rotationPrepared = false;
|
||||
try {
|
||||
if (managedToken != null && managedRotator != null) {
|
||||
managedRotator.reserve(secret.getArn(), region);
|
||||
managedReservationAcquired = true;
|
||||
}
|
||||
if (rotationRules != null) {
|
||||
secret.setRotationRules(rotationRules);
|
||||
}
|
||||
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.
|
||||
synchronized (lockFor(secret.getArn())) {
|
||||
if (managedToken != null && managedRotator != null) {
|
||||
secret = resolveSecret(secret.getArn(), region);
|
||||
if (secret.getVersions() != null && secret.getVersions().containsKey(managedToken)) {
|
||||
return secret;
|
||||
}
|
||||
managedReleases.add(secret.getArn());
|
||||
}
|
||||
SecretVersion pendingVersion = findVersionByStage(secret, "AWSPENDING");
|
||||
if (pendingVersion != null) {
|
||||
SecretVersion currentVersion = findVersionByStage(secret, "AWSCURRENT");
|
||||
if (currentVersion == null || !pendingVersion.getVersionId().equals(currentVersion.getVersionId())) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"A previous rotation isn't complete. That rotation will be reattempted.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
persist(secret, region);
|
||||
if (rotationLambdaArn != null) {
|
||||
secret.setRotationLambdaArn(rotationLambdaArn);
|
||||
}
|
||||
if (rotationRules != null) {
|
||||
secret.setRotationRules(rotationRules);
|
||||
}
|
||||
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()));
|
||||
persist(secret, region);
|
||||
rotationPrepared = true;
|
||||
}
|
||||
} finally {
|
||||
if (!rotationPrepared) {
|
||||
if (managedToken != null && managedRotator != null) {
|
||||
clearManagedRotation(secret.getArn(), managedToken);
|
||||
}
|
||||
if (managedReservationAcquired) {
|
||||
managedRotator.release(secret.getArn(), region);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (serviceManaged) {
|
||||
LOG.infov("Enabled service-managed rotation for secret: {0}", secret.getName());
|
||||
if (managedRotator == null) {
|
||||
return secret;
|
||||
}
|
||||
if (!rotateImmediately) {
|
||||
LOG.infov("Enabled service-managed rotation for secret: {0}", secret.getName());
|
||||
return secret;
|
||||
}
|
||||
String arn = secret.getArn();
|
||||
try {
|
||||
rotationExecutor.submit(() -> executeManagedRotation(arn, managedToken, region, managedRotator));
|
||||
} catch (RuntimeException e) {
|
||||
clearManagedRotation(arn, managedToken);
|
||||
managedRotator.release(arn, region);
|
||||
throw e;
|
||||
}
|
||||
LOG.infov("Started service-managed rotation for secret: {0}", secret.getName());
|
||||
return secret;
|
||||
}
|
||||
|
||||
@@ -1367,6 +1464,90 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
return secret;
|
||||
}
|
||||
|
||||
private void executeManagedRotation(String secretArn, String token, String region,
|
||||
ManagedSecretRotator rotator) {
|
||||
try {
|
||||
AtomicInteger committed = new AtomicInteger();
|
||||
rotator.rotate(secretArn, region, new ManagedSecretRotator.Rotation() {
|
||||
@Override
|
||||
public void commit(Supplier<String> changeBackend, Runnable rollbackBackend) {
|
||||
try {
|
||||
String newValue = changeBackend.get();
|
||||
synchronized (lockFor(secretArn)) {
|
||||
Secret current = resolveSecret(secretArn, region);
|
||||
putManagedRotationVersion(current, token, current.getCurrentVersionId(), newValue);
|
||||
current.setLastRotatedDate(Instant.now());
|
||||
current.setLastChangedDate(Instant.now());
|
||||
persist(current, region);
|
||||
}
|
||||
committed.set(1);
|
||||
} catch (RuntimeException e) {
|
||||
rollbackBackend.run();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
});
|
||||
if (committed.get() == 0) {
|
||||
throw new IllegalStateException("The managed secret rotator did not commit a new value");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.errorv(e, "Managed rotation failed for secret {0}", secretArn);
|
||||
synchronized (lockFor(secretArn)) {
|
||||
Secret current = resolveSecret(secretArn, region);
|
||||
if (current.getVersions() != null) {
|
||||
SecretVersion pending = current.getVersions().remove(token);
|
||||
if (pending != null) {
|
||||
persist(current, region);
|
||||
}
|
||||
}
|
||||
persist(current, region);
|
||||
}
|
||||
} finally {
|
||||
clearManagedRotation(secretArn, token);
|
||||
rotator.release(secretArn, region);
|
||||
}
|
||||
}
|
||||
|
||||
private void clearManagedRotation(String secretArn, String token) {
|
||||
synchronized (lockFor(secretArn)) {
|
||||
if (managedRotationTokens.remove(secretArn, token)) {
|
||||
managedReleases.remove(secretArn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void putManagedRotationVersion(Secret secret, String token, String previousVersionId,
|
||||
String secretString) {
|
||||
if (secret.getVersions() == null) {
|
||||
secret.setVersions(new HashMap<>());
|
||||
}
|
||||
for (SecretVersion version : secret.getVersions().values()) {
|
||||
if (version.getVersionStages().contains(AWSPREVIOUS)) {
|
||||
List<String> stages = new ArrayList<>(version.getVersionStages());
|
||||
stages.remove(AWSPREVIOUS);
|
||||
version.setVersionStages(stages);
|
||||
}
|
||||
}
|
||||
if (previousVersionId != null) {
|
||||
SecretVersion previous = secret.getVersions().get(previousVersionId);
|
||||
if (previous != null) {
|
||||
List<String> stages = new ArrayList<>(previous.getVersionStages());
|
||||
stages.remove(AWSCURRENT);
|
||||
if (!stages.contains(AWSPREVIOUS)) {
|
||||
stages.add(AWSPREVIOUS);
|
||||
}
|
||||
previous.setVersionStages(stages);
|
||||
}
|
||||
}
|
||||
SecretVersion rotated = new SecretVersion();
|
||||
rotated.setVersionId(token);
|
||||
rotated.setSecretString(secretString);
|
||||
rotated.setVersionStages(List.of(AWSCURRENT));
|
||||
rotated.setCreatedDate(Instant.now());
|
||||
secret.getVersions().put(token, rotated);
|
||||
secret.setCurrentVersionId(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* The full ARN of the rotation function {@code reference} names, in the secret's partition and
|
||||
* account unless the reference names its own. A reference Lambda cannot read is refused with
|
||||
|
||||
Reference in new issue
Block a user