Passwords and accounts

This documentation was generated with the assistance of AI. Please report any inaccuracies.

Password storage

Passwords are stored by a DelegatingPasswordEncoder whose default is Argon2id ({argon2@SpringSecurity_v5_8}); bcrypt and PBKDF2 hashes keep working. The encoder is a framework type, so it lives in api/web (PasswordConfiguration); the application layer reaches it through the PasswordHasher port of the domain.

    /**
     * Creates the password encoder: a delegating encoder whose default is Argon2, with bcrypt and PBKDF2 kept for
     * legacy hashes.
     *
     * @return the delegating password encoder.
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new DelegatingPasswordEncoder(DEFAULT_ENCODING_ID, Map.of(
                DEFAULT_ENCODING_ID, Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(),
                BCRYPT_ENCODING_ID, new BCryptPasswordEncoder(),
                PBKDF2_ENCODING_ID, Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()));
    }

After a successful sign-in with a legacy hash, the authentication provider (PasswordAuthenticationConfiguration, see Login pages and the BFF) re-encodes the verified password with the default algorithm and hands the new hash to UserAccountUserDetailsService, which is also a UserDetailsPasswordService. It stores the hash through UpgradePasswordHashUseCase.replaceHash, so existing users migrate without a reset.

    @Override
    public UserDetails updatePassword(final UserDetails user, final String newPassword) {
        final var account = findUserAccountUseCase.execute(user.getUsername())
                .orElseThrow(() -> new UsernameNotFoundException("User not found: " + user.getUsername()));
        upgradePasswordHashUseCase.replaceHash(account, newPassword);
        return userDetailsMapper.toUserDetails(account, newPassword);
    }
    /**
     * Stores a password hash that was already produced by the current algorithm, as the authentication framework
     * does after a sign-in (it re-encodes the verified clear-text password itself).
     *
     * @param account         the account that just signed in.
     * @param encodedPassword the new encoded password.
     */
    public void replaceHash(final UserAccount account, final String encodedPassword) {
        userAccountRepository.updatePassword(account.id(), encodedPassword);
    }

Password policy and compromised passwords

PasswordPolicy (module domain) requires between 12 and 128 characters. New passwords are also checked against the Have I Been Pwned range API (only a hash prefix leaves the server) through the CompromisedPasswordCheck port. The check is on by default; set authserver.password.compromised-check.enabled=false to turn it off, for example offline. Tests mock the port.

    /**
     * Finds the rules a candidate password breaks.
     *
     * @param username name of the account the password is for; the username rule is skipped when it is {@code null}
     *                 or blank.
     * @param password the candidate password; {@code null} is treated as an empty password.
     * @return the broken rules, empty when the password is acceptable.
     */
    public List<PasswordViolation> violations(final String username, final String password) {
        final var candidate = password == null ? "" : password;
        final var violations = new ArrayList<PasswordViolation>();
        final var length = candidate.codePointCount(0, candidate.length());
        if (length < MIN_LENGTH) {
            violations.add(PasswordViolation.TOO_SHORT);
        }
        if (length > MAX_LENGTH) {
            violations.add(PasswordViolation.TOO_LONG);
        }
        if (!isBlank(username)
                && candidate.toLowerCase(Locale.ROOT).contains(username.toLowerCase(Locale.ROOT))) {
            violations.add(PasswordViolation.CONTAINS_USERNAME);
        }
        return List.copyOf(violations);
    }

    /**
     * Tells whether a candidate password follows every rule.
     *
     * @param username name of the account the password is for.
     * @param password the candidate password.
     * @return {@code true} when no rule is broken.
     */
    public boolean isValid(final String username, final String password) {
        return violations(username, password).isEmpty();
    }
    /**
     * Creates the check backed by the Have I Been Pwned range API.
     *
     * @return the enabled check.
     */
    @Bean
    @ConditionalOnProperty(name = ENABLED_PROPERTY, havingValue = "true", matchIfMissing = true)
    public CompromisedPasswordCheck haveIBeenPwnedCompromisedPasswordCheck() {
        return new SpringCompromisedPasswordCheck(new HaveIBeenPwnedRestApiPasswordChecker());
    }

    /**
     * Creates the no-op check used when the property disables the check.
     *
     * @return a check that never reports a password as compromised.
     */
    @Bean
    @ConditionalOnProperty(name = ENABLED_PROPERTY, havingValue = "false")
    public CompromisedPasswordCheck noOpCompromisedPasswordCheck() {
        return password -> false;
    }

Account API

AccountController exposes the account operations under /api/account. They are defined by the contract apis/auth-server/rest-server/auth-server-api-v1.yaml: AccountController implements the AccountApi interface generated from it (see apis/README.md).

Endpoint Access Behavior

POST /api/account/register

Public, rate limited

Creates a disabled-until-verified account and e-mails a verification link (a signed JWT). The answer is always the same 202 (see Registration never reveals a taken address or username). If the e-mail cannot be sent, nothing is registered and the answer is 503.

GET /api/account/verify

Public, rate limited

Verifies the e-mail address with the token from the link and enables the account. A link works once: replayed, even before it expires, it is answered as an invalid token, so it can never re-enable an account that was disabled after its verification.

POST /api/account/password

Bearer token for the API audience

Changes the password of the caller after checking the current one, and revokes every authorization of the user in the same transaction.

POST /api/account/password/reset-request

Public, rate limited

E-mails a reset link to a registered address. An unknown address is never mailed, so the endpoint cannot be used to send mail to arbitrary addresses; it costs the same token work and gets the same 202, even when a link cannot be delivered.

POST /api/account/password/reset

Public, rate limited

Sets a new password with a single-use reset token and revokes every authorization of the user. Every check (token, password policy including the username rule, compromised-password check) runs before the token is consumed, so a rejected password does not use up the link.

The reset token is a random opaque value stored only as a hash, with an expiry and a used timestamp, in the account_tokens table (see Data model). ExpiredAccountTokenCleanupJob deletes the expired ones (authserver.account.cleanup.cron, default 0 30 * * * *).

Transactions are demarcated by the use cases, never by the adapters: every use case is @Transactional (readOnly = true when it only reads), and an architecture test fails the build when one is not. So the new password hash and the revocation of the user’s authorizations, the consumed reset token and the new hash, the new account and its e-mail each commit or roll back together. The mail adapter reports a delivery failure as an AccountMailException (never the mail framework’s own type), so the transaction rolls back and nothing is left for a message that was never sent.

Registration never reveals a taken address or username

The answer of POST /api/account/register is the same in every case, and the password is always hashed, so neither the answer nor its timing tells whether the address or the username exists. What the address receives differs only where its owner learns nothing new:

  • a registered address gets an "already registered" message: its owner already knows it has an account;

  • a new address with a taken username gets the usual verification message, but its token names no account, so following the link fails exactly like an expired one. Nothing is created, and the username is never confirmed to whoever controls the address.

    /**
     * Registers an account.
     *
     * @param username name the user will sign in with.
     * @param email    e-mail address of the user.
     * @param password the chosen clear-text password.
     * @throws InvalidPasswordException     if the password breaks the policy.
     * @throws CompromisedPasswordException if the password is known to be compromised.
     */
    @Transactional
    public void execute(final String username, final String email, final String password) {
        final var violations = passwordPolicy.violations(username, password);
        if (!violations.isEmpty()) {
            throw new InvalidPasswordException(violations);
        }
        if (compromisedPasswordCheck.isCompromised(password)) {
            throw new CompromisedPasswordException("The chosen password is known to be compromised");
        }
        // hashed in every case, so that a taken address or username costs the same as a new one
        final var encodedPassword = passwordHasher.encode(password);
        if (userAccountRepository.findByEmail(email).isPresent()) {
            accountMailer.sendAlreadyRegistered(email);
            return;
        }
        final var id = UUID.randomUUID();
        // issued in every remaining case; with a taken username it names no account and verifies nothing
        final var token = signedTokenService.issue(id.toString(), AccountToken.PURPOSE_EMAIL_VERIFICATION,
                VERIFICATION_TTL);
        if (!userAccountRepository.existsByUsername(username)) {
            userAccountRepository.save(new UserAccount(id, username, encodedPassword, false,
                    List.of(DEFAULT_AUTHORITY), email, false, UserAccount.DEFAULT_TENANT));
        }
        accountMailer.sendEmailVerification(email, token);
    }
    /**
     * Requests a password reset.
     *
     * @param email e-mail address of the user.
     */
    @Transactional
    public void execute(final String email) {
        final var token = tokenGenerator.generate();
        final var hashedToken = tokenGenerator.hash(token);
        // an unknown address gets nothing: the token above was generated and hashed all the same
        userAccountRepository.findByEmail(email)
                .ifPresent(account -> sendReset(account, email, token, hashedToken));
    }

    /**
     * Stores the reset token and mails it.
     *
     * @param account     the account to reset.
     * @param email       address to send the message to.
     * @param token       the reset token.
     * @param hashedToken hash of the reset token.
     */
    private void sendReset(final UserAccount account, final String email, final String token,
                           final String hashedToken) {
        accountTokenRepository.store(new AccountToken(UUID.randomUUID(), account.id(),
                AccountToken.PURPOSE_PASSWORD_RESET, hashedToken, clock.instant().plus(RESET_TTL), null));
        accountMailer.sendPasswordReset(email, token);
    }
    /**
     * Resets the password of the user the token was issued to. The token is looked up without being consumed, every
     * check runs, and only then is the token consumed; the consumption is atomic, so of two concurrent resets with
     * the same token only one succeeds.
     *
     * @param token       the reset token received by e-mail.
     * @param newPassword the clear-text new password.
     * @throws InvalidPasswordException     if the password breaks the policy.
     * @throws CompromisedPasswordException if the password is known to be compromised.
     * @throws InvalidAccountTokenException if the token is unknown, expired, used or its account is gone.
     */
    @Transactional
    public void execute(final String token, final String newPassword) {
        final var hashedToken = tokenGenerator.hash(token);
        final var now = clock.instant();
        final var stored = accountTokenRepository
                .findUsable(hashedToken, AccountToken.PURPOSE_PASSWORD_RESET, now)
                .orElseThrow(InvalidAccountTokenException::new);
        final var account = userAccountRepository.findById(stored.userId())
                .orElseThrow(InvalidAccountTokenException::new);
        requirePolicy(account.username(), newPassword);
        requireNotCompromised(newPassword);
        accountTokenRepository.consume(hashedToken, AccountToken.PURPOSE_PASSWORD_RESET, now)
                .orElseThrow(InvalidAccountTokenException::new);
        userAccountRepository.updatePassword(account.id(), passwordHasher.encode(newPassword));
        revokeUserAuthorizationsUseCase.execute(account.username());
    }
    /** Statement that marks a token as used and returns it, only when it is unused and not expired. */
    private static final String CONSUME_TOKEN = """
            UPDATE account_tokens SET used_at = ?
            WHERE hashed_token = ? AND purpose = ? AND used_at IS NULL AND expires_at > ?
            RETURNING id, user_id, purpose, hashed_token, expires_at, used_at
            """;

The verification is effective once because the persistence adapter only flips an unverified address:

    /**
     * Statement that verifies the e-mail address and enables the account, only while the address is still
     * unverified: a verification link is effective once, so replaying it cannot re-enable an account that was
     * disabled afterwards.
     */
    private static final String MARK_EMAIL_VERIFIED = """
            UPDATE users SET email_verified = TRUE, enabled = TRUE, updated_at = CURRENT_TIMESTAMP
            WHERE id = ? AND email_verified = FALSE
            """;

Rate limiting

The unauthenticated account endpoints (register, verify, reset request, reset) are rate limited by AccountRateLimiter in api/web, built on Bucket4j token buckets: one bucket per client address and, when the request names one, one per e-mail address, each refilled in full at the end of every window, so neither a single client nor many clients aiming at one address can flood mailboxes or guess reset tokens. A request over a limit gets 429 Too Many Requests, a problem detail (urn:problem:account:rate-limited) and a Retry-After header in seconds. The buckets are kept in a Caffeine cache bounded per kind of key, which also drops a bucket idle for a whole window. They are in memory, so each instance applies the limits on its own; Bucket4j’s ProxyManager (for example bucket4j-postgresql) can move them to a shared store when several instances run. The client address is request.getRemoteAddr(), so behind a reverse proxy set server.forward-headers-strategy.

Property Default Meaning

authserver.account.rate-limit.enabled

true

Whether the limits apply at all.

authserver.account.rate-limit.window

PT15M

Length of the window the requests are counted in.

authserver.account.rate-limit.per-client

20

Requests one client address may make in a window.

authserver.account.rate-limit.per-email

5

Requests that may name one e-mail address in a window.

authserver.account.rate-limit.max-tracked-keys

10000

Buckets kept at most per kind of key.

/**
 * Rate limiter of the unauthenticated account endpoints (register, verify, reset request, reset), built on
 * <a href="https://bucket4j.com">Bucket4j</a> token buckets ({@link FixedWindowBuckets}). Requests are limited twice:
 * per client address, and per e-mail address when the request names one, so neither a single client nor many clients
 * aiming at one address can flood the server (and the mailboxes) with account mail or guess reset tokens. Each bucket
 * holds the limit of its key and is refilled all at once every {@link AccountRateLimitProperties#window()}.
 *
 * <p>The buckets of each kind of key live in a Caffeine cache bounded to
 * {@link AccountRateLimitProperties#maxTrackedKeys()} entries, which also drops a bucket idle for a whole window
 * (it would be full again anyway). They live in this instance only: several instances each apply the limits on
 * their own, until the buckets move to a shared store through a Bucket4j {@code ProxyManager} (for example
 * {@code bucket4j-postgresql}). The client address is {@code request.getRemoteAddr()}, so behind a proxy
 * {@code server.forward-headers-strategy} must be set for it to be the real client.
 */
@Component
@EnableConfigurationProperties(AccountRateLimitProperties.class)
public final class AccountRateLimiter {

    /** Limits, window and bound of the tracked keys. */
    private final AccountRateLimitProperties properties;

    /** Buckets per client address. */
    private final FixedWindowBuckets clients;

    /** Buckets per (lower-cased) e-mail address. */
    private final FixedWindowBuckets emails;

    /**
     * Creates the limiter.
     *
     * @param properties limits, window and bound of the tracked keys.
     * @param clock      source of the current time.
     */
    public AccountRateLimiter(final AccountRateLimitProperties properties, final Clock clock) {
        this.properties = properties;
        clients = new FixedWindowBuckets(clock, properties.window(), properties.maxTrackedKeys());
        emails = new FixedWindowBuckets(clock, properties.window(), properties.maxTrackedKeys());
    }

    /**
     * Counts one request and rejects it once a limit is exceeded.
     *
     * @param clientAddress address of the calling client.
     * @param email         e-mail address the request names, or {@code null}.
     * @throws AccountRateLimitExceededException if the client or the e-mail address exceeded its limit.
     */
    public void check(final String clientAddress, final String email) {
        if (!properties.enabled()) {
            return;
        }
        consume(clients, clientAddress, properties.perClient());
        if (email != null) {
            consume(emails, email.toLowerCase(Locale.ROOT), properties.perEmail());
        }
    }

    /**
     * Tells how many keys of each kind are tracked, after any pending eviction.
     *
     * @return the number of client keys plus the number of e-mail keys.
     */
    long trackedKeys() {
        return clients.trackedKeys() + emails.trackedKeys();
    }

    /**
     * Takes one token from the bucket of a key, creating the bucket on first use.
     *
     * @param buckets buckets of one kind of key.
     * @param key     the key.
     * @param limit   requests the key may make per window.
     * @throws AccountRateLimitExceededException if the bucket is empty.
     */
    private static void consume(final FixedWindowBuckets buckets, final String key, final int limit) {
        final var wait = buckets.tryConsume(key, limit);
        if (wait.isPresent()) {
            throw new AccountRateLimitExceededException(wait.get());
        }
    }
}