8000 Apply VERIFY_EMAIL resend cooldown on new authentication sessions by julioo19 · Pull Request #54947 · 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 @@ -134,14 +134,19 @@ private void process(RequiredActionContext context, boolean isChallenge) {
Response challenge;
authSession.setClientNote(AuthorizationEndpointBase.APP_INITIATED_FLOW, null);

Long remaining = EmailCooldownManager.retrieveCooldownEntry(context, EMAIL_RESEND_COOLDOWN_KEY_PREFIX);
// 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)) {
if (!Objects.equals(authSession.getAuthNote(Constants.VERIFY_EMAIL_KEY), email)
&& !(isCurrentActionTriggeredFromAIA(context) && isChallenge)
&& remaining == null) {
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.

Thanks Copilot, this is correct: two concurrent requests can both read no cooldown before either write is committed (the write is deferred until the Infinispan transaction commits), so both would send an e-mail.

I left it out of this PR on purpose:

That said, it's the maintainers' call: I'm happy to include an atomic reservation here, or to align with #55511 in whichever order you prefer to merge them.

// 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);
} else {
// Either a verification e-mail was already sent for this auth session, or one was sent
// recently for this user (possibly from another auth session): render the page without sending
challenge = loginFormsProvider.createResponse(UserModel.RequiredAction.VERIFY_EMAIL);
}

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 @@ -254,6 +254,8 @@ private void registerUserSuccessWithEmailVerificationWithForgetPasswordImpl() th
// Receive the email and click it on browser2
MimeMessage message = mailServer.getLastReceivedMessage();
String forgetPasswordEmailLink = MailUtils.getPasswordResetEmailLink(message);
// 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 @@ -50,6 +50,8 @@
import org.keycloak.testframework.realm.UserBuilder;
import org.keycloak.testframework.remote.runonserver.InjectRunOnSer 8000 ver;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.remote.timeoffset.InjectTimeOffSet;
import org.keycloak.testframework.remote.timeoffset.TimeOffSet;
import org.keycloak.testframework.ui.annotations.InjectPage;
import org.keycloak.testframework.ui.annotations.InjectWebDriver;
import org.keycloak.testframework.ui.page.IdpConfirmLinkPage;
Expand Down Expand Up @@ -109,6 +111,9 @@ public class OrganizationPostBrokerMembershipTest {
@InjectPage
LoginUsernamePage loginUsernamePage;

@InjectTimeOffSet(enableForCaches = true)
TimeOffSet timeOffSet;

@InjectPage
LoginUpdateProfilePage updateProfilePage;

Expand Down Expand Up @@ -191,7 +196,8 @@ public void testForceSyncRequiresVerificationWhenEmailChangesOnRetry() throws Ex
UserRepresentation providerUser = providerRealm.admin().users().searchByUsername(user.getUsername(), true).get(0);
providerUser.setEmail(changedEmail);
providerRealm.admin().users().get(providerUser.getId()).update(providerUser);

// wait out the per-user verify email cooldown so the retry can send to the new address
timeOffSet.set(40);
retryBrokerLoginAndLinkAccount(user);

verifyEmailPage.assertCurrent();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ abstract class AbstractSslEmailTest {
@InjectRealm(config = SslEmailRealmConfig.class)
ManagedRealm realm;

@InjectUser(config = TestUser.class)
// each method receives a new userId
@InjectUser(config = TestUser.class, lifecycle = LifeCycle.METHOD)
ManagedUser user;

@InjectEvents
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.events.EventAssertion;
import org.keycloak.testframework.events.Events;
import org.keycloak.testframework.injection.LifeCycle;
import org.keycloak.testframework.mail.MailServer;
import org.keycloak.testframework.mail.annotations.InjectMailServer;
import org.keycloak.testframework.oauth.OAuthClient;
Expand Down Expand Up @@ -55,7 +56,8 @@ class EmailPlainAuthTest {
@InjectRealm(config = VerifyEmailRealmConfig.class)
ManagedRealm realm;

@InjectUser(config = TestUser.class)
// each method receives a new userId
@InjectUser(config = TestUser.class, lifecycle = LifeCycle.METHOD)
ManagedUser user;

@InjectEvents
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,41 @@ public void verifyEmailResendTooFast() {

}

@Test
public void verifyEmailNewSessionRespectsResendCooldown() {
oauth.openLoginForm();
loginPage.login("test-user@localhost", "password");

verifyEmailPage.assertCurrent();
Assertions.assertEquals(1, mail.getReceivedMessages().length);

// Clearing the cookies makes the next login start a new authentication session
driver.manage().deleteAllCookies();

oauth.openLoginForm();
loginPage.login("test-user@localhost", "password");

verifyEmailPage.assertCurrent();

// The resend cooldown is per user, so the new session must not send another e-mail
Assertions.assertEquals(1, mail.getReceivedMessages().length);

verifyEmailPage.clickResendEmail();
assertThat(verifyEmailPage.getFeedbackText(), Matchers.containsString("You must wait"));

try {
// Move the clock past the cooldown, a new session sends the e-mail again
timeOffSet.set(40);
driver.manage().deleteAllCookies();
oauth.openLoginForm();
loginPage.login("test-user@localhost", "password");
verifyEmailPage.assertCurrent();
Assertions.assertEquals(2, mail.getReceivedMessages().length);
} finally {
timeOffSet.set(0);
}
}

@Test
public void verifyEmailResendWithRefreshes() throws IOException {
oauth.openLoginForm();
Expand Down
0