Skip to content
Merged
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`, default value, always force re-authentication, `false`, keep the user logged in if the same browser was used, `only-federated`, force 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 @@ -698,6 +698,12 @@ The emails are sent by the `email` executor. It has 4 threads by default and sta
Custom email template providers, including ones that extend `FreeMarkerEmailTemplateProvider`, still send the email right away, so for them the response time still depends on the mail server.
To send it in the background, a provider that extends `FreeMarkerEmailTemplateProvider` can override `supportsBackgroundDelivery()`. Other providers need to implement `EmailTemplateProvider.renderPasswordReset` and `send(RenderedEmail, int, EmailDeliveryListener)`.

=== 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 @@ -78,6 +79,9 @@ 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-";
private static final String EMAIL_COOLDOWN_UNKNOWN_USER_KEY_PREFIX = "reset-credential-email-cooldown-unknown-";
private static final int EMAIL_COOLDOWN_UNKNOWN_USER_KEYS = 10000;

@Override
public void authenticate(AuthenticationFlowContext context) {
Expand Down Expand Up @@ -107,6 +111,7 @@ public void authenticate(AuthenticationFlowContext context) {
.error(Errors.INVALID_EMAIL);
}
UserModel recipient = deliverable ? user : dummyUser(context, username);
boolean inCooldown = !startEmailCooldown(context, user, username);
Comment thread
gaoyikeshuer marked this conversation as resolved.
Resolved

int validityInSecs = context.getRealm().getActionTokenGeneratedByUserLifespan(ResetCredentialsActionToken.TOKEN_TYPE);
int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;
Expand All @@ -122,7 +127,9 @@ public void authenticate(AuthenticationFlowContext context) {
try {
EmailTemplateProvider emailTemplateProvider = context.getSession().getProvider(EmailTemplateProvider.class).setRealm(context.getRealm()).setUser(recipient).setAuthenticationSession(authenticationSession);
RenderedEmail email = emailTemplateProvider.renderPasswordReset(link, expirationInMinutes);
if (deliverable) {
if (deliverable && inCooldown) {
failedEvent(event, user, username).error(Errors.SLOW_DOWN);
} else if (deliverable) {
if (email == null) {
// this provider can only send right away
emailTemplateProvider.sendPasswordReset(link, expirationInMinutes);
Expand All @@ -140,6 +147,15 @@ public void authenticate(AuthenticationFlowContext context) {
context.forkWithSuccessMessage(new FormMessage(Messages.EMAIL_SENT));
}

// unknown users share a fixed number of entries, picked from the typed name, so a repeated request does the same work as for a known user
private static boolean startEmailCooldown(AuthenticationFlowContext context, UserModel user, String username) {
if (user != null) {
return EmailCooldownManager.addCooldownEntryIfAbsent(context, EMAIL_COOLDOWN_KEY_PREFIX, user.getId());
}
int entry = Math.floorMod(Objects.hashCode(KeycloakModelUtils.toLowerCaseSafe(username)), EMAIL_COOLDOWN_UNKNOWN_USER_KEYS);
return EmailCooldownManager.addCooldownEntryIfAbsent(context, EMAIL_COOLDOWN_UNKNOWN_USER_KEY_PREFIX, String.valueOf(entry));
}

private static UserModel dummyUser(AuthenticationFlowContext context, String username) {
UserModel user = new InMemoryUserAdapter(context.getSession(), context.getRealm(), KeycloakModelUtils.generateId());
user.setUsername(username == null ? "unknown" : username);
Expand Down Expand Up @@ -257,6 +273,13 @@ If this property is true (default), the user needs to login again after the rese
.options(Arrays.asList(Boolean.TRUE.toString(), Boolean.FALSE.toString(), FEDERATED_OPTION))
.defaultValue(Boolean.TRUE.toString())
.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
Expand Up @@ -2,6 +2,8 @@

import java.util.List;

import org.keycloak.authentication.authenticators.resetcred.ResetCredentialEmail;
import org.keycloak.authentication.requiredactions.util.EmailCooldownManager;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.testframework.annotations.InjectUser;
Expand All @@ -19,6 +21,8 @@
import org.keycloak.tests.common.TestRealmUserConfig;
import org.keycloak.testsuite.util.FlowUtil;

import org.junit.jupiter.api.BeforeEach;

@KeycloakIntegrationTest
public abstract class AbstractResetCredentialsAlternativeFlowsTest extends AbstractAppInitiatedActionTest {

Expand All @@ -40,6 +44,13 @@ public abstract class AbstractResetCredentialsAlternativeFlowsTest extends Abstr
@InjectPage
protected LoginPasswordResetPage resetPasswordPage;

// 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, managedUser.getId());
runOnServer.run(session -> session.singleUseObjects().remove(cooldownKey));
}

void revertResetCredentialsFlows() {
runOnServer.run(session -> {
AuthenticationFlowModel alternativeResetCredentialsFlow = session.getContext().getRealm().getResetCredentialsFlow();
Expand Down
Loading
Loading