Skip to content

Commit 520d656

Browse files
dkotterjeffpaulInfinite-Null
authored
Add user access controls to each feature (#1297)
Added - Role and user based access controls for features and experiments. Co-authored-by: dkotter <dkotter@git.wordpress.org> Co-authored-by: jeffpaul <jeffpaul@git.wordpress.org> Co-authored-by: Infinite-Null <ankitkumarshah@git.wordpress.org>
1 parent 5a1f305 commit 520d656

56 files changed

Lines changed: 2848 additions & 331 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/DEVELOPER_GUIDE.md‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,37 @@ class My_Experiment extends Abstract_Feature {
7676
public function register(): void {
7777
// Register your hooks here
7878
add_action( 'init', array( $this, 'initialize' ) );
79-
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
79+
add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) );
8080
add_filter( 'the_content', array( $this, 'filter_content' ) );
8181
}
8282

83+
/**
84+
* Registers the experiment's UI hooks.
85+
*
86+
* Only runs for users allowed to use the experiment.
87+
*
88+
* @since x.x.x
89+
*/
90+
public function register_ui(): void {
91+
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
92+
}
93+
94+
/**
95+
* Registers the experiment's abilities.
96+
*
97+
* @since x.x.x
98+
*/
99+
public function register_abilities(): void {
100+
$this->register_feature_ability(
101+
'my-plugin/my-ability',
102+
array(
103+
'label' => __( 'My Ability', 'ai' ),
104+
'description' => __( 'Description of what my ability does.', 'ai' ),
105+
'ability_class' => My_Ability::class, // Your Abstract_Ability subclass.
106+
)
107+
);
108+
}
109+
83110
/**
84111
* Initializes the experiment.
85112
*
@@ -134,6 +161,14 @@ The optional `usage` key in `load_metadata()` tells site owners, in short phrase
134161

135162
Keep the "At a Glance" section of the experiment's doc in `docs/experiments` in sync with these values.
136163

164+
#### Access Control
165+
166+
`register()` is the only required method. `register_ui()` runs only for users allowed to use the feature, or for everyone when the feature does not opt in to access control. Put asset enqueues, columns, row or bulk actions, and admin menu items there. Abilities, meta, frontend output, cron, and REST routes stay in `register()`.
167+
168+
Register your feature's abilities with `register_feature_ability()` so its access control settings apply wherever the ability runs. Abilities registered directly with `wp_register_ability()` are not tied to any feature.
169+
170+
The optional `access_control` metadata key opts the feature in to access control settings. It is opt-in and defaults to `false`. Set `'access_control' => true` only once the feature registers its abilities with `register_feature_ability()` and its UI hooks in `register_ui()`. See [Access Controls](admin/access-controls.md).
171+
137172
If you want a complete end-to-end reference instead of a starter snippet, see the [Custom Experiment Reference](experiments/custom-experiment-reference.md). It points to the in-repo `Example_Experiment` implementation and shows a minimal third-party plugin example using the same extension points.
138173

139174
### Step 3: Register the Experiment
@@ -196,6 +231,8 @@ class My_Experiment extends Abstract_Feature {
196231
}
197232
```
198233

234+
`register_ui()` runs separately from `register()`, so if your experiment also implements `register_ui()`, repeat the requirement check there.
235+
199236
## Plugin API
200237

201238
The plugin provides a set of hooks and filters to allow third-party developers to extend its functionality.

‎docs/admin/access-controls.md‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
# Access Controls
2+
3+
## Summary
4+
5+
Access Controls let administrators limit each supported AI feature to chosen roles and specific users. A restriction applies wherever the feature's abilities run, not just in the plugin's own screens. Nothing changes for anyone until an administrator turns access control on for a feature **and saves**.
6+
7+
## Overview
8+
9+
### For End Users
10+
11+
On the AI settings page (**Settings → AI**), open the **Developer Tools** menu (the wrench icon) and select **Access controls**. Each enabled feature that supports access control then shows:
12+
13+
- **Enable access control**: turns the restriction on or off for that feature.
14+
- **Roles**: one checkbox per role that has the `edit_posts` capability. **Administrator** and **Editor** are checked by default.
15+
- **Users**: search for and add individual users. Listed users can always use the feature, whatever their role.
16+
- **Save**: appears once you change something. Nothing is stored until you click it.
17+
18+
When the **Access controls** view is turned off, a feature that is actually restricted shows "Access restricted to selected roles and users." so the restriction stays visible. Turning the view off never clears saved settings.
19+
20+
### What changes, and when
21+
22+
- **Access control off** (the default): access is identical to before. Anyone who passes the feature's normal permission checks can use it.
23+
- **Turned on but not saved**: nothing is written, so access is still identical to before.
24+
- **Turned on and saved**: only the checked roles and the listed users can use the feature. If you save without touching the defaults, Administrator and Editor are saved. That can be stricter than before. For example, Authors and Contributors lose access.
25+
- **No roles checked and no users listed**: nobody can use the feature, including administrators.
26+
27+
On multisite, super admins can always use every feature.
28+
29+
Access control only ever adds a restriction. Each ability's own permission checks still apply, so adding a user here does not let them edit posts they otherwise could not.
30+
31+
### Where the restriction applies
32+
33+
The restriction applies to the feature's abilities on every path they run:
34+
35+
- the plugin's own buttons and screens in wp-admin and the editor (users without access do not get the feature's UI);
36+
- the Abilities REST API (`/wp-abilities/v1/abilities/{name}/run`);
37+
- MCP over HTTP;
38+
- `runAbility()` in JavaScript, and server-side calls to `wp_get_ability()->execute()`;
39+
- abilities one feature calls from another. For example, alt text generated during Image Generation is checked against the Alt Text Generation feature's settings;
40+
- Text to Speech's own REST routes (`/ai/v1/text-to-speech/{id}`), which are not abilities but check the same capability.
41+
42+
A user without access gets a `wpai_feature_access_denied` error (HTTP 401 when logged out, 403 when logged in).
43+
44+
**Automatic runs are not affected.** Work the feature does on its own, without a user asking, carries on whatever the access settings say. For example, Comment Moderation still analyses new comments, and Text to Speech jobs that are already queued still finish.
45+
46+
**WP-CLI without `--user` is not restricted.** Commands run through WP-CLI without `--user` bypass access control. With an explicit `--user`, the restriction applies to that user, so `wp mcp-adapter serve --user=bob` respects Bob's access. This includes MCP over STDIO, which runs through WP-CLI.
47+
48+
### Which features support it
49+
50+
Only features whose `access_control` metadata is `true` show these controls. Access control is opt-in. Every built-in feature outside the **Admin** category opts in, and so do Comment Moderation and Suggest Reply. Other admin features already require `manage_options`. Third-party features must set `'access_control' => true` to opt in.
51+
52+
### Settings export and import
53+
54+
Access control settings are **not** included in [settings export and import](settings-import-export.md). Role slugs and user IDs differ between sites, so configure access controls on each site directly.
55+
56+
## Stored options
57+
58+
Each supported feature stores three options, registered in their own option group (`ai_experiments_access`) and exposed through the core `/wp/v2/settings` endpoint:
59+
60+
| Option | Type | Default |
61+
|---|---|---|
62+
| `wpai_feature_<id>_access_control_enabled` | boolean | `false` |
63+
| `wpai_feature_<id>_roles` | list of role slugs | unset, meaning no role restriction |
64+
| `wpai_feature_<id>_users` | list of user IDs | `[]` |
65+
66+
An unset roles option is different from an empty list. Unset means "no restriction yet". A saved empty list means "no role has access".
67+
68+
## For Developers
69+
70+
### The `wpai_use_feature` capability
71+
72+
Access is decided by the `wpai_use_feature` meta capability, with the feature ID as its argument:
73+
74+
```php
75+
if ( current_user_can( 'wpai_use_feature', 'title-generation' ) ) {
76+
// The current user may use Title Generation.
77+
}
78+
```
79+
80+
The plugin maps it to `exist` (allowed) or `do_not_allow` (denied) in a `map_meta_cap` filter at priority 10. The recommended way to extend the check is your own `map_meta_cap` filter at a later priority that adds a requirement to the plugin's result. The following example also requires `publish_posts` for Title Generation. The admin's role and user settings stay in force, so a user must pass both:
81+
82+
```php
83+
add_filter(
84+
'map_meta_cap',
85+
static function ( array $caps, string $cap, int $user_id, array $args ): array {
86+
if ( 'wpai_use_feature' === $cap && 'title-generation' === ( $args[0] ?? '' ) ) {
87+
// Also require publish_posts, on top of the access control settings.
88+
$caps[] = 'publish_posts';
89+
}
90+
return $caps;
91+
},
92+
20,
93+
4
94+
);
95+
```
96+
97+
Run your filter after priority 10 so it sees the plugin's result. Append to `$caps` rather than replacing it: returning a new array discards the plugin's decision.
98+
99+
The `user_has_cap` filter also works, but it only sees the primitive `exist` or `do_not_allow` result, not the roles and users behind it. Core never grants `do_not_allow`, so `user_has_cap` is mainly useful for denying access.
100+
101+
### Linking abilities to features
102+
103+
Features register their abilities with `Abstract_Feature::register_feature_ability()`. It adds the feature ID to the ability's `wpai_feature` meta key and then calls `wp_register_ability()`. The plugin checks `wpai_use_feature` for that feature whenever an ability with this meta key runs.
104+
105+
Abilities registered directly with `wp_register_ability()` are not tied to any feature, so only their own `permission_callback` applies. `register_feature_ability()` adds the meta key only for features that opt in with `'access_control' => true`.
106+
107+
On WordPress 7.0.x, the check applies only to abilities whose class extends `Abstract_Ability`, because the core `wp_ability_permission_result` filter arrives in WordPress 7.1.
108+
109+
Feature UI that should be hidden from users without access belongs in `register_ui()`. See the [Developer Guide](../DEVELOPER_GUIDE.md).

‎docs/experiments/custom-experiment-reference.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ The example is intentionally small and uses the same APIs and patterns as the pl
99
- Creating a feature class by extending `Abstract_Feature`
1010
- Registering the experiment with the AI plugin
1111
- Adding metadata such as the label, description, and category
12-
- Hooking into WordPress actions and filters in `register()`
12+
- Hooking into WordPress actions and filters in `register()`, and user-facing hooks in `register_ui()`
1313
- Disabling the experiment with the standard feature filters
1414

1515
## Reference Class
@@ -52,6 +52,10 @@ class My_Experiment extends Abstract_Feature {
5252
}
5353

5454
public function register(): void {
55+
// Abilities, meta, frontend output, cron, and REST routes go here.
56+
}
57+
58+
public function register_ui(): void {
5559
add_action( 'admin_notices', array( $this, 'render_notice' ) );
5660
}
5761

@@ -78,7 +82,10 @@ add_action(
7882

7983
- `Abstract_Feature` provides the shared experiment lifecycle used throughout the plugin.
8084
- `load_metadata()` keeps labels and descriptions in one place, matching built-in experiments.
81-
- `register()` is where the experiment attaches behavior through WordPress hooks.
85+
- `register()` is the required method where the experiment attaches behavior through WordPress hooks.
86+
- `register_ui()` runs only for users allowed to use the feature, or for everyone when the feature does not opt in to access control. Put asset enqueues, columns, row or bulk actions, and admin menu items there. Abilities, meta, frontend output, cron, and REST routes stay in `register()`.
87+
- Register your feature's abilities with `register_feature_ability()` so its access control settings apply wherever the ability runs. Abilities registered directly with `wp_register_ability()` are not tied to any feature.
88+
- The optional `access_control` metadata key opts the feature in to [access control settings](../admin/access-controls.md). It is opt-in and defaults to `false`, so this example does not opt in. Set `'access_control' => true` only once the feature registers its abilities with `register_feature_ability()` and its UI hooks in `register_ui()`.
8289
- `wpai_register_features` is the safest entry point for third-party plugins because it registers your feature after the plugin sets up its registry.
8390

8491
## Alternative Registration Method

‎includes/Abstracts/Abstract_Ability.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,31 @@ abstract protected function execute_callback( $input );
106106
*/
107107
abstract protected function permission_callback( $input );
108108

109+
/**
110+
* {@inheritDoc}
111+
*
112+
* Back-fills the core `wp_ability_permission_result` filter on WordPress
113+
* versions that predate it (< 7.1), so authorization layers hooked to it
114+
* apply on every supported version. Remove once the minimum is 7.1.
115+
*
116+
* @since x.x.x
117+
*
118+
* @param mixed $input Optional. The input data for permission checking.
119+
* @return bool|\WP_Error Whether the ability has the necessary permission.
120+
*/
121+
public function check_permissions( $input = null ) {
122+
$result = parent::check_permissions( $input );
123+
124+
if ( version_compare( get_bloginfo( 'version' ), '7.1-alpha', '>=' ) ) {
125+
return $result;
126+
}
127+
128+
/** This filter is documented in wp-includes/abilities-api/class-wp-ability.php */
129+
$filtered = apply_filters( 'wp_ability_permission_result', $result, $this->get_name(), $input, $this ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Back-fills the core hook on WordPress < 7.1.
130+
131+
return is_bool( $filtered ) || is_wp_error( $filtered ) ? $filtered : false;
132+
}
133+
109134
/**
110135
* Returns the meta of the ability.
111136
*

‎includes/Abstracts/Abstract_Feature.php‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
namespace WordPress\AI\Abstracts;
1111

1212
use InvalidArgumentException;
13+
use WP_Ability;
14+
use WordPress\AI\Access_Control\Feature_Access;
1315
use WordPress\AI\Contracts\Feature;
1416
use WordPress\AI\Features\Feature_Category;
1517

@@ -91,6 +93,14 @@ abstract class Abstract_Feature implements Feature {
9193
*/
9294
private array $usage;
9395

96+
/**
97+
* Whether per-feature access control applies to this feature.
98+
*
99+
* @since x.x.x
100+
* @var bool
101+
*/
102+
private bool $access_control;
103+
94104
/**
95105
* Constructor.
96106
*
@@ -132,6 +142,8 @@ final public function __construct() {
132142
$this->image = $metadata['image'] ?? '';
133143
$this->capability = $metadata['capability'] ?? 'text_generation';
134144
$this->usage = self::normalize_usage( $metadata['usage'] ?? array() );
145+
146+
$this->access_control = (bool) ( $metadata['access_control'] ?? false );
135147
}
136148

137149
/**
@@ -165,7 +177,7 @@ private static function normalize_usage( $usage ): array {
165177
* Loads feature metadata.
166178
*
167179
* Must return an array with keys: label, description.
168-
* Optionally includes: category, stability, image, capability, usage.
180+
* Optionally includes: category, stability, image, capability, usage, access_control.
169181
*
170182
* The `usage` key summarizes, in short user-facing phrases, when the
171183
* feature runs, what it sends to the AI provider, and how many requests
@@ -175,8 +187,14 @@ private static function normalize_usage( $usage ): array {
175187
* Features that make no AI requests can set `details` instead of
176188
* `requests` to describe what they store or change.
177189
*
190+
* The `access_control` key opts the feature in to per-feature role/user
191+
* access control. It is opt-in and defaults to false. A feature should
192+
* opt in only once it registers its abilities with
193+
* register_feature_ability() and its UI hooks in register_ui().
194+
*
178195
* @since 0.6.0
179196
* @since 1.5.0 Added the `usage` key.
197+
* @since x.x.x Added the `access_control` key.
180198
*
181199
* @return array{
182200
* label: string,
@@ -185,6 +203,7 @@ private static function normalize_usage( $usage ): array {
185203
* stability?: 'deprecated'|'experimental'|'stable',
186204
* image?: string,
187205
* capability?: string,
206+
* access_control?: bool,
188207
* usage?: array{
189208
* trigger?: 'automatic'|'on_demand'|'none',
190209
* runs?: string,
@@ -399,6 +418,47 @@ final public static function get_field_option_name( string $option_name ): strin
399418
return 'wpai_feature_' . static::get_id() . '_field_' . $option_name;
400419
}
401420

421+
/**
422+
* Checks whether per-feature access control applies to this feature.
423+
*
424+
* @since x.x.x
425+
*
426+
* @return bool True if admins can restrict this feature to roles and users.
427+
*/
428+
public function supports_access_control(): bool {
429+
return $this->access_control;
430+
}
431+
432+
/**
433+
* Registers user-facing hooks: asset enqueues, list table columns, row and
434+
* bulk actions, admin menu items.
435+
*
436+
* @since x.x.x
437+
*/
438+
public function register_ui(): void {
439+
// No-op by default.
440+
}
441+
442+
/**
443+
* Registers an ability owned by this feature.
444+
*
445+
* @since x.x.x
446+
*
447+
* @param lowercase-string&non-falsy-string $name The ability name, with namespace.
448+
* @param array<string, mixed> $args The ability registration args.
449+
* @return \WP_Ability|null The registered ability, or null on failure.
450+
*/
451+
protected function register_feature_ability( string $name, array $args ): ?WP_Ability {
452+
if ( $this->supports_access_control() ) {
453+
$meta = isset( $args['meta'] ) && is_array( $args['meta'] ) ? $args['meta'] : array();
454+
455+
$meta[ Feature_Access::ABILITY_META_KEY ] = static::get_id();
456+
$args['meta'] = $meta;
457+
}
458+
459+
return wp_register_ability( $name, $args );
460+
}
461+
402462
/**
403463
* {@inheritDoc}
404464
*

0 commit comments

Comments
 (0)