Skip to content

context=admin executes admin_init before anything on init is executed potentially causing fatal errors #6010

Open
@kkmuffme

Description

@kkmuffme

Bug Report

Describe the current, buggy behavior
Describe how other contributors can replicate this bug
Describe what you expect as the correct outcome

in theme functions.php add:

function init_cb() {
    var_dump( 'this is init' );
}
add_action( 'init', 'init_cb' );

function admin_init_cb() {
    var_dump( 'this is admin init' );
}
add_action( 'admin_init', 'admin_init_cb' );

Then run:

wp --user=1 --context=admin eval ""

You will get:

this is admin init
this is init

However, this is the opposite order of what it would normally be in an wp-admin request.

Let us know what environment you are running this on

WP 6.6
WP CLI 2.11.0

Provide a possible solution

  1. The issue is https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L45 is run on init hook with earliest priority (PHP_INT_MIN)
    To keep it consistent with WP core, it needs to be loaded on wp_loaded with PHP_INT_MAX (last hook in settings.php)

  2. And the user auth https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L44 is wrong too. Normally the user is set up already on plugins_loaded - therefore that needs to be called on plugins_loaded with PHP_INT_MIN

  3. Also there's a bug here https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L63 - when a --user is provided, it should use that user and not arbitrarily fall back to ID 1 since this will make current_user_can checks fail and therefore the context=admin is pointless, since it's an unauthenticated request anyway
    EDIT: looks like the correct code is there https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Runner.php#L1655 but the user then gets overwritten by the wrong user in https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L63 (since that init hook was added later it runs after) - I guess a simple check whether the user is set already in https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L63 would be sufficient before overwriting it with id 1

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions