Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion docs/DEVELOPER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,37 @@ class My_Experiment extends Abstract_Feature {
public function register(): void {
// Register your hooks here
add_action( 'init', array( $this, 'initialize' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) );
add_filter( 'the_content', array( $this, 'filter_content' ) );
}

/**
* Registers the experiment's UI hooks.
*
* Only runs for users allowed to use the experiment.
*
* @since x.x.x
*/
public function register_ui(): void {
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
}

/**
* Registers the experiment's abilities.
*
* @since x.x.x
*/
public function register_abilities(): void {
$this->register_feature_ability(
'my-plugin/my-ability',
array(
'label' => __( 'My Ability', 'ai' ),
'description' => __( 'Description of what my ability does.', 'ai' ),
'ability_class' => My_Ability::class, // Your Abstract_Ability subclass.
)
);
}

/**
* Initializes the experiment.
*
Expand Down Expand Up @@ -134,6 +161,14 @@ The optional `usage` key in `load_metadata()` tells site owners, in short phrase

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

#### Access Control

`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()`.

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.

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).

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.

### Step 3: Register the Experiment
Expand Down Expand Up @@ -196,6 +231,8 @@ class My_Experiment extends Abstract_Feature {
}
```

`register_ui()` runs separately from `register()`, so if your experiment also implements `register_ui()`, repeat the requirement check there.

## Plugin API

The plugin provides a set of hooks and filters to allow third-party developers to extend its functionality.
Expand Down
109 changes: 109 additions & 0 deletions docs/admin/access-controls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# Access Controls

## Summary

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**.

## Overview

### For End Users

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:

- **Enable access control**: turns the restriction on or off for that feature.
- **Roles**: one checkbox per role that has the `edit_posts` capability. **Administrator** and **Editor** are checked by default.
- **Users**: search for and add individual users. Listed users can always use the feature, whatever their role.
- **Save**: appears once you change something. Nothing is stored until you click it.

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.

### What changes, and when

- **Access control off** (the default): access is identical to before. Anyone who passes the feature's normal permission checks can use it.
- **Turned on but not saved**: nothing is written, so access is still identical to before.
- **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.
- **No roles checked and no users listed**: nobody can use the feature, including administrators.

On multisite, super admins can always use every feature.

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.

### Where the restriction applies

The restriction applies to the feature's abilities on every path they run:

- the plugin's own buttons and screens in wp-admin and the editor (users without access do not get the feature's UI);
- the Abilities REST API (`/wp-abilities/v1/abilities/{name}/run`);
- MCP over HTTP;
- `runAbility()` in JavaScript, and server-side calls to `wp_get_ability()->execute()`;
- abilities one feature calls from another. For example, alt text generated during Image Generation is checked against the Alt Text Generation feature's settings;
- Text to Speech's own REST routes (`/ai/v1/text-to-speech/{id}`), which are not abilities but check the same capability.

A user without access gets a `wpai_feature_access_denied` error (HTTP 401 when logged out, 403 when logged in).

**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.

**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.

### Which features support it

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.

### Settings export and import

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.

## Stored options

Each supported feature stores three options, registered in their own option group (`ai_experiments_access`) and exposed through the core `/wp/v2/settings` endpoint:

| Option | Type | Default |
|---|---|---|
| `wpai_feature_<id>_access_control_enabled` | boolean | `false` |
| `wpai_feature_<id>_roles` | list of role slugs | unset, meaning no role restriction |
| `wpai_feature_<id>_users` | list of user IDs | `[]` |

An unset roles option is different from an empty list. Unset means "no restriction yet". A saved empty list means "no role has access".

## For Developers

### The `wpai_use_feature` capability

Access is decided by the `wpai_use_feature` meta capability, with the feature ID as its argument:

```php
if ( current_user_can( 'wpai_use_feature', 'title-generation' ) ) {
// The current user may use Title Generation.
}
```

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:

```php
add_filter(
'map_meta_cap',
static function ( array $caps, string $cap, int $user_id, array $args ): array {
if ( 'wpai_use_feature' === $cap && 'title-generation' === ( $args[0] ?? '' ) ) {
// Also require publish_posts, on top of the access control settings.
$caps[] = 'publish_posts';
}
return $caps;
},
20,
4
);
```

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.

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.

### Linking abilities to features

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.

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`.

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.

Feature UI that should be hidden from users without access belongs in `register_ui()`. See the [Developer Guide](../DEVELOPER_GUIDE.md).
11 changes: 9 additions & 2 deletions docs/experiments/custom-experiment-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ The example is intentionally small and uses the same APIs and patterns as the pl
- Creating a feature class by extending `Abstract_Feature`
- Registering the experiment with the AI plugin
- Adding metadata such as the label, description, and category
- Hooking into WordPress actions and filters in `register()`
- Hooking into WordPress actions and filters in `register()`, and user-facing hooks in `register_ui()`
- Disabling the experiment with the standard feature filters

## Reference Class
Expand Down Expand Up @@ -52,6 +52,10 @@ class My_Experiment extends Abstract_Feature {
}

public function register(): void {
// Abilities, meta, frontend output, cron, and REST routes go here.
}

public function register_ui(): void {
add_action( 'admin_notices', array( $this, 'render_notice' ) );
}

Expand All @@ -78,7 +82,10 @@ add_action(

- `Abstract_Feature` provides the shared experiment lifecycle used throughout the plugin.
- `load_metadata()` keeps labels and descriptions in one place, matching built-in experiments.
- `register()` is where the experiment attaches behavior through WordPress hooks.
- `register()` is the required method where the experiment attaches behavior through WordPress hooks.
- `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()`.
- 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.
- 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()`.
- `wpai_register_features` is the safest entry point for third-party plugins because it registers your feature after the plugin sets up its registry.

## Alternative Registration Method
Expand Down
25 changes: 25 additions & 0 deletions includes/Abstracts/Abstract_Ability.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,31 @@ abstract protected function execute_callback( $input );
*/
abstract protected function permission_callback( $input );

/**
* {@inheritDoc}
*
* Back-fills the core `wp_ability_permission_result` filter on WordPress
* versions that predate it (< 7.1), so authorization layers hooked to it
* apply on every supported version. Remove once the minimum is 7.1.
*
* @since x.x.x
*
* @param mixed $input Optional. The input data for permission checking.
* @return bool|\WP_Error Whether the ability has the necessary permission.
*/
public function check_permissions( $input = null ) {
$result = parent::check_permissions( $input );

if ( version_compare( get_bloginfo( 'version' ), '7.1-alpha', '>=' ) ) {
return $result;
}

/** This filter is documented in wp-includes/abilities-api/class-wp-ability.php */
$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.

return is_bool( $filtered ) || is_wp_error( $filtered ) ? $filtered : false;
}

/**
* Returns the meta of the ability.
*
Expand Down
62 changes: 61 additions & 1 deletion includes/Abstracts/Abstract_Feature.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
namespace WordPress\AI\Abstracts;

use InvalidArgumentException;
use WP_Ability;
use WordPress\AI\Access_Control\Feature_Access;
use WordPress\AI\Contracts\Feature;
use WordPress\AI\Features\Feature_Category;

Expand Down Expand Up @@ -91,6 +93,14 @@ abstract class Abstract_Feature implements Feature {
*/
private array $usage;

/**
* Whether per-feature access control applies to this feature.
*
* @since x.x.x
* @var bool
*/
private bool $access_control;

/**
* Constructor.
*
Expand Down Expand Up @@ -132,6 +142,8 @@ final public function __construct() {
$this->image = $metadata['image'] ?? '';
$this->capability = $metadata['capability'] ?? 'text_generation';
$this->usage = self::normalize_usage( $metadata['usage'] ?? array() );

$this->access_control = (bool) ( $metadata['access_control'] ?? false );
}

/**
Expand Down Expand Up @@ -165,7 +177,7 @@ private static function normalize_usage( $usage ): array {
* Loads feature metadata.
*
* Must return an array with keys: label, description.
* Optionally includes: category, stability, image, capability, usage.
* Optionally includes: category, stability, image, capability, usage, access_control.
*
* The `usage` key summarizes, in short user-facing phrases, when the
* feature runs, what it sends to the AI provider, and how many requests
Expand All @@ -175,8 +187,14 @@ private static function normalize_usage( $usage ): array {
* Features that make no AI requests can set `details` instead of
* `requests` to describe what they store or change.
*
* The `access_control` key opts the feature in to per-feature role/user
* access control. It is opt-in and defaults to false. A feature should
* opt in only once it registers its abilities with
* register_feature_ability() and its UI hooks in register_ui().
*
* @since 0.6.0
* @since 1.5.0 Added the `usage` key.
* @since x.x.x Added the `access_control` key.
*
* @return array{
* label: string,
Expand All @@ -185,6 +203,7 @@ private static function normalize_usage( $usage ): array {
* stability?: 'deprecated'|'experimental'|'stable',
* image?: string,
* capability?: string,
* access_control?: bool,
* usage?: array{
* trigger?: 'automatic'|'on_demand'|'none',
* runs?: string,
Expand Down Expand Up @@ -399,6 +418,47 @@ final public static function get_field_option_name( string $option_name ): strin
return 'wpai_feature_' . static::get_id() . '_field_' . $option_name;
}

/**
* Checks whether per-feature access control applies to this feature.
*
* @since x.x.x
*
* @return bool True if admins can restrict this feature to roles and users.
*/
public function supports_access_control(): bool {
return $this->access_control;
}

/**
* Registers user-facing hooks: asset enqueues, list table columns, row and
* bulk actions, admin menu items.
*
* @since x.x.x
*/
public function register_ui(): void {
// No-op by default.
}

/**
* Registers an ability owned by this feature.
*
* @since x.x.x
*
* @param lowercase-string&non-falsy-string $name The ability name, with namespace.
* @param array<string, mixed> $args The ability registration args.
* @return \WP_Ability|null The registered ability, or null on failure.
*/
protected function register_feature_ability( string $name, array $args ): ?WP_Ability {
if ( $this->supports_access_control() ) {
$meta = isset( $args['meta'] ) && is_array( $args['meta'] ) ? $args['meta'] : array();

$meta[ Feature_Access::ABILITY_META_KEY ] = static::get_id();
$args['meta'] = $meta;
}

return wp_register_ability( $name, $args );
}

/**
* {@inheritDoc}
*
Expand Down
Loading
Loading