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 @@ -45,6 +45,8 @@ If you do not want to reset the OTP, set the `Reset - Conditional OTP` sub-flow
image:images/reset-credential-email-config.png[Send Reset Email Configuration]
+
If you want to change default behavior for the force login option, click the *Send Reset Email* settings icon in the flow, define an *Alias*, and select the best *Force login after reset* option for you (`true`, always force re-authentication, `false`, keep the user logged in if the same browser was used, `only-federated`, default value that forces login again only for federated users).
+
The same settings contain *Cooldown between reset emails (seconds)*. {project_name} sends at most one reset email to the same user during this time, which is 30 seconds by default, so the form cannot be used to flood the inbox of a user. A request made during the cooldown gets the same response, but no email is sent. Set it to `0` to send an email for every request. Someone who knows a username can request an email each time the cooldown ends, so a request by the user in between may not send a new one. The email that was sent still contains a working link.
. Click *Authentication* in the menu.
. Click the *Required actions* tab.
. Ensure *Update Password* is enabled.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,12 @@ Log parsers that interpret backslash escapes still read the original value and n
Log parsers that match on the exact logged text must be updated to expect the doubled backslash.
The change does not apply when the listener is configured with `--spi-events-listener--jboss-logging--quotes=none` or `--spi-events-listener--jboss-logging--sanitize=false`.

=== Reset password emails have a cooldown

The *Forgot password* form now sends at most one email to the same user every 30 seconds. A request made during the cooldown gets the same response, but no email is sent, and a `SEND_RESET_PASSWORD_ERROR` event with the error `slow_down` is recorded. Before, every request sent an email, so anyone who knew a username or an email address could flood the inbox of that user.

To change the cooldown, click the settings icon of the *Send Reset Email* step in the *Reset Credentials* flow and set *Cooldown between reset emails (seconds)*. The value `0` turns the cooldown off.

=== OIDC identity provider now respects `email_verified=false` from the ID token when Trust Email is enabled
// https://github.com/keycloak/keycloak/issues/54245

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.keycloak.authentication.AuthenticatorFactory;
import org.keycloak.authentication.actiontoken.resetcred.ResetCredentialsActionToken;
import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
import org.keycloak.authentication.requiredactions.util.EmailCooldownManager;
import org.keycloak.common.util.Time;
import org.keycloak.credential.CredentialModel;
import org.keycloak.credential.CredentialProvider;
Expand Down Expand Up @@ -73,6 +74,7 @@ public class ResetCredentialEmail implements Authenticator, AuthenticatorFactory
public static final String PROVIDER_ID = "reset-credential-email";
public static final String FORCE_LOGIN = "force-login";
public static final String FEDERATED_OPTION = "only-federated";
public static final String EMAIL_COOLDOWN_KEY_PREFIX = "reset-credential-email-cooldown-known-";

@Override
public void authenticate(AuthenticationFlowContext context) {
Expand Down Expand Up @@ -110,6 +112,15 @@ public void authenticate(AuthenticationFlowContext context) {
return;
}

if (!EmailCooldownManager.addCooldownEntryIfAbsent(context, EMAIL_COOLDOWN_KEY_PREFIX, user.getId())) {
event.clone().event(EventType.SEND_RESET_PASSWORD)
.detail(Details.USERNAME, username)
.user(user)
.error(Errors.SLOW_DOWN);
context.forkWithSuccessMessage(new FormMessage(Messages.EMAIL_SENT));
return;
}

int validityInSecs = context.getRealm().getActionTokenGeneratedByUserLifespan(ResetCredentialsActionToken.TOKEN_TYPE);
int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;

Expand Down Expand Up @@ -228,6 +239,13 @@ public List<ProviderConfigProperty> getConfigProperties() {
.options(Arrays.asList(Boolean.TRUE.toString(), Boolean.FALSE.toString(), FEDERATED_OPTION))
.defaultValue(FEDERATED_OPTION)
.add()
.property()
.name(EmailCooldownManager.EMAIL_RESEND_COOLDOWN_SECONDS)
.label("Cooldown between reset emails (seconds)")
.helpText("Minimum delay in seconds before another reset email is sent to the same user. Set it to 0 to send an email for every request.")
.type(ProviderConfigProperty.INTEGER_TYPE)
.defaultValue(EmailCooldownManager.EMAIL_RESEND_COOLDOWN_DEFAULT_SECONDS)
.add()
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@

package org.keycloak.authentication.requiredactions.util;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.RequiredActionContext;
import org.keycloak.common.util.Time;
import org.keycloak.jose.jws.crypto.HashUtils;
import org.keycloak.models.AuthenticatorConfigModel;
import org.keycloak.models.RequiredActionProviderModel;
import org.keycloak.models.SingleUseObjectProvider;
import org.keycloak.provider.ProviderConfigProperty;
Expand Down Expand Up @@ -52,6 +56,20 @@ public static void addCooldownEntry(RequiredActionContext context, String keyPre
cache.put(getCacheKey(context, keyPrefix), cooldownSeconds, Map.of(KEY_EXPIRE, Long.toString(Time.currentTime() + 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
*/
public static boolean addCooldownEntryIfAbsent(AuthenticationFlowContext context, String keyPrefix, String id) {
long cooldownSeconds = getCooldownInSeconds(context.getAuthenticatorConfig());
return cooldownSeconds <= 0 || context.getSession().singleUseObjects().putIfAbsent(getHashedCacheKey(keyPrefix, id), cooldownSeconds);
}

// the id of a federated user can be longer than the key the database store allows, so it is hashed
public static String getHashedCacheKey(String keyPrefix, String id) {
return keyPrefix + HashUtils.sha256UrlEncodedHash(id, StandardCharsets.UTF_8);
}

public static ProviderConfigProperty createCooldownConfigProperty() {
ProviderConfigProperty cooldown = new ProviderConfigProperty();
cooldown.setName(EMAIL_RESEND_COOLDOWN_SECONDS);
Expand All @@ -66,6 +84,19 @@ private static String getCacheKey(RequiredActionContext context, String keyPrefi
return keyPrefix + context.getUser().getId();
}

private static long getCooldownInSeconds(AuthenticatorConfigModel config) {
String value = config != null ? config.getConfig().get(EMAIL_RESEND_COOLDOWN_SECONDS) : null;
if (value == null || value.isBlank()) {
return EMAIL_RESEND_COOLDOWN_DEFAULT_SECONDS;
}
try {
return Long.parseLong(value.trim());
} catch (NumberFormatException e) {
logger.warnf("Invalid value for %s: %s. Using the default.", EMAIL_RESEND_COOLDOWN_SECONDS, value);
return EMAIL_RESEND_COOLDOWN_DEFAULT_SECONDS;
}
}

private static long getCooldownInSeconds(RequiredActionContext context) {
try {
RequiredActionProviderModel model = context.getRealm().getRequiredActionProviderByAlias(context.getAction());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
package org.keycloak.tests.forms;

import java.io.IOException;
import java.util.Map;

import jakarta.mail.internet.MimeMessage;

import org.keycloak.admin.client.resource.AuthenticationManagementResource;
import org.keycloak.authentication.authenticators.resetcred.ResetCredentialEmail;
import org.keycloak.authentication.requiredactions.util.EmailCooldownManager;
import org.keycloak.broker.oidc.OIDCIdentityProviderFactory;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventType;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.representations.idm.AuthenticatorConfigRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.services.validation.Validation;
Expand All @@ -30,13 +36,16 @@
import org.keycloak.testframework.realm.RealmBuilder;
import org.keycloak.testframework.realm.RealmConfig;
import org.keycloak.testframework.realm.UserBuilder;
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.LoginPage;
import org.keycloak.testframework.ui.page.LoginPasswordResetPage;
import org.keycloak.testframework.ui.page.LoginPasswordUpdatePage;
import org.keycloak.testframework.ui.page.RegisterPage;
import org.keycloak.testframework.ui.webdriver.ManagedWebDriver;
import org.keycloak.testframework.util.ApiUtil;
import org.keycloak.tests.utils.MailUtils;
import org.keycloak.testsuite.util.MailServerConfiguration;

Expand All @@ -45,6 +54,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;

@KeycloakIntegrationTest
public class ResetPasswordTest {
Expand Down Expand Up @@ -91,6 +101,9 @@ public class ResetPasswordTest {
@InjectEvents(realmRef = CONSUMER_REALM_NAME)
protected Events events;

@InjectTimeOffSet(enableForCaches = true)
protected TimeOffSet timeOffSet;

@Test
public void shouldOfferAllOidcOptionOnLoginPageUserTriesToResetTheirPasswordAndGoesBack() {
IdentityProviderRepresentation idp = IdentityProviderBuilder.create()
Expand Down Expand Up @@ -245,6 +258,77 @@ public void resetPasswordExactMaxLengthUsername() {
.details(Details.USERNAME, "a".repeat(Validation.MAX_USERNAME_LENGTH));
}

@Test
public void resetPasswordSendsOneEmailDuringCooldown() {
String userId = consumerRealm.admin().users().search(USER_LOGIN).get(0).getId();

submitResetPasswordForm(USER_LOGIN);
EventAssertion.expectRequiredAction(events.poll())
.type(EventType.SEND_RESET_PASSWORD)
.userId(userId);
assertTrue(mailServer.waitForIncomingEmail(1));

// the username and the email are the same user, so they share the cooldown
submitResetPasswordForm(USER_EMAIL);
EventAssertion.assertError(events.poll())
.type(EventType.SEND_RESET_PASSWORD_ERROR)
.error(Errors.SLOW_DOWN)
.userId(userId)
.details(Details.USERNAME, USER_EMAIL);
assertFalse(mailServer.waitForIncomingEmail(1000, 2), "Unexpected email was received");

timeOffSet.set(EmailCooldownManager.EMAIL_RESEND_COOLDOWN_DEFAULT_SECONDS + 1);

submitResetPasswordForm(USER_LOGIN);
EventAssertion.expectRequiredAction(events.poll())
.type(EventType.SEND_RESET_PASSWORD)
.userId(userId);
assertTrue(mailServer.waitForIncomingEmail(2));
}

@Test
public void resetPasswordSendsEveryEmailWhenCooldownIsDisabled() {
configureEmailCooldown("0");

submitResetPasswordForm(USER_LOGIN);
submitResetPasswordForm(USER_LOGIN);

assertTrue(mailServer.waitForIncomingEmail(2));
}

@Test
public void resetPasswordUsesDefaultCooldownWhenValueIsInvalid() {
configureEmailCooldown("30s");

submitResetPasswordForm(USER_LOGIN);
submitResetPasswordForm(USER_LOGIN);

assertTrue(mailServer.waitForIncomingEmail(1));
assertFalse(mailServer.waitForIncomingEmail(1000, 2), "Unexpected email was received");
}

private void submitResetPasswordForm(String username) {
oauth.openLoginForm();
loginPage.assertCurrent();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword(username);
loginPage.assertCurrent();
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
}

private void configureEmailCooldown(String seconds) {
AuthenticationManagementResource flows = consumerRealm.admin().flows();
String executionId = flows.getExecutions(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW).stream()
.filter(e -> ResetCredentialEmail.PROVIDER_ID.equals(e.getProviderId()))
.findAny().orElseThrow().getId();
AuthenticatorConfigRepresentation config = new AuthenticatorConfigRepresentation();
config.setAlias("reset-email-cooldown");
config.setConfig(Map.of(EmailCooldownManager.EMAIL_RESEND_COOLDOWN_SECONDS, seconds));
String configId = ApiUtil.getCreatedId(flows.newExecutionConfig(executionId, config));
consumerRealm.cleanup().add(r -> r.flows().removeAuthenticatorConfig(configId));
}

static class ConsumerRealmConfig implements RealmConfig {
@Override
public RealmBuilder configure(RealmBuilder realm) {
Expand Down
17 changes: 17 additions & 0 deletions tests/base/src/test/java/org/keycloak/tests/i18n/EmailTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@

import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.authentication.authenticators.resetcred.ResetCredentialEmail;
import org.keycloak.authentication.requiredactions.util.EmailCooldownManager;
import org.keycloak.http.simple.SimpleHttp;
import org.keycloak.http.simple.SimpleHttpResponse;
import org.keycloak.models.UserModel;
Expand All @@ -47,6 +49,8 @@
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.realm.ManagedUser;
import org.keycloak.testframework.remote.runonserver.InjectRunOnServer;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.server.KeycloakUrls;
import org.keycloak.testframework.ui.annotations.InjectPage;
import org.keycloak.testframework.ui.annotations.InjectWebDriver;
Expand All @@ -67,6 +71,7 @@
import org.apache.http.message.BasicNameValuePair;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
Expand Down Expand Up @@ -121,6 +126,16 @@ public class EmailTest {
@InjectKeycloakUrls
KeycloakUrls keycloakUrls;

@InjectRunOnServer
RunOnServerClient runOnServer;

// the user is shared, so a reset email requested by the test before would stop the next one
@BeforeEach
public void clearEmailCooldown() {
String cooldownKey = EmailCooldownManager.getHashedCacheKey(ResetCredentialEmail.EMAIL_COOLDOWN_KEY_PREFIX, user.getId());
runOnServer.run(session -> session.singleUseObjects().remove(cooldownKey));
}

private void changeUserLocale(String locale) {
UserRepresentation userRep = user.admin().toRepresentation();
userRep.singleAttribute(UserModel.LOCALE, locale);
Expand Down Expand Up @@ -247,6 +262,8 @@ public void restPasswordEmailWithAcceptLanguageHeader() throws MessagingExceptio


private void sendResetPasswordEmail() {
// some tests request several emails in a row
clearEmailCooldown();
oauth.openLoginForm();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@

import org.keycloak.authentication.authenticators.browser.CookieAuthenticatorFactory;
import org.keycloak.authentication.authenticators.browser.UsernamePasswordFormFactory;
import org.keycloak.authentication.authenticators.resetcred.ResetCredentialEmail;
import org.keycloak.authentication.authenticators.sessionlimits.UserSessionLimitsAuthenticatorFactory;
import org.keycloak.authentication.requiredactions.util.EmailCooldownManager;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventType;
Expand Down Expand Up @@ -135,6 +137,9 @@ public void setup() {
// Reset password
UserModel user = session.users().getUserByUsername(realm, username);
user.credentialManager().updateCredential(UserCredentialModel.password(password));

// a reset email requested by the test before would stop the next one
session.singleUseObjects().remove(EmailCooldownManager.getHashedCacheKey(ResetCredentialEmail.EMAIL_COOLDOWN_KEY_PREFIX, user.getId()));
});

events.clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

import org.keycloak.authentication.authenticators.resetcred.ResetCredentialEmail;
import org.keycloak.authentication.requiredactions.util.EmailCooldownManager;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.RealmModel;
Expand Down Expand Up @@ -211,6 +213,13 @@ private void triggerForgetPasswordForUser(String usernameInput, int expectedCoun

String emailAddress = MailUtils.getRecipient(message);
Assertions.assertEquals(expectedEmail, emailAddress);

// the next email for the same user would not be sent during the cooldown
testingClient.server().run((KeycloakSession session) -> {
RealmModel realm = LDAPTestContext.init(session).getRealm();
UserModel user = session.users().getUserByUsername(realm, "johnkeycloak");
session.singleUseObjects().remove(EmailCooldownManager.getHashedCacheKey(ResetCredentialEmail.EMAIL_COOLDOWN_KEY_PREFIX, user.getId()));
});
}

private static void changeEmailAddressInLDAP(KeycloakTestingClient testingClient, String newEmail) {
Expand Down
Loading
Loading