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
18 changes: 18 additions & 0 deletions features/context.feature
Original file line number Diff line number Diff line change
Expand Up @@ -350,3 +350,21 @@ Feature: Context handling via --context global flag
"""
Error: Invalid user ID, email or login: 'non_existent_user'
"""

Scenario: Admin context does not leave persistent session tokens behind
Given a WP install

When I run `wp --context=admin eval "echo count( WP_Session_Tokens::get_instance( 1 )->get_all() ) . ' ' . ( wp_validate_auth_cookie( \$_COOKIE[ AUTH_COOKIE ], 'auth' ) ?: 'invalid' );"`
Then STDOUT should be:
"""
1 1
"""

When I run `wp plugin list`
And I run `wp theme list`
And I run `wp --context=admin eval ''`
And I run `wp eval "echo count( WP_Session_Tokens::get_instance( 1 )->get_all() );"`
Then STDOUT should be:
"""
0
"""
21 changes: 19 additions & 2 deletions php/WP_CLI/Context/Admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use WP_CLI;
use WP_CLI\Context;
use WP_CLI\Fetchers\User;
use WP_Session_Tokens;
use WP_User;

/**
Expand Down Expand Up @@ -141,6 +142,10 @@ private function get_fake_admin_page(): string {
* A lot of premium plugins/themes have their custom update routines locked
* behind an is_admin() call.
*
* A single session token is shared by both auth cookies and destroyed
* again on shutdown, so that running commands in the admin context does
* not leave stale sessions behind for the admin user.
*
* @param int<1, max> $admin_user_id to log in as
*
* @return void
Expand All @@ -150,16 +155,28 @@ private function log_in_as_admin_user( $admin_user_id ): void {

$expiration = time() + DAY_IN_SECONDS;

$manager = WP_Session_Tokens::get_instance( $admin_user_id );
$token = $manager->create( $expiration );

WP_CLI::add_wp_hook(
'shutdown',
static function () use ( $manager, $token ) {
$manager->destroy( $token );
}
);
Comment thread
swissspidy marked this conversation as resolved.

$_COOKIE[ AUTH_COOKIE ] = wp_generate_auth_cookie(
$admin_user_id,
$expiration,
'auth'
'auth',
$token
);

$_COOKIE[ SECURE_AUTH_COOKIE ] = wp_generate_auth_cookie(
$admin_user_id,
$expiration,
'secure_auth'
'secure_auth',
$token
);
}

Expand Down
Loading