From 19b352db2d8cf3fadb92cc03235ff39412d44c4b Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 16 Oct 2026 10:58:39 +0200 Subject: [PATCH 1/8] Abilities API: Allow abilities to declare required capabilities. Adds a `required_capabilities` argument to `wp_register_ability()`. It is a list of capabilities the current user must have to run the ability. `WP_Ability::check_permissions()` checks these capabilities first. The `permission_callback` only runs when they all pass. The callback is optional when the list is not empty. `wp_get_abilities()` accepts a new `current_user_can` argument. It leaves out abilities that declare capabilities the current user doesn't have, without calling any permission callbacks. The REST list route gets a matching query parameter and includes `required_capabilities` in the response. Core abilities that only check `manage_options` now use the new argument. See #66325. Co-Authored-By: Claude Opus 5.5 --- src/wp-includes/abilities-api.php | 45 ++- .../class-wp-abilities-registry.php | 12 +- .../abilities-api/class-wp-ability.php | 134 ++++++- src/wp-includes/abilities.php | 36 +- .../abilities/class-wp-abilities-settings.php | 32 +- ...s-wp-rest-abilities-v1-list-controller.php | 61 ++-- .../phpunit/tests/abilities-api/wpAbility.php | 329 ++++++++++++++++++ .../tests/abilities-api/wpGetAbilities.php | 134 +++++++ .../wpRestAbilitiesV1ListController.php | 78 ++++- 9 files changed, 768 insertions(+), 93 deletions(-) diff --git a/src/wp-includes/abilities-api.php b/src/wp-includes/abilities-api.php index abd3684273a5a..ef40c8e0a61e2 100644 --- a/src/wp-includes/abilities-api.php +++ b/src/wp-includes/abilities-api.php @@ -29,25 +29,23 @@ * wp_register_ability( * 'my-plugin/export-users', * array( - * 'label' => __( 'Export Users', 'my-plugin' ), - * 'description' => __( 'Exports user data to CSV format.', 'my-plugin' ), - * 'category' => 'data-export', - * 'execute_callback' => 'my_plugin_export_users', - * 'permission_callback' => function(): bool { - * return current_user_can( 'export' ); - * }, - * 'input_schema' => array( + * 'label' => __( 'Export Users', 'my-plugin' ), + * 'description' => __( 'Exports user data to CSV format.', 'my-plugin' ), + * 'category' => 'data-export', + * 'execute_callback' => 'my_plugin_export_users', + * 'required_capabilities' => array( 'export' ), + * 'input_schema' => array( * 'type' => 'string', * 'enum' => array( 'subscriber', 'contributor', 'author', 'editor', 'administrator' ), * 'description' => __( 'Limits the export to users with this role.', 'my-plugin' ), * 'required' => false, * ), - * 'output_schema' => array( + * 'output_schema' => array( * 'type' => 'string', * 'description' => __( 'User data in CSV format.', 'my-plugin' ), * 'required' => true, * ), - * 'meta' => array( + * 'meta' => array( * 'public' => true, * ), * ) @@ -234,6 +232,7 @@ * @since 6.9.0 * @since 7.1.0 Added the `public` meta argument. * @since 7.2.0 The `category` argument is now optional and defaults to `uncategorized`. + * @since 7.2.0 Added the `required_capabilities` argument. * * @see WP_Abilities_Registry::register() * @see wp_register_ability_category() @@ -254,10 +253,16 @@ * @type callable $execute_callback Required. A callback function to execute when the ability is invoked. * Receives optional mixed input data and must return either a result * value (any type) or a `WP_Error` object on failure. - * @type callable $permission_callback Required. A callback function to check permissions before execution. + * @type callable $permission_callback Optional. A callback function to check permissions before execution. * Receives optional mixed input data (same as `execute_callback`) and * must return `true`/`false` for simple checks, or `WP_Error` for - * detailed error responses. + * detailed error responses. Required unless `$required_capabilities` + * is not empty. Public abilities must set it to `__return_true`. + * @type list $required_capabilities Optional. Capabilities the current user must have to run the + * ability. Each one is checked with `current_user_can()` before + * `permission_callback` runs. Use it for checks that don't depend + * on the input. Abilities the current user can't run can then be + * left out when listing them. Default empty array. * @type array $input_schema Optional. JSON Schema definition for validating the ability's input. * Must be a valid JSON Schema object defining the structure and * constraints for input data. Used for automatic validation and @@ -477,6 +482,7 @@ function wp_get_ability( string $name ): ?WP_Ability { * * @since 6.9.0 * @since 7.1.0 Added the `$args` parameter for filtering support. + * @since 7.2.0 Added the `current_user_can` argument. * * @see WP_Abilities_Registry::get_all_registered() * @@ -491,6 +497,11 @@ function wp_get_ability( string $name ): ?WP_Ability { * @type array $meta Filter by meta key/value pairs. All conditions must * match (AND logic). Supports nested arrays for structured * meta, e.g. `array( 'mcp' => array( 'public' => true ) )`. + * @type bool $current_user_can Whether to leave out abilities that declare required + * capabilities the current user doesn't have. Abilities + * without required capabilities are always included, + * because their permission may depend on the input. + * Permission callbacks are not called. Default false. * @type callable $item_include_callback Optional. A callback invoked per ability after declarative * filters. Receives a WP_Ability instance, returns bool. * Return true to include, false to exclude. @@ -514,6 +525,7 @@ function wp_get_abilities( array $args = array() ): array { $category = isset( $args['category'] ) && is_string( $args['category'] ) ? $args['category'] : ''; $namespace = isset( $args['namespace'] ) && is_string( $args['namespace'] ) ? rtrim( $args['namespace'], '/' ) . '/' : ''; $meta = isset( $args['meta'] ) && is_array( $args['meta'] ) ? $args['meta'] : array(); + $current_user_can = ! empty( $args['current_user_can'] ); $item_include_callback = isset( $args['item_include_callback'] ) && is_callable( $args['item_include_callback'] ) ? $args['item_include_callback'] : null; $result_callback = isset( $args['result_callback'] ) && is_callable( $args['result_callback'] ) ? $args['result_callback'] : null; @@ -535,6 +547,15 @@ function wp_get_abilities( array $args = array() ): array { continue; } + // Step 1d: Filter by the capabilities the ability requires from the current user. + if ( $current_user_can ) { + foreach ( $ability->get_required_capabilities() as $capability ) { + if ( ! current_user_can( $capability ) ) { + continue 2; + } + } + } + // Step 2: Caller-scoped per-item callback. $include = true; if ( null !== $item_include_callback ) { diff --git a/src/wp-includes/abilities-api/class-wp-abilities-registry.php b/src/wp-includes/abilities-api/class-wp-abilities-registry.php index 90a2349a89ce1..8302d35e02360 100644 --- a/src/wp-includes/abilities-api/class-wp-abilities-registry.php +++ b/src/wp-includes/abilities-api/class-wp-abilities-registry.php @@ -42,6 +42,7 @@ final class WP_Abilities_Registry { * @since 6.9.0 * @since 7.1.0 Added the `public` meta argument. * @since 7.2.0 The `category` argument is now optional and defaults to `uncategorized`. + * @since 7.2.0 Added the `required_capabilities` argument. * * @see wp_register_ability() * @@ -57,8 +58,11 @@ final class WP_Abilities_Registry { * Defaults to `uncategorized`. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback A callback function to check permissions before execution. + * @type callable $permission_callback Optional. A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. + * Required unless `$required_capabilities` is not empty. + * @type list $required_capabilities Optional. Capabilities the current user must have to run the + * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. * @type array $output_schema Optional. JSON Schema definition for the ability's output. * @type array $meta { @@ -115,6 +119,7 @@ public function register( string $name, array $args ): ?WP_Ability { * @since 6.9.0 * @since 7.1.0 Added the `public` meta argument. * @since 7.2.0 The `category` argument is now optional and defaults to `uncategorized`. + * @since 7.2.0 Added the `required_capabilities` argument. * * @param array $args { * An associative array of arguments for the ability. @@ -125,8 +130,11 @@ public function register( string $name, array $args ): ?WP_Ability { * Defaults to `uncategorized`. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback A callback function to check permissions before execution. + * @type callable $permission_callback Optional. A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. + * Required unless `$required_capabilities` is not empty. + * @type list $required_capabilities Optional. Capabilities the current user must have to run the + * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. * @type array $output_schema Optional. JSON Schema definition for the ability's output. * @type array $meta { diff --git a/src/wp-includes/abilities-api/class-wp-ability.php b/src/wp-includes/abilities-api/class-wp-ability.php index 88853f6496a31..e3d5470ee77f7 100644 --- a/src/wp-includes/abilities-api/class-wp-ability.php +++ b/src/wp-includes/abilities-api/class-wp-ability.php @@ -123,6 +123,14 @@ class WP_Ability { */ protected $permission_callback; + /** + * The optional capabilities the current user must have to run the ability. + * + * @since 7.2.0 + * @var list + */ + protected $required_capabilities = array(); + /** * The optional ability metadata. * @@ -140,6 +148,7 @@ class WP_Ability { * * @since 6.9.0 * @since 7.1.0 Added the `public` meta argument. + * @since 7.2.0 Added the `required_capabilities` argument. * * @see wp_register_ability() * @@ -152,8 +161,11 @@ class WP_Ability { * @type string $category The ability category slug this ability belongs to. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback A callback function to check permissions before execution. + * @type callable $permission_callback Optional. A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. + * Required unless `$required_capabilities` is not empty. + * @type list $required_capabilities Optional. Capabilities the current user must have to run the + * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. * @type array $output_schema Optional. JSON Schema definition for the ability's output. * @type array $meta { @@ -211,6 +223,7 @@ public function __construct( string $name, array $args ) { * * @since 6.9.0 * @since 7.1.0 Added the `public` meta argument. + * @since 7.2.0 Added the `required_capabilities` argument. * * @see WP_Abilities_Registry::register() * @@ -222,8 +235,11 @@ public function __construct( string $name, array $args ) { * @type string $category The ability category slug this ability belongs to. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback A callback function to check permissions before execution. + * @type callable $permission_callback Optional. A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. + * Required unless `$required_capabilities` is not empty. + * @type list $required_capabilities Optional. Capabilities the current user must have to run the + * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. Required if ability accepts an input. * @type array $output_schema Optional. JSON Schema definition for the ability's output. * @type array $meta { @@ -255,8 +271,11 @@ public function __construct( string $name, array $args ) { * @type string $category The ability category slug this ability belongs to. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback A callback function to check permissions before execution. + * @type callable $permission_callback Optional. A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. + * Required unless `$required_capabilities` is not empty. + * @type list $required_capabilities Optional. Capabilities the current user must have to run the + * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. * @type array $output_schema Optional. JSON Schema definition for the ability's output. * @type array $meta { @@ -307,13 +326,30 @@ protected function prepare_properties( array $args ): array { ); } - // If we are not overriding `ability_class` parameter during instantiation, then we need to validate the permission_callback. - if ( get_class( $this ) === self::class && ( empty( $args['permission_callback'] ) || ! is_callable( $args['permission_callback'] ) ) ) { + if ( isset( $args['required_capabilities'] ) && ! self::is_valid_capability_list( $args['required_capabilities'] ) ) { throw new InvalidArgumentException( - __( 'The ability properties must provide a valid `permission_callback` function.' ) + __( 'The ability properties should provide a valid `required_capabilities` list of non-empty strings.' ) ); } + /* + * If we are not overriding `ability_class` parameter during instantiation, then we need to validate the permission_callback. + * It can be left out when the ability declares at least one required capability. + */ + if ( get_class( $this ) === self::class ) { + if ( isset( $args['permission_callback'] ) ) { + if ( ! is_callable( $args['permission_callback'] ) ) { + throw new InvalidArgumentException( + __( 'The ability properties must provide a valid `permission_callback` function.' ) + ); + } + } elseif ( empty( $args['required_capabilities'] ) ) { + throw new InvalidArgumentException( + __( 'The ability properties must provide a valid `permission_callback` function or a non-empty `required_capabilities` list.' ) + ); + } + } + // Optional args only need to be of the correct type if they are present. if ( isset( $args['input_schema'] ) && ! is_array( $args['input_schema'] ) ) { throw new InvalidArgumentException( @@ -351,6 +387,8 @@ protected function prepare_properties( array $args ): array { ); } + $args['required_capabilities'] ??= array(); + // Set defaults for optional meta. $args['meta'] = wp_parse_args( $args['meta'] ?? array(), @@ -453,6 +491,17 @@ public function get_meta(): array { return $this->meta; } + /** + * Retrieves the capabilities the current user must have to run the ability. + * + * @since 7.2.0 + * + * @return list The required capabilities. Empty when the ability declares none. + */ + public function get_required_capabilities(): array { + return $this->required_capabilities; + } + /** * Retrieves a specific metadata item for the ability. * @@ -576,6 +625,27 @@ public function validate_input( $input = null ) { return true; } + /** + * Checks whether a value is a list of non-empty capability strings. + * + * @since 7.2.0 + * + * @param mixed $capabilities The value to check. + * @return bool Whether the value is a valid list of capabilities. + */ + private static function is_valid_capability_list( $capabilities ): bool { + if ( ! is_array( $capabilities ) || ! array_is_list( $capabilities ) ) { + return false; + } + + foreach ( $capabilities as $capability ) { + if ( ! is_string( $capability ) || '' === trim( $capability ) ) { + return false; + } + } + return true; + } + /** * Invokes a callable, ensuring the input is passed through only if the input schema is defined. * @@ -613,11 +683,19 @@ protected function invoke_callback( callable $callback, $input = null ) { * Please note that input is not automatically validated against the input schema. * Use `validate_input()` method to validate input before calling this method if needed. * - * The {@see 'wp_ability_permission_result'} filter fires after the registered - * `permission_callback` returns, allowing plugins to override the result. + * The checks run in this order: + * + * 1. When the ability declares `required_capabilities`, each one is checked with + * `current_user_can()`. The check fails right away if one is missing. + * 2. When all capabilities pass and the ability has a `permission_callback`, it runs + * with the given input. + * + * The {@see 'wp_ability_permission_result'} filter fires on the final result, allowing + * plugins to override it. * * @since 6.9.0 * @since 7.1.0 Added the `wp_ability_permission_result` filter. + * @since 7.2.0 Checks the `required_capabilities` before the `permission_callback`. * * @see validate_input() * @@ -625,7 +703,11 @@ protected function invoke_callback( callable $callback, $input = null ) { * @return bool|WP_Error Whether the ability has the necessary permission. */ public function check_permissions( $input = null ) { - if ( ! is_callable( $this->permission_callback ) ) { + /* + * Custom ability classes skip the registration checks, so they are repeated here. + * A permission callback that is set must be callable, even when required capabilities pass. + */ + if ( null !== $this->permission_callback && ! is_callable( $this->permission_callback ) ) { return new WP_Error( 'ability_invalid_permission_callback', /* translators: %s ability name. */ @@ -633,22 +715,48 @@ public function check_permissions( $input = null ) { ); } - $permission = $this->invoke_callback( $this->permission_callback, $input ); + if ( null === $this->permission_callback && empty( $this->required_capabilities ) ) { + return new WP_Error( + 'ability_missing_permission_callback', + /* translators: %s ability name. */ + sprintf( __( 'Ability "%s" does not have a permission callback or required capabilities.' ), $this->name ) + ); + } + + /* + * Both checks must pass. A check that isn't set is skipped, so the other one decides. + * The permission callback only runs when the required capabilities pass. + */ + $permission = true; + foreach ( $this->required_capabilities as $capability ) { + if ( ! current_user_can( $capability ) ) { + $permission = false; + break; + } + } + + if ( $permission && null !== $this->permission_callback ) { + $permission = $this->invoke_callback( $this->permission_callback, $input ); + } /** * Filters the result of an ability's permission check. * - * Fires after the registered `permission_callback` returns. Plugins can use this to layer + * Fires after the `required_capabilities` check and the registered `permission_callback`. + * It also fires when a required capability is missing. Plugins can use this to layer * additional authorization rules on top of the ability's own permission logic — for example, * multi-factor authorization gates or temporary permission elevation for trusted contexts. * * Filters can return `true` to grant, `false` to deny, or a `WP_Error` to deny with a specific - * error code and message. The filter receives whatever the `permission_callback` produced. + * error code and message. The filter receives `false` when a required capability is missing. + * Otherwise, it receives whatever the `permission_callback` produced, or `true` when there is none. * Any other return value is coerced to `false`. * * @since 7.1.0 + * @since 7.2.0 Also fires with `false` when a required capability is missing. * - * @param bool|WP_Error $permission The permission result returned by `permission_callback`. + * @param bool|WP_Error $permission The permission result from the required capabilities check + * and the `permission_callback`. * @param string $ability_name The name of the ability. * @param mixed $input The input data for the permission check. * @param WP_Ability $ability The ability instance. diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php index a6a904181777f..5b2e84ab3bb2c 100644 --- a/src/wp-includes/abilities.php +++ b/src/wp-includes/abilities.php @@ -112,10 +112,10 @@ function wp_register_core_abilities(): void { wp_register_ability( 'core/get-site-info', array( - 'label' => __( 'Get Site Information' ), - 'description' => __( 'Returns site information configured in WordPress. By default returns all fields, or optionally a filtered subset.' ), - 'category' => $category_site, - 'input_schema' => array( + 'label' => __( 'Get Site Information' ), + 'description' => __( 'Returns site information configured in WordPress. By default returns all fields, or optionally a filtered subset.' ), + 'category' => $category_site, + 'input_schema' => array( 'type' => 'object', 'properties' => array( 'fields' => array( @@ -130,12 +130,12 @@ function wp_register_core_abilities(): void { 'additionalProperties' => false, 'default' => array(), ), - 'output_schema' => array( + 'output_schema' => array( 'type' => 'object', 'properties' => $site_info_properties, 'additionalProperties' => false, ), - 'execute_callback' => static function ( $input = array() ) use ( $site_info_fields ): array { + 'execute_callback' => static function ( $input = array() ) use ( $site_info_fields ): array { $input = is_array( $input ) ? $input : array(); $requested_fields = ! empty( $input['fields'] ) ? $input['fields'] : $site_info_fields; @@ -150,10 +150,8 @@ function wp_register_core_abilities(): void { return $result; }, - 'permission_callback' => static function (): bool { - return current_user_can( 'manage_options' ); - }, - 'meta' => array( + 'required_capabilities' => array( 'manage_options' ), + 'meta' => array( 'annotations' => array( 'readonly' => true, 'destructive' => false, @@ -316,10 +314,10 @@ function wp_register_core_abilities(): void { wp_register_ability( 'core/get-environment-info', array( - 'label' => __( 'Get Environment Info' ), - 'description' => __( 'Returns core details about the site\'s runtime context for diagnostics and compatibility (environment, PHP runtime, database server info, WordPress version). By default returns all fields, or optionally a filtered subset.' ), - 'category' => $category_site, - 'input_schema' => array( + 'label' => __( 'Get Environment Info' ), + 'description' => __( 'Returns core details about the site\'s runtime context for diagnostics and compatibility (environment, PHP runtime, database server info, WordPress version). By default returns all fields, or optionally a filtered subset.' ), + 'category' => $category_site, + 'input_schema' => array( 'type' => 'object', 'properties' => array( 'fields' => array( @@ -334,12 +332,12 @@ function wp_register_core_abilities(): void { 'additionalProperties' => false, 'default' => array(), ), - 'output_schema' => array( + 'output_schema' => array( 'type' => 'object', 'properties' => $environment_info_properties, 'additionalProperties' => false, ), - 'execute_callback' => static function ( $input = array() ) use ( $environment_info_fields ): array { + 'execute_callback' => static function ( $input = array() ) use ( $environment_info_fields ): array { global $wpdb; /** @var array{ fields?: string[] } $input */ @@ -360,10 +358,8 @@ function wp_register_core_abilities(): void { return array_intersect_key( $all, array_flip( $requested_fields ) ); }, - 'permission_callback' => static function (): bool { - return current_user_can( 'manage_options' ); - }, - 'meta' => array( + 'required_capabilities' => array( 'manage_options' ), + 'meta' => array( 'annotations' => array( 'readonly' => true, 'destructive' => false, diff --git a/src/wp-includes/abilities/class-wp-abilities-settings.php b/src/wp-includes/abilities/class-wp-abilities-settings.php index 953eb92ef8ab4..3beb82570ccfe 100644 --- a/src/wp-includes/abilities/class-wp-abilities-settings.php +++ b/src/wp-includes/abilities/class-wp-abilities-settings.php @@ -81,18 +81,16 @@ private function register_settings_get(): void { wp_register_ability( 'core/settings-get', array( - 'label' => __( 'Get Settings' ), - 'description' => __( 'Returns WordPress settings as a flat map of setting name to value. By default returns all settings exposed to abilities, or optionally a subset filtered by settings group, by setting name, or both. A setting whose value does not match its schema is left out. Requires an authenticated user who can manage options.' ), - 'category' => self::CATEGORY, - 'input_schema' => $this->get_settings_get_input_schema( $groups, array_map( 'strval', array_keys( $this->exposed_settings ) ) ), - 'output_schema' => $this->get_settings_get_output_schema(), - 'execute_callback' => function ( $input = array() ): array { + 'label' => __( 'Get Settings' ), + 'description' => __( 'Returns WordPress settings as a flat map of setting name to value. By default returns all settings exposed to abilities, or optionally a subset filtered by settings group, by setting name, or both. A setting whose value does not match its schema is left out. Requires an authenticated user who can manage options.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_settings_get_input_schema( $groups, array_map( 'strval', array_keys( $this->exposed_settings ) ) ), + 'output_schema' => $this->get_settings_get_output_schema(), + 'execute_callback' => function ( $input = array() ): array { return $this->execute_settings_get( $input ); }, - 'permission_callback' => function (): bool { - return $this->check_permission(); - }, - 'meta' => array( + 'required_capabilities' => array( 'manage_options' ), + 'meta' => array( 'annotations' => array( 'readonly' => true, 'destructive' => false, @@ -161,20 +159,6 @@ private function execute_settings_get( $input = array() ): array { return $result; } - /** - * Permission callback for the settings abilities. - * - * The settings abilities read site options, so they are gated on the `manage_options` - * capability regardless of the input. - * - * @since 7.2.0 - * - * @return bool True if the current user can manage options. - */ - private function check_permission(): bool { - return current_user_can( 'manage_options' ); - } - /** * Builds the input schema for the `core/settings-get` ability: optional filters by group and/or name. * diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php index 5547e7e002f02..a028708d7ba6b 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php @@ -103,6 +103,10 @@ public function get_items( $request ) { $query_args['meta'] = array_merge( $request['meta'], $query_args['meta'] ); } + if ( ! empty( $request['current_user_can'] ) ) { + $query_args['current_user_can'] = true; + } + $abilities = wp_get_abilities( $query_args ); $page = $request['page']; @@ -204,13 +208,14 @@ public function get_item_permissions_check( $request ) { */ public function prepare_item_for_response( $ability, $request ) { $data = array( - 'name' => $ability->get_name(), - 'label' => $ability->get_label(), - 'description' => $ability->get_description(), - 'category' => $ability->get_category(), - 'input_schema' => wp_prepare_json_schema_for_client( $ability->get_input_schema() ), - 'output_schema' => wp_prepare_json_schema_for_client( $ability->get_output_schema() ), - 'meta' => $ability->get_meta(), + 'name' => $ability->get_name(), + 'label' => $ability->get_label(), + 'description' => $ability->get_description(), + 'category' => $ability->get_category(), + 'required_capabilities' => $ability->get_required_capabilities(), + 'input_schema' => wp_prepare_json_schema_for_client( $ability->get_input_schema() ), + 'output_schema' => wp_prepare_json_schema_for_client( $ability->get_output_schema() ), + 'meta' => $ability->get_meta(), ); $context = $request['context'] ?? 'view'; @@ -245,6 +250,7 @@ public function prepare_item_for_response( $ability, $request ) { * * @since 6.9.0 * @since 7.1.0 Added the `meta.public` property. + * @since 7.2.0 Added the `required_capabilities` property. * * @return array Item schema data. */ @@ -254,43 +260,52 @@ public function get_item_schema(): array { 'title' => 'ability', 'type' => 'object', 'properties' => array( - 'name' => array( + 'name' => array( 'description' => __( 'Unique identifier for the ability.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), - 'label' => array( + 'label' => array( 'description' => __( 'Display label for the ability.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), - 'description' => array( + 'description' => array( 'description' => __( 'Description of the ability.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), - 'category' => array( + 'category' => array( 'description' => __( 'Ability category this ability belongs to.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), - 'input_schema' => array( + 'required_capabilities' => array( + 'description' => __( 'Capabilities the current user must have to run the ability.' ), + 'type' => 'array', + 'items' => array( + 'type' => 'string', + ), + 'context' => array( 'view', 'edit' ), + 'readonly' => true, + ), + 'input_schema' => array( 'description' => __( 'JSON Schema for the ability input.' ), 'type' => 'object', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), - 'output_schema' => array( + 'output_schema' => array( 'description' => __( 'JSON Schema for the ability output.' ), 'type' => 'object', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), - 'meta' => array( + 'meta' => array( 'description' => __( 'Meta information about the ability.' ), 'type' => 'object', 'properties' => array( @@ -332,38 +347,39 @@ public function get_item_schema(): array { * * @since 6.9.0 * @since 7.1.0 Added the `namespace` and `meta` parameters and the `rest_abilities_collection_params` filter. + * @since 7.2.0 Added the `current_user_can` parameter. * * @return array Collection parameters. */ public function get_collection_params(): array { $query_params = array( - 'context' => $this->get_context_param( array( 'default' => 'view' ) ), - 'page' => array( + 'context' => $this->get_context_param( array( 'default' => 'view' ) ), + 'page' => array( 'description' => __( 'Current page of the collection.' ), 'type' => 'integer', 'default' => 1, 'minimum' => 1, ), - 'per_page' => array( + 'per_page' => array( 'description' => __( 'Maximum number of items to be returned in result set.' ), 'type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 100, ), - 'category' => array( + 'category' => array( 'description' => __( 'Limit results to abilities in specific ability category.' ), 'type' => 'string', 'sanitize_callback' => 'sanitize_key', 'validate_callback' => 'rest_validate_request_arg', ), - 'namespace' => array( + 'namespace' => array( 'description' => __( 'Limit results to abilities in a specific namespace.' ), 'type' => 'string', 'sanitize_callback' => 'sanitize_key', 'validate_callback' => 'rest_validate_request_arg', ), - 'meta' => array( + 'meta' => array( 'description' => __( 'Limit results to abilities matching all of the given meta fields.' ), 'type' => 'object', 'properties' => array( @@ -390,6 +406,11 @@ public function get_collection_params(): array { ), 'additionalProperties' => true, ), + 'current_user_can' => array( + 'description' => __( 'Limit results to abilities whose required capabilities the current user has. Abilities that declare no required capabilities are always included.' ), + 'type' => 'boolean', + 'default' => false, + ), ); /** diff --git a/tests/phpunit/tests/abilities-api/wpAbility.php b/tests/phpunit/tests/abilities-api/wpAbility.php index e1b125d8da069..5a088b6edbc0d 100644 --- a/tests/phpunit/tests/abilities-api/wpAbility.php +++ b/tests/phpunit/tests/abilities-api/wpAbility.php @@ -2126,4 +2126,333 @@ public function test_execute_ignores_schema_sanitize_callback() { $this->assertSame( 'raw value', $result, 'Input should reach the execute callback unmodified (no sanitization).' ); $this->assertFalse( $callback_invoked, 'Schema sanitize_callback must not run.' ); } + + /** + * Returns the test ability properties with required capabilities and no permission callback. + * + * @param string[] $capabilities The required capabilities. + * @return array The ability properties. + */ + private function get_properties_with_required_capabilities( array $capabilities ): array { + $args = self::$test_ability_properties; + unset( $args['permission_callback'] ); + $args['required_capabilities'] = $capabilities; + + return $args; + } + + /** + * Tests that required capabilities default to an empty array. + * + * @ticket 66325 + * + * @covers WP_Ability::get_required_capabilities + */ + public function test_required_capabilities_default_to_empty_array() { + $ability = new WP_Ability( self::$test_ability_name, self::$test_ability_properties ); + + $this->assertSame( array(), $ability->get_required_capabilities() ); + } + + /** + * Tests that null required capabilities are treated as an empty array. + * + * @ticket 66325 + * + * @covers WP_Ability::prepare_properties + * @covers WP_Ability::get_required_capabilities + */ + public function test_null_required_capabilities_default_to_empty_array() { + $args = self::$test_ability_properties; + $args['required_capabilities'] = null; + + $ability = new WP_Ability( self::$test_ability_name, $args ); + + $this->assertSame( array(), $ability->get_required_capabilities() ); + } + + /** + * Tests that an ability can declare required capabilities without a permission callback. + * + * @ticket 66325 + * + * @covers WP_Ability::prepare_properties + * @covers WP_Ability::get_required_capabilities + */ + public function test_required_capabilities_replace_permission_callback() { + $ability = new WP_Ability( + self::$test_ability_name, + $this->get_properties_with_required_capabilities( array( 'edit_posts', 'manage_options' ) ) + ); + + $this->assertSame( array( 'edit_posts', 'manage_options' ), $ability->get_required_capabilities() ); + } + + /** + * Tests that an empty list of required capabilities doesn't replace the permission callback. + * + * @ticket 66325 + * + * @covers WP_Ability::prepare_properties + */ + public function test_empty_required_capabilities_without_permission_callback_throws_exception() { + $this->expectException( InvalidArgumentException::class ); + $this->expectExceptionMessage( 'The ability properties must provide a valid `permission_callback` function or a non-empty `required_capabilities` list.' ); + + new WP_Ability( self::$test_ability_name, $this->get_properties_with_required_capabilities( array() ) ); + } + + /** + * Tests that an invalid permission callback throws even when required capabilities are set. + * + * @ticket 66325 + * + * @covers WP_Ability::prepare_properties + */ + public function test_invalid_permission_callback_with_required_capabilities_throws_exception() { + $args = $this->get_properties_with_required_capabilities( array( 'read' ) ); + $args['permission_callback'] = 'not_a_callable_function'; + + $this->expectException( InvalidArgumentException::class ); + $this->expectExceptionMessage( 'The ability properties must provide a valid `permission_callback` function.' ); + + new WP_Ability( self::$test_ability_name, $args ); + } + + /** + * Data provider for invalid required capabilities. + * + * @return array + */ + public function data_invalid_required_capabilities(): array { + return array( + 'string' => array( 'manage_options' ), + 'empty string' => array( array( '' ) ), + 'whitespace only' => array( array( " \t" ) ), + 'non-string' => array( array( 'read', 1 ) ), + 'associative' => array( array( 'cap' => 'manage_options' ) ), + 'non-sequential' => array( array( 1 => 'manage_options' ) ), + 'nested array' => array( array( array( 'manage_options' ) ) ), + 'boolean' => array( true ), + 'null in the list' => array( array( null ) ), + ); + } + + /** + * Tests that invalid required capabilities throw an exception. + * + * @ticket 66325 + * + * @covers WP_Ability::prepare_properties + * + * @dataProvider data_invalid_required_capabilities + * + * @param mixed $capabilities The invalid required capabilities. + */ + public function test_invalid_required_capabilities_throw_exception( $capabilities ) { + $args = self::$test_ability_properties; + $args['required_capabilities'] = $capabilities; + + $this->expectException( InvalidArgumentException::class ); + $this->expectExceptionMessage( 'The ability properties should provide a valid `required_capabilities` list of non-empty strings.' ); + + new WP_Ability( self::$test_ability_name, $args ); + } + + /** + * Tests that check_permissions() grants access when the user has all required capabilities. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_check_permissions_grants_when_user_has_required_capabilities() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $ability = new WP_Ability( + self::$test_ability_name, + $this->get_properties_with_required_capabilities( array( 'edit_posts', 'manage_options' ) ) + ); + + $this->assertTrue( $ability->check_permissions() ); + } + + /** + * Tests that check_permissions() denies access when the user misses one required capability. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_check_permissions_denies_when_user_misses_a_required_capability() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); + + $ability = new WP_Ability( + self::$test_ability_name, + $this->get_properties_with_required_capabilities( array( 'edit_posts', 'manage_options' ) ) + ); + + $this->assertFalse( $ability->check_permissions() ); + } + + /** + * Tests that the permission callback doesn't run when a required capability is missing. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_check_permissions_skips_permission_callback_when_capability_is_missing() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); + + $callback_calls = 0; + $args = self::$test_ability_properties; + $args['required_capabilities'] = array( 'manage_options' ); + $args['permission_callback'] = static function () use ( &$callback_calls ): bool { + ++$callback_calls; + return true; + }; + + $ability = new WP_Ability( self::$test_ability_name, $args ); + + $this->assertFalse( $ability->check_permissions() ); + $this->assertSame( 0, $callback_calls, 'The permission callback should not run when a required capability is missing.' ); + } + + /** + * Tests that the permission callback runs with the input when all required capabilities pass. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_check_permissions_runs_permission_callback_after_required_capabilities() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $args = self::$test_ability_properties; + $args['input_schema'] = array( 'type' => 'integer' ); + $args['required_capabilities'] = array( 'manage_options' ); + $args['permission_callback'] = static function ( int $input ) { + return 7 === $input ? true : new WP_Error( 'wrong_input', 'Wrong input.' ); + }; + + $ability = new WP_Ability( self::$test_ability_name, $args ); + + $this->assertTrue( $ability->check_permissions( 7 ) ); + + $result = $ability->check_permissions( 3 ); + $this->assertWPError( $result ); + $this->assertSame( 'wrong_input', $result->get_error_code() ); + } + + /** + * Tests that the wp_ability_permission_result filter fires when a required capability is missing. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_permission_result_filter_can_grant_missing_required_capability() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); + + $filter = static function ( $permission, $ability_name ) { + if ( false === $permission && self::$test_ability_name === $ability_name ) { + return true; + } + return $permission; + }; + + add_filter( 'wp_ability_permission_result', $filter, 10, 2 ); + + $ability = new WP_Ability( + self::$test_ability_name, + $this->get_properties_with_required_capabilities( array( 'manage_options' ) ) + ); + $result = $ability->execute(); + + remove_filter( 'wp_ability_permission_result', $filter, 10 ); + + $this->assertSame( 0, $result, 'The filter should be able to grant a missing required capability.' ); + } + + /** + * Creates an ability with a custom class, which skips the registration checks. + * + * @param array $args The ability properties. + * @return WP_Ability The ability instance. + */ + private function create_custom_class_ability( array $args ): WP_Ability { + return new class( self::$test_ability_name, $args ) extends WP_Ability {}; + } + + /** + * Tests that check_permissions() returns an error when a custom class has neither a + * permission callback nor required capabilities. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_check_permissions_custom_class_without_permission_callback_or_capabilities() { + $args = self::$test_ability_properties; + unset( $args['permission_callback'] ); + + $result = $this->create_custom_class_ability( $args )->check_permissions(); + + $this->assertWPError( $result ); + $this->assertSame( 'ability_missing_permission_callback', $result->get_error_code() ); + } + + /** + * Tests that check_permissions() returns an error when a custom class has a permission + * callback that is not callable and no required capabilities. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_check_permissions_custom_class_with_invalid_permission_callback() { + $args = self::$test_ability_properties; + $args['permission_callback'] = 'not_a_callable_function'; + + $result = $this->create_custom_class_ability( $args )->check_permissions(); + + $this->assertWPError( $result ); + $this->assertSame( 'ability_invalid_permission_callback', $result->get_error_code() ); + } + + /** + * Tests that check_permissions() doesn't grant access when a custom class has a permission + * callback that is not callable, even if the user has all required capabilities. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_check_permissions_custom_class_with_invalid_permission_callback_and_capabilities() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $args = $this->get_properties_with_required_capabilities( array( 'manage_options' ) ); + $args['permission_callback'] = 'not_a_callable_function'; + + $result = $this->create_custom_class_ability( $args )->check_permissions(); + + $this->assertWPError( $result ); + $this->assertSame( 'ability_invalid_permission_callback', $result->get_error_code() ); + } + + /** + * Tests that check_permissions() works for a custom class with only required capabilities. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + */ + public function test_check_permissions_custom_class_with_required_capabilities_only() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $ability = $this->create_custom_class_ability( $this->get_properties_with_required_capabilities( array( 'manage_options' ) ) ); + + $this->assertTrue( $ability->check_permissions() ); + } } diff --git a/tests/phpunit/tests/abilities-api/wpGetAbilities.php b/tests/phpunit/tests/abilities-api/wpGetAbilities.php index 475ef341d869f..9246ae1f749ee 100644 --- a/tests/phpunit/tests/abilities-api/wpGetAbilities.php +++ b/tests/phpunit/tests/abilities-api/wpGetAbilities.php @@ -797,4 +797,138 @@ static function ( WP_Ability $a ) { $this->assertNotContains( 'test/ability-beta', $names ); $this->assertNotContains( 'other/ability-gamma', $names ); } + + // ------------------------------------------------------------------------- + // Current user capabilities filter + // ------------------------------------------------------------------------- + + /** + * Registers abilities with and without required capabilities. + */ + private function register_abilities_with_required_capabilities(): void { + $this->simulate_wp_abilities_init(); + + $this->register_test_ability( + 'test/admin-only', + array( + 'permission_callback' => null, + 'required_capabilities' => array( 'manage_options' ), + ) + ); + $this->register_test_ability( + 'test/editor-and-up', + array( + 'permission_callback' => null, + 'required_capabilities' => array( 'edit_others_posts' ), + ) + ); + $this->register_test_ability( + 'test/input-dependent', + array( + 'permission_callback' => static function (): bool { + return false; + }, + ) + ); + } + + /** + * Tests that the current_user_can filter leaves out abilities the current user can't run. + * + * @ticket 66325 + */ + public function test_filter_by_current_user_can_excludes_missing_capabilities(): void { + $this->register_abilities_with_required_capabilities(); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); + + $result = wp_get_abilities( array( 'current_user_can' => true ) ); + + $this->assertArrayNotHasKey( 'test/admin-only', $result ); + $this->assertArrayHasKey( 'test/editor-and-up', $result ); + $this->assertArrayHasKey( 'test/input-dependent', $result, 'Abilities without required capabilities should stay in the result.' ); + } + + /** + * Tests that the current_user_can filter keeps abilities the current user can run. + * + * @ticket 66325 + */ + public function test_filter_by_current_user_can_includes_all_for_administrator(): void { + $this->register_abilities_with_required_capabilities(); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $result = wp_get_abilities( array( 'current_user_can' => true ) ); + + $this->assertArrayHasKey( 'test/admin-only', $result ); + $this->assertArrayHasKey( 'test/editor-and-up', $result ); + $this->assertArrayHasKey( 'test/input-dependent', $result ); + } + + /** + * Tests that abilities are not filtered by capabilities unless the caller asks for it. + * + * @ticket 66325 + */ + public function test_filter_by_current_user_can_is_off_by_default(): void { + $this->register_abilities_with_required_capabilities(); + wp_set_current_user( 0 ); + + $result = wp_get_abilities(); + + $this->assertArrayHasKey( 'test/admin-only', $result ); + $this->assertArrayHasKey( 'test/editor-and-up', $result ); + $this->assertArrayHasKey( 'test/input-dependent', $result ); + } + + /** + * Tests that the current_user_can filter doesn't call permission callbacks. + * + * @ticket 66325 + */ + public function test_filter_by_current_user_can_does_not_call_permission_callbacks(): void { + $this->simulate_wp_abilities_init(); + + $callback_calls = 0; + $this->register_test_ability( + 'test/tracked', + array( + 'required_capabilities' => array( 'read' ), + 'permission_callback' => static function () use ( &$callback_calls ): bool { + ++$callback_calls; + return true; + }, + ) + ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); + + $result = wp_get_abilities( array( 'current_user_can' => true ) ); + + $this->assertArrayHasKey( 'test/tracked', $result ); + $this->assertSame( 0, $callback_calls ); + } + + /** + * Tests that the current_user_can filter runs before item_include_callback. + * + * @ticket 66325 + */ + public function test_filter_by_current_user_can_runs_before_item_include_callback(): void { + $this->register_abilities_with_required_capabilities(); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); + + $seen = array(); + $result = wp_get_abilities( + array( + 'namespace' => 'test', + 'current_user_can' => true, + 'item_include_callback' => static function ( WP_Ability $ability ) use ( &$seen ): bool { + $seen[] = $ability->get_name(); + return true; + }, + ) + ); + + $this->assertSame( array( 'test/input-dependent' ), $seen ); + $this->assertSame( array( 'test/input-dependent' ), array_keys( $result ) ); + } } diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php index 0315b67dd9997..8f8b9163c9ab5 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php @@ -322,6 +322,7 @@ public function test_get_items(): void { * Test getting a specific ability. * * @ticket 64098 + * @ticket 66325 */ public function test_get_item(): void { $request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities/test/calculator' ); @@ -330,11 +331,12 @@ public function test_get_item(): void { $this->assertSame( 200, $response->get_status() ); $data = $response->get_data(); - $this->assertCount( 7, $data, 'Response should contain all fields.' ); + $this->assertCount( 8, $data, 'Response should contain all fields.' ); $this->assertSame( 'test/calculator', $data['name'] ); $this->assertSame( 'Calculator', $data['label'] ); $this->assertSame( 'Performs basic calculations', $data['description'] ); $this->assertSame( 'math', $data['category'] ); + $this->assertSame( array(), $data['required_capabilities'] ); $this->assertArrayHasKey( 'input_schema', $data ); $this->assertArrayHasKey( 'output_schema', $data ); $this->assertArrayHasKey( 'meta', $data ); @@ -652,6 +654,7 @@ public function test_context_parameter(): void { * Test schema retrieval. * * @ticket 64098 + * @ticket 66325 */ public function test_get_schema(): void { $request = new WP_REST_Request( 'OPTIONS', '/wp-abilities/v1/abilities' ); @@ -668,7 +671,7 @@ public function test_get_schema(): void { $properties = $schema['properties']; // Assert the count of properties to catch when new keys are added - $this->assertCount( 7, $properties, 'Schema should have exactly 7 properties. If this fails, update this test to include the new property.' ); + $this->assertCount( 8, $properties, 'Schema should have exactly 8 properties. If this fails, update this test to include the new property.' ); // Check all expected properties exist $this->assertArrayHasKey( 'name', $properties ); @@ -678,6 +681,7 @@ public function test_get_schema(): void { $this->assertArrayHasKey( 'output_schema', $properties ); $this->assertArrayHasKey( 'meta', $properties ); $this->assertArrayHasKey( 'category', $properties ); + $this->assertArrayHasKey( 'required_capabilities', $properties ); } /** @@ -1267,4 +1271,74 @@ public function test_required_property_booleans_converted_to_draft_04_array(): v $this->assertSame( array( 'id' ), $data['output_schema']['required'] ); $this->assertArrayNotHasKey( 'required', $data['output_schema']['properties']['id'] ); } + + /** + * Registers an ability that only administrators can run. + */ + private function register_admin_only_ability(): void { + $this->register_test_ability( + 'test/admin-only', + array( + 'label' => 'Admin only', + 'description' => 'Requires the manage_options capability.', + 'category' => 'general', + 'execute_callback' => '__return_true', + 'required_capabilities' => array( 'manage_options' ), + 'meta' => array( 'show_in_rest' => true ), + ) + ); + } + + /** + * Test that the response includes the required capabilities. + * + * @ticket 66325 + */ + public function test_get_item_includes_required_capabilities(): void { + $this->register_admin_only_ability(); + + $request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities/test/admin-only' ); + $response = $this->server->dispatch( $request ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertSame( array( 'manage_options' ), $response->get_data()['required_capabilities'] ); + } + + /** + * Test that the current_user_can parameter leaves out abilities the current user can't run. + * + * @ticket 66325 + */ + public function test_filter_by_current_user_can(): void { + $this->register_admin_only_ability(); + + $request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities' ); + $request->set_param( 'per_page', 100 ); + + $names = wp_list_pluck( $this->server->dispatch( $request )->get_data(), 'name' ); + $this->assertContains( 'test/admin-only', $names, 'Abilities are not filtered by capabilities by default.' ); + + $request->set_param( 'current_user_can', 'true' ); + + $names = wp_list_pluck( $this->server->dispatch( $request )->get_data(), 'name' ); + $this->assertNotContains( 'test/admin-only', $names ); + $this->assertContains( 'test/calculator', $names, 'Abilities without required capabilities stay in the result.' ); + } + + /** + * Test that the current_user_can parameter keeps abilities an administrator can run. + * + * @ticket 66325 + */ + public function test_filter_by_current_user_can_as_administrator(): void { + $this->register_admin_only_ability(); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities' ); + $request->set_param( 'per_page', 100 ); + $request->set_param( 'current_user_can', true ); + + $names = wp_list_pluck( $this->server->dispatch( $request )->get_data(), 'name' ); + $this->assertContains( 'test/admin-only', $names ); + } } From 4e4d2783f2f51f9a1edd4c16441217b06b9c37ef Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 16 Oct 2026 11:18:23 +0200 Subject: [PATCH 2/8] Abilities API: Clarify capability filtering and permission validation. --- src/wp-includes/abilities-api.php | 61 ++++++++++--------- .../abilities-api/class-wp-ability.php | 18 ++---- ...s-wp-rest-abilities-v1-list-controller.php | 22 +++---- .../phpunit/tests/abilities-api/wpAbility.php | 4 +- .../tests/abilities-api/wpGetAbilities.php | 30 ++++----- .../wpRestAbilitiesV1ListController.php | 12 ++-- 6 files changed, 72 insertions(+), 75 deletions(-) diff --git a/src/wp-includes/abilities-api.php b/src/wp-includes/abilities-api.php index ef40c8e0a61e2..35a6f99a4e146 100644 --- a/src/wp-includes/abilities-api.php +++ b/src/wp-includes/abilities-api.php @@ -257,7 +257,10 @@ * Receives optional mixed input data (same as `execute_callback`) and * must return `true`/`false` for simple checks, or `WP_Error` for * detailed error responses. Required unless `$required_capabilities` - * is not empty. Public abilities must set it to `__return_true`. + * is not empty. Abilities that allow execution without authorization checks + * must set it to `__return_true` and omit required capabilities. + * This is independent of the `public` metadata flag, which controls + * exposure to clients rather than authorization. * @type list $required_capabilities Optional. Capabilities the current user must have to run the * ability. Each one is checked with `current_user_can()` before * `permission_callback` runs. Use it for checks that don't depend @@ -482,32 +485,34 @@ function wp_get_ability( string $name ): ?WP_Ability { * * @since 6.9.0 * @since 7.1.0 Added the `$args` parameter for filtering support. - * @since 7.2.0 Added the `current_user_can` argument. + * @since 7.2.0 Added the `has_required_capabilities` argument. * * @see WP_Abilities_Registry::get_all_registered() * * @param array $args { * Optional. Arguments to filter the returned abilities. Default empty array (returns all). * - * @type string $category Filter by category slug. Only abilities whose category - * exactly matches the given slug are included. - * @type string $namespace Filter by ability namespace prefix. Pass the namespace - * without a trailing slash, e.g. `'woocommerce'` matches - * `'woocommerce/create-order'`. - * @type array $meta Filter by meta key/value pairs. All conditions must - * match (AND logic). Supports nested arrays for structured - * meta, e.g. `array( 'mcp' => array( 'public' => true ) )`. - * @type bool $current_user_can Whether to leave out abilities that declare required - * capabilities the current user doesn't have. Abilities - * without required capabilities are always included, - * because their permission may depend on the input. - * Permission callbacks are not called. Default false. - * @type callable $item_include_callback Optional. A callback invoked per ability after declarative - * filters. Receives a WP_Ability instance, returns bool. - * Return true to include, false to exclude. - * @type callable $result_callback Optional. A callback invoked once on the full matched - * array. Receives WP_Ability[], must return WP_Ability[]. - * Use for sorting, slicing, or reshaping the result. + * @type string $category Filter by category slug. Only abilities whose category + * exactly matches the given slug are included. + * @type string $namespace Filter by ability namespace prefix. Pass the namespace + * without a trailing slash, e.g. `'woocommerce'` matches + * `'woocommerce/create-order'`. + * @type array $meta Filter by meta key/value pairs. All conditions must + * match (AND logic). Supports nested arrays for structured + * meta, e.g. `array( 'mcp' => array( 'public' => true ) )`. + * @type bool $has_required_capabilities Whether to leave out abilities that declare required + * capabilities the current user doesn't have. Abilities + * without required capabilities are always included, + * because their permission may depend on the input. + * Permission callbacks and the `wp_ability_permission_result` filter + * are not called. Inclusion does not guarantee permission to execute. + * False disables capability filtering. Default false. + * @type callable $item_include_callback Optional. A callback invoked per ability after declarative + * filters. Receives a WP_Ability instance, returns bool. + * Return true to include, false to exclude. + * @type callable $result_callback Optional. A callback invoked once on the full matched + * array. Receives WP_Ability[], must return WP_Ability[]. + * Use for sorting, slicing, or reshaping the result. * } * @return WP_Ability[] An array of registered WP_Ability instances matching the given args, * keyed by ability name. Returns an empty array if no abilities are @@ -522,12 +527,12 @@ function wp_get_abilities( array $args = array() ): array { $abilities = $registry->get_all_registered(); - $category = isset( $args['category'] ) && is_string( $args['category'] ) ? $args['category'] : ''; - $namespace = isset( $args['namespace'] ) && is_string( $args['namespace'] ) ? rtrim( $args['namespace'], '/' ) . '/' : ''; - $meta = isset( $args['meta'] ) && is_array( $args['meta'] ) ? $args['meta'] : array(); - $current_user_can = ! empty( $args['current_user_can'] ); - $item_include_callback = isset( $args['item_include_callback'] ) && is_callable( $args['item_include_callback'] ) ? $args['item_include_callback'] : null; - $result_callback = isset( $args['result_callback'] ) && is_callable( $args['result_callback'] ) ? $args['result_callback'] : null; + $category = isset( $args['category'] ) && is_string( $args['category'] ) ? $args['category'] : ''; + $namespace = isset( $args['namespace'] ) && is_string( $args['namespace'] ) ? rtrim( $args['namespace'], '/' ) . '/' : ''; + $meta = isset( $args['meta'] ) && is_array( $args['meta'] ) ? $args['meta'] : array(); + $has_required_capabilities = ! empty( $args['has_required_capabilities'] ); + $item_include_callback = isset( $args['item_include_callback'] ) && is_callable( $args['item_include_callback'] ) ? $args['item_include_callback'] : null; + $result_callback = isset( $args['result_callback'] ) && is_callable( $args['result_callback'] ) ? $args['result_callback'] : null; $matched = array(); @@ -548,7 +553,7 @@ function wp_get_abilities( array $args = array() ): array { } // Step 1d: Filter by the capabilities the ability requires from the current user. - if ( $current_user_can ) { + if ( $has_required_capabilities ) { foreach ( $ability->get_required_capabilities() as $capability ) { if ( ! current_user_can( $capability ) ) { continue 2; diff --git a/src/wp-includes/abilities-api/class-wp-ability.php b/src/wp-includes/abilities-api/class-wp-ability.php index e3d5470ee77f7..ead5f5de70073 100644 --- a/src/wp-includes/abilities-api/class-wp-ability.php +++ b/src/wp-includes/abilities-api/class-wp-ability.php @@ -703,11 +703,11 @@ protected function invoke_callback( callable $callback, $input = null ) { * @return bool|WP_Error Whether the ability has the necessary permission. */ public function check_permissions( $input = null ) { - /* - * Custom ability classes skip the registration checks, so they are repeated here. - * A permission callback that is set must be callable, even when required capabilities pass. - */ - if ( null !== $this->permission_callback && ! is_callable( $this->permission_callback ) ) { + // A permission callback may be omitted only when required capabilities are declared. + if ( + ! is_callable( $this->permission_callback ) && + ( null !== $this->permission_callback || empty( $this->required_capabilities ) ) + ) { return new WP_Error( 'ability_invalid_permission_callback', /* translators: %s ability name. */ @@ -715,14 +715,6 @@ public function check_permissions( $input = null ) { ); } - if ( null === $this->permission_callback && empty( $this->required_capabilities ) ) { - return new WP_Error( - 'ability_missing_permission_callback', - /* translators: %s ability name. */ - sprintf( __( 'Ability "%s" does not have a permission callback or required capabilities.' ), $this->name ) - ); - } - /* * Both checks must pass. A check that isn't set is skipped, so the other one decides. * The permission callback only runs when the required capabilities pass. diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php index a028708d7ba6b..fdc2e36b7f947 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php @@ -103,8 +103,8 @@ public function get_items( $request ) { $query_args['meta'] = array_merge( $request['meta'], $query_args['meta'] ); } - if ( ! empty( $request['current_user_can'] ) ) { - $query_args['current_user_can'] = true; + if ( ! empty( $request['has_required_capabilities'] ) ) { + $query_args['has_required_capabilities'] = true; } $abilities = wp_get_abilities( $query_args ); @@ -347,39 +347,39 @@ public function get_item_schema(): array { * * @since 6.9.0 * @since 7.1.0 Added the `namespace` and `meta` parameters and the `rest_abilities_collection_params` filter. - * @since 7.2.0 Added the `current_user_can` parameter. + * @since 7.2.0 Added the `has_required_capabilities` parameter. * * @return array Collection parameters. */ public function get_collection_params(): array { $query_params = array( - 'context' => $this->get_context_param( array( 'default' => 'view' ) ), - 'page' => array( + 'context' => $this->get_context_param( array( 'default' => 'view' ) ), + 'page' => array( 'description' => __( 'Current page of the collection.' ), 'type' => 'integer', 'default' => 1, 'minimum' => 1, ), - 'per_page' => array( + 'per_page' => array( 'description' => __( 'Maximum number of items to be returned in result set.' ), 'type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 100, ), - 'category' => array( + 'category' => array( 'description' => __( 'Limit results to abilities in specific ability category.' ), 'type' => 'string', 'sanitize_callback' => 'sanitize_key', 'validate_callback' => 'rest_validate_request_arg', ), - 'namespace' => array( + 'namespace' => array( 'description' => __( 'Limit results to abilities in a specific namespace.' ), 'type' => 'string', 'sanitize_callback' => 'sanitize_key', 'validate_callback' => 'rest_validate_request_arg', ), - 'meta' => array( + 'meta' => array( 'description' => __( 'Limit results to abilities matching all of the given meta fields.' ), 'type' => 'object', 'properties' => array( @@ -406,8 +406,8 @@ public function get_collection_params(): array { ), 'additionalProperties' => true, ), - 'current_user_can' => array( - 'description' => __( 'Limit results to abilities whose required capabilities the current user has. Abilities that declare no required capabilities are always included.' ), + 'has_required_capabilities' => array( + 'description' => __( 'Limit results to abilities whose required capabilities the current user has. Abilities that declare no required capabilities are always included. Permission callbacks and permission result filters are not evaluated, so inclusion does not guarantee permission to execute. False disables capability filtering.' ), 'type' => 'boolean', 'default' => false, ), diff --git a/tests/phpunit/tests/abilities-api/wpAbility.php b/tests/phpunit/tests/abilities-api/wpAbility.php index 5a088b6edbc0d..ba1f54c9dc73c 100644 --- a/tests/phpunit/tests/abilities-api/wpAbility.php +++ b/tests/phpunit/tests/abilities-api/wpAbility.php @@ -2376,7 +2376,7 @@ public function test_permission_result_filter_can_grant_missing_required_capabil } /** - * Creates an ability with a custom class, which skips the registration checks. + * Creates an ability with a custom class, which skips the base class's callback validation. * * @param array $args The ability properties. * @return WP_Ability The ability instance. @@ -2400,7 +2400,7 @@ public function test_check_permissions_custom_class_without_permission_callback_ $result = $this->create_custom_class_ability( $args )->check_permissions(); $this->assertWPError( $result ); - $this->assertSame( 'ability_missing_permission_callback', $result->get_error_code() ); + $this->assertSame( 'ability_invalid_permission_callback', $result->get_error_code() ); } /** diff --git a/tests/phpunit/tests/abilities-api/wpGetAbilities.php b/tests/phpunit/tests/abilities-api/wpGetAbilities.php index 9246ae1f749ee..a19a645a557d3 100644 --- a/tests/phpunit/tests/abilities-api/wpGetAbilities.php +++ b/tests/phpunit/tests/abilities-api/wpGetAbilities.php @@ -833,15 +833,15 @@ private function register_abilities_with_required_capabilities(): void { } /** - * Tests that the current_user_can filter leaves out abilities the current user can't run. + * Tests that the has_required_capabilities filter excludes abilities whose declared capabilities the current user lacks. * * @ticket 66325 */ - public function test_filter_by_current_user_can_excludes_missing_capabilities(): void { + public function test_filter_by_has_required_capabilities_excludes_missing_capabilities(): void { $this->register_abilities_with_required_capabilities(); wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); - $result = wp_get_abilities( array( 'current_user_can' => true ) ); + $result = wp_get_abilities( array( 'has_required_capabilities' => true ) ); $this->assertArrayNotHasKey( 'test/admin-only', $result ); $this->assertArrayHasKey( 'test/editor-and-up', $result ); @@ -849,15 +849,15 @@ public function test_filter_by_current_user_can_excludes_missing_capabilities(): } /** - * Tests that the current_user_can filter keeps abilities the current user can run. + * Tests that the has_required_capabilities filter keeps abilities whose declared capabilities the current user has. * * @ticket 66325 */ - public function test_filter_by_current_user_can_includes_all_for_administrator(): void { + public function test_filter_by_has_required_capabilities_includes_all_for_administrator(): void { $this->register_abilities_with_required_capabilities(); wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); - $result = wp_get_abilities( array( 'current_user_can' => true ) ); + $result = wp_get_abilities( array( 'has_required_capabilities' => true ) ); $this->assertArrayHasKey( 'test/admin-only', $result ); $this->assertArrayHasKey( 'test/editor-and-up', $result ); @@ -869,7 +869,7 @@ public function test_filter_by_current_user_can_includes_all_for_administrator() * * @ticket 66325 */ - public function test_filter_by_current_user_can_is_off_by_default(): void { + public function test_filter_by_has_required_capabilities_is_off_by_default(): void { $this->register_abilities_with_required_capabilities(); wp_set_current_user( 0 ); @@ -881,11 +881,11 @@ public function test_filter_by_current_user_can_is_off_by_default(): void { } /** - * Tests that the current_user_can filter doesn't call permission callbacks. + * Tests that the has_required_capabilities filter doesn't call permission callbacks. * * @ticket 66325 */ - public function test_filter_by_current_user_can_does_not_call_permission_callbacks(): void { + public function test_filter_by_has_required_capabilities_does_not_call_permission_callbacks(): void { $this->simulate_wp_abilities_init(); $callback_calls = 0; @@ -901,27 +901,27 @@ public function test_filter_by_current_user_can_does_not_call_permission_callbac ); wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); - $result = wp_get_abilities( array( 'current_user_can' => true ) ); + $result = wp_get_abilities( array( 'has_required_capabilities' => true ) ); $this->assertArrayHasKey( 'test/tracked', $result ); $this->assertSame( 0, $callback_calls ); } /** - * Tests that the current_user_can filter runs before item_include_callback. + * Tests that the has_required_capabilities filter runs before item_include_callback. * * @ticket 66325 */ - public function test_filter_by_current_user_can_runs_before_item_include_callback(): void { + public function test_filter_by_has_required_capabilities_runs_before_item_include_callback(): void { $this->register_abilities_with_required_capabilities(); wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); $seen = array(); $result = wp_get_abilities( array( - 'namespace' => 'test', - 'current_user_can' => true, - 'item_include_callback' => static function ( WP_Ability $ability ) use ( &$seen ): bool { + 'namespace' => 'test', + 'has_required_capabilities' => true, + 'item_include_callback' => static function ( WP_Ability $ability ) use ( &$seen ): bool { $seen[] = $ability->get_name(); return true; }, diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php index 8f8b9163c9ab5..917e1c0d79c7b 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php @@ -1305,11 +1305,11 @@ public function test_get_item_includes_required_capabilities(): void { } /** - * Test that the current_user_can parameter leaves out abilities the current user can't run. + * Test that the has_required_capabilities parameter excludes abilities whose declared capabilities the current user lacks. * * @ticket 66325 */ - public function test_filter_by_current_user_can(): void { + public function test_filter_by_has_required_capabilities(): void { $this->register_admin_only_ability(); $request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities' ); @@ -1318,7 +1318,7 @@ public function test_filter_by_current_user_can(): void { $names = wp_list_pluck( $this->server->dispatch( $request )->get_data(), 'name' ); $this->assertContains( 'test/admin-only', $names, 'Abilities are not filtered by capabilities by default.' ); - $request->set_param( 'current_user_can', 'true' ); + $request->set_param( 'has_required_capabilities', 'true' ); $names = wp_list_pluck( $this->server->dispatch( $request )->get_data(), 'name' ); $this->assertNotContains( 'test/admin-only', $names ); @@ -1326,17 +1326,17 @@ public function test_filter_by_current_user_can(): void { } /** - * Test that the current_user_can parameter keeps abilities an administrator can run. + * Test that the has_required_capabilities parameter keeps abilities whose declared capabilities an administrator has. * * @ticket 66325 */ - public function test_filter_by_current_user_can_as_administrator(): void { + public function test_filter_by_has_required_capabilities_as_administrator(): void { $this->register_admin_only_ability(); wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); $request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities' ); $request->set_param( 'per_page', 100 ); - $request->set_param( 'current_user_can', true ); + $request->set_param( 'has_required_capabilities', true ); $names = wp_list_pluck( $this->server->dispatch( $request )->get_data(), 'name' ); $this->assertContains( 'test/admin-only', $names ); From 410a5ac6e5fce82ccbffa3fa2240e26eb32aa8c1 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 16 Oct 2026 11:22:36 +0200 Subject: [PATCH 3/8] Tests: Update the REST API JS client fixture for the abilities capability filter. See #66325. Co-Authored-By: Claude Opus 5.5 --- tests/qunit/fixtures/wp-api-generated.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/qunit/fixtures/wp-api-generated.js b/tests/qunit/fixtures/wp-api-generated.js index 0f627b5e14569..7abc9b9795d82 100644 --- a/tests/qunit/fixtures/wp-api-generated.js +++ b/tests/qunit/fixtures/wp-api-generated.js @@ -12756,6 +12756,12 @@ mockedApiResponse.Schema = { }, "additionalProperties": true, "required": false + }, + "has_required_capabilities": { + "description": "Limit results to abilities whose required capabilities the current user has. Abilities that declare no required capabilities are always included. Permission callbacks and permission result filters are not evaluated, so inclusion does not guarantee permission to execute. False disables capability filtering.", + "type": "boolean", + "default": false, + "required": false } } } From fce5cd0d1095f9165e4e9b9c0f49b677ff453c6a Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 16 Oct 2026 11:28:26 +0200 Subject: [PATCH 4/8] Abilities API: Simplify the docs for required capabilities. Uses shorter and more consistent wording for `permission_callback`, `required_capabilities`, and the `has_required_capabilities` filter. Removes reasoning that was repeated in several places. See #66325. Co-Authored-By: Claude Opus 5.5 --- src/wp-includes/abilities-api.php | 28 ++++++------- .../class-wp-abilities-registry.php | 8 ++-- .../abilities-api/class-wp-ability.php | 40 +++++++++---------- ...s-wp-rest-abilities-v1-list-controller.php | 2 +- tests/qunit/fixtures/wp-api-generated.js | 2 +- 5 files changed, 36 insertions(+), 44 deletions(-) diff --git a/src/wp-includes/abilities-api.php b/src/wp-includes/abilities-api.php index 35a6f99a4e146..e4826e657830c 100644 --- a/src/wp-includes/abilities-api.php +++ b/src/wp-includes/abilities-api.php @@ -253,19 +253,17 @@ * @type callable $execute_callback Required. A callback function to execute when the ability is invoked. * Receives optional mixed input data and must return either a result * value (any type) or a `WP_Error` object on failure. - * @type callable $permission_callback Optional. A callback function to check permissions before execution. + * @type callable $permission_callback Required unless `$required_capabilities` lists at least one capability. + * A callback function to check permissions before execution. * Receives optional mixed input data (same as `execute_callback`) and * must return `true`/`false` for simple checks, or `WP_Error` for - * detailed error responses. Required unless `$required_capabilities` - * is not empty. Abilities that allow execution without authorization checks - * must set it to `__return_true` and omit required capabilities. - * This is independent of the `public` metadata flag, which controls - * exposure to clients rather than authorization. + * detailed error responses. To let everyone run the ability, + * use `__return_true`. The `public` meta flag doesn't affect + * this. It only controls where the ability is shown. * @type list $required_capabilities Optional. Capabilities the current user must have to run the * ability. Each one is checked with `current_user_can()` before * `permission_callback` runs. Use it for checks that don't depend - * on the input. Abilities the current user can't run can then be - * left out when listing them. Default empty array. + * on the input. Default empty array. * @type array $input_schema Optional. JSON Schema definition for validating the ability's input. * Must be a valid JSON Schema object defining the structure and * constraints for input data. Used for automatic validation and @@ -500,13 +498,11 @@ function wp_get_ability( string $name ): ?WP_Ability { * @type array $meta Filter by meta key/value pairs. All conditions must * match (AND logic). Supports nested arrays for structured * meta, e.g. `array( 'mcp' => array( 'public' => true ) )`. - * @type bool $has_required_capabilities Whether to leave out abilities that declare required - * capabilities the current user doesn't have. Abilities - * without required capabilities are always included, - * because their permission may depend on the input. - * Permission callbacks and the `wp_ability_permission_result` filter - * are not called. Inclusion does not guarantee permission to execute. - * False disables capability filtering. Default false. + * @type bool $has_required_capabilities Whether to leave out abilities whose required capabilities + * the current user doesn't have. Abilities without required + * capabilities are always included. Permission callbacks + * and filters don't run, so an included ability can still + * deny execution. Default false. * @type callable $item_include_callback Optional. A callback invoked per ability after declarative * filters. Receives a WP_Ability instance, returns bool. * Return true to include, false to exclude. @@ -552,7 +548,7 @@ function wp_get_abilities( array $args = array() ): array { continue; } - // Step 1d: Filter by the capabilities the ability requires from the current user. + // Step 1d: Leave out abilities whose required capabilities the current user doesn't have. if ( $has_required_capabilities ) { foreach ( $ability->get_required_capabilities() as $capability ) { if ( ! current_user_can( $capability ) ) { diff --git a/src/wp-includes/abilities-api/class-wp-abilities-registry.php b/src/wp-includes/abilities-api/class-wp-abilities-registry.php index 8302d35e02360..6790ed853516f 100644 --- a/src/wp-includes/abilities-api/class-wp-abilities-registry.php +++ b/src/wp-includes/abilities-api/class-wp-abilities-registry.php @@ -58,9 +58,9 @@ final class WP_Abilities_Registry { * Defaults to `uncategorized`. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback Optional. A callback function to check permissions before execution. + * @type callable $permission_callback A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. - * Required unless `$required_capabilities` is not empty. + * Required unless `$required_capabilities` lists at least one capability. * @type list $required_capabilities Optional. Capabilities the current user must have to run the * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. @@ -130,9 +130,9 @@ public function register( string $name, array $args ): ?WP_Ability { * Defaults to `uncategorized`. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback Optional. A callback function to check permissions before execution. + * @type callable $permission_callback A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. - * Required unless `$required_capabilities` is not empty. + * Required unless `$required_capabilities` lists at least one capability. * @type list $required_capabilities Optional. Capabilities the current user must have to run the * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. diff --git a/src/wp-includes/abilities-api/class-wp-ability.php b/src/wp-includes/abilities-api/class-wp-ability.php index ead5f5de70073..0867420cfaeb9 100644 --- a/src/wp-includes/abilities-api/class-wp-ability.php +++ b/src/wp-includes/abilities-api/class-wp-ability.php @@ -161,9 +161,9 @@ class WP_Ability { * @type string $category The ability category slug this ability belongs to. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback Optional. A callback function to check permissions before execution. + * @type callable $permission_callback A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. - * Required unless `$required_capabilities` is not empty. + * Required unless `$required_capabilities` lists at least one capability. * @type list $required_capabilities Optional. Capabilities the current user must have to run the * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. @@ -235,9 +235,9 @@ public function __construct( string $name, array $args ) { * @type string $category The ability category slug this ability belongs to. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback Optional. A callback function to check permissions before execution. + * @type callable $permission_callback A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. - * Required unless `$required_capabilities` is not empty. + * Required unless `$required_capabilities` lists at least one capability. * @type list $required_capabilities Optional. Capabilities the current user must have to run the * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. Required if ability accepts an input. @@ -271,9 +271,9 @@ public function __construct( string $name, array $args ) { * @type string $category The ability category slug this ability belongs to. * @type callable $execute_callback A callback function to execute when the ability is invoked. * Receives optional mixed input and returns mixed result or WP_Error. - * @type callable $permission_callback Optional. A callback function to check permissions before execution. + * @type callable $permission_callback A callback function to check permissions before execution. * Receives optional mixed input and returns bool or WP_Error. - * Required unless `$required_capabilities` is not empty. + * Required unless `$required_capabilities` lists at least one capability. * @type list $required_capabilities Optional. Capabilities the current user must have to run the * ability. They are checked before `$permission_callback`. * @type array $input_schema Optional. JSON Schema definition for the ability's input. @@ -333,8 +333,8 @@ protected function prepare_properties( array $args ): array { } /* - * If we are not overriding `ability_class` parameter during instantiation, then we need to validate the permission_callback. - * It can be left out when the ability declares at least one required capability. + * Validate the permission_callback, unless a custom `ability_class` is used. + * It can be left out when the ability declares required capabilities. */ if ( get_class( $this ) === self::class ) { if ( isset( $args['permission_callback'] ) ) { @@ -695,7 +695,7 @@ protected function invoke_callback( callable $callback, $input = null ) { * * @since 6.9.0 * @since 7.1.0 Added the `wp_ability_permission_result` filter. - * @since 7.2.0 Checks the `required_capabilities` before the `permission_callback`. + * @since 7.2.0 Added the `required_capabilities` check. * * @see validate_input() * @@ -715,10 +715,7 @@ public function check_permissions( $input = null ) { ); } - /* - * Both checks must pass. A check that isn't set is skipped, so the other one decides. - * The permission callback only runs when the required capabilities pass. - */ + // Both checks must pass. A check that isn't set is skipped. $permission = true; foreach ( $this->required_capabilities as $capability ) { if ( ! current_user_can( $capability ) ) { @@ -734,21 +731,20 @@ public function check_permissions( $input = null ) { /** * Filters the result of an ability's permission check. * - * Fires after the `required_capabilities` check and the registered `permission_callback`. - * It also fires when a required capability is missing. Plugins can use this to layer - * additional authorization rules on top of the ability's own permission logic — for example, + * Fires after the required capabilities check and the `permission_callback`. Plugins can use this + * to layer additional authorization rules on top of the ability's own permission logic — for example, * multi-factor authorization gates or temporary permission elevation for trusted contexts. * - * Filters can return `true` to grant, `false` to deny, or a `WP_Error` to deny with a specific - * error code and message. The filter receives `false` when a required capability is missing. - * Otherwise, it receives whatever the `permission_callback` produced, or `true` when there is none. - * Any other return value is coerced to `false`. + * The filter receives `false` when a required capability is missing. Otherwise, it receives the + * result of `permission_callback`, or `true` when there is none. Filters can return `true` to grant, + * `false` to deny, or a `WP_Error` to deny with a specific error code and message. Any other return + * value is coerced to `false`. * * @since 7.1.0 * @since 7.2.0 Also fires with `false` when a required capability is missing. * - * @param bool|WP_Error $permission The permission result from the required capabilities check - * and the `permission_callback`. + * @param bool|WP_Error $permission The result of the required capabilities check and the + * `permission_callback`. * @param string $ability_name The name of the ability. * @param mixed $input The input data for the permission check. * @param WP_Ability $ability The ability instance. diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php index fdc2e36b7f947..da2bb71fc51fd 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-list-controller.php @@ -407,7 +407,7 @@ public function get_collection_params(): array { 'additionalProperties' => true, ), 'has_required_capabilities' => array( - 'description' => __( 'Limit results to abilities whose required capabilities the current user has. Abilities that declare no required capabilities are always included. Permission callbacks and permission result filters are not evaluated, so inclusion does not guarantee permission to execute. False disables capability filtering.' ), + 'description' => __( 'Limit results to abilities whose required capabilities the current user has. Abilities without required capabilities are always included. Permission callbacks don\'t run, so an included ability can still deny execution.' ), 'type' => 'boolean', 'default' => false, ), diff --git a/tests/qunit/fixtures/wp-api-generated.js b/tests/qunit/fixtures/wp-api-generated.js index 7abc9b9795d82..befd5cf9a0575 100644 --- a/tests/qunit/fixtures/wp-api-generated.js +++ b/tests/qunit/fixtures/wp-api-generated.js @@ -12758,7 +12758,7 @@ mockedApiResponse.Schema = { "required": false }, "has_required_capabilities": { - "description": "Limit results to abilities whose required capabilities the current user has. Abilities that declare no required capabilities are always included. Permission callbacks and permission result filters are not evaluated, so inclusion does not guarantee permission to execute. False disables capability filtering.", + "description": "Limit results to abilities whose required capabilities the current user has. Abilities without required capabilities are always included. Permission callbacks don't run, so an included ability can still deny execution.", "type": "boolean", "default": false, "required": false From c44600ecb091c72d482cede1dd57fd46258c6c08 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 16 Oct 2026 11:41:46 +0200 Subject: [PATCH 5/8] Abilities API: Clarify permission validation conditions. --- src/wp-includes/abilities-api/class-wp-ability.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/wp-includes/abilities-api/class-wp-ability.php b/src/wp-includes/abilities-api/class-wp-ability.php index 0867420cfaeb9..442d44fb6dfb3 100644 --- a/src/wp-includes/abilities-api/class-wp-ability.php +++ b/src/wp-includes/abilities-api/class-wp-ability.php @@ -703,11 +703,13 @@ protected function invoke_callback( callable $callback, $input = null ) { * @return bool|WP_Error Whether the ability has the necessary permission. */ public function check_permissions( $input = null ) { - // A permission callback may be omitted only when required capabilities are declared. - if ( - ! is_callable( $this->permission_callback ) && - ( null !== $this->permission_callback || empty( $this->required_capabilities ) ) - ) { + // A permission callback that is set must be callable. + $is_invalid_callback = null !== $this->permission_callback && ! is_callable( $this->permission_callback ); + + // Without a permission callback, the ability must declare required capabilities. + $is_missing_check = null === $this->permission_callback && empty( $this->required_capabilities ); + + if ( $is_invalid_callback || $is_missing_check ) { return new WP_Error( 'ability_invalid_permission_callback', /* translators: %s ability name. */ From f3b2b46593449e29c5d7edea5aa4a54adef44e44 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 16 Oct 2026 11:45:51 +0200 Subject: [PATCH 6/8] Abilities API: Clarify the invalid permission configuration message. --- src/wp-includes/abilities-api/class-wp-ability.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/abilities-api/class-wp-ability.php b/src/wp-includes/abilities-api/class-wp-ability.php index 442d44fb6dfb3..c7e32ad8efd64 100644 --- a/src/wp-includes/abilities-api/class-wp-ability.php +++ b/src/wp-includes/abilities-api/class-wp-ability.php @@ -713,7 +713,7 @@ public function check_permissions( $input = null ) { return new WP_Error( 'ability_invalid_permission_callback', /* translators: %s ability name. */ - sprintf( __( 'Ability "%s" does not have a valid permission callback.' ), $this->name ) + sprintf( __( 'Ability "%s" must provide a valid permission callback, or omit it and declare required capabilities.' ), $this->name ) ); } From 8e37e2c5412aecc5819d6a4efbcaa24551080654 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Mon, 19 Oct 2026 11:48:43 +0200 Subject: [PATCH 7/8] Abilities API: Align the `wp_register_ability()` argument docs. Co-Authored-By: Claude Opus 5.5 --- src/wp-includes/abilities-api.php | 54 +++++++++++++++---------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/src/wp-includes/abilities-api.php b/src/wp-includes/abilities-api.php index e4826e657830c..36c1af8a07e86 100644 --- a/src/wp-includes/abilities-api.php +++ b/src/wp-includes/abilities-api.php @@ -244,34 +244,34 @@ * @param array $args { * An associative array of arguments for configuring the ability. * - * @type string $label Required. The human-readable label for the ability. - * @type string $description Required. A detailed description of what the ability does - * and when it should be used. - * @type string $category Optional. The ability category slug this ability belongs to. - * Defaults to `uncategorized`. Custom categories must be registered - * via `wp_register_ability_category()` before registering the ability. - * @type callable $execute_callback Required. A callback function to execute when the ability is invoked. - * Receives optional mixed input data and must return either a result - * value (any type) or a `WP_Error` object on failure. - * @type callable $permission_callback Required unless `$required_capabilities` lists at least one capability. - * A callback function to check permissions before execution. - * Receives optional mixed input data (same as `execute_callback`) and - * must return `true`/`false` for simple checks, or `WP_Error` for - * detailed error responses. To let everyone run the ability, - * use `__return_true`. The `public` meta flag doesn't affect - * this. It only controls where the ability is shown. + * @type string $label Required. The human-readable label for the ability. + * @type string $description Required. A detailed description of what the ability does + * and when it should be used. + * @type string $category Optional. The ability category slug this ability belongs to. + * Defaults to `uncategorized`. Custom categories must be registered + * via `wp_register_ability_category()` before registering the ability. + * @type callable $execute_callback Required. A callback function to execute when the ability is invoked. + * Receives optional mixed input data and must return either a result + * value (any type) or a `WP_Error` object on failure. + * @type callable $permission_callback Required unless `$required_capabilities` lists at least one capability. + * A callback function to check permissions before execution. + * Receives optional mixed input data (same as `execute_callback`) and + * must return `true`/`false` for simple checks, or `WP_Error` for + * detailed error responses. To let everyone run the ability, + * use `__return_true`. The `public` meta flag doesn't affect + * this. It only controls where the ability is shown. * @type list $required_capabilities Optional. Capabilities the current user must have to run the - * ability. Each one is checked with `current_user_can()` before - * `permission_callback` runs. Use it for checks that don't depend - * on the input. Default empty array. - * @type array $input_schema Optional. JSON Schema definition for validating the ability's input. - * Must be a valid JSON Schema object defining the structure and - * constraints for input data. Used for automatic validation and - * API documentation. - * @type array $output_schema Optional. JSON Schema definition for the ability's output. - * Describes the structure of successful return values from - * `execute_callback`. Used for documentation and validation. - * @type array $meta { + * ability. Each one is checked with `current_user_can()` before + * `permission_callback` runs. Use it for checks that don't depend + * on the input. Default empty array. + * @type array $input_schema Optional. JSON Schema definition for validating the ability's input. + * Must be a valid JSON Schema object defining the structure and + * constraints for input data. Used for automatic validation and + * API documentation. + * @type array $output_schema Optional. JSON Schema definition for the ability's output. + * Describes the structure of successful return values from + * `execute_callback`. Used for documentation and validation. + * @type array $meta { * Optional. Additional metadata for the ability. * * @type array $annotations { From 8f7d992e8bcf10a3a759571a58bfef2278080407 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Mon, 19 Oct 2026 11:48:44 +0200 Subject: [PATCH 8/8] Tests: Consolidate the required capabilities tests. Merges similar tests into data providers and groups the helpers. Keeps the ticket reference only on newly added tests. Co-Authored-By: Claude Opus 5.5 --- .../phpunit/tests/abilities-api/wpAbility.php | 153 ++++++++---------- .../tests/abilities-api/wpGetAbilities.php | 64 ++++---- .../wpRestAbilitiesV1ListController.php | 2 - 3 files changed, 100 insertions(+), 119 deletions(-) diff --git a/tests/phpunit/tests/abilities-api/wpAbility.php b/tests/phpunit/tests/abilities-api/wpAbility.php index ba1f54c9dc73c..e446c3faf22db 100644 --- a/tests/phpunit/tests/abilities-api/wpAbility.php +++ b/tests/phpunit/tests/abilities-api/wpAbility.php @@ -2142,31 +2142,41 @@ private function get_properties_with_required_capabilities( array $capabilities } /** - * Tests that required capabilities default to an empty array. - * - * @ticket 66325 + * Creates an ability with a custom class, which skips the base class's callback validation. * - * @covers WP_Ability::get_required_capabilities + * @param array $args The ability properties. + * @return WP_Ability The ability instance. */ - public function test_required_capabilities_default_to_empty_array() { - $ability = new WP_Ability( self::$test_ability_name, self::$test_ability_properties ); + private function create_custom_class_ability( array $args ): WP_Ability { + return new class( self::$test_ability_name, $args ) extends WP_Ability {}; + } - $this->assertSame( array(), $ability->get_required_capabilities() ); + /** + * Data provider for required capabilities that default to an empty array. + * + * @return array}> + */ + public static function data_required_capabilities_default_to_empty_array(): array { + return array( + 'not set' => array( array() ), + 'null' => array( array( 'required_capabilities' => null ) ), + ); } /** - * Tests that null required capabilities are treated as an empty array. + * Tests that required capabilities default to an empty array. * * @ticket 66325 * * @covers WP_Ability::prepare_properties * @covers WP_Ability::get_required_capabilities + * + * @dataProvider data_required_capabilities_default_to_empty_array + * + * @param array $overrides The properties to merge into the test ability properties. */ - public function test_null_required_capabilities_default_to_empty_array() { - $args = self::$test_ability_properties; - $args['required_capabilities'] = null; - - $ability = new WP_Ability( self::$test_ability_name, $args ); + public function test_required_capabilities_default_to_empty_array( array $overrides ) { + $ability = new WP_Ability( self::$test_ability_name, array_merge( self::$test_ability_properties, $overrides ) ); $this->assertSame( array(), $ability->get_required_capabilities() ); } @@ -2224,7 +2234,7 @@ public function test_invalid_permission_callback_with_required_capabilities_thro * * @return array */ - public function data_invalid_required_capabilities(): array { + public static function data_invalid_required_capabilities(): array { return array( 'string' => array( 'manage_options' ), 'empty string' => array( array( '' ) ), @@ -2260,39 +2270,39 @@ public function test_invalid_required_capabilities_throw_exception( $capabilitie } /** - * Tests that check_permissions() grants access when the user has all required capabilities. + * Data provider for permission checks based on required capabilities. * - * @ticket 66325 - * - * @covers WP_Ability::check_permissions + * @return array */ - public function test_check_permissions_grants_when_user_has_required_capabilities() { - wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); - - $ability = new WP_Ability( - self::$test_ability_name, - $this->get_properties_with_required_capabilities( array( 'edit_posts', 'manage_options' ) ) + public static function data_check_permissions_with_required_capabilities(): array { + return array( + 'user has all capabilities' => array( 'administrator', true ), + 'user misses one capability' => array( 'editor', false ), + 'user misses all capabilities' => array( 'subscriber', false ), ); - - $this->assertTrue( $ability->check_permissions() ); } /** - * Tests that check_permissions() denies access when the user misses one required capability. + * Tests that check_permissions() grants access only when the user has all required capabilities. * * @ticket 66325 * * @covers WP_Ability::check_permissions + * + * @dataProvider data_check_permissions_with_required_capabilities + * + * @param string $role The role of the current user. + * @param bool $expected The expected permission result. */ - public function test_check_permissions_denies_when_user_misses_a_required_capability() { - wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); + public function test_check_permissions_with_required_capabilities( string $role, bool $expected ) { + wp_set_current_user( self::factory()->user->create( array( 'role' => $role ) ) ); $ability = new WP_Ability( self::$test_ability_name, $this->get_properties_with_required_capabilities( array( 'edit_posts', 'manage_options' ) ) ); - $this->assertFalse( $ability->check_permissions() ); + $this->assertSame( $expected, $ability->check_permissions() ); } /** @@ -2305,10 +2315,9 @@ public function test_check_permissions_denies_when_user_misses_a_required_capabi public function test_check_permissions_skips_permission_callback_when_capability_is_missing() { wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); - $callback_calls = 0; - $args = self::$test_ability_properties; - $args['required_capabilities'] = array( 'manage_options' ); - $args['permission_callback'] = static function () use ( &$callback_calls ): bool { + $callback_calls = 0; + $args = $this->get_properties_with_required_capabilities( array( 'manage_options' ) ); + $args['permission_callback'] = static function () use ( &$callback_calls ): bool { ++$callback_calls; return true; }; @@ -2329,10 +2338,9 @@ public function test_check_permissions_skips_permission_callback_when_capability public function test_check_permissions_runs_permission_callback_after_required_capabilities() { wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); - $args = self::$test_ability_properties; - $args['input_schema'] = array( 'type' => 'integer' ); - $args['required_capabilities'] = array( 'manage_options' ); - $args['permission_callback'] = static function ( int $input ) { + $args = $this->get_properties_with_required_capabilities( array( 'manage_options' ) ); + $args['input_schema'] = array( 'type' => 'integer' ); + $args['permission_callback'] = static function ( int $input ) { return 7 === $input ? true : new WP_Error( 'wrong_input', 'Wrong input.' ); }; @@ -2376,66 +2384,43 @@ public function test_permission_result_filter_can_grant_missing_required_capabil } /** - * Creates an ability with a custom class, which skips the base class's callback validation. - * - * @param array $args The ability properties. - * @return WP_Ability The ability instance. - */ - private function create_custom_class_ability( array $args ): WP_Ability { - return new class( self::$test_ability_name, $args ) extends WP_Ability {}; - } - - /** - * Tests that check_permissions() returns an error when a custom class has neither a - * permission callback nor required capabilities. + * Data provider for custom class abilities without a valid permission check. * - * @ticket 66325 - * - * @covers WP_Ability::check_permissions + * @return array}> */ - public function test_check_permissions_custom_class_without_permission_callback_or_capabilities() { - $args = self::$test_ability_properties; - unset( $args['permission_callback'] ); - - $result = $this->create_custom_class_ability( $args )->check_permissions(); - - $this->assertWPError( $result ); - $this->assertSame( 'ability_invalid_permission_callback', $result->get_error_code() ); + public static function data_check_permissions_custom_class_without_valid_permission_check(): array { + return array( + 'no permission callback or capabilities' => array( + array( 'permission_callback' => null ), + ), + 'invalid permission callback' => array( + array( 'permission_callback' => 'not_a_callable_function' ), + ), + 'invalid permission callback and capabilities' => array( + array( + 'permission_callback' => 'not_a_callable_function', + 'required_capabilities' => array( 'manage_options' ), + ), + ), + ); } /** - * Tests that check_permissions() returns an error when a custom class has a permission - * callback that is not callable and no required capabilities. + * Tests that check_permissions() returns an error when a custom class has no valid + * permission callback, even if the user has all required capabilities. * * @ticket 66325 * * @covers WP_Ability::check_permissions - */ - public function test_check_permissions_custom_class_with_invalid_permission_callback() { - $args = self::$test_ability_properties; - $args['permission_callback'] = 'not_a_callable_function'; - - $result = $this->create_custom_class_ability( $args )->check_permissions(); - - $this->assertWPError( $result ); - $this->assertSame( 'ability_invalid_permission_callback', $result->get_error_code() ); - } - - /** - * Tests that check_permissions() doesn't grant access when a custom class has a permission - * callback that is not callable, even if the user has all required capabilities. * - * @ticket 66325 + * @dataProvider data_check_permissions_custom_class_without_valid_permission_check * - * @covers WP_Ability::check_permissions + * @param array $overrides The properties to merge into the test ability properties. */ - public function test_check_permissions_custom_class_with_invalid_permission_callback_and_capabilities() { + public function test_check_permissions_custom_class_without_valid_permission_check( array $overrides ) { wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); - $args = $this->get_properties_with_required_capabilities( array( 'manage_options' ) ); - $args['permission_callback'] = 'not_a_callable_function'; - - $result = $this->create_custom_class_ability( $args )->check_permissions(); + $result = $this->create_custom_class_ability( array_merge( self::$test_ability_properties, $overrides ) )->check_permissions(); $this->assertWPError( $result ); $this->assertSame( 'ability_invalid_permission_callback', $result->get_error_code() ); diff --git a/tests/phpunit/tests/abilities-api/wpGetAbilities.php b/tests/phpunit/tests/abilities-api/wpGetAbilities.php index a19a645a557d3..3618a4070bc34 100644 --- a/tests/phpunit/tests/abilities-api/wpGetAbilities.php +++ b/tests/phpunit/tests/abilities-api/wpGetAbilities.php @@ -833,51 +833,49 @@ private function register_abilities_with_required_capabilities(): void { } /** - * Tests that the has_required_capabilities filter excludes abilities whose declared capabilities the current user lacks. + * Data provider for filtering by the current user's required capabilities. * - * @ticket 66325 + * @return array, 2: string[]}> */ - public function test_filter_by_has_required_capabilities_excludes_missing_capabilities(): void { - $this->register_abilities_with_required_capabilities(); - wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); - - $result = wp_get_abilities( array( 'has_required_capabilities' => true ) ); - - $this->assertArrayNotHasKey( 'test/admin-only', $result ); - $this->assertArrayHasKey( 'test/editor-and-up', $result ); - $this->assertArrayHasKey( 'test/input-dependent', $result, 'Abilities without required capabilities should stay in the result.' ); + public static function data_filter_by_has_required_capabilities(): array { + return array( + 'editor misses a capability' => array( + 'editor', + array( 'has_required_capabilities' => true ), + array( 'test/editor-and-up', 'test/input-dependent' ), + ), + 'administrator has all' => array( + 'administrator', + array( 'has_required_capabilities' => true ), + array( 'test/admin-only', 'test/editor-and-up', 'test/input-dependent' ), + ), + 'filter is off by default' => array( + '', + array(), + array( 'test/admin-only', 'test/editor-and-up', 'test/input-dependent' ), + ), + ); } /** - * Tests that the has_required_capabilities filter keeps abilities whose declared capabilities the current user has. + * Tests that the has_required_capabilities filter leaves out abilities whose declared + * capabilities the current user lacks. Abilities without required capabilities stay. * * @ticket 66325 - */ - public function test_filter_by_has_required_capabilities_includes_all_for_administrator(): void { - $this->register_abilities_with_required_capabilities(); - wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); - - $result = wp_get_abilities( array( 'has_required_capabilities' => true ) ); - - $this->assertArrayHasKey( 'test/admin-only', $result ); - $this->assertArrayHasKey( 'test/editor-and-up', $result ); - $this->assertArrayHasKey( 'test/input-dependent', $result ); - } - - /** - * Tests that abilities are not filtered by capabilities unless the caller asks for it. * - * @ticket 66325 + * @dataProvider data_filter_by_has_required_capabilities + * + * @param string $role The role of the current user. Empty for a logged-out user. + * @param array $args The arguments passed to wp_get_abilities(). + * @param string[] $expected The expected ability names. */ - public function test_filter_by_has_required_capabilities_is_off_by_default(): void { + public function test_filter_by_has_required_capabilities( string $role, array $args, array $expected ): void { $this->register_abilities_with_required_capabilities(); - wp_set_current_user( 0 ); + wp_set_current_user( '' === $role ? 0 : self::factory()->user->create( array( 'role' => $role ) ) ); - $result = wp_get_abilities(); + $result = wp_get_abilities( array_merge( array( 'namespace' => 'test' ), $args ) ); - $this->assertArrayHasKey( 'test/admin-only', $result ); - $this->assertArrayHasKey( 'test/editor-and-up', $result ); - $this->assertArrayHasKey( 'test/input-dependent', $result ); + $this->assertSameSets( $expected, array_keys( $result ) ); } /** diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php index 917e1c0d79c7b..feb442fd1e462 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php @@ -322,7 +322,6 @@ public function test_get_items(): void { * Test getting a specific ability. * * @ticket 64098 - * @ticket 66325 */ public function test_get_item(): void { $request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities/test/calculator' ); @@ -654,7 +653,6 @@ public function test_context_parameter(): void { * Test schema retrieval. * * @ticket 64098 - * @ticket 66325 */ public function test_get_schema(): void { $request = new WP_REST_Request( 'OPTIONS', '/wp-abilities/v1/abilities' );