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
6 changes: 6 additions & 0 deletions assets/src/js/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ const wpGoogleLogin = {
}

this.googleLoginButton = this.form.querySelector( '.wp_google_login' );

// Some screens reuse the form ID without the button, e.g. Two-Factor's challenge form.
if ( null === this.googleLoginButton ) {
return;
}

this.googleLoginButton.classList.remove( 'hidden' );
// HTML is cloned from existing HTML node.
this.form.append( this.googleLoginButton );
Expand Down
53 changes: 36 additions & 17 deletions src/Modules/Login.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

use WP_User;
use WP_Error;
use stdClass;
use Throwable;
use Exception;
use RtCamp\GoogleLogin\Utils\Helper;
Expand Down Expand Up @@ -53,6 +52,14 @@ class Login implements ModuleInterface {
*/
private $authenticated = false;

/**
* Redirect URL from the OAuth state, set once the user
* has been authenticated from plugin.
*
* @var string
*/
private $redirect_to = '';

/**
* Login constructor.
*
Expand Down Expand Up @@ -88,11 +95,14 @@ public function init(): void {
add_action( 'authenticate', [ $this, 'authenticate' ], 20 );
add_action( 'rtcamp.google_register_user', [ $this->authenticator, 'register' ] );
add_action( 'rtcamp.google_user_created', [ $this, 'user_meta' ] );
add_action( 'wp_login', [ $this, 'login_redirect' ] );

/**
* Filters.
*/
// Redirect via filter instead of `wp_login` so other `wp_login` callbacks (e.g. Two-Factor) can run.
// Runs early (priority 1) so the state destination acts as the initial value, as `redirect_to` does
// for password logins in wp-login.php, and other `login_redirect` filters can still override it.
add_filter( 'login_redirect', [ $this, 'login_redirect' ], 1 );
add_filter( 'rtcamp.google_redirect_url', [ $this, 'redirect_url' ] );
add_filter( 'rtcamp.google_login_state', [ $this, 'state_redirect' ] );
add_filter( 'login_message', [ $this, 'filter_login_message' ] );
Expand Down Expand Up @@ -168,6 +178,20 @@ public function authenticate( $user = null ) {
if ( $user instanceof WP_User ) {
$this->authenticated = true;

if ( ! empty( $decoded_state['redirect_to'] ) && is_string( $decoded_state['redirect_to'] ) ) {
// Same sanitization and allowed-host validation as wp_safe_redirect().
$this->redirect_to = wp_validate_redirect( wp_sanitize_redirect( $decoded_state['redirect_to'] ), '' );

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking, and older than this PR, but this PR now owns redirect handling, so flagging it here. state_redirect() (L245) reads redirect_to with FILTER_SANITIZE_FULL_SPECIAL_CHARS, so a target like https://example.com/page/?a=1&b=2 is stored in the state as ?a=1&b=2. wp_sanitize_redirect() keeps &, ; and letters, so we end up redirecting to a URL where the second param is named amp;b.

Helper::get_redirect_url() already uses FILTER_SANITIZE_URL for the same param. Could we switch state_redirect() to that, here or in a follow-up issue? wp_validate_redirect() here already handles the safety side.

}

if ( $this->redirect_to ) {
/*
* Deliberately set the requested redirect for this request. Two-Factor copies it into its
* challenge form, which carries it to the `validate_2fa` request; without this, 2FA users
* lose the destination. Slashed to match core's superglobals (Two-Factor unslashes it).
*/
$_REQUEST['redirect_to'] = wp_slash( $this->redirect_to );
}

/**
* Fires once the user has been authenticated via Google OAuth.
*
Expand Down Expand Up @@ -224,7 +248,8 @@ public function redirect_url( string $url ): string {
* @return array
*/
public function state_redirect( array $state ): array {
$redirect_to = Helper::filter_input( INPUT_GET, 'redirect_to', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
// FILTER_SANITIZE_URL keeps `&` intact (FULL_SPECIAL_CHARS turns it into `&`); `$options` must be an int.
$redirect_to = Helper::filter_input( INPUT_GET, 'redirect_to', FILTER_SANITIZE_URL, 0 );
/**
* Filter the default redirect URL in case redirect_to param is not available.
* Default to admin URL.
Expand All @@ -237,24 +262,18 @@ public function state_redirect( array $state ): array {
}

/**
* Add a redirect once user has been authenticated successfully.
* Redirect to the URL from state once user has been authenticated successfully.
*
* @return void
* @param string $redirect_to Redirect destination URL.
*
* @return string
*/
public function login_redirect(): void {
$state = Helper::filter_input( INPUT_GET, 'state', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

if ( ! $state || ! $this->authenticated ) {
return;
public function login_redirect( $redirect_to ) {
if ( ! $this->authenticated || empty( $this->redirect_to ) ) {
return $redirect_to;
}

$state = base64_decode( $state );
$state = $state ? json_decode( $state ) : null;

if ( ( $state instanceof stdClass ) && ! empty( $state->provider ) && 'google' === $state->provider && ! empty( $state->redirect_to ) ) {
wp_safe_redirect( $state->redirect_to, 302, 'Login with Google' );
exit;
}
return $this->redirect_to;
}

/**
Expand Down
164 changes: 157 additions & 7 deletions tests/php/Unit/Modules/LoginTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ public function setUp(): void {
$this->testee = new Testee( $this->ghClientMock, $this->authenticatorMock );
}

/**
* Run after each test.
*
* @return void
*/
public function tearDown(): void {
// Login::authenticate() sets this superglobal; clear it even when an assertion fails.
unset( $_REQUEST['redirect_to'] );

parent::tearDown();
}

/**
* @covers ::name
*/
Expand All @@ -78,7 +90,7 @@ public function testInit() {
WP_Mock::expectActionAdded( 'authenticate', [ $this->testee, 'authenticate' ], 20 );
WP_Mock::expectActionAdded( 'rtcamp.google_register_user', [ $this->authenticatorMock, 'register' ] );
WP_Mock::expectActionAdded( 'rtcamp.google_user_created', [ $this->testee, 'user_meta' ] );
WP_Mock::expectActionAdded( 'wp_login', [ $this->testee, 'login_redirect' ] );
WP_Mock::expectFilterAdded( 'login_redirect', [ $this->testee, 'login_redirect' ], 1 );
WP_Mock::expectFilterAdded( 'rtcamp.google_redirect_url', [ $this->testee, 'redirect_url' ] );
WP_Mock::expectFilterAdded( 'rtcamp.google_login_state', [ $this->testee, 'state_redirect' ] );

Expand Down Expand Up @@ -431,7 +443,8 @@ public function testStateRedirectWithRedirectTo() {
[
INPUT_GET,
'redirect_to',
FILTER_SANITIZE_FULL_SPECIAL_CHARS
FILTER_SANITIZE_URL,
0
]
)->andReturn( 'https://example.com/state-page' );

Expand All @@ -450,7 +463,8 @@ public function testStateRedirectWithoutRedirectTo() {
[
INPUT_GET,
'redirect_to',
FILTER_SANITIZE_FULL_SPECIAL_CHARS
FILTER_SANITIZE_URL,
0
]
)->andReturn( null );

Expand All @@ -470,17 +484,153 @@ public function testStateRedirectWithoutRedirectTo() {
/**
* @covers ::login_redirect
*/
public function testLoginRedirectWithNotStateAuthenticated() {
public function testLoginRedirectWhenNotAuthenticated() {
$data = $this->testee->login_redirect( 'https://example.com/wp-admin/' );
$this->assertSame( 'https://example.com/wp-admin/', $data );
}

/**
* @covers ::authenticate
* @covers ::login_redirect
*/
public function testLoginRedirectUsesStateRedirectAfterAuthentication() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add the negative case as well: wp_validate_redirect() returns '' for a host that isn't allowed (e.g. https://evil.example/). In that case we should assert that:

  • $_REQUEST['redirect_to'] is not set, and
  • login_redirect( 'https://example.com/wp-admin/' ) returns its input unchanged.

This is the open-redirect guard, so it's the branch that matters most to cover. A non-string redirect_to in the state (e.g. an array or int) would be a cheap extra case for the is_string() check.

$this->mockSuccessfulGoogleAuthentication( 'https://example.com/state-page' );

$this->wpMockFunction(
'wp_sanitize_redirect',
[ 'https://example.com/state-page' ],
1,
'https://example.com/state-page'
);

$this->wpMockFunction(
'wp_validate_redirect',
[ 'https://example.com/state-page', '' ],
1,
'https://example.com/state-page'
);

$this->wpMockFunction(
'wp_slash',
[ 'https://example.com/state-page' ],
1,
'https://example.com/state-page'
);

$this->testee->authenticate();

$this->assertSame( 'https://example.com/state-page', $_REQUEST['redirect_to'] );
$this->assertSame( 'https://example.com/state-page', $this->testee->login_redirect( 'https://example.com/wp-admin/' ) );
}

/**
* Open-redirect guard: an off-site destination in the state is dropped.
*
* @covers ::authenticate
* @covers ::login_redirect
*/
public function testLoginRedirectIgnoresOffsiteStateRedirect() {
$this->mockSuccessfulGoogleAuthentication( 'https://evil.example/' );

$this->wpMockFunction(
'wp_sanitize_redirect',
[ 'https://evil.example/' ],
1,
'https://evil.example/'
);

// `wpMockFunction()` skips empty return values, so set `''` directly.
WP_Mock::userFunction(
'wp_validate_redirect',
[
'times' => 1,
'args' => [ 'https://evil.example/', '' ],
'return' => '',
]
);

WP_Mock::userFunction( 'wp_slash', [ 'times' => 0 ] );

$this->testee->authenticate();

$this->assertArrayNotHasKey( 'redirect_to', $_REQUEST );
$this->assertSame( 'https://example.com/wp-admin/', $this->testee->login_redirect( 'https://example.com/wp-admin/' ) );
}

/**
* A non-string `redirect_to` in the state is ignored without being validated.
*
* @covers ::authenticate
* @covers ::login_redirect
*/
public function testLoginRedirectIgnoresNonStringStateRedirect() {
$this->mockSuccessfulGoogleAuthentication( [ 'https://example.com/state-page' ] );

WP_Mock::userFunction( 'wp_sanitize_redirect', [ 'times' => 0 ] );
WP_Mock::userFunction( 'wp_validate_redirect', [ 'times' => 0 ] );
WP_Mock::userFunction( 'wp_slash', [ 'times' => 0 ] );

$this->testee->authenticate();

$this->assertArrayNotHasKey( 'redirect_to', $_REQUEST );
$this->assertSame( 'https://example.com/wp-admin/', $this->testee->login_redirect( 'https://example.com/wp-admin/' ) );
}

/**
* Mock a successful Google authentication with the given `redirect_to` in the state.
*
* @param mixed $redirect_to Value of `redirect_to` in the state.
*
* @return void
*/
private function mockSuccessfulGoogleAuthentication( $redirect_to ): void {
$state = base64_encode(
json_encode(
[
'provider' => 'google',
'nonce' => 'testnonce',
'state_token' => 'valid_token',
'redirect_to' => $redirect_to,
]
)
);

$helperMock = Mockery::mock( 'alias:' . Helper::class );
$helperMock->expects( 'filter_input' )->once()->withArgs(
[
INPUT_GET,
'code',
FILTER_SANITIZE_FULL_SPECIAL_CHARS
]
)->andReturn( 'abc' );

$helperMock->expects( 'filter_input' )->once()->withArgs(
[
INPUT_GET,
'state',
FILTER_SANITIZE_FULL_SPECIAL_CHARS
]
)->andReturn( [] );
)->andReturn( $state );

$helperMock->expects( 'verify_state_token' )->once()->with( 'valid_token' )->andReturn( true );
$helperMock->expects( 'set_state_cookie' )->once()->andReturnNull();

$this->wpMockFunction(
'wp_verify_nonce',
[
'testnonce',
'login_with_google',
],
1,
true
);

$this->ghClientMock->expects( $this->once() )
->method( 'user' )
->willReturn( (object) [ 'email' => 'fakeemail@domain.com' ] );

$data = $this->testee->login_redirect();
$this->assertNull( $data );
$this->authenticatorMock->expects( $this->once() )
->method( 'authenticate' )
->willReturn( Mockery::mock( 'WP_User' ) );
}
}
Loading