From ae1e52bd395c607567bacc3a8be42c7af3c9848c Mon Sep 17 00:00:00 2001 From: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:27:10 +0100 Subject: [PATCH 1/5] Admit a single concurrent verification email send per cooldown window Closes #55405 Signed-off-by: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> --- .../requiredactions/VerifyEmail.java | 14 +++++---- .../util/EmailCooldownManager.java | 30 ++++++++++++++++++- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/VerifyEmail.java b/services/src/main/java/org/keycloak/authentication/requiredactions/VerifyEmail.java index 15c1ff6c8a8f..dc9dd724c19a 100755 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/VerifyEmail.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/VerifyEmail.java @@ -136,11 +136,15 @@ private void process(RequiredActionContext context, boolean isChallenge) { // Do not allow resending e-mail by simple page refresh, i.e. when e-mail sent, it should be resent properly via email-verification endpoint if (!Objects.equals(authSession.getAuthNote(Constants.VERIFY_EMAIL_KEY), email) && !(isCurrentActionTriggeredFromAIA(context) && isChallenge)) { - // Adding the cooldown entry first to prevent concurrent operations - EmailCooldownManager.addCooldownEntry(context, EMAIL_RESEND_COOLDOWN_KEY_PREFIX); - authSession.setAuthNote(Constants.VERIFY_EMAIL_KEY, email); - EventBuilder event = context.getEvent().clone().event(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, email); - challenge = sendVerifyEmail(context, event); + // Atomically claim the cooldown slot so that concurrent requests cannot each send a verification email + if (EmailCooldownManager.addCooldownEntryIfAbsent(context, EMAIL_RESEND_COOLDOWN_KEY_PREFIX)) { + authSession.setAuthNote(Constants.VERIFY_EMAIL_KEY, email); + EventBuilder event = context.getEvent().clone().event(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, email); + challenge = sendVerifyEmail(context, event); + } else { + // A concurrent request already claimed the slot; re-render the page without sending another email + challenge = loginFormsProvider.createResponse(UserModel.RequiredAction.VERIFY_EMAIL); + } } else { challenge = loginFormsProvider.createResponse(UserModel.RequiredAction.VERIFY_EMAIL); } diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/util/EmailCooldownManager.java b/services/src/main/java/org/keycloak/authentication/requiredactions/util/EmailCooldownManager.java index e5bac3fefb4c..46340605558f 100644 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/util/EmailCooldownManager.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/util/EmailCooldownManager.java @@ -45,7 +45,13 @@ public static Long retrieveCooldownEntry(RequiredActionContext context, String k if (cooldownDetails == null) { return null; } - long remaining = (Long.parseLong(cooldownDetails.get(KEY_EXPIRE)) - Time.currentTime()); + String expire = cooldownDetails.get(KEY_EXPIRE); + if (expire == null) { + // A concurrent request has just claimed the cooldown slot but has not recorded the expiry yet; + // treat the user as being in cooldown for the full configured window. + return getCooldownInSeconds(context); + } + long remaining = (Long.parseLong(expire) - Time.currentTime()); // Avoid the awkward situation where due to rounding the value is zero return remaining > 0 ? remaining : null; } @@ -56,6 +62,28 @@ public static void addCooldownEntry(RequiredActionContext context, String keyPre cache.put(getCacheKey(context, keyPrefix), cooldownSeconds, Map.of(KEY_EXPIRE, Long.toString(Time.currentTime() + cooldownSeconds))); } + /** + * Atomically admits a single email send for the user in the given cooldown window and records the window's expiry. + * The check and the insert happen in one {@link SingleUseObjectProvider#putIfAbsent} call, so of several + * concurrent requests only one is admitted; the others get {@code false} and must not send an email. + * + * @return {@code true} if this request won the slot and should send the email + */ + public static boolean addCooldownEntryIfAbsent(RequiredActionContext context, String keyPrefix) { + long cooldownSeconds = getCooldownInSeconds(context); + if (cooldownSeconds <= 0) { + return true; + } + SingleUseObjectProvider cache = context.getSession().singleUseObjects(); + String key = getCacheKey(context, keyPrefix); + if (!cache.putIfAbsent(key, cooldownSeconds)) { + return false; + } + // Record the expiry so a later request can show the remaining cooldown time. + cache.put(key, cooldownSeconds, Map.of(KEY_EXPIRE, Long.toString(Time.currentTime() + cooldownSeconds))); + return true; + } + /** * Adds a cooldown entry for the id if there isn't one yet. The check and the add happen in one call, so two requests at the same time can't both get through. * @return false if the id is still in cooldown From eeb952ee39932f10f33dba5a47452d6fe805abb0 Mon Sep 17 00:00:00 2001 From: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:21:52 +0100 Subject: [PATCH 2/5] Do not re-anchor the verify email cooldown TTL with a deferred put putIfAbsent is applied immediately, but put() is deferred to transaction commit after the email send, which extended the key's TTL past the recorded expiry and rejected valid retries in that gap. Rely on the putIfAbsent lifespan alone; retrieveCooldownEntry reports the full configured window when no expiry is recorded. Signed-off-by: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> --- .../util/EmailCooldownManager.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/util/EmailCooldownManager.java b/services/src/main/java/org/keycloak/authentication/requiredactions/util/EmailCooldownManager.java index 46340605558f..5563f5e93d62 100644 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/util/EmailCooldownManager.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/util/EmailCooldownManager.java @@ -47,8 +47,8 @@ public static Long retrieveCooldownEntry(RequiredActionContext context, String k } String expire = cooldownDetails.get(KEY_EXPIRE); if (expire == null) { - // A concurrent request has just claimed the cooldown slot but has not recorded the expiry yet; - // treat the user as being in cooldown for the full configured window. + // Entries created by the atomic claim (addCooldownEntryIfAbsent) record no expiry, since the + // putIfAbsent lifespan already bounds the cooldown; report the full configured window. return getCooldownInSeconds(context); } long remaining = (Long.parseLong(expire) - Time.currentTime()); @@ -63,7 +63,7 @@ public static void addCooldownEntry(RequiredActionContext context, String keyPre } /** - * Atomically admits a single email send for the user in the given cooldown window and records the window's expiry. + * Atomically admits a single email send for the user in the given cooldown window. * The check and the insert happen in one {@link SingleUseObjectProvider#putIfAbsent} call, so of several * concurrent requests only one is admitted; the others get {@code false} and must not send an email. * @@ -75,13 +75,11 @@ public static boolean addCooldownEntryIfAbsent(RequiredActionContext context, St return true; } SingleUseObjectProvider cache = context.getSession().singleUseObjects(); - String key = getCacheKey(context, keyPrefix); - if (!cache.putIfAbsent(key, cooldownSeconds)) { - return false; - } - // Record the expiry so a later request can show the remaining cooldown time. - cache.put(key, cooldownSeconds, Map.of(KEY_EXPIRE, Long.toString(Time.currentTime() + cooldownSeconds))); - return true; + // putIfAbsent is applied immediately and its lifespan bounds the cooldown window. We deliberately do not + // record the expiry as a second entry: put() is deferred to transaction commit, after the email is sent, + // which would re-anchor the key's TTL past the intended expiry and reject valid retries in that gap. + // retrieveCooldownEntry reports the full configured window when no expiry is recorded. + return cache.putIfAbsent(getCacheKey(context, keyPrefix), cooldownSeconds); } /** From 35250938c82d533c995f632733b3e2c365457390 Mon Sep 17 00:00:00 2001 From: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:06:28 +0000 Subject: [PATCH 3/5] Align registration email verification tests with the verify email cooldown Advance the cache clock via enableForCaches, and wait out the per-user cooldown in the forget-password flow before a second automatic verification email is expected, matching the cross-session throttle this change enforces. Signed-off-by: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> --- .../tests/forms/RegisterWithEmailVerificationTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/base/src/test/java/org/keycloak/tests/forms/RegisterWithEmailVerificationTest.java b/tests/base/src/test/java/org/keycloak/tests/forms/RegisterWithEmailVerificationTest.java index 3ae083d83f56..caf38bc5b6e0 100644 --- a/tests/base/src/test/java/org/keycloak/tests/forms/RegisterWithEmailVerificationTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/forms/RegisterWithEmailVerificationTest.java @@ -100,7 +100,7 @@ public class RegisterWithEmailVerificationTest { @InjectPage(ref = "verifyEmailPage", webDriverRef = "driver") VerifyEmailPage verifyEmailPage; - @InjectTimeOffSet + @InjectTimeOffSet(enableForCaches = true) TimeOffSet timeOffSet; @InjectWebDriver(ref = "driver2", lifecycle = LifeCycle.CLASS) @@ -255,6 +255,8 @@ private void registerUserSuccessWithEmailVerificationWithForgetPasswordImpl() th assertTrue(mailServer.waitForIncomingEmail(2)); MimeMessage message = mailServer.getLastReceivedMessage(); String forgetPasswordEmailLink = MailUtils.getPasswordResetEmailLink(message); + // Issue 55405: wait out the per-user verify email cooldown so the reset flow can send a fresh verification email + timeOffSet.set(40); driver2.open(forgetPasswordEmailLink); // Need to verify email now From 39a39c330bf85c3781a595a866725bea97049b34 Mon Sep 17 00:00:00 2001 From: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:33:03 +0100 Subject: [PATCH 4/5] Add a concurrent admission regression test for the verify email cooldown Drive EmailCooldownManager.addCooldownEntryIfAbsent and retrieveCooldownEntry across concurrent transactions, rather than the putIfAbsent primitive directly, so a regression in the cooldown admission the fix adds is caught: of twenty concurrent requests for one user exactly one is admitted, a further request within the window is rejected with the remaining cooldown reported, and once the window elapses a new request is admitted again. Runs against embedded and remote Infinispan through the model suite. Signed-off-by: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> --- .../SingleUseObjectModelTest.java | 186 ++++++++++++++++++ 1 file changed, 186 insertions(+) diff --git a/testsuite/model/src/test/java/org/keycloak/testsuite/model/singleUseObject/SingleUseObjectModelTest.java b/testsuite/model/src/test/java/org/keycloak/testsuite/model/singleUseObject/SingleUseObjectModelTest.java index d4fd1f2b5c90..a77483e5607a 100644 --- a/testsuite/model/src/test/java/org/keycloak/testsuite/model/singleUseObject/SingleUseObjectModelTest.java +++ b/testsuite/model/src/test/java/org/keycloak/testsuite/model/singleUseObject/SingleUseObjectModelTest.java @@ -17,25 +17,40 @@ package org.keycloak.testsuite.model.singleUseObject; +import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.IntStream; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; + +import org.keycloak.authentication.RequiredActionContext; +import org.keycloak.authentication.requiredactions.util.EmailCooldownManager; +import org.keycloak.common.ClientConnection; import org.keycloak.common.util.Time; import org.keycloak.connections.infinispan.InfinispanConnectionProvider; +import org.keycloak.events.EventBuilder; +import org.keycloak.forms.login.LoginFormsProvider; +import org.keycloak.http.HttpRequest; import org.keycloak.infinispan.util.InfinispanUtils; import org.keycloak.models.Constants; import org.keycloak.models.DefaultActionTokenKey; import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.RealmModel; +import org.keycloak.models.RequiredActionConfigModel; import org.keycloak.models.SingleUseObjectProvider; import org.keycloak.models.UserModel; import org.keycloak.models.sessions.infinispan.InfinispanSingleUseObjectProviderFactory; import org.keycloak.models.sessions.infinispan.entities.SingleUseObjectValueEntity; +import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.revoketokens.jpa.RevokedTokenExpirationAction; +import org.keycloak.sessions.AuthenticationSessionModel; import org.keycloak.testsuite.model.KeycloakModelTest; import org.keycloak.testsuite.model.RequireProvider; @@ -243,6 +258,177 @@ public void testNonPositiveLifespan() { }); } + @Test + public void testConcurrentCooldownAdmitsSingleSend() { + // Issue 55405: of several concurrent verify-email requests for the same user, only one may be admitted + // to send within the cooldown window. This drives EmailCooldownManager.addCooldownEntryIfAbsent, the + // method VerifyEmail relies on, rather than the putIfAbsent primitive directly, so a regression in the + // manager (a non-atomic check-then-write, or a write deferred to transaction commit) is caught: either + // would let more than one caller through here. + KeycloakSessionFactory factory = getFactory(); + String keyPrefix = "test-verify-email-cooldown-" + UUID.randomUUID() + "-"; + + long admitted = IntStream.range(0, 20).parallel() + .filter(i -> KeycloakModelUtils.runJobInTransactionWithResult(factory, + session -> EmailCooldownManager.addCooldownEntryIfAbsent(cooldownContext(session), keyPrefix))) + .count(); + Assert.assertEquals(1, admitted); + + // While the window is still open, a further request is rejected and the remaining cooldown is reported. + KeycloakModelUtils.runJobInTransaction(factory, session -> { + RequiredActionContext context = cooldownContext(session); + Assert.assertFalse(EmailCooldownManager.addCooldownEntryIfAbsent(context, keyPrefix)); + Assert.assertNotNull(EmailCooldownManager.retrieveCooldownEntry(context, keyPrefix)); + }); + + // Once the cooldown lifespan has elapsed, the entry is gone and a new request is admitted again. + setTimeOffset(EmailCooldownManager.EMAIL_RESEND_COOLDOWN_DEFAULT_SECONDS + 10); + try { + KeycloakModelUtils.runJobInTransaction(factory, session -> { + RequiredActionContext context = cooldownContext(session); + Assert.assertNull(EmailCooldownManager.retrieveCooldownEntry(context, keyPrefix)); + Assert.assertTrue(EmailCooldownManager.addCooldownEntryIfAbsent(context, keyPrefix)); + }); + } finally { + setTimeOffset(0); + } + } + + private RequiredActionContext cooldownContext(KeycloakSession session) { + RealmModel realm = session.realms().getRealm(realmId); + session.getContext().setRealm(realm); + UserModel user = session.users().getUserById(realm, userId); + return new CooldownRequiredActionContext(session, realm, user); + } + + /** + * Minimal {@link RequiredActionContext} that exposes only what {@link EmailCooldownManager} reads: the + * session (for the single-use store), the realm and action (for the configured cooldown) and the user + * (for the cache key). Everything else is unused by the cooldown methods and therefore unsupported. + */ + private static final class CooldownRequiredActionContext implements RequiredActionContext { + + private final KeycloakSession session; + private final RealmModel realm; + private final UserModel user; + + private CooldownRequiredActionContext(KeycloakSession session, RealmModel realm, UserModel user) { + this.session = session; + this.realm = realm; + this.user = user; + } + + @Override + public KeycloakSession getSession() { + return session; + } + + @Override + public RealmModel getRealm() { + return realm; + } + + @Override + public UserModel getUser() { + return user; + } + + @Override + public String getAction() { + return UserModel.RequiredAction.VERIFY_EMAIL.name(); + } + + @Override + public URI getActionUrl(String code) { + throw new UnsupportedOperationException(); + } + + @Override + public URI getActionUrl() { + throw new UnsupportedOperationException(); + } + + @Override + public LoginFormsProvider form() { + throw new UnsupportedOperationException(); + } + + @Override + public Response getChallenge() { + throw new UnsupportedOperationException(); + } + + @Override + public EventBuilder getEvent() { + throw new UnsupportedOperationException(); + } + + @Override + public AuthenticationSessionModel getAuthenticationSession() { + throw new UnsupportedOperationException(); + } + + @Override + public ClientConnection getConnection() { + throw new UnsupportedOperationException(); + } + + @Override + public UriInfo getUriInfo() { + throw new UnsupportedOperationException(); + } + + @Override + public HttpRequest getHttpRequest() { + throw new UnsupportedOperationException(); + } + + @Override + public RequiredActionConfigModel getConfig() { + throw new UnsupportedOperationException(); + } + + @Override + public String generateCode() { + throw new UnsupportedOperationException(); + } + + @Override + public Status getStatus() { + throw new UnsupportedOperationException(); + } + + @Override + public String getErrorMessage() { + throw new UnsupportedOperationException(); + } + + @Override + public void challenge(Response response) { + throw new UnsupportedOperationException(); + } + + @Override + public void failure(String errorMessage) { + throw new UnsupportedOperationException(); + } + + @Override + public void success() { + throw new UnsupportedOperationException(); + } + + @Override + public void cancel() { + throw new UnsupportedOperationException(); + } + + @Override + public void ignore() { + throw new UnsupportedOperationException(); + } + } + @Test public void testCluster() throws InterruptedException { AtomicInteger index = new AtomicInteger(); From be2def30e4ddc2d3b64168c4ca8e9c2eb5ba27ef Mon Sep 17 00:00:00 2001 From: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:54:52 +0100 Subject: [PATCH 5/5] Mark the losing concurrent verify email request as handled When a concurrent request loses the atomic cooldown claim it previously left VERIFY_EMAIL_KEY unset, so a page refresh after the cooldown expired would send another verification email without an explicit resend. Set the note on that branch as well, matching the request that wins the claim; an explicit resend still goes through the email-verification endpoint, which clears the note. Signed-off-by: Tochukwu Chikezie <95018735+Praiztl@users.noreply.github.com> --- .../keycloak/authentication/requiredactions/VerifyEmail.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/VerifyEmail.java b/services/src/main/java/org/keycloak/authentication/requiredactions/VerifyEmail.java index dc9dd724c19a..81fca766a210 100755 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/VerifyEmail.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/VerifyEmail.java @@ -142,7 +142,10 @@ private void process(RequiredActionContext context, boolean isChallenge) { EventBuilder event = context.getEvent().clone().event(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, email); challenge = sendVerifyEmail(context, event); } else { - // A concurrent request already claimed the slot; re-render the page without sending another email + // A concurrent request already claimed the slot and is sending the email. Mark this session as + // handled as well, so a later page refresh does not send another email once the cooldown expires; + // an explicit resend still goes through the email-verification endpoint, which clears this note. + authSession.setAuthNote(Constants.VERIFY_EMAIL_KEY, email); challenge = loginFormsProvider.createResponse(UserModel.RequiredAction.VERIFY_EMAIL); } } else {