Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(secretsmanager): bound rotation threads and lock storage (#4344)

Niels Kootstra3096a3cf7cc0
diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java
index eb5e719602..4b2a71101b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java
@@ -23,20 +23,20 @@ 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;
-
import java.time.Instant;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
@@ -63,11 +63,44 @@ public class SecretsManagerService implements ResourceProvider {
private final LambdaService lambdaService;
private final ObjectMapper objectMapper;
private final KmsService kmsService;
- private final ExecutorService rotationExecutor = Executors.newCachedThreadPool();
- private final ConcurrentHashMap<String, Object> rotationLocks = new ConcurrentHashMap<>();
+
+ // Fixed threads with an unbounded queue: a burst of rotations is queued, not rejected,
+ // because RotateSecret documents no overload error.
+ static final int ROTATION_EXECUTOR_POOL_SIZE = Math.max(4, Runtime.getRuntime().availableProcessors());
+ private final ExecutorService rotationExecutor =
+ Executors.newFixedThreadPool(ROTATION_EXECUTOR_POOL_SIZE, new RotationThreadFactory());
+
+ // Fixed stripes instead of one lock per ARN, which was never removed. Secrets that share a
+ // stripe only contend; no lock is held while a rotation Lambda runs.
+ private static final int ROTATION_LOCK_STRIPE_COUNT = 32;
+ private final Object[] rotationLockStripes = newLockStripes(ROTATION_LOCK_STRIPE_COUNT);
+
+ private static Object[] newLockStripes(int count) {
+ Object[] stripes = new Object[count];
+ for (int i = 0; i < count; i++) {
+ stripes[i] = new Object();
+ }
+ return stripes;
+ }
private Object lockFor(String secretArn) {
- return rotationLocks.computeIfAbsent(secretArn, k -> new Object());
+ int index = Math.floorMod(secretArn.hashCode(), rotationLockStripes.length);
+ return rotationLockStripes[index];
+ }
+
+ /** Names rotation threads for diagnostics. */
+ private static final class RotationThreadFactory implements ThreadFactory {
+ private final AtomicInteger nextId = new AtomicInteger(1);
+
+ @Override
+ public Thread newThread(Runnable runnable) {
+ // Set explicitly: a new thread otherwise inherits these from whichever thread grows the
+ // pool, and a daemon rotation thread could be cut off mid-rotation at JVM exit.
+ Thread thread = new Thread(runnable, "secretsmanager-rotation-" + nextId.getAndIncrement());
+ thread.setDaemon(false);
+ thread.setPriority(Thread.NORM_PRIORITY);
+ return thread;
+ }
}
@Inject
diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationBoundsTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationBoundsTest.java
new file mode 100644
index 0000000000..fbda6a3ea2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerRotationBoundsTest.java
@@ -0,0 +1,85 @@
+package io.github.hectorvent.floci.services.secretsmanager;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Rotations used to run on an unbounded thread pool, one thread per rotation that could not
+ * reuse an idle one. They now share a fixed pool.
+ */
+class SecretsManagerRotationBoundsTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String LAMBDA_ARN = "arn:aws:lambda:us-east-1:000000000000:function:rotate";
+
+ @Test
+ void rotationThreadCountDoesNotScaleWithConcurrentRotations() throws Exception {
+ LambdaService mockLambda = Mockito.mock(LambdaService.class);
+ AtomicInteger concurrentInvocations = new AtomicInteger();
+ AtomicInteger peakConcurrentInvocations = new AtomicInteger();
+ CountDownLatch release = new CountDownLatch(1);
+
+ Mockito.when(mockLambda.invoke(Mockito.anyString(), Mockito.anyString(),
+ Mockito.any(byte[].class), Mockito.any()))
+ .thenAnswer(invocation -> {
+ int inFlight = concurrentInvocations.incrementAndGet();
+ peakConcurrentInvocations.updateAndGet(peak -> Math.max(peak, inFlight));
+ try {
+ release.await(10, TimeUnit.SECONDS);
+ } finally {
+ concurrentInvocations.decrementAndGet();
+ }
+ InvokeResult ok = new InvokeResult();
+ ok.setStatusCode(200);
+ return ok;
+ });
+
+ SecretsManagerService svc = new SecretsManagerService(new InMemoryStorage<String, Secret>(), 30,
+ new RegionResolver(REGION, "000000000000"), mockLambda, new ObjectMapper());
+
+ int secretCount = 300;
+ for (int i = 0; i < secretCount; i++) {
+ String name = "thread-bound-" + i;
+ svc.createSecret(name, "v1", null, null, null, null, REGION);
+ svc.rotateSecret(name, null, LAMBDA_ARN, null, true, REGION);
+ }
+
+ // Let the pool ramp up to its cap and stay there; a run of unchanged readings means every
+ // task that is ever going to start running concurrently already has.
+ long deadline = System.currentTimeMillis() + 5000;
+ int lastSeen = -1;
+ int stableReadings = 0;
+ while (System.currentTimeMillis() < deadline && stableReadings < 5) {
+ int now = peakConcurrentInvocations.get();
+ if (now == lastSeen) {
+ stableReadings++;
+ } else {
+ stableReadings = 0;
+ lastSeen = now;
+ }
+ Thread.sleep(20);
+ }
+
+ release.countDown();
+ svc.shutdown();
+
+ int peak = peakConcurrentInvocations.get();
+ assertTrue(peak <= SecretsManagerService.ROTATION_EXECUTOR_POOL_SIZE,
+ "rotation ran " + peak + " secrets concurrently out of " + secretCount
+ + " submitted; the rotation executor must be bounded by its pool size of "
+ + SecretsManagerService.ROTATION_EXECUTOR_POOL_SIZE + ", not one thread per secret");
+ }
+}