From fa3488b9a30c2bf79e0db3a6b7d50423d255c7ad Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 26 Nov 2026 13:03:19 -0600 Subject: [PATCH] perf(cognito): generate a user pool's signing key pair on first use (#9543) --- .../aws/services/cognito/CognitoService.java | 112 ++++++++++++----- .../services/cognito/CognitoServiceTest.java | 116 ++++++++++++++++++ 2 files changed, 194 insertions(+), 34 deletions(-) diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoService.java b/src/main/java/io/floci/aws/services/cognito/CognitoService.java index 7734535bbf..a8cbbd3374 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoService.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoService.java @@ -466,7 +466,7 @@ public class CognitoService implements ResourceProvider, StoredResourceArns { populateUserPool(pool, request); requireCustomSenderKey(pool, true, region); - ensureJwtSigningKeys(pool); + ensureSigningKeyId(pool); ensureRefreshTokenSecret(pool); poolStore.put(id, pool); LOG.infov("Created User Pool: {0}", id); @@ -836,9 +836,9 @@ public class CognitoService implements ResourceProvider, StoredResourceArns { public UserPool describeUserPool(String id) { UserPool pool = poolStore.get(id) .orElseThrow(() -> userPoolNotFound(id)); - boolean generatedKeys = ensureJwtSigningKeys(pool); + boolean generatedKeyId = ensureSigningKeyId(pool); boolean generatedSecret = ensureRefreshTokenSecret(pool); - if (generatedKeys || generatedSecret) { + if (generatedKeyId || generatedSecret) { poolStore.put(id, pool); } return pool; @@ -1253,10 +1253,14 @@ public class CognitoService implements ResourceProvider, StoredResourceArns { } // Same lock as the provider mutations: a create or update that interleaves with // this cascade would otherwise reinstate a provider for a pool that is going away. - synchronized (identityProviderLock) { - identityProviderStore.scan(k -> k.startsWith(prefix)) - .forEach(p -> identityProviderStore.delete(identityProviderKey(id, p.getProviderName()))); - poolStore.delete(id); + // The pool lock as well: a first use generating the pool's signing key pair writes the stored + // pool back under it, and must not reinstate a pool deleted while the key pair was made. + synchronized (poolLock(id)) { + synchronized (identityProviderLock) { + identityProviderStore.scan(k -> k.startsWith(prefix)) + .forEach(p -> identityProviderStore.delete(identityProviderKey(id, p.getProviderName()))); + poolStore.delete(id); + } } } @@ -5767,7 +5771,7 @@ public class CognitoService implements ResourceProvider, StoredResourceArns { } String getSigningKeyId(UserPool pool) { - ensureJwtSigningKeys(pool); + ensureSigningKeyId(pool); return pool.getSigningKeyId(); } @@ -5796,37 +5800,77 @@ public class CognitoService implements ResourceProvider, StoredResourceArns { } } - private boolean ensureJwtSigningKeys(UserPool pool) { + private boolean ensureSigningKeyId(UserPool pool) { synchronized (pool) { - boolean changed = false; - - if (pool.getSigningKeyId() == null || pool.getSigningKeyId().isBlank()) { - pool.setSigningKeyId(pool.getId()); - changed = true; + if (pool.getSigningKeyId() != null && !pool.getSigningKeyId().isBlank()) { + return false; } - - if (pool.getSigningPrivateKey() == null || pool.getSigningPrivateKey().isBlank() - || pool.getSigningPublicKey() == null || pool.getSigningPublicKey().isBlank()) { - try { - KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); - generator.initialize(2048); - KeyPair keyPair = generator.generateKeyPair(); - - pool.setSigningPrivateKey( - Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); - pool.setSigningPublicKey( - Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); - changed = true; - } catch (Exception e) { - throw new RuntimeException("Failed to generate Cognito RSA signing keypair", e); - } - } - - if (changed && pool.getId() != null) { + pool.setSigningKeyId(pool.getId()); + if (pool.getId() != null) { pool.setLastModifiedDate(System.currentTimeMillis() / 1000L); } + return true; + } + } - return changed; + /** + * Generates the pool's RSA signing key pair the first time a token is signed or its JWKS is read, + * rather than on CreateUserPool, since a 2048-bit key costs tens of milliseconds. The pool lock + * serialises this with UpdateUserPool, which replaces the stored pool with a copy: the key pair + * goes on the stored pool and on the caller's instance, so the JWKS and every token share it. + * Generating it is not a change the caller made, so it leaves LastModifiedDate alone. + */ + private void ensureJwtSigningKeys(UserPool pool) { + if (hasSigningKeyPair(pool)) { + return; + } + Object lock = pool.getId() != null ? poolLock(pool.getId()) : pool; + synchronized (lock) { + UserPool stored = pool.getId() != null + ? poolStore.get(pool.getId()).filter(p -> Objects.equals(p.getArn(), pool.getArn())).orElse(null) + : null; + if (stored != null && stored != pool && hasSigningKeyPair(stored)) { + copySigningKeyPair(stored, pool); + return; + } + if (hasSigningKeyPair(pool)) { + return; + } + ensureSigningKeyId(pool); + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + synchronized (pool) { + pool.setSigningPublicKey( + Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); + pool.setSigningPrivateKey( + Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); + } + } catch (Exception e) { + throw new RuntimeException("Failed to generate Cognito RSA signing keypair", e); + } + if (stored != null) { + if (stored != pool) { + copySigningKeyPair(pool, stored); + } + poolStore.put(stored.getId(), stored); + } + } + } + + private static boolean hasSigningKeyPair(UserPool pool) { + synchronized (pool) { + return pool.getSigningPrivateKey() != null && !pool.getSigningPrivateKey().isBlank() + && pool.getSigningPublicKey() != null && !pool.getSigningPublicKey().isBlank(); + } + } + + private static void copySigningKeyPair(UserPool from, UserPool to) { + synchronized (to) { + to.setSigningKeyId(from.getSigningKeyId()); + to.setSigningPublicKey(from.getSigningPublicKey()); + to.setSigningPrivateKey(from.getSigningPrivateKey()); } } diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java index dbaa5a0b69..512b4974a9 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoServiceTest.java @@ -46,6 +46,8 @@ import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.nio.charset.StandardCharsets; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -53,6 +55,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -415,6 +418,119 @@ class CognitoServiceTest { assertEquals(signingKeyId, restored.getSigningKeyId(), "the pool keeps the keys it signs with"); } + @Test + @SuppressWarnings("unchecked") + void signingKeyPairIsMadeOnFirstUseAndTheJwksVerifiesEveryLaterToken() throws Exception { + UserPool pool = createPoolAndUser(); + long lastModified = pool.getLastModifiedDate(); + assertNull(poolStore.get(pool.getId()).orElseThrow().getSigningPrivateKey(), + "CreateUserPool leaves the key pair to the first token or JWKS read"); + + RSAPublicKey jwksKey = service.getSigningPublicKey(service.describeUserPool(pool.getId())); + UserPoolClient client = openClient(service, pool.getId(), "lazy-key-client", false); + Map auth = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + String token = (String) ((Map) auth.get("AuthenticationResult")).get("IdToken"); + + UserPool described = service.describeUserPool(pool.getId()); + assertEquals(jwksKey, service.getSigningPublicKey(described), "the JWKS is stable across fetches"); + assertTrue(signatureVerifies(token, jwksKey), "the JWKS fetched before sign-in verifies the token"); + assertEquals(lastModified, described.getLastModifiedDate(), "making the key pair is not a pool update"); + } + + @Test + void signingKeyPairSurvivesAPersistenceRoundTripAndAPersistedPoolWithoutOneGetsOne() throws Exception { + UserPool pool = service.createUserPool(Map.of("PoolName", "persisted"), "us-east-1"); + RSAPublicKey original = service.getSigningPublicKey(service.describeUserPool(pool.getId())); + + UserPool reloaded = MAPPER.readValue(MAPPER.writeValueAsBytes(poolStore.get(pool.getId()).orElseThrow()), + UserPool.class); + poolStore.put(reloaded.getId(), reloaded); + assertEquals(original, service.getSigningPublicKey(service.describeUserPool(pool.getId())), + "a persisted pool keeps the key pair it already signs with"); + + reloaded.setSigningPublicKey(null); + reloaded.setSigningPrivateKey(null); + UserPool legacy = MAPPER.readValue(MAPPER.writeValueAsBytes(reloaded), UserPool.class); + poolStore.put(legacy.getId(), legacy); + RSAPublicKey generated = service.getSigningPublicKey(service.describeUserPool(pool.getId())); + assertNotNull(poolStore.get(pool.getId()).orElseThrow().getSigningPrivateKey(), + "a pool persisted without a key pair gets one stored on first use"); + assertEquals(generated, service.getSigningPublicKey(service.describeUserPool(pool.getId()))); + } + + @Test + void concurrentFirstUsesOfAPoolAgreeOnOneSigningKeyPair() throws Exception { + UserPool pool = service.createUserPool(Map.of("PoolName", "racing"), "us-east-1"); + int threads = 8; + ExecutorService executor = Executors.newFixedThreadPool(threads); + CountDownLatch start = new CountDownLatch(1); + try { + List> keys = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + int index = i; + keys.add(executor.submit(() -> { + start.await(); + if (index % 2 == 0) { + service.updateUserPool(Map.of("UserPoolId", pool.getId(), "PoolName", "racing-" + index), + "us-east-1"); + } + UserPool copy = MAPPER.convertValue(service.describeUserPool(pool.getId()), UserPool.class); + return service.getSigningPublicKey(copy); + })); + } + start.countDown(); + Set distinct = new HashSet<>(); + for (Future key : keys) { + distinct.add(key.get(30, TimeUnit.SECONDS)); + } + assertEquals(1, distinct.size(), "every caller signs with the key pair the JWKS serves"); + assertEquals(distinct.iterator().next(), + service.getSigningPublicKey(service.describeUserPool(pool.getId()))); + } finally { + executor.shutdownNow(); + } + } + + @Test + void aFirstUseRacingDeleteUserPoolNeverBringsThePoolBack() throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + for (int round = 0; round < 5; round++) { + UserPool pool = service.createUserPool(Map.of("PoolName", "deleted-" + round), "us-east-1"); + CountDownLatch start = new CountDownLatch(1); + Future firstUse = executor.submit(() -> { + start.await(); + return service.getSigningPublicKey(service.describeUserPool(pool.getId())); + }); + Future delete = executor.submit(() -> { + start.await(); + service.deleteUserPool(pool.getId()); + return null; + }); + start.countDown(); + delete.get(30, TimeUnit.SECONDS); + try { + firstUse.get(30, TimeUnit.SECONDS); + } catch (ExecutionException expected) { + // The delete may land first, and the first use then finds no pool: that is fine. + } + AwsException gone = assertThrows(AwsException.class, () -> service.describeUserPool(pool.getId())); + assertEquals("ResourceNotFoundException", gone.getErrorCode(), "round " + round); + } + } finally { + executor.shutdownNow(); + } + } + + private static boolean signatureVerifies(String jwt, RSAPublicKey key) throws Exception { + int lastDot = jwt.lastIndexOf('.'); + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(key); + verifier.update(jwt.substring(0, lastDot).getBytes(StandardCharsets.UTF_8)); + return verifier.verify(Base64.getUrlDecoder().decode(jwt.substring(lastDot + 1))); + } + @Test void restoreUserPoolClientSettingsPutsBackWhatAnUpdateChanged() { UserPool pool = service.createUserPool(Map.of("PoolName", "pool"), "us-east-1");