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,18 @@ 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.
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 and is sending the email. Mark this session as
// handled as well, so a l 8000 ater 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 {
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 @@ -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;

Expand Down Expand Up @@ -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();
Expand Down
0