8000 Admit a single concurrent verification email send per cooldown window by Praiztl · Pull Request #55511 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Comment thread
Praiztl marked this conversation as resolved.
8000 Resolved
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point. The model test guards the putIfAbsent primitive rather than VerifyEmail's use of it, so it would not catch a revert of the gating change here. A deterministic test that races an automatic send against an explicit resend through VerifyEmail needs a way to hold one request between the cooldown read and the atomic claim, and the tests/ harness drives requests through a single browser session with no such hook, so it cannot be made reliable without a small test seam in the challenge path. I would rather not add that seam unilaterally. If a maintainer has a preferred approach (a seam in VerifyEmail, or a different level at which to assert the single send), I am happy to add it. Leaving this open for that steer.

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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
// 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);
Comment thread
Praiztl marked this conversation as resolved.
Resolved
}
long remaining = (Long.parseLong(expire) - Time.currentTime());
// Avoid the awkward situation where due to rounding the value is zero
return remaining > 0 ? remaining : null;
}
Expand All @@ -56,6 +62,26 @@ 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.
* 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();
// 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);
}

/**
* 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,21 @@
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.IntStream;

import org.keycloak.common.util.Time;
import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
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.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.testsuite.model.KeycloakModelTest;
import org.keycloak.testsuite.model.RequireProvider;
Expand Down Expand Up @@ -243,6 +246,30 @@ public void testNonPositiveLifespan() {
});
}

@Test
public void testConcurrentPutIfAbsentAdmitsSingleCaller() {
// Guards the atomic admission that VerifyEmail relies on (issue 55405): of several concurrent requests
// for the same key, only one may be admitted to send a verification email within the cooldown window.
// A non-atomic check-then-write would let more than one caller through here.
String key = "verify-email-cooldown-" + UUID.randomUUID();
KeycloakSessionFactory factory = getFactory();

long admitted = IntStream.range(0, 20).parallel()
.filter(i -> KeycloakModelUtils.runJobInTransactionWithResult(factory,
session -> session.singleUseObjects().putIfAbsent(key, 60)))
.count();
Assert.assertEquals(1, admitted);

// Once the cooldown lifespan has elapsed, a new request is admitted again.
setTimeOffset(70);
try {
Assert.assertTrue(KeycloakModelUtils.runJobInTransactionWithResult(factory,
session -> session.singleUseObjects().putIfAbsent(key, 60)));
} finally {
setTimeOffset(0);
}
}

@Test
public void testCluster() throws InterruptedException {
AtomicInteger index = new AtomicInteger();
Expand Down
0