diff --git a/src/wp-includes/abilities-api.php b/src/wp-includes/abilities-api.php index abd3684273a5a..36c1af8a07e86 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() @@ -245,27 +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. 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. - * @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 { + * @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 { * Optional. Additional metadata for the ability. * * @type array $annotations { @@ -477,26 +483,32 @@ 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 `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 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 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. + * @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 @@ -511,11 +523,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(); - $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(); @@ -535,6 +548,15 @@ function wp_get_abilities( array $args = array() ): array { continue; } + // 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 ) ) { + 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..6790ed853516f 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() * @@ -59,6 +60,9 @@ final class WP_Abilities_Registry { * Receives optional mixed input and returns mixed result or WP_Error. * @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` 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. * @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. @@ -127,6 +132,9 @@ public function register( string $name, array $args ): ?WP_Ability { * Receives optional mixed input and returns mixed result or WP_Error. * @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` 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. * @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..c7e32ad8efd64 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() * @@ -154,6 +163,9 @@ class WP_Ability { * Receives optional mixed input and returns mixed result or WP_Error. * @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` 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. * @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() * @@ -224,6 +237,9 @@ public function __construct( string $name, array $args ) { * Receives optional mixed input and returns mixed result or WP_Error. * @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` 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. * @type array $output_schema Optional. JSON Schema definition for the ability's output. * @type array $meta { @@ -257,6 +273,9 @@ public function __construct( string $name, array $args ) { * Receives optional mixed input and returns mixed result or WP_Error. * @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` 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. * @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.' ) ); } + /* + * 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'] ) ) { + 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 Added the `required_capabilities` check. * * @see validate_input() * @@ -625,30 +703,50 @@ 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 ) ) { + // 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. */ - 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 ) ); } - $permission = $this->invoke_callback( $this->permission_callback, $input ); + // 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 ) ) { + $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 - * 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 whatever the `permission_callback` produced. - * 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 returned by `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/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..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 @@ -103,6 +103,10 @@ public function get_items( $request ) { $query_args['meta'] = array_merge( $request['meta'], $query_args['meta'] ); } + if ( ! empty( $request['has_required_capabilities'] ) ) { + $query_args['has_required_capabilities'] = 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 `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( @@ -390,6 +406,11 @@ 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 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/phpunit/tests/abilities-api/wpAbility.php b/tests/phpunit/tests/abilities-api/wpAbility.php index e1b125d8da069..e446c3faf22db 100644 --- a/tests/phpunit/tests/abilities-api/wpAbility.php +++ b/tests/phpunit/tests/abilities-api/wpAbility.php @@ -2126,4 +2126,318 @@ 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; + } + + /** + * 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 {}; + } + + /** + * 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 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_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() ); + } + + /** + * 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 static 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 ); + } + + /** + * Data provider for permission checks based on required capabilities. + * + * @return array + */ + 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 ), + ); + } + + /** + * 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_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->assertSame( $expected, $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 = $this->get_properties_with_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 = $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.' ); + }; + + $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.' ); + } + + /** + * Data provider for custom class abilities without a valid permission check. + * + * @return array}> + */ + 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 no valid + * permission callback, even if the user has all required capabilities. + * + * @ticket 66325 + * + * @covers WP_Ability::check_permissions + * + * @dataProvider data_check_permissions_custom_class_without_valid_permission_check + * + * @param array $overrides The properties to merge into the test ability properties. + */ + public function test_check_permissions_custom_class_without_valid_permission_check( array $overrides ) { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $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() ); + } + + /** + * 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..3618a4070bc34 100644 --- a/tests/phpunit/tests/abilities-api/wpGetAbilities.php +++ b/tests/phpunit/tests/abilities-api/wpGetAbilities.php @@ -797,4 +797,136 @@ 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; + }, + ) + ); + } + + /** + * Data provider for filtering by the current user's required capabilities. + * + * @return array, 2: string[]}> + */ + 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 leaves out abilities whose declared + * capabilities the current user lacks. Abilities without required capabilities stay. + * + * @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( string $role, array $args, array $expected ): void { + $this->register_abilities_with_required_capabilities(); + wp_set_current_user( '' === $role ? 0 : self::factory()->user->create( array( 'role' => $role ) ) ); + + $result = wp_get_abilities( array_merge( array( 'namespace' => 'test' ), $args ) ); + + $this->assertSameSets( $expected, array_keys( $result ) ); + } + + /** + * Tests that the has_required_capabilities filter doesn't call permission callbacks. + * + * @ticket 66325 + */ + public function test_filter_by_has_required_capabilities_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( 'has_required_capabilities' => true ) ); + + $this->assertArrayHasKey( 'test/tracked', $result ); + $this->assertSame( 0, $callback_calls ); + } + + /** + * Tests that the has_required_capabilities filter runs before item_include_callback. + * + * @ticket 66325 + */ + 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', + 'has_required_capabilities' => 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..feb442fd1e462 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesV1ListController.php @@ -330,11 +330,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 ); @@ -668,7 +669,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 +679,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 +1269,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 has_required_capabilities parameter excludes abilities whose declared capabilities the current user lacks. + * + * @ticket 66325 + */ + public function test_filter_by_has_required_capabilities(): 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( 'has_required_capabilities', '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 has_required_capabilities parameter keeps abilities whose declared capabilities an administrator has. + * + * @ticket 66325 + */ + 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( 'has_required_capabilities', true ); + + $names = wp_list_pluck( $this->server->dispatch( $request )->get_data(), 'name' ); + $this->assertContains( 'test/admin-only', $names ); + } } diff --git a/tests/qunit/fixtures/wp-api-generated.js b/tests/qunit/fixtures/wp-api-generated.js index 0f627b5e14569..befd5cf9a0575 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 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 } } }