feat(msk): scheduled reconcile for SCRAM secret changes (#6384)

* feat(msk): scheduled reconcile for SCRAM secret changes

* fix(msk): match AWS error for SCRAM secrets scheduled for deletion

* fix(msk): suppress repeated SCRAM reconciliation warnings

* feat(msk): make SCRAM reconciliation interval configurable

* docs(msk): clarify SCRAM user revocation and restoration

* fix(msk): reconcile clusters independently with threaded workers

* docs(msk): correct the docs after reconcile multi-threading changes

* fix(msk): reuse Secrets Manager scheduled deletion error message

* fix(msk): start SCRAM reconciliation at application startup
This commit is contained in:
Isak Lindbeck authored and GitHub committed 2026-10-24 19:49:40 -04:00
1 parent 381ad1f00b
commit bc18cbbdaa
8 files changed
+1107 -96

No files matched your search

+14
View File
@@ -40,6 +40,7 @@ Floci emulates Amazon MSK by orchestrating **Redpanda** containers. This provide
| `FLOCI_SERVICES_MSK_DEFAULT_IMAGE` | `redpandadata/redpanda:latest` | Docker image for Redpanda (Kafka) containers |
| `FLOCI_SERVICES_MSK_KAFKA_HOST_PORT_BASE` | `9300` | First host port a broker's Kafka listener can be published on |
| `FLOCI_SERVICES_MSK_KAFKA_HOST_PORT_MAX` | `9399` | Last host port a broker's Kafka listener can be published on |
| `FLOCI_SERVICES_MSK_SCRAM_RECONCILIATION_INTERVAL_MS` | `5000` | SCRAM secret reconciliation interval (ms) |
| `FLOCI_SERVICES_MSK_BOOTSTRAP_HOSTNAME` | _(unset)_ | Floci in a container only: hostname the host listener advertises, and when set, `GetBootstrapBrokers` returns `<container-name>:9092,<hostname>:<host port>` instead of the Docker-network address |
## How it works
@@ -132,6 +133,19 @@ The secrets must contain JSON such as `{"username":"alice","password":"pw"}`.
`unprocessedScramSecrets`; reassociation and removal of an unassociated ARN return
`InvalidSecretArn`.
Floci schedules SCRAM reconciliation jobs every five seconds by default, measured as
a delay after each scheduling sweep. Sweeps do not wait for broker operations to finish,
and clusters with queued or running jobs are skipped. Set
`FLOCI_SERVICES_MSK_SCRAM_RECONCILIATION_INTERVAL_MS` to change this delay in milliseconds.
This is Floci's timing, not an AWS synchronization guarantee.
When an associated secret is scheduled for deletion or permanently deleted, reconciliation
revokes its broker user but retains the association in `ListScramSecrets`. Restoring a secret
whose deletion was scheduled causes reconciliation to recreate its broker user using the
current credentials, without requiring reassociation. Permanently deleted secrets cannot
be restored; creating a secret with the same name produces a different ARN and requires
a new association.
## Examples
```bash
@@ -1575,6 +1575,9 @@ public interface EmulatorConfig {
@WithDefault("9399")
int kafkaHostPortMax();
@WithDefault("5000")
long scramReconciliationIntervalMs();
/**
* Only applies when Floci runs in a container. Each broker then has a second Kafka
* listener, published to a host port from the kafka-host-port range so clients on the
@@ -15,17 +15,17 @@ import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import io.github.hectorvent.floci.services.kms.model.KmsKeySpec;
import io.github.hectorvent.floci.services.kms.model.KmsKeyUsage;
import io.github.hectorvent.floci.services.msk.model.ClusterState;
import io.github.hectorvent.floci.services.msk.model.MskCluster;
import io.github.hectorvent.floci.services.msk.model.MskScramAssociations;
import io.github.hectorvent.floci.services.msk.model.ScramSecretAssociation;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService.BatchGetSecretValueError;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService.BatchGetSecretValueResult;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService.BatchSecretValue;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import jakarta.annotation.PostConstruct;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import io.quarkus.runtime.StartupEvent;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -33,9 +33,15 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
@@ -51,9 +57,19 @@ public class MskScramSecretsService {
private final SecretsManagerService secretsManagerService;
private final KmsService kmsService;
private final ObjectMapper objectMapper;
private final ScheduledExecutorService reconciler = Executors.newSingleThreadScheduledExecutor();
private final ThreadPoolExecutor reconciliationWorkers = new ThreadPoolExecutor(
4, 4, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(128));
private final Set<String> pendingReconciliations = ConcurrentHashMap.newKeySet();
private final Map<String, Object> clusterLocks = new ConcurrentHashMap<>();
private final Map<String, ClusterReconciliationFailure> clusterReconciliationFailures = new ConcurrentHashMap<>();
private record ClusterReconciliationFailure(Class<?> type, String message) {}
private final Map<ReconciliationKey, ReconciliationFailure> secretReconciliationFailures = new ConcurrentHashMap<>();
private record ReconciliationKey(String clusterArn, String secretArn) {}
private record ReconciliationFailure(String errorCode, String message) {}
@Inject
public MskScramSecretsService(StorageFactory storageFactory, EmulatorConfig config, MskService mskService,
RedpandaManager redpandaManager, SecretsManagerService secretsManagerService,
@@ -68,37 +84,147 @@ public class MskScramSecretsService {
this.objectMapper = objectMapper;
}
@PostConstruct
public void init() {
void onStart(@Observes StartupEvent ignored) {
if (!config.services().msk().enabled()) {
return;
}
long intervalMs = config.services().msk().scramReconciliationIntervalMs();
if (intervalMs <= 0) {
throw new IllegalArgumentException("floci.services.msk.scram-reconciliation-interval-ms must be greater than zero.");
}
reconciler.scheduleWithFixedDelay(() -> {
try {
reconcileScramSecrets();
scheduleScramReconciliation();
} catch (RuntimeException e) {
LOG.error("MSK SCRAM reconciliation failed; retrying on the next scheduled run", e);
}
}, 5, 5, TimeUnit.SECONDS);
}, intervalMs, intervalMs, TimeUnit.MILLISECONDS);
}
@PreDestroy
public void shutdown() {
reconciler.shutdown();
reconciliationWorkers.shutdownNow();
}
private Object clusterLock(String clusterArn) {
return clusterLocks.computeIfAbsent(String.valueOf(clusterArn), ignored -> new Object());
}
void reconcileScramSecrets() {
for (AccountAwareStorageBackend.AccountEntry<MskScramAssociations> entry
: storage.scanAllAccountEntries(key -> true)) {
synchronized (clusterLock(entry.key())) {
if (mskService.getClusterForAccount(entry.accountId(), entry.key()).isEmpty()) {
storage.deleteForAccount(entry.accountId(), entry.key());
private void scheduleScramReconciliation() {
int deferredClusters = 0;
for (AccountAwareStorageBackend.AccountEntry<MskScramAssociations> entry : storage.scanAllAccountEntries(key -> true)) {
String clusterArn = entry.key();
if (!pendingReconciliations.add(clusterArn)) {
continue;
}
try {
reconciliationWorkers.execute(() -> runClusterReconciliation(entry));
} catch (RejectedExecutionException e) {
pendingReconciliations.remove(clusterArn);
if (!reconciliationWorkers.isShutdown()) {
deferredClusters++;
}
}
}
if (deferredClusters > 0) {
LOG.warnv("MSK SCRAM reconciliation workers are full; retrying {0} clusters on the next scheduled run",
deferredClusters);
}
}
private void runClusterReconciliation(AccountAwareStorageBackend.AccountEntry<MskScramAssociations> entry) {
String clusterArn = entry.key();
try {
reconcileCluster(clusterArn, entry.accountId());
clusterReconciliationFailures.remove(clusterArn);
} catch (RuntimeException e) {
ClusterReconciliationFailure failure = new ClusterReconciliationFailure(e.getClass(), e.getMessage());
if (!failure.equals(clusterReconciliationFailures.put(clusterArn, failure))) {
LOG.errorv(e, "MSK SCRAM reconciliation failed for cluster {0}; retrying on the next scheduled run",
clusterArn);
} else {
LOG.debugv(e, "MSK SCRAM reconciliation failed for cluster {0}; retrying on the next scheduled run",
clusterArn);
}
} finally {
pendingReconciliations.remove(clusterArn);
}
}
void reconcileCluster(String clusterArn, String accountId) {
synchronized (clusterLock(clusterArn)) {
Optional<MskCluster> clusterGet = mskService.getClusterForAccount(accountId, clusterArn);
if (clusterGet.isEmpty()) {
storage.deleteForAccount(accountId, clusterArn);
secretReconciliationFailures.keySet().removeIf(key -> key.clusterArn().equals(clusterArn));
} else {
reconcileScramSecretsForCluster(clusterGet.get(), clusterArn);
}
}
}
private void reconcileScramSecretsForCluster(MskCluster cluster, String clusterArn) {
if (mskService.isServerless(cluster) || cluster.getState() != ClusterState.ACTIVE) {
return;
}
MskScramAssociations clusterAssociations = associationsFor(clusterArn);
for (String secretArn : new ArrayList<>(clusterAssociations.getAssociations().keySet())) {
ReconciliationKey reconciliationKey = new ReconciliationKey(clusterArn, secretArn);
try {
reconcileScramSecret(secretArn, clusterAssociations, cluster);
secretReconciliationFailures.remove(reconciliationKey);
} catch (AwsException e) {
ReconciliationFailure failure = new ReconciliationFailure(e.getErrorCode(), e.getMessage());
if (!failure.equals(secretReconciliationFailures.put(reconciliationKey, failure))) {
LOG.warnv("Could not reconcile MSK SCRAM secret {0} for cluster {1}: {2}",
secretArn, clusterArn, e.getErrorCode());
} else {
LOG.debugv("Could not reconcile MSK SCRAM secret {0} for cluster {1}: {2}",
secretArn, clusterArn, e.getErrorCode());
}
}
}
}
private void reconcileScramSecret(String secretArn, MskScramAssociations clusterAssociations, MskCluster cluster) {
ScramSecretAssociation association = clusterAssociations.getAssociations().get(secretArn);
if (association == null) {
// Should never happen
throw new AwsException("InternalServerErrorException", "SCRAM association is missing during reconciliation.", 500);
}
if (association.isDisassociating()) {
// Recover if disassociation was interrupted
removeScramAssociation(cluster, clusterAssociations, secretArn);
return;
}
Optional<Secret> secret = describeSecret(secretArn);
if (secret.isEmpty() || secret.get().getDeletedDate() != null) {
// Revoke credentials for secret that are deleted or scheduled for deletion, but keep the association
revokeScramCredentials(cluster, clusterAssociations, association);
return;
}
SecretVersion secretVersion = getCurrentSecretVersion(secret.get());
boolean versionIdChanged = !Objects.equals(secretVersion.getVersionId(), association.getAppliedVersionId());
boolean containerIdChanged = !Objects.equals(cluster.getContainerId(), association.getAppliedContainerId());
// Reapply if the secret or cluster container has changed
// Reapply if credentials where revoked, which can happen if the secret was deleted and then restored
if (association.isCredentialsRevoked() || versionIdChanged || containerIdChanged) {
applyScramCredentials(cluster, clusterAssociations, association, secretVersion);
}
}
private void revokeScramCredentials(MskCluster cluster, MskScramAssociations state, ScramSecretAssociation association) {
if (association.isCredentialsRevoked()) {
// Skip repeated delete calls to the cluster
return;
}
deleteScramUser(cluster, state, association);
association.setCredentialsRevoked(true);
putAssociations(cluster.getClusterArn(), state);
}
public List<Map<String, String>> batchAssociateScramSecret(String clusterArn, List<String> secretArns) {
synchronized (clusterLock(clusterArn)) {
MskCluster cluster = scramCluster(clusterArn);
@@ -118,8 +244,10 @@ public class MskScramSecretsService {
}
validateSecretEncryption(secret);
// Amazon MSK reads only the AWSCURRENT version of an associated secret
BatchSecretValue secretValue = readSecret(secretArn);
applyScramCredentials(cluster, state, secretArn, secretValue);
SecretVersion secretVersion = getCurrentSecretVersion(secret);
ScramSecretAssociation association = state.getAssociations()
.computeIfAbsent(secretArn, ignored -> new ScramSecretAssociation());
applyScramCredentials(cluster, state, association, secretVersion);
} catch (AwsException e) {
if (newAssociation && state.getAssociations().remove(secretArn) != null) {
putAssociations(clusterArn, state);
@@ -248,14 +376,21 @@ public class MskScramSecretsService {
}
private void applyScramCredentials(MskCluster cluster, MskScramAssociations state,
String secretArn, BatchSecretValue secretValue) {
ScramCredentials credentials = readScramCredentials(secretValue.secretString());
ScramSecretAssociation association, SecretVersion secretValue) {
ScramCredentials credentials = readScramCredentials(secretValue.getSecretString());
boolean ownershipChanged = !Objects.equals(association.getUsername(), credentials.username());
if (ownershipChanged) {
deleteScramUser(cluster, state, association);
association.setUsername(credentials.username());
// Persist ownership changes before updating the broker; mark the version as applied only after success.
putAssociations(cluster.getClusterArn(), state);
}
if (!config.services().msk().mock()) {
redpandaManager.createUser(cluster, credentials.username(), credentials.password());
}
ScramSecretAssociation association = new ScramSecretAssociation();
association.setUsername(credentials.username());
state.getAssociations().put(secretArn, association);
association.setAppliedVersionId(secretValue.getVersionId());
association.setAppliedContainerId(cluster.getContainerId());
association.setCredentialsRevoked(false);
putAssociations(cluster.getClusterArn(), state);
}
@@ -264,33 +399,64 @@ public class MskScramSecretsService {
if (association == null) {
return;
}
if (association.getUsername() != null && !config.services().msk().mock()) {
redpandaManager.deleteUser(cluster, association.getUsername());
if (!association.isDisassociating()) {
association.setDisassociating(true);
// Persist the removal intent before deleting broker credentials so a failure does not lose it.
putAssociations(cluster.getClusterArn(), state);
}
deleteScramUser(cluster, state, association);
state.getAssociations().remove(secretArn);
putAssociations(cluster.getClusterArn(), state);
secretReconciliationFailures.remove(new ReconciliationKey(cluster.getClusterArn(), secretArn));
}
private BatchSecretValue readSecret(String secretArn) {
// Exact-ARN batch reads select AWSCURRENT without updating access timestamps.
BatchGetSecretValueResult result = secretsManagerService.batchGetSecretValue(
List.of(secretArn), AwsArnUtils.parse(secretArn).region());
if (result != null && result.values() != null && result.errors() != null) {
if (result.values().isEmpty() && result.errors().size() == 1) {
BatchGetSecretValueError error = result.errors().getFirst();
if (error != null && secretArn.equals(error.secretId())
&& error.errorCode() != null && error.message() != null) {
int status = "AccessDeniedException".equals(error.errorCode()) ? 403 : 400;
throw new AwsException(error.errorCode(), error.message(), status);
}
} else if (result.values().size() == 1 && result.errors().isEmpty()) {
BatchSecretValue value = result.values().getFirst();
if (value != null && secretArn.equals(value.arn()) && value.versionId() != null) {
return value;
private void deleteScramUser(MskCluster cluster, MskScramAssociations state, ScramSecretAssociation association) {
String username = association.getUsername();
// Revoked credentials have already been deleted
if (username != null && !association.isCredentialsRevoked()) {
if (!config.services().msk().mock()) {
redpandaManager.deleteUser(cluster, username);
}
// Allow a user existing in multiple secrets to be reconciled again
invalidateUserAssociations(state, username);
}
}
private void invalidateUserAssociations(MskScramAssociations state, String username) {
for (ScramSecretAssociation association : state.getAssociations().values()) {
if (username.equals(association.getUsername())) {
association.setAppliedVersionId(null);
association.setAppliedContainerId(null);
}
}
}
private Optional<Secret> describeSecret(String secretArn) {
try {
Secret secret = secretsManagerService.describeSecret(secretArn, AwsArnUtils.parse(secretArn).region());
return Optional.of(secret);
} catch (AwsException e) {
if ("ResourceNotFoundException".equals(e.getErrorCode())) {
return Optional.empty();
}
throw e;
}
}
private SecretVersion getCurrentSecretVersion(Secret secret) {
if (secret.getDeletedDate() != null) {
throw new AwsException("InternalServerError",
SecretsManagerService.SCHEDULED_DELETION_ERROR_MESSAGE, 500);
}
if (secret.getVersions() != null) {
for (SecretVersion version : secret.getVersions().values()) {
if (version.getVersionStages() != null && version.getVersionStages().contains("AWSCURRENT")) {
return version;
}
}
}
throw new AwsException("InternalServerError", "Unexpected Secrets Manager batch response.", 500);
throw new AwsException("ResourceNotFoundException",
"Secrets Manager can't find the specified secret value for staging label: AWSCURRENT", 400);
}
record ScramCredentials(String username, String password) {
@@ -6,6 +6,10 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
public class ScramSecretAssociation {
private String username;
private String appliedVersionId;
private String appliedContainerId;
private boolean credentialsRevoked;
private boolean disassociating;
public String getUsername() {
return username;
@@ -15,4 +19,35 @@ public class ScramSecretAssociation {
this.username = username;
}
public String getAppliedVersionId() {
return appliedVersionId;
}
public void setAppliedVersionId(String appliedVersionId) {
this.appliedVersionId = appliedVersionId;
}
public String getAppliedContainerId() {
return appliedContainerId;
}
public void setAppliedContainerId(String appliedContainerId) {
this.appliedContainerId = appliedContainerId;
}
public boolean isCredentialsRevoked() {
return credentialsRevoked;
}
public void setCredentialsRevoked(boolean credentialsRevoked) {
this.credentialsRevoked = credentialsRevoked;
}
public boolean isDisassociating() {
return disassociating;
}
public void setDisassociating(boolean disassociating) {
this.disassociating = disassociating;
}
}
@@ -62,6 +62,9 @@ public class SecretsManagerService implements ResourceProvider {
private static final String PENDING_DELETION_STATE = "PendingDeletion";
private static final Pattern SECRET_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9/_+=.@-]+");
public static final String SCHEDULED_DELETION_ERROR_MESSAGE =
"You can't perform this operation on the secret because it was marked for deletion.";
private final StorageBackend<String, Secret> store;
private final int defaultRecoveryWindowDays;
private final RegionResolver regionResolver;
@@ -1566,7 +1569,7 @@ public class SecretsManagerService implements ResourceProvider {
Secret secret = resolveSecret(secretId, region);
if (secret.getDeletedDate() != null) {
errors.add(new BatchGetSecretValueError(secretId, "InvalidRequestException",
"You can't perform this operation on the secret because it was marked for deletion."));
SCHEDULED_DELETION_ERROR_MESSAGE));
continue;
}
@@ -1792,7 +1795,7 @@ public class SecretsManagerService implements ResourceProvider {
private void throwIfPendingDeletion(Secret secret) {
if (secret.getDeletedDate() != null) {
throw new AwsException("InvalidRequestException",
"You can't perform this operation on the secret because it was marked for deletion.", 400);
SCHEDULED_DELETION_ERROR_MESSAGE, 400);
}
}
+1
View File
@@ -478,6 +478,7 @@ floci:
msk:
enabled: true
mock: false
scram-reconciliation-interval-ms: 5000
default-image: "redpandadata/redpanda:latest"
kafka-host-port-base: 9300
kafka-host-port-max: 9399
File diff suppressed because it is too large. Load diff
+1
View File
@@ -182,6 +182,7 @@ floci:
msk:
enabled: true
mock: true
scram-reconciliation-interval-ms: 5000
default-image: "redpandadata/redpanda:latest"
amazonmq:
enabled: true