Skip to content

Add REST endpoints for the login challenge and revalidation - #1045

Open
chubes4 wants to merge 3 commits into
WordPress:masterfrom
chubes4:feat/rest-login-challenge
Open

chubes4 wants to merge 3 commits into
WordPress:masterfrom
chubes4:feat/rest-login-challenge

Conversation

@chubes4

@chubes4 chubes4 commented Nov 17, 2026 •

Copy link
Copy Markdown

What?

Lets any authentication integration complete Two-Factor without a stock wp-login.php or Two Factor screen, including clients that authenticate with bearer tokens (native and headless apps) rather than cookies:

  • Two_Factor_Core::verify_authentication_code( WP_User $user, string $provider_key, array $args ): public, non-rendering verification. Returns true, array( 'status' => 'code_sent' ) after a resend, or a structured WP_Error.
  • Two_Factor_Core::get_login_challenge( WP_User $user ): returns { provider, providers: [{ key, label }] } for the challenge prompt.
  • two_factor_current_session_two_factor_time filter (int|false $time, WP_User $user): lets non-cookie sessions report when they passed two-factor. It drives the revalidation grace checks, so token sessions can manage settings (Add REST provider management and server-owned TOTP enrollment #935) and revalidate.
  • POST /two-factor/1.0/login: the cookie login route, which completes the second factor for a pending login using the login nonce.
  • POST /two-factor/1.0/revalidate: revalidates the current session, cookie or token.
  • Revalidation-required REST errors now carry data.revalidation = { required: true, rest_route: '/two-factor/1.0/revalidate', url } and status 403.

Fixes #1044

Why?

Today the second factor can only be completed on wp-login.php?action=validate_2fa, and changing settings outside the grace window needs wp-login.php?action=revalidate_2fa. Sites that keep members away from stock WordPress screens either expose those screens just for 2FA or re-implement nonce checks, rate limiting, failed-attempt accounting and session flags themselves.

The first version of this PR only covered cookie clients. A native app that authenticates with bearer tokens can't use a route that sets a cookie. It needs a verification call that returns data instead of rendering a page. And current_user_can_update_two_factor_options() only reads cookie session metadata, so a token session could never manage settings or revalidate (it got two_factor_session_required). The expanded scope is described in #1044 (comment).

This complements #935 (REST provider management and server-owned TOTP enrollment, #934). With the filter, a token session can call #935's routes, and when the grace window has passed it can revalidate in place through /revalidate.

How?

One verification path

  • process_provider_attempt() (private) holds the rate limiting, pre-processing (resend), validation, failed-attempt accounting, wp_login_failed and the compromised-password reset. Nothing is rendered there.
    • The login and revalidation forms reach it through process_provider(). Providers read the form fields as before.
    • verify_authentication_code() passes the code and resend in as arguments. Providers receive them through validate_authentication_code() and pre_process_authentication_with_args().
    • The REST routes call verify_authentication_code().
  • wp_login_failed now fires inside process_provider_attempt() for invalid and rate-limited attempts, instead of in each caller. The forms fire it exactly as before, and the REST routes and direct callers now get it too.
  • In the compromised-password case it returns two_factor_password_reset_required. process_provider() still renders show_password_reset_error() and exits for the form path, so form behavior and messages are unchanged.
  • Login completion (complete_two_factor_login()) and revalidation bookkeeping (complete_two_factor_revalidation()) are shared by the forms and the REST handlers.

verify_authentication_code() contract

$args: code (string), resend (bool). Nothing is read from $_REQUEST, nothing is output, and it never exits. An empty $provider_key uses the primary provider. A requested provider the user hasn't enabled is an error, not a silent fallback.

Result Meaning
true Code valid. The caller completes the login (issues its session or token).
array( 'status' => 'code_sent' ) The provider sent a new code (email resend). Not counted as a failure.
two_factor_invalid (401) Wrong code. Failure recorded, wp_login_failed fired.
two_factor_too_fast (429) Rate limited. data.retry_after in seconds. Attempt not counted.
two_factor_provider_not_enabled (400) Requested provider isn't enabled for the user. Not counted.
two_factor_password_reset_required (403) Failed-attempt limit reached while logged out. The password was reset and emails sent, as in the form.
two_factor_provider_missing (403) The user has no usable provider.

It must only be called after the user's password (or other primary credential) has been verified.

Non-cookie sessions

get_current_session_two_factor_time() defaults to the cookie session's two-factor-login metadata and applies two_factor_current_session_two_factor_time. If nothing hooks the filter, behavior is unchanged. A token plugin returns the time its session passed or last revalidated two-factor, 0 for a known session that hasn't passed two-factor yet (it may still revalidate), or false for no session. is_current_user_session_two_factor(), and with it current_user_can_update_two_factor_options() and maybe_mark_current_session_two_factor(), read the filtered value.

/revalidate accepts a request that has a cookie session or a non-false filtered time. Other requests (for example application passwords, or tokens nobody reports) still get 400 two_factor_session_required. On success it fires two_factor_user_revalidated( $user, $provider ), which is where token plugins record the new time. The cookie session metadata is only updated when a cookie session exists. update_current_user_session() now returns false instead of erroring when the token has no stored session.

Endpoint contract

POST /two-factor/1.0/login (public; the login nonce is the credential): user_id, login_nonce, optional provider, code, resend, remember, redirect_to.

Outcome Response
Unknown user, missing/expired/mismatched nonce 401 two_factor_invalid_login_nonce, one message for all cases, no new nonce
No code and no resend 200 {result: "challenge", user_id, provider, providers: [{key, label}], login_nonce, expires}
resend handled by the provider 200 {result: "code_sent", ...same fields}
Wrong code 401 two_factor_invalid, data.login_nonce/data.expires
Rate limited 429 two_factor_too_fast, data.retry_after + Retry-After header, new nonce
Requested provider not enabled 400 two_factor_provider_not_enabled + new nonce
Failed-attempt limit reached 403 two_factor_password_reset_required; pending login nonce deleted
Success 200 {result: "authenticated", user_id, provider, redirect_to} plus auth cookies

Every non-success response after the nonce is verified rotates the nonce, as the form does when it re-renders. redirect_to goes through the form's login_redirect and capability fallback, then wp_validate_redirect().

POST /two-factor/1.0/revalidate (logged in): optional provider, code, resend. Returns 401 rest_not_logged_in when logged out and 400 two_factor_session_required as described above. It gives the same challenge, code_sent and error responses as /login, without nonce fields. On success it returns 200 {result: "revalidated", user_id, provider, two_factor_login}. Cookie-authenticated REST requests already require the wp_rest nonce, which replaces the form's revalidation nonce.

Provider methods (backwards compatible)

  • validate_authentication_code( $user, $code ): the default falls back to validate_authentication( $user ), so third-party providers keep working. TOTP, Email and Recovery Codes override it and normalize the code the same way their form fields do.
  • pre_process_authentication_with_args( $user, $args ): the default falls back to pre_process_authentication(). Email sends a new code when resend is true.
  • Two_Factor_Provider::sanitize_code(): the value-based counterpart of sanitize_code_from_request().

Security parity

  • Same nonce verification and failure logging as the form. Responses don't reveal whether a user exists, and the provider list only appears after the nonce or session is verified.
  • Same rate limiting (resend included), backoff, failure counter and compromised-password reset. A logged-in revalidation never resets the password, same as the form.
  • The filter is a trust boundary. Only the authentication plugin that owns the current request should hook it.
  • One deliberate difference: after a compromised-password reset, /login deletes the pending login nonce. The form path is unchanged.

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude
Used for: Repository investigation, implementation, tests, and PR drafting. The shared path was checked against the existing form handlers, provider methods and form-flow tests.

Testing Instructions

tests/class-two-factor-rest-login-api.php covers /login and /revalidate. New for token sessions:

  • revalidation through the filter succeeds and fires two_factor_user_revalidated with no cookie session
  • a filtered 0 (not yet two-factor) may revalidate
  • a wrong code fires wp_login_failed and not the revalidated action
  • without the filter, a non-cookie request is still refused with two_factor_session_required

New tests/class-two-factor-verification-api.php covers:

  • verify_authentication_code(): success with no output and no login, primary-provider default, $_REQUEST ignored, invalid (401, failure counted, wp_login_failed), rate limited (429 + retry_after, not counted), provider not enabled (400), password reset required (403, password changed, no output), and email resend (code_sent, then the code validates)
  • get_login_challenge() with and without two-factor
  • the filter: the cookie value is the default and is passed to the filter; a simulated token session (no cookie session, filter returns time()) can DELETE /two-factor/1.0/totp, which without the filter fails with 403 revalidation_required carrying data.revalidation.rest_route; the grace window still applies to the filtered time

The existing form-flow tests (process_provider, validate_login_form_2fa, revalidate_login_form_2fa) pass unchanged.

Run in wp-env:

  • composer test-single: OK (396 tests, 1568 assertions)
  • composer test-multisite: OK (396 tests, 1568 assertions)
  • composer lint (PHPCS), composer lint-phpstan, composer lint-compat (PHP 7.2+): pass

Manual (token integration): after verifying the password, call Two_Factor_Core::get_login_challenge( $user ), show the prompt, then Two_Factor_Core::verify_authentication_code( $user, $provider, array( 'code' => $code ) ) and issue your token on true. Hook two_factor_current_session_two_factor_time to return your session's verified-at time, and two_factor_user_revalidated to update it.

Changelog Entry

Added - A non-rendering two-factor verification API, a session time filter for non-cookie sessions, and REST endpoints to complete the login challenge and revalidate without the wp-login.php screens.

Written directly by Extra Chill Bot (AI agent) for Chris Huber.

Open WordPress Playground Preview

Adds POST /two-factor/1.0/login and POST /two-factor/1.0/revalidate so
custom front-ends can complete the second factor and revalidate a session
without the wp-login.php screens. Both run through the same provider
processing as the forms; providers receive REST codes through
validate_authentication_code() with a request-based fallback.

Fixes WordPress#1044
@github-actions

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Unlinked Accounts

The following contributors have not linked their GitHub and WordPress.org accounts: @chubes4.

Contributors, please read how to link your accounts to ensure your work is properly credited in WordPress releases.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Unlinked contributors: chubes4.


To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

Two_Factor_Core::verify_authentication_code() verifies a code for any
authentication integration (bearer tokens, headless logins) with the same
processing as the forms, returning true, a code_sent result, or a WP_Error.
get_login_challenge() describes the challenge. The
two_factor_current_session_two_factor_time filter lets non-cookie sessions
report when they passed two-factor, so they can manage settings and use
POST /revalidate. Revalidation-required errors carry data.revalidation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

REST endpoints for completing the login challenge and revalidation

1 participant