From 5d4d82aec977e7f1ec2fba7e155517a2f5c2b8b8 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Tue, 17 Nov 2026 22:06:33 +0000 Subject: [PATCH 1/2] Abilities API: Add the `core/user-create`, `core/user-update` and `core/user-delete` abilities. Add three abilities to the `user` category: - `core/user-create` creates a user from `data` and returns it. The password is generated and never returned: the new user receives the email with the link to set one. - `core/user-update` updates the given attributes of the user matched by `where` and returns it. - `core/user-delete` deletes the user matched by `where`, or on multisite removes the user from the current site. `reassign` is required: the ID of the user who takes over the content, or false. The attributes that can be written are the email, name, first name, last name, nickname, slug, description, URL, locale and roles, plus the username on create. Each call checks the capabilities of the current user for the target user and for the roles it sets. The `fields` and item schemas of `core/users-query` move to private helpers that the new abilities share. That ability is registered as before. --- src/wp-includes/abilities.php | 3 +- .../abilities/class-wp-abilities-users.php | 1116 +++++++++++++- .../testcase-user-write-ability.php | 999 +++++++++++++ .../wpRegisterCoreUserCreateAbility.php | 1176 +++++++++++++++ .../wpRegisterCoreUserDeleteAbility.php | 967 ++++++++++++ .../wpRegisterCoreUserUpdateAbility.php | 1301 +++++++++++++++++ .../wpRegisterCoreUsersAbility.php | 6 +- .../wpRestAbilitiesUsersController.php | 412 ++++++ 8 files changed, 5953 insertions(+), 27 deletions(-) create mode 100644 tests/phpunit/tests/abilities-api/testcase-user-write-ability.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreUserCreateAbility.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreUserDeleteAbility.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreUserUpdateAbility.php diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php index 835c19e04f949..6326f7c58e31b 100644 --- a/src/wp-includes/abilities.php +++ b/src/wp-includes/abilities.php @@ -50,6 +50,7 @@ function wp_register_core_ability_categories(): void { * * @since 6.9.0 * @since 7.2.0 Added the `core/content-query`, `core/settings-get`, and `core/users-query` abilities. + * @since 7.3.0 Added the `core/user-create`, `core/user-update`, and `core/user-delete` abilities. * * @global wpdb $wpdb WordPress database abstraction object. */ @@ -374,7 +375,7 @@ function wp_register_core_abilities(): void { // Register the settings abilities (currently the read-only `core/settings-get`). ( new WP_Abilities_Settings() )->register(); - // Register the user abilities (currently the read-only `core/users-query`). + // Register the user abilities: `core/users-query`, `core/user-create`, `core/user-update`, and `core/user-delete`. ( new WP_Abilities_Users() )->register(); // Register the content abilities (currently the read-only `core/content-query`). diff --git a/src/wp-includes/abilities/class-wp-abilities-users.php b/src/wp-includes/abilities/class-wp-abilities-users.php index a0f21de801e95..a07080ef01ce5 100644 --- a/src/wp-includes/abilities/class-wp-abilities-users.php +++ b/src/wp-includes/abilities/class-wp-abilities-users.php @@ -17,12 +17,15 @@ * roles, or published-post authorship. Field-level access is enforced per user by * omitting fields the current user cannot view. * + * Also registers the `core/user-create`, `core/user-update`, and `core/user-delete` + * abilities, which write a single user through Core's regular user functions and + * return the written user in the same shape as `core/users-query`. + * * Unlike the core abilities registered directly in wp_register_core_abilities() as - * self-contained closures, the users ability lives in a dedicated class - * because its callbacks and schemas share helpers: the permission and execute - * callbacks read the input through the same code, and the input schema, output - * schema, and field normalization are built from the same field definitions. - * Future write-oriented user abilities can reuse them as well. + * self-contained closures, the user abilities live in a dedicated class + * because their callbacks and schemas share helpers: the callbacks read the input + * through the same code, and the input schemas, output schemas, and field + * normalization are built from the same field definitions. * * Only register() is public. The ability callbacks are closures that call private * methods, so callers go through the Abilities API, such as @@ -30,6 +33,7 @@ * checks permissions before running them. * * @since 7.2.0 + * @since 7.3.0 Added the `core/user-create`, `core/user-update`, and `core/user-delete` abilities. * * @access private */ @@ -91,15 +95,38 @@ final class WP_Abilities_Users { 'avatar_urls', ); + /** + * The user data key each profile attribute of the write abilities is saved as. + * + * The username and the email are not listed: they are passed to the saves separately. + * + * @since 7.3.0 + * @var array + */ + private const PROFILE_ATTRIBUTES = array( + 'name' => 'display_name', + 'first_name' => 'first_name', + 'last_name' => 'last_name', + 'nickname' => 'nickname', + 'slug' => 'user_nicename', + 'description' => 'description', + 'url' => 'user_url', + 'locale' => 'locale', + ); + /** * Registers all user abilities. * * Must run on the `wp_abilities_api_init` hook. * * @since 7.2.0 + * @since 7.3.0 Registers the `core/user-create`, `core/user-update`, and `core/user-delete` abilities. */ public function register(): void { $this->register_users_query(); + $this->register_user_create(); + $this->register_user_update(); + $this->register_user_delete(); } /** @@ -137,6 +164,110 @@ private function register_users_query(): void { ); } + /** + * Registers the `core/user-create` ability. + * + * @since 7.3.0 + */ + private function register_user_create(): void { + wp_register_ability( + 'core/user-create', + array( + 'label' => __( 'Create User' ), + 'description' => __( 'Creates a user and returns it. No password is set: WordPress generates one and emails the new user a link to choose their own, and the site administrator gets the usual new user notice. On multisite, the user becomes a member of the current site. Requires permission to create users.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_user_create_input_schema(), + 'output_schema' => $this->get_user_item_schema(), + 'execute_callback' => function ( $input = array() ) { + return $this->execute_user_create( $input ); + }, + 'required_capabilities' => array( 'create_users' ), + 'meta' => array( + 'annotations' => array( + 'readonly' => false, + 'destructive' => false, + 'idempotent' => false, + ), + 'public' => true, + ), + ) + ); + } + + /** + * Registers the `core/user-update` ability. + * + * @since 7.3.0 + */ + private function register_user_update(): void { + wp_register_ability( + 'core/user-update', + array( + 'label' => __( 'Update User' ), + 'description' => __( 'Updates the given attributes of a user and returns the user. Attributes that are left out keep their stored values. Changing roles requires permission to promote the user; changing any other attribute requires permission to edit the user. Requires an authenticated user.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_user_update_input_schema(), + 'output_schema' => $this->get_user_item_schema(), + 'execute_callback' => function ( $input = array() ) { + return $this->execute_user_update( $input ); + }, + 'permission_callback' => static function (): bool { + return is_user_logged_in(); + }, + 'meta' => array( + 'annotations' => array( + 'readonly' => false, + 'destructive' => false, + 'idempotent' => true, + ), + 'public' => true, + ), + ) + ); + } + + /** + * Registers the `core/user-delete` ability. + * + * @since 7.3.0 + */ + private function register_user_delete(): void { + wp_register_ability( + 'core/user-delete', + array( + 'label' => __( 'Delete User' ), + 'description' => __( 'Deletes a user. `reassign` is required: the ID of the user who takes over the content of the deleted user, or false to delete the content with the user. With false, posts and pages go to the Trash where the site has one, and other content is deleted permanently (media too, unless the site keeps a Trash for media); posts of a type that is not deleted with its author, such as patterns, stay as they are. On multisite, the user is removed from the current site instead and the account stays in the network; there, false leaves the content in place. Requires permission to delete users, or on multisite to remove users.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_user_delete_input_schema(), + 'output_schema' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'outcome' ), + 'properties' => array( + 'outcome' => array( + 'type' => 'string', + 'description' => __( 'What happened to the user: `deleted`, or `removed` from the current site on multisite.' ), + ), + ), + ), + 'execute_callback' => function ( $input = array() ) { + return $this->execute_user_delete( $input ); + }, + 'permission_callback' => static function (): bool { + return current_user_can( is_multisite() ? 'remove_users' : 'delete_users' ); + }, + 'meta' => array( + 'annotations' => array( + 'readonly' => false, + 'destructive' => true, + 'idempotent' => false, + ), + 'public' => true, + ), + ) + ); + } + /** * Permission callback for the `core/users-query` ability. * @@ -314,6 +445,648 @@ private function execute_users_query( $input = array() ) { return $this->prepare_output( $users, $total_users, $total_pages ); } + /** + * Executes the `core/user-create` ability. + * + * @since 7.3.0 + * + * @param array $input Optional. The ability input, as prepared by WP_Ability::execute(). Default empty array. + * @return array|WP_Error The new user, or a WP_Error on failure. + */ + private function execute_user_create( array $input = array() ) { + // Checked again after the gate, whose result a filter can change. + if ( ! current_user_can( 'create_users' ) ) { + return new WP_Error( + 'user_cannot_create', + __( 'Sorry, you are not allowed to create new users.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + $data = $input['data'] ?? array(); + $roles = null; + if ( array_key_exists( 'roles', $data ) ) { + $roles = $this->check_roles( $data['roles'], null ); + if ( is_wp_error( $roles ) ) { + return $roles; + } + } + + $error = $this->check_attributes( $data, null ); + if ( $error ) { + return $error; + } + + $password = wp_generate_password( 24 ); + $profile = $this->get_profile_userdata( $data ); + + if ( is_multisite() ) { + $signup = wpmu_validate_user_signup( $data['username'], $data['email'] ); + if ( is_wp_error( $signup['errors'] ) && $signup['errors']->has_errors() ) { + $codes = $signup['errors']->get_error_codes(); + $param = 'data'; + $code = $codes[0]; + $paths = array( + 'user_name' => 'data[username]', + 'user_email' => 'data[email]', + ); + foreach ( $paths as $field_code => $path ) { + if ( in_array( $field_code, $codes, true ) ) { + $param = $path; + $code = $field_code; + break; + } + } + + return $this->invalid_attribute_error( $param, $signup['errors']->get_error_message( $code ) ); + } + + $user_id = wpmu_create_user( $data['username'], $password, $data['email'] ); + if ( ! $user_id ) { + return $this->create_failed_error(); + } + + $result = empty( $profile ) ? true : wp_update_user( array( 'ID' => $user_id ) + $profile ); + if ( ! is_wp_error( $result ) ) { + $result = add_user_to_blog( get_current_blog_id(), $user_id, '' ); + } + + if ( is_wp_error( $result ) ) { + /* + * Undo the network account this call created, and only that one, so a failed + * call leaves the number of users unchanged. The first error is returned + * whatever the cleanup returns. + */ + require_once ABSPATH . 'wp-admin/includes/ms.php'; + wpmu_delete_user( $user_id ); + + return $this->save_error( $result, array_keys( $data ) ); + } + } else { + $userdata = array( + 'user_login' => wp_slash( $data['username'] ), + 'user_email' => wp_slash( $data['email'] ), + 'user_pass' => $password, + ) + $profile; + + // The roles are set after the save, so the user never holds the default role. + if ( null !== $roles ) { + $userdata['role'] = ''; + } + + $user_id = wp_insert_user( $userdata ); + if ( is_wp_error( $user_id ) ) { + return $this->save_error( $user_id, array_keys( $data ) ); + } + if ( ! $user_id ) { + return $this->create_failed_error(); + } + } + + if ( null !== $roles ) { + $this->set_user_roles( $user_id, $roles ); + } + + wp_send_new_user_notifications( $user_id, 'both' ); + + return $this->format_written_user( $user_id, $input ); + } + + /** + * Executes the `core/user-update` ability. + * + * @since 7.3.0 + * + * @param array $input Optional. The ability input, as prepared by WP_Ability::execute(). Default empty array. + * @return array|WP_Error The updated user, or a WP_Error on failure. + */ + private function execute_user_update( array $input = array() ) { + // Checked again after the gate, whose result a filter can change. + if ( ! is_user_logged_in() ) { + return new WP_Error( + 'user_cannot_edit', + __( 'Sorry, you are not allowed to edit this user.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + $target = $this->get_target_user( $input ); + if ( ! $target ) { + return $this->not_found_error(); + } + + // Only the keys of `data` choose the capability, before any value is read. + $data = $input['data'] ?? array(); + $keys = array_keys( $data ); + + if ( in_array( 'roles', $keys, true ) && ! current_user_can( 'promote_user', $target->ID ) ) { + return new WP_Error( + 'user_cannot_edit_roles', + __( 'Sorry, you are not allowed to edit roles of this user.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( array( 'roles' ) !== $keys && ! current_user_can( 'edit_user', $target->ID ) ) { + return new WP_Error( + 'user_cannot_edit', + __( 'Sorry, you are not allowed to edit this user.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + $attributes = array_merge( array( 'email', 'roles' ), array_keys( self::PROFILE_ATTRIBUTES ) ); + $sent = array_values( array_intersect( $keys, $attributes ) ); + if ( empty( $sent ) ) { + return $this->get_validation_error( + 'data', + array(), + array( + 'type' => 'object', + 'minProperties' => 1, + ) + ); + } + + $roles = null; + if ( array_key_exists( 'roles', $data ) ) { + $roles = $this->check_roles( $data['roles'], $target ); + if ( is_wp_error( $roles ) ) { + return $roles; + } + } + + $error = $this->check_attributes( $data, $target ); + if ( $error ) { + return $error; + } + + // The save never receives a role or a username. + $userdata = $this->get_profile_userdata( $data ); + if ( array_key_exists( 'email', $data ) ) { + $userdata['user_email'] = wp_slash( $data['email'] ); + } + + if ( ! empty( $userdata ) ) { + $result = wp_update_user( array( 'ID' => $target->ID ) + $userdata ); + if ( is_wp_error( $result ) ) { + return $this->save_error( $result, $sent ); + } + } + + if ( null !== $roles ) { + $this->set_user_roles( $target->ID, $roles ); + } + + return $this->format_written_user( $target->ID, $input ); + } + + /** + * Executes the `core/user-delete` ability. + * + * On multisite, the user is removed from the current site, and the network account stays. + * + * @since 7.3.0 + * + * @param array $input Optional. The ability input, as prepared by WP_Ability::execute(). Default empty array. + * @return array|WP_Error The outcome, or a WP_Error on failure. + */ + private function execute_user_delete( array $input = array() ) { + // Checked again after the gate, whose result a filter can change. + if ( ! current_user_can( is_multisite() ? 'remove_users' : 'delete_users' ) ) { + return $this->cannot_delete_error(); + } + + $target = $this->get_target_user( $input ); + if ( ! $target ) { + return $this->not_found_error(); + } + + if ( ! current_user_can( is_multisite() ? 'remove_user' : 'delete_user', $target->ID ) ) { + return $this->cannot_delete_error(); + } + + // Only `false` reassigns nothing. Every other value must name a user. + $reassign = $input['reassign'] ?? null; + if ( false !== $reassign ) { + $reassign_user = is_int( $reassign ) && $reassign >= 1 ? get_userdata( $reassign ) : false; + + /* + * Intentionally strict: on multisite, the user who takes over the content must be a + * member of the current site, although the removal would hand it to any user. + */ + if ( ! $reassign_user || $reassign_user->ID === $target->ID || ! is_user_member_of_blog( $reassign_user->ID ) ) { + return $this->invalid_attribute_error( 'reassign', __( 'Invalid user ID for reassignment.' ), 'user_invalid_reassign' ); + } + + $reassign = $reassign_user->ID; + } + + // The stored state decides the outcome, not the return value of the deletion. + if ( is_multisite() ) { + remove_user_from_blog( $target->ID, get_current_blog_id(), false === $reassign ? 0 : $reassign ); + + $outcome = 'removed'; + $done = ! is_user_member_of_blog( $target->ID ); + } else { + require_once ABSPATH . 'wp-admin/includes/user.php'; + + if ( false === $reassign ) { + wp_delete_user( $target->ID ); + } else { + wp_delete_user( $target->ID, $reassign ); + } + + $outcome = 'deleted'; + $done = ! get_userdata( $target->ID ); + } + + if ( ! $done ) { + return new WP_Error( + 'user_delete_failed', + __( 'The user cannot be deleted.' ), + array( 'status' => 500 ) + ); + } + + return array( 'outcome' => $outcome ); + } + + /** + * Looks up the user that `where.id` names. + * + * The ID is read once, and the returned user is the one every later check and write + * uses. On multisite, a user who is not a member of the current site is not returned, + * for every caller, so it cannot be told apart from an ID that does not exist. + * + * @since 7.3.0 + * + * @param array $input The ability input. + * @return WP_User|null The user, or null when the ID is invalid or names no member of the current site. + */ + private function get_target_user( array $input ): ?WP_User { + $id = $input['where']['id'] ?? 0; + $user = $id >= 1 ? get_userdata( $id ) : false; + + return $user && is_user_member_of_blog( $user->ID ) ? $user : null; + } + + /** + * Checks the roles to assign. + * + * Runs for each role in list order, whatever the input schema allowed, since a role + * can be unregistered, or the editable roles narrowed, after the schema was built. + * + * @since 7.3.0 + * + * @param string[] $roles The `roles` input. + * @param WP_User|null $target The user to update, or null on create. + * @return string[]|WP_Error The roles, or a WP_Error for the first role that cannot be assigned. + */ + private function check_roles( array $roles, ?WP_User $target ) { + $error = $this->get_validation_error( + 'data[roles]', + $roles, + array( + 'type' => 'array', + 'minItems' => 1, + ) + ); + if ( $error ) { + return $error; + } + + require_once ABSPATH . 'wp-admin/includes/user.php'; + $editable_roles = get_editable_roles(); + + // Users cannot give themselves a role that would take away their right to edit users. + $is_own_role_change = $target && get_current_user_id() === $target->ID && ! ( is_multisite() && current_user_can( 'manage_sites' ) ); + + foreach ( $roles as $role ) { + $role_object = get_role( $role ); + if ( ! $role_object ) { + return $this->invalid_attribute_error( + 'data[roles]', + /* translators: %s: Role key. */ + sprintf( __( 'The role %s does not exist.' ), $role ) + ); + } + + // A role with an empty entry in the editable roles is not editable, like a missing one. + if ( ( $is_own_role_change && ! $role_object->has_cap( 'edit_users' ) ) || empty( $editable_roles[ $role ] ) ) { + return new WP_Error( + 'user_cannot_assign_role', + __( 'Sorry, you are not allowed to give users that role.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + } + + return $roles; + } + + /** + * Checks the attributes to save, in a fixed order. + * + * The checks that depend on the save's sanitizing compute the value as the save + * does. A value that ends empty, too long or taken is refused here; everything else + * is stored as the save sanitizes it. + * + * @since 7.3.0 + * + * @param array $data The `data` input. + * @param WP_User|null $target The user to update, or null on create. + * @return WP_Error|null A WP_Error for the first attribute that cannot be saved, or null. + */ + private function check_attributes( array $data, ?WP_User $target ): ?WP_Error { + if ( ! $target ) { + $error = $this->get_validation_error( + 'data[username]', + $data, + array( + 'type' => 'object', + 'required' => array( 'username' ), + ), + 'data' + ); + if ( $error ) { + return $error; + } + + $username = $data['username']; + + /* + * Intentionally strict: a username that strict sanitizing would change is refused, + * also when a filter of validate_username() accepts it. + */ + if ( sanitize_user( $username, true ) !== $username || ! validate_username( $username ) ) { + return $this->invalid_attribute_error( 'data[username]', __( 'This username is invalid because it uses illegal characters. Please enter a valid username.' ) ); + } + + /** This filter is documented in wp-includes/user.php */ + $illegal_logins = array_map( 'strtolower', (array) apply_filters( 'illegal_user_logins', array() ) ); + if ( in_array( strtolower( $username ), $illegal_logins, true ) ) { + return $this->invalid_attribute_error( 'data[username]', __( 'Sorry, that username is not allowed.' ) ); + } + + if ( mb_strlen( $username ) > 60 ) { + return $this->invalid_attribute_error( 'data[username]', __( 'Username may not be longer than 60 characters.' ) ); + } + + if ( username_exists( $username ) ) { + return $this->invalid_attribute_error( 'data[username]', __( 'Sorry, that username already exists!' ), 'user_exists' ); + } + + $error = $this->get_validation_error( + 'data[email]', + $data, + array( + 'type' => 'object', + 'required' => array( 'email' ), + ), + 'data' + ); + if ( $error ) { + return $error; + } + } + + if ( array_key_exists( 'email', $data ) ) { + if ( ! is_email( $data['email'] ) ) { + return $this->invalid_attribute_error( 'data[email]', __( 'Invalid email address.' ) ); + } + + /* + * Intentionally strict: an address that the save would store differently from the + * address sent is refused, rather than stored changed. + */ + /** This filter is documented in wp-includes/user.php */ + if ( wp_unslash( apply_filters( 'pre_user_email', wp_slash( $data['email'] ) ) ) !== $data['email'] ) { + return $this->invalid_attribute_error( 'data[email]', __( 'Invalid email address.' ) ); + } + + // Intentionally strict: the address is refused past the column size rather than cut short. + $error = $this->get_validation_error( + 'data[email]', + $data['email'], + array( + 'type' => 'string', + 'maxLength' => 100, + ) + ); + if ( $error ) { + return $error; + } + + // The address of another user is refused, the target's own is not. + $email_user_id = email_exists( $data['email'] ); + if ( $email_user_id && ( ! $target || $email_user_id !== $target->ID ) ) { + return $this->invalid_attribute_error( 'data[email]', __( 'Sorry, that email address is already used!' ), 'user_exists' ); + } + } + + if ( array_key_exists( 'name', $data ) ) { + /* + * Intentionally strict: the name is counted as the save would store it, and refused + * when that is empty or past the column size, rather than saved empty or cut short. + */ + /** This filter is documented in wp-includes/user.php */ + $name = wp_unslash( apply_filters( 'pre_user_display_name', wp_slash( $data['name'] ) ) ); + $error = $this->get_validation_error( + 'data[name]', + $name, + array( + 'type' => 'string', + 'minLength' => 1, + 'maxLength' => 250, + ) + ); + if ( $error ) { + return $error; + } + } + + if ( array_key_exists( 'nickname', $data ) ) { + // Intentionally strict: a nickname with nothing left after sanitizing is refused rather than saved empty. + $error = $this->get_validation_error( + 'data[nickname]', + sanitize_text_field( $data['nickname'] ), + array( + 'type' => 'string', + 'minLength' => 1, + ) + ); + if ( $error ) { + return $error; + } + } + + if ( array_key_exists( 'slug', $data ) ) { + /** This filter is documented in wp-includes/user.php */ + $slug = (string) apply_filters( 'pre_user_nicename', sanitize_title( sanitize_user( wp_slash( $data['slug'] ), true ) ) ); + if ( '' === $slug ) { + return $this->invalid_attribute_error( 'data[slug]', __( 'Invalid slug.' ) ); + } + + if ( mb_strlen( $slug ) > 50 ) { + return $this->invalid_attribute_error( 'data[slug]', __( 'Nicename may not be longer than 50 characters.' ) ); + } + + // Intentionally strict: the slug of another user is refused rather than saved with a numeric suffix. + $slug_user = get_user_by( 'slug', $slug ); + if ( $slug_user && ( ! $target || $slug_user->ID !== $target->ID ) ) { + return $this->invalid_attribute_error( 'data[slug]', __( 'Invalid slug.' ) ); + } + } + + if ( array_key_exists( 'url', $data ) && '' !== $data['url'] ) { + /** This filter is documented in wp-includes/user.php */ + $url = (string) apply_filters( 'pre_user_url', wp_slash( $data['url'] ) ); + + // Intentionally strict: a URL with nothing left after sanitizing is refused rather than saved empty. + $error = $this->get_validation_error( + 'data[url]', + $url, + array( + 'type' => 'string', + 'minLength' => 1, + ) + ); + if ( $error ) { + return $error; + } + + if ( mb_strlen( $url ) > 100 ) { + return $this->invalid_attribute_error( 'data[url]', __( 'User URL may not be longer than 100 characters.' ) ); + } + } + + if ( array_key_exists( 'locale', $data ) ) { + $error = $this->get_validation_error( + 'data[locale]', + $data['locale'], + array( + 'type' => 'string', + 'enum' => $this->get_locales(), + ) + ); + if ( $error ) { + return $error; + } + } + + return null; + } + + /** + * Builds the user data for a save from the profile attributes, key by key. + * + * Values are slashed, since the saves expect slashed data. + * + * @since 7.3.0 + * + * @param array $data The `data` input. + * @return array The user data, keyed as the saves expect. + */ + private function get_profile_userdata( array $data ): array { + $userdata = array(); + foreach ( self::PROFILE_ATTRIBUTES as $name => $key ) { + if ( array_key_exists( $name, $data ) ) { + $userdata[ $key ] = wp_slash( $data[ $name ] ); + } + } + + return $userdata; + } + + /** + * Gives a user exactly the given roles, in the given order. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @param string[] $roles The roles, at least one. + */ + private function set_user_roles( int $user_id, array $roles ): void { + $user = new WP_User( $user_id ); + $user->set_role( (string) array_shift( $roles ) ); + foreach ( $roles as $role ) { + $user->add_role( $role ); + } + } + + /** + * Formats a user that was just written. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @param array $input The ability input. + * @return array The formatted user data. + */ + private function format_written_user( int $user_id, array $input ): array { + /* + * Intentionally strict: a caller who may neither edit this user nor list users gets + * the ID only, so a write never shows a user that the caller could not otherwise read. + */ + if ( get_current_user_id() !== $user_id && ! current_user_can( 'edit_user', $user_id ) && ! current_user_can( 'list_users' ) ) { + return array( 'id' => $user_id ); + } + + return $this->format_user( new WP_User( $user_id ), $this->normalize_fields( $input ) ); + } + + /** + * Builds the error for an error that a save returned. + * + * An error about an attribute that was sent is reported for that attribute. Every + * other error keeps its code, message and data, carries no `params`, and gets status + * 500 when it has no status yet. + * + * @since 7.3.0 + * + * @param WP_Error $error The error the save returned. + * @param string[] $sent The names of the attributes that were sent. + * @return WP_Error The error to return. + */ + private function save_error( WP_Error $error, array $sent ): WP_Error { + $attributes = array( + 'existing_user_login' => 'username', + 'empty_user_login' => 'username', + 'user_login_too_long' => 'username', + 'invalid_username' => 'username', + 'existing_user_email' => 'email', + 'empty_user_nicename' => 'slug', + 'user_nicename_too_long' => 'slug', + 'user_url_too_long' => 'url', + ); + + $code = (string) $error->get_error_code(); + if ( isset( $attributes[ $code ] ) && in_array( $attributes[ $code ], $sent, true ) ) { + return $this->invalid_attribute_error( + "data[{$attributes[ $code ]}]", + $error->get_error_message(), + str_starts_with( $code, 'existing_' ) ? 'user_exists' : 'user_invalid_attribute' + ); + } + + $data = $error->get_error_data(); + $error->add_data( array_merge( array( 'status' => 500 ), is_array( $data ) ? $data : array() ) ); + + return $error; + } + + /** + * Returns the locales a user can be given: the site default, `en_US`, and the installed languages. + * + * @since 7.3.0 + * + * @return string[] The locales. + */ + private function get_locales(): array { + return array_values( array_unique( array_merge( array( '', 'en_US' ), get_available_languages() ) ) ); + } + /** * Reads an object member of the input, such as `where` or `pagination`. * @@ -750,15 +1523,7 @@ private function get_users_query_input_schema(): array { ), 'description' => __( 'Selects the users to return. Every given filter must match, and a list matches users with any of its values. Results are ordered by username, and values that match no readable user are left out rather than causing an error. If omitted, every readable user is returned. Callers without permission to list users only see public authors, who have published posts in a publicly viewable post type. To read your own profile, use the `core/get-user-info` ability.' ), ), - 'fields' => array( - 'type' => 'array', - 'uniqueItems' => true, - 'items' => array( - 'type' => 'string', - 'enum' => $this->get_field_paths(), - ), - 'description' => __( 'Limit each returned user to these fields. A field such as `registered` returns all of its sub-fields, while a path such as `registered.gmt` returns only that sub-field. If omitted or empty, a lean set of common read fields is returned. The `id` field is always included, and fields the current user cannot view are omitted rather than causing an error.' ), - ), + 'fields' => $this->get_fields_input_schema( __( 'Limit each returned user to these fields. A field such as `registered` returns all of its sub-fields, while a path such as `registered.gmt` returns only that sub-field. If omitted or empty, a lean set of common read fields is returned. The `id` field is always included, and fields the current user cannot view are omitted rather than causing an error.' ) ), 'pagination' => array( 'type' => 'object', 'additionalProperties' => false, @@ -787,10 +1552,6 @@ private function get_users_query_input_schema(): array { * Every request returns the same shape: a page of users in `items`, and the totals * across all pages in `pagination`. * - * Only `id` is required in a user, because it is always returned. The other fields - * are optional because the `fields` input lets the caller request any subset, and - * restricted fields are omitted when unavailable. - * * @since 7.2.0 * * @return array The output JSON Schema. @@ -804,12 +1565,7 @@ private function get_users_query_output_schema(): array { 'items' => array( 'type' => 'array', 'description' => __( 'The readable users on the requested page.' ), - 'items' => array( - 'type' => 'object', - 'additionalProperties' => false, - 'required' => array( 'id' ), - 'properties' => $this->get_user_properties(), - ), + 'items' => $this->get_user_item_schema(), ), 'pagination' => array( 'type' => 'object', @@ -1018,4 +1774,316 @@ private function invalid_filter_error( string $param, string $message ): WP_Erro ) ); } + + /** + * Builds the error for an input value that cannot be applied. + * + * The error data maps the value's input path to the message under `params`. + * + * @since 7.3.0 + * + * @param string $param The input path, such as `data[email]`. + * @param string $message The error message. + * @param string $code Optional. The error code. Default 'user_invalid_attribute'. + * @return WP_Error The error. + */ + private function invalid_attribute_error( string $param, string $message, string $code = 'user_invalid_attribute' ): WP_Error { + return new WP_Error( + $code, + $message, + array( + 'status' => 400, + 'params' => array( $param => $message ), + ) + ); + } + + /** + * Validates a value against a schema, and builds the error for it when it fails. + * + * Used for the checks the input schema also makes, since a filter can skip schema + * validation, and for checks on a computed value, such as its length after sanitizing, + * so the error has a schema validation message. + * + * @since 7.3.0 + * + * @param string $param The input path the error is reported for. + * @param mixed $value The value to validate. + * @param array $schema The schema to validate the value against. + * @param string $path Optional. The path the message names. Default the input path. + * @return WP_Error|null The error, or null when the value is valid. + */ + private function get_validation_error( string $param, $value, array $schema, string $path = '' ): ?WP_Error { + $result = rest_validate_value_from_schema( $value, $schema, '' === $path ? $param : $path ); + + return is_wp_error( $result ) ? $this->invalid_attribute_error( $param, $result->get_error_message() ) : null; + } + + /** + * Builds the error for a `where.id` that names no member of the current site. + * + * @since 7.3.0 + * + * @return WP_Error The not found error. + */ + private function not_found_error(): WP_Error { + return new WP_Error( 'user_not_found', __( 'Invalid user ID.' ), array( 'status' => 404 ) ); + } + + /** + * Builds the error for a caller who may not delete, or on multisite remove, the user. + * + * @since 7.3.0 + * + * @return WP_Error The permission error. + */ + private function cannot_delete_error(): WP_Error { + return new WP_Error( + 'user_cannot_delete', + is_multisite() ? __( 'Sorry, you are not allowed to remove users.' ) : __( 'Sorry, you are not allowed to delete this user.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + /** + * Builds the error for a create save that returned no user. + * + * @since 7.3.0 + * + * @return WP_Error The error. + */ + private function create_failed_error(): WP_Error { + return new WP_Error( 'user_create_failed', __( 'Error creating new user.' ), array( 'status' => 500 ) ); + } + + /** + * Builds the schema of the `fields` input. + * + * @since 7.3.0 + * + * @param string $description The description of the input. + * @return array The `fields` JSON Schema. + */ + private function get_fields_input_schema( string $description ): array { + return array( + 'type' => 'array', + 'uniqueItems' => true, + 'items' => array( + 'type' => 'string', + 'enum' => $this->get_field_paths(), + ), + 'description' => $description, + ); + } + + /** + * Builds the schema of the `fields` input of the create and update abilities. + * + * @since 7.3.0 + * + * @return array The `fields` JSON Schema. + */ + private function get_user_fields_input_schema(): array { + return $this->get_fields_input_schema( __( 'Limit the returned user to these fields. A field such as `registered` returns all of its sub-fields, while a path such as `registered.gmt` returns only that sub-field. If omitted or empty, a lean set of common read fields is returned. The `id` field is always included, and fields the current user cannot view are omitted rather than causing an error.' ) ); + } + + /** + * Builds the schema of a user, as returned by the user abilities. + * + * Only `id` is required, because it is always returned. The other fields are optional + * because the `fields` input lets the caller request any subset, and restricted fields + * are omitted when unavailable. + * + * @since 7.3.0 + * + * @return array The user JSON Schema. + */ + private function get_user_item_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'id' ), + 'properties' => $this->get_user_properties(), + ); + } + + /** + * Builds the schema of the `where` input of the update and delete abilities. + * + * @since 7.3.0 + * + * @return array The `where` JSON Schema. + */ + private function get_where_id_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'id' ), + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'minimum' => 1, + 'description' => __( 'Unique identifier for the user.' ), + ), + ), + 'description' => __( 'Selects the user. On multisite, only members of the current site can be selected.' ), + ); + } + + /** + * Builds the attribute schemas of the `data` input of the create and update abilities. + * + * The `roles` and `locale` enums hold the roles and languages available when the + * ability is registered. The callbacks check both again, since either can change later. + * + * @since 7.3.0 + * + * @param bool $is_create Whether the schemas are for the create ability, which also takes a username. + * @return array The attribute JSON Schemas, keyed by attribute name. + */ + private function get_user_data_properties( bool $is_create ): array { + $properties = array(); + if ( $is_create ) { + $properties['username'] = array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( 'Login name for the user.' ), + ); + } + + return $properties + array( + 'email' => array( + 'type' => 'string', + 'format' => 'email', + 'maxLength' => 100, + 'description' => __( 'The email address for the user.' ), + ), + 'name' => array( + 'type' => 'string', + 'minLength' => 1, + 'maxLength' => 250, + 'description' => __( 'Display name for the user.' ), + ), + 'first_name' => array( + 'type' => 'string', + 'description' => __( 'First name for the user.' ), + ), + 'last_name' => array( + 'type' => 'string', + 'description' => __( 'Last name for the user.' ), + ), + 'nickname' => array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( 'The nickname for the user.' ), + ), + 'slug' => array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( 'An alphanumeric identifier for the user.' ), + ), + 'description' => array( + 'type' => 'string', + 'description' => __( 'Description of the user.' ), + ), + 'url' => array( + 'type' => 'string', + 'description' => __( 'URL of the user.' ), + ), + 'locale' => array( + 'type' => 'string', + 'enum' => $this->get_locales(), + 'description' => __( 'Locale for the user.' ), + ), + 'roles' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'items' => array( + 'type' => 'string', + 'enum' => array_keys( wp_roles()->roles ), + ), + 'description' => __( 'Roles assigned to the user.' ), + ), + ); + } + + /** + * Builds the input schema for the `core/user-create` ability. + * + * @since 7.3.0 + * + * @return array The input JSON Schema. + */ + private function get_user_create_input_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'data' ), + 'properties' => array( + 'data' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'username', 'email' ), + 'properties' => $this->get_user_data_properties( true ), + 'description' => __( 'The attributes of the new user. Without `roles`, the user gets the default role of the site, or on multisite no role on the current site.' ), + ), + 'fields' => $this->get_user_fields_input_schema(), + ), + ); + } + + /** + * Builds the input schema for the `core/user-update` ability. + * + * @since 7.3.0 + * + * @return array The input JSON Schema. + */ + private function get_user_update_input_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'where', 'data' ), + 'properties' => array( + 'where' => $this->get_where_id_schema(), + 'data' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => $this->get_user_data_properties( false ), + 'description' => __( 'The attributes to change. `roles` replaces all roles of the user.' ), + ), + 'fields' => $this->get_user_fields_input_schema(), + ), + ); + } + + /** + * Builds the input schema for the `core/user-delete` ability. + * + * @since 7.3.0 + * + * @return array The input JSON Schema. + */ + private function get_user_delete_input_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'where', 'reassign' ), + 'properties' => array( + 'where' => $this->get_where_id_schema(), + 'reassign' => array( + /* + * Intentionally strict: 0, an empty string and null are refused rather than read + * as reassigning nothing, so the content is only left unassigned when false is + * sent. True passes this schema and is refused by the execute callback. + */ + 'type' => array( 'integer', 'boolean' ), + 'minimum' => 1, + 'description' => __( 'The ID of the user who takes over the content of the deleted user, or false to reassign nothing. True is not accepted.' ), + ), + ), + ); + } } diff --git a/tests/phpunit/tests/abilities-api/testcase-user-write-ability.php b/tests/phpunit/tests/abilities-api/testcase-user-write-ability.php new file mode 100644 index 0000000000000..11426774f11e7 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/testcase-user-write-ability.php @@ -0,0 +1,999 @@ + + */ + protected const USER_ABILITIES = array( 'core/users-query', 'core/user-create', 'core/user-update', 'core/user-delete' ); + + /** + * An ID that no user has. + * + * @since 7.3.0 + * + * @var int + */ + protected const MISSING_ID = 987654321; + + /** + * Stands, in the tables of refused attributes, for the message a name of 251 letters + * gets when schema validation is skipped. + * + * @since 7.3.0 + * + * @var string + */ + protected const LONG_NAME_MESSAGE = 'message of a name of 251 letters'; + + /** + * The default roles, one shared user each. + * + * @since 7.3.0 + * + * @var list + */ + protected const ROLES = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' ); + + /** + * The custom roles of the shared users, with their capabilities. + * + * @since 7.3.0 + * + * @var array> + */ + protected const CUSTOM_ROLES = array( + 'creator' => array( 'read', 'create_users' ), + 'promoter' => array( 'read', 'promote_users' ), + 'lister_promoter' => array( 'read', 'promote_users', 'list_users' ), + ); + + /** + * The fields only a caller who may edit the user can read. + * + * @since 7.3.0 + * + * @var list + */ + protected const PRIVATE_FIELDS = array( 'username', 'email', 'first_name', 'last_name', 'nickname', 'locale', 'registered', 'roles' ); + + /** + * Every top-level output field. + * + * @since 7.3.0 + * + * @var list + */ + protected const ALL_FIELDS = array( 'id', 'name', 'description', 'url', 'link', 'slug', 'avatar_urls', 'username', 'email', 'first_name', 'last_name', 'nickname', 'locale', 'registered', 'roles' ); + + /** + * The fields returned when none are requested. + * + * @since 7.3.0 + * + * @var list + */ + protected const DEFAULT_FIELDS = array( 'id', 'name', 'link', 'slug', 'avatar_urls' ); + + /** + * The status and message of each error code with a fixed message. + * + * @since 7.3.0 + * + * @var array + */ + protected const ERRORS = array( + 'user_cannot_create' => array( 403, 'Sorry, you are not allowed to create new users.' ), + 'user_not_found' => array( 404, 'Invalid user ID.' ), + 'user_cannot_edit' => array( 403, 'Sorry, you are not allowed to edit this user.' ), + 'user_cannot_edit_roles' => array( 403, 'Sorry, you are not allowed to edit roles of this user.' ), + 'user_cannot_assign_role' => array( 403, 'Sorry, you are not allowed to give users that role.' ), + 'user_cannot_delete' => array( 403, 'Sorry, you are not allowed to delete this user.' ), + 'user_invalid_reassign' => array( 400, 'Invalid user ID for reassignment.' ), + 'user_create_failed' => array( 500, 'Error creating new user.' ), + 'user_delete_failed' => array( 500, 'The user cannot be deleted.' ), + ); + + /** + * Shared user IDs keyed by role or fixture name. + * + * @since 7.3.0 + * + * @var array + */ + protected static $user_ids = array(); + + /** + * The ID of a second site on multisite. + * + * @since 7.3.0 + * + * @var int + */ + protected static $site_id = 0; + + /** + * The passwords of 24 characters generated during the current test. + * + * @since 7.3.0 + * + * @var list + */ + protected $generated_passwords = array(); + + /** + * How often each watched filter ran during the current test. + * + * @since 7.3.0 + * + * @var array + */ + protected $filter_runs = array(); + + /** + * Creates the shared users and, on multisite, a second site. + * + * Each user of a role has the username `uwt_` and the email + * `uwt-@example.test`. + * + * @since 7.3.0 + * + * @param WP_UnitTest_Factory $factory The unit test factory. + */ + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void { + require_once ABSPATH . 'wp-admin/includes/user.php'; + require_once ABSPATH . 'wp-admin/includes/bookmark.php'; + + foreach ( self::CUSTOM_ROLES as $role => $capabilities ) { + add_role( "uwt_{$role}", "UWT {$role}", array_fill_keys( $capabilities, true ) ); + } + + $roles = array_merge( self::ROLES, array_map( static fn( $role ) => "uwt_{$role}", array_keys( self::CUSTOM_ROLES ) ) ); + foreach ( $roles as $role ) { + $name = str_replace( 'uwt_', '', $role ); + self::$user_ids[ $name ] = $factory->user->create( + array( + 'role' => $role, + 'user_login' => "uwt_{$name}", + 'user_email' => "uwt-{$name}@example.test", + ) + ); + } + + self::$user_ids['manager'] = $factory->user->create( + array( + 'role' => 'administrator', + 'user_login' => 'uwt_manager', + 'user_email' => 'uwt-manager@example.test', + ) + ); + + if ( ! is_multisite() ) { + return; + } + + grant_super_admin( self::$user_ids['manager'] ); + + self::$site_id = (int) $factory->blog->create(); + + self::$user_ids['outsider'] = $factory->user->create( + array( + 'role' => 'author', + 'user_login' => 'uwt_outsider', + 'user_email' => 'uwt-outsider@example.test', + ) + ); + remove_user_from_blog( self::$user_ids['outsider'], get_current_blog_id() ); + add_user_to_blog( self::$site_id, self::$user_ids['outsider'], 'author' ); + + self::$user_ids['outside_super_admin'] = $factory->user->create( + array( + 'role' => 'administrator', + 'user_login' => 'uwt_outside_super_admin', + 'user_email' => 'uwt-outside-super-admin@example.test', + ) + ); + remove_user_from_blog( self::$user_ids['outside_super_admin'], get_current_blog_id() ); + grant_super_admin( self::$user_ids['outside_super_admin'] ); + + self::$user_ids['network_editor'] = $factory->user->create( + array( + 'role' => 'administrator', + 'user_login' => 'uwt_network_editor', + 'user_email' => 'uwt-network-editor@example.test', + ) + ); + get_userdata( self::$user_ids['network_editor'] )->add_cap( 'manage_network_users' ); + } + + /** + * Removes the custom roles, the super admins and the second site, and forgets the fixtures. + * + * @since 7.3.0 + */ + public static function wpTearDownAfterClass(): void { + if ( is_multisite() ) { + foreach ( array( 'manager', 'outside_super_admin' ) as $name ) { + if ( isset( self::$user_ids[ $name ] ) ) { + revoke_super_admin( self::$user_ids[ $name ] ); + } + } + if ( self::$site_id ) { + wp_delete_site( self::$site_id ); + } + } + + foreach ( array_keys( self::CUSTOM_ROLES ) as $role ) { + remove_role( "uwt_{$role}" ); + } + + self::$user_ids = array(); + self::$site_id = 0; + } + + /** + * Clears the sent mail, unregisters the user abilities, registers the user category + * and records the generated passwords. + * + * @since 7.3.0 + */ + public function set_up(): void { + parent::set_up(); + + reset_phpmailer_instance(); + + foreach ( self::USER_ABILITIES as $ability_name ) { + if ( wp_has_ability( $ability_name ) ) { + wp_unregister_ability( $ability_name ); + } + } + + if ( ! wp_has_ability_category( 'user' ) ) { + global $wp_current_filter; + $wp_current_filter[] = 'wp_abilities_api_categories_init'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it. + wp_register_ability_category( + 'user', + array( + 'label' => 'User', + 'description' => 'User.', + ) + ); + array_pop( $wp_current_filter ); + } + + $this->generated_passwords = array(); + $this->filter_runs = array(); + add_filter( + 'random_password', + function ( $password, $length ) { + if ( 24 === (int) $length ) { + $this->generated_passwords[] = $password; + } + + return $password; + }, + 10, + 2 + ); + } + + /** + * Unregisters the user abilities and the category. + * + * @since 7.3.0 + */ + public function tear_down(): void { + foreach ( self::USER_ABILITIES as $ability_name ) { + if ( wp_has_ability( $ability_name ) ) { + wp_unregister_ability( $ability_name ); + } + } + + if ( wp_has_ability_category( 'user' ) ) { + wp_unregister_ability_category( 'user' ); + } + + reset_phpmailer_instance(); + + parent::tear_down(); + } + + /** + * Registers the user abilities inside a faked init action. + * + * @since 7.3.0 + */ + protected function register_abilities(): void { + global $wp_current_filter; + $wp_current_filter[] = 'wp_abilities_api_init'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it. + ( new WP_Abilities_Users() )->register(); + array_pop( $wp_current_filter ); + } + + /** + * Registers the user abilities and returns the execute callback of the ability under test. + * + * The callback calls private methods, so tests that reach the checks behind the + * permission check capture it from the registration arguments. + * + * @since 7.3.0 + * + * @return array The execute callback, keyed by argument name. + */ + protected function get_ability_callbacks(): array { + $ability = static::ABILITY; + $callbacks = array(); + + add_filter( + 'wp_register_ability_args', + static function ( array $args, string $name ) use ( &$callbacks, $ability ): array { + if ( $ability === $name && isset( $args['execute_callback'] ) ) { + $callbacks = array( 'execute_callback' => $args['execute_callback'] ); + } + + return $args; + }, + 10, + 2 + ); + + $this->register_abilities(); + + $this->assertArrayHasKey( 'execute_callback', $callbacks, "The {$ability} ability should be registered with callbacks." ); + + return $callbacks; + } + + /** + * Runs the registered ability under test with the given input. + * + * @since 7.3.0 + * + * @param mixed $input The ability input. + * @return mixed The ability result. + */ + protected function run_ability( $input ) { + $ability = static::ABILITY; + + $this->assertTrue( wp_has_ability( $ability ), "The {$ability} ability should be registered." ); + + return wp_get_ability( $ability )->execute( $input ); + } + + /** + * Makes the abilities skip schema validation of their input. + * + * @since 7.3.0 + */ + protected function skip_input_validation(): void { + add_filter( 'wp_ability_validate_input', '__return_true' ); + } + + /** + * Returns the message a name of 251 letters gets when schema validation is skipped, + * and turns validation on again. + * + * @since 7.3.0 + * + * @param array $input The ability input, with a name of 251 letters. + * @return string The message. + */ + protected function get_long_name_message( array $input ): string { + $this->skip_input_validation(); + $result = $this->run_ability( $input ); + remove_filter( 'wp_ability_validate_input', '__return_true' ); + + return $result instanceof WP_Error ? $result->get_error_message() : 'A name of 251 letters should be refused.'; + } + + /** + * Logs in as the shared user with the given role or fixture name, or logs out. + * + * @since 7.3.0 + * + * @param string $name The role or fixture name, or an empty string to log out. + */ + protected function login_as( string $name ): void { + wp_set_current_user( '' === $name ? 0 : self::$user_ids[ $name ] ); + } + + /** + * Creates a user for a test that changes it. + * + * @since 7.3.0 + * + * @param string $login The username, also used for the email. + * @param array $args Optional. More user arguments. Default empty array. + * @return int The user ID. + */ + protected function create_target( string $login, array $args = array() ): int { + return self::factory()->user->create( + array_merge( + array( + 'role' => 'author', + 'user_login' => $login, + 'user_email' => "{$login}@example.test", + ), + $args + ) + ); + } + + /** + * Counts the runs of a filter from now on. + * + * @since 7.3.0 + * + * @param string $hook The filter. + */ + protected function watch_filter( string $hook ): void { + $this->filter_runs[ $hook ] = 0; + add_filter( + $hook, + function ( $value ) use ( $hook ) { + ++$this->filter_runs[ $hook ]; + return $value; + } + ); + } + + /** + * Asserts that a watched filter did not run. + * + * @since 7.3.0 + * + * @param string $hook The filter. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_filter_not_run( string $hook, string $context ): void { + $this->assertSame( 0, $this->filter_runs[ $hook ] ?? null, "{$context}: the {$hook} filter should not run." ); + } + + /** + * Takes a snapshot of the stored users and what they own: every user row and user + * meta row (roles, capabilities and site memberships included), the authors and + * statuses of the posts, the owners of the links, the super admins and the mail sent. + * + * @since 7.3.0 + * + * @return array The snapshot. + */ + protected function snapshot(): array { + global $wpdb; + + return array( + 'users' => $wpdb->get_results( "SELECT * FROM {$wpdb->users} ORDER BY ID", ARRAY_A ), + 'user_meta' => $wpdb->get_results( "SELECT user_id, meta_key, meta_value FROM {$wpdb->usermeta} ORDER BY umeta_id", ARRAY_A ), + 'posts' => $wpdb->get_results( "SELECT ID, post_author, post_status FROM {$wpdb->posts} ORDER BY ID", ARRAY_A ), + 'links' => $wpdb->get_results( "SELECT link_id, link_owner FROM {$wpdb->links} ORDER BY link_id", ARRAY_A ), + 'super_admins' => is_multisite() ? get_site_option( 'site_admins', array() ) : array(), + 'mail' => wp_list_pluck( $this->get_mails(), 'subject' ), + ); + } + + /** + * Asserts that a refused call changed nothing and sent no mail. + * + * @since 7.3.0 + * + * @param array $before The snapshot taken before the call. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_unchanged( array $before, string $context ): void { + $after = $this->snapshot(); + + $this->assertSame( array(), $after['mail'], "{$context}: no mail should be sent." ); + $this->assertSame( $before, $after, "{$context}: nothing should change." ); + } + + /** + * Returns the mail sent since the last reset. + * + * @since 7.3.0 + * + * @return list, subject: string, body: string}> The mails, with + * the recipient addresses. + */ + protected function get_mails(): array { + $mails = array(); + foreach ( tests_retrieve_phpmailer_instance()->mock_sent as $mail ) { + $mails[] = array( + 'to' => array_map( 'strtolower', array_column( $mail['to'], 0 ) ), + 'subject' => $mail['subject'], + 'body' => $mail['body'], + ); + } + + return $mails; + } + + /** + * Returns the site name as the mails show it. + * + * @since 7.3.0 + * + * @return string The site name. + */ + protected function get_mail_site_name(): string { + return wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); + } + + /** + * Reads a user through core/users-query, as the current user. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @param list $fields Optional. The fields. Default the default fields. + * @return array|null The user item, or null when it was not returned. + */ + protected function query_user( int $user_id, array $fields = array() ): ?array { + $this->assertTrue( wp_has_ability( 'core/users-query' ), 'The core/users-query ability should be registered.' ); + + $input = array( 'where' => array( 'ids' => array( $user_id ) ) ); + if ( ! empty( $fields ) ) { + $input['fields'] = $fields; + } + + $result = wp_get_ability( 'core/users-query' )->execute( $input ); + + $this->assertIsArray( $result, 'The user should be readable through core/users-query.' ); + + return $result['items'][0] ?? null; + } + + /** + * Asserts that a write result is a user item equal to what core/users-query shows. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param list $fields The requested fields, or an empty list for the default ones. + * @param string $context What the call was, for the assertion messages. + * @return int The user ID. + */ + protected function assert_user_item( $result, array $fields, string $context ): int { + $this->assertIsArray( $result, "{$context}: the call should succeed." ); + $this->assertArrayHasKey( 'id', $result, "{$context}: the output should hold the ID." ); + $this->assertIsInt( $result['id'], "{$context}: the ID should be an integer." ); + + $this->assertSame( $this->query_user( $result['id'], $fields ), $result, "{$context}: the output should be what core/users-query shows for the stored user." ); + + return $result['id']; + } + + /** + * Asserts that a result is an error with the given code and status. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $code The expected error code. + * @param int $status The expected error status. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_error( $result, string $code, int $status, string $context ): void { + $this->assertWPError( $result, "{$context}: the call should fail." ); + $this->assertSame( $code, $result->get_error_code(), "{$context}: the error code should be {$code}." ); + + $data = $result->get_error_data(); + $this->assertIsArray( $data, "{$context}: the error should carry data." ); + $this->assertSame( $status, $data['status'] ?? null, "{$context}: the error status should be {$status}." ); + } + + /** + * Asserts that a result is an error with a fixed message, and its status, which is + * 401 instead of 403 when nobody is logged in. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $code The expected error code. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_core_error( $result, string $code, string $context ): void { + list( $status, $message ) = self::ERRORS[ $code ]; + + if ( 403 === $status && ! is_user_logged_in() ) { + $status = 401; + } + if ( 'user_cannot_delete' === $code && is_multisite() ) { + $message = 'Sorry, you are not allowed to remove users.'; + } + + $this->assert_error( $result, $code, $status, $context ); + $this->assertSame( $message, $result->get_error_message(), "{$context}: the message should be the {$code} message." ); + } + + /** + * Asserts that a result is a 400 error about one input value. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $code The expected error code. + * @param string $param The input path of the value. + * @param string $context What the call was, for the assertion messages. + * @param string|null $message Optional. The expected message. Default null, any message. + */ + protected function assert_value_error( $result, string $code, string $param, string $context, ?string $message = null ): void { + $this->assert_error( $result, $code, 400, $context ); + + if ( null !== $message ) { + $this->assertSame( $message, $result->get_error_message(), "{$context}: the message should be the one for {$param}." ); + } + + $this->assertNotSame( '', $result->get_error_message(), "{$context}: the message should give the reason." ); + $this->assertSame( array( $param => $result->get_error_message() ), $result->get_error_data()['params'] ?? null, "{$context}: the params should hold only {$param}, with the message." ); + } + + /** + * Asserts that a result is the error of a call that the permission check refused. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_refused( $result, string $context ): void { + $this->assertWPError( $result, "{$context}: the call should fail." ); + $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), "{$context}: the permission check should refuse the call." ); + } + + /** + * Asserts that a result is the error of input the schema refused. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_invalid_input( $result, string $context ): void { + $this->assertWPError( $result, "{$context}: the call should fail." ); + $this->assertSame( 'ability_invalid_input', $result->get_error_code(), "{$context}: the schema should refuse the input." ); + } + + /** + * Asserts that no generated password shows in a result or in the mail sent. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_password_not_leaked( $result, string $context ): void { + $haystacks = array( 'output' => (string) wp_json_encode( is_wp_error( $result ) ? array( $result->get_error_messages(), $result->get_error_data() ) : $result ) ); + foreach ( $this->get_mails() as $index => $mail ) { + $haystacks[ "mail {$index}" ] = $mail['subject'] . "\n" . $mail['body']; + } + + foreach ( $this->generated_passwords as $password ) { + foreach ( $haystacks as $where => $haystack ) { + $this->assertStringNotContainsString( $password, $haystack, "{$context}: the generated password should not be in the {$where}." ); + } + } + } + + /** + * Normalizes a schema for comparison: removes the descriptions, sorts the keys of + * objects and sorts lists of plain values. + * + * @since 7.3.0 + * + * @param mixed $schema The schema. + * @return mixed The normalized schema. + */ + protected function normalize_schema( $schema ) { + if ( ! is_array( $schema ) ) { + return $schema; + } + + if ( isset( $schema['description'] ) && is_string( $schema['description'] ) ) { + unset( $schema['description'] ); + } + + $schema = array_map( array( $this, 'normalize_schema' ), $schema ); + + if ( array_is_list( $schema ) ) { + if ( count( $schema ) === count( array_filter( $schema, 'is_scalar' ) ) ) { + sort( $schema ); + } + } else { + ksort( $schema ); + } + + return $schema; + } + + /** + * Returns the schema of the attributes that create and update share. + * + * @since 7.3.0 + * + * @return array The property schemas, keyed by attribute. + */ + protected function get_profile_property_schemas(): array { + return array( + 'email' => array( + 'type' => 'string', + 'format' => 'email', + 'maxLength' => 100, + ), + 'name' => array( + 'type' => 'string', + 'minLength' => 1, + 'maxLength' => 250, + ), + 'first_name' => array( 'type' => 'string' ), + 'last_name' => array( 'type' => 'string' ), + 'nickname' => array( + 'type' => 'string', + 'minLength' => 1, + ), + 'slug' => array( + 'type' => 'string', + 'minLength' => 1, + ), + 'description' => array( 'type' => 'string' ), + 'url' => array( 'type' => 'string' ), + 'locale' => array( + 'type' => 'string', + 'enum' => array_merge( array( '', 'en_US' ), get_available_languages() ), + ), + 'roles' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'items' => array( + 'type' => 'string', + 'enum' => array_keys( wp_roles()->roles ), + ), + ), + ); + } + + /** + * Returns the schema of `where` of update and delete. + * + * @since 7.3.0 + * + * @return array The schema. + */ + protected function get_where_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'id' ), + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'minimum' => 1, + ), + ), + ); + } + + /** + * Asserts that the output schema of the ability under test is the core/users-query item. + * + * @since 7.3.0 + */ + protected function assert_output_schema_is_the_query_item(): void { + $this->register_abilities(); + + $this->assertTrue( wp_has_ability( static::ABILITY ), 'The ability should be registered.' ); + + $schema = wp_get_ability( static::ABILITY )->get_output_schema(); + $item = wp_get_ability( 'core/users-query' )->get_output_schema()['properties']['items']['items']; + + $this->assertSame( array( 'id' ), $schema['required'] ?? null, 'The output should require the ID.' ); + $this->assertFalse( $schema['additionalProperties'] ?? null, 'The output should not take unknown keys.' ); + $this->assertSame( $this->normalize_schema( $item ), $this->normalize_schema( $schema ), 'The output should be the core/users-query user item.' ); + } + + /** + * Asserts the registration of the ability under test. + * + * @since 7.3.0 + * + * @param string $label The label. + * @param bool $destructive Whether the ability is destructive. + * @param bool $idempotent Whether the ability is idempotent. + */ + protected function assert_registration( string $label, bool $destructive, bool $idempotent ): void { + $this->register_abilities(); + + $ability = wp_get_ability( static::ABILITY ); + + $this->assertInstanceOf( WP_Ability::class, $ability, 'The ability should be registered.' ); + $this->assertSame( $label, $ability->get_label(), 'The ability should have its label.' ); + $this->assertSame( 'user', $ability->get_category(), 'The ability should use the user category.' ); + $this->assertTrue( $ability->get_meta_item( 'show_in_rest', false ), 'The ability should be shown in the run route.' ); + + $annotations = $ability->get_meta_item( 'annotations', array() ); + $this->assertFalse( $annotations['readonly'] ?? null, 'The ability should not be marked read-only.' ); + $this->assertSame( $destructive, $annotations['destructive'] ?? null, 'The destructive annotation should be set.' ); + $this->assertSame( $idempotent, $annotations['idempotent'] ?? null, 'The idempotent annotation should be set.' ); + } + + /** + * Returns input keys that are not attributes, with a value for each. + * + * @return array The keys and values. + */ + public static function data_keys_outside_the_allow_list(): array { + return array( + 'password' => array( 'password', 'uwt-chosen-password' ), + 'user_pass' => array( 'user_pass', 'uwt-chosen-password' ), + 'role' => array( 'role', 'administrator' ), + 'meta_input' => array( 'meta_input', array( 'uwt_meta' => 'set' ) ), + 'meta' => array( 'meta', array( 'uwt_meta' => 'set' ) ), + 'user_activation_key' => array( 'user_activation_key', 'uwt-key' ), + 'capabilities' => array( 'wp_capabilities', array( 'administrator' => true ) ), + 'user_level' => array( 'user_level', 10 ), + 'id' => array( 'id', 1 ), + ); + } + + /** + * Returns the keys outside the allow list as one `data` fragment. + * + * @since 7.3.0 + * + * @return array The keys and values. + */ + protected function get_keys_outside_the_allow_list(): array { + $data = array(); + foreach ( self::data_keys_outside_the_allow_list() as $row ) { + $data[ $row[0] ] = $row[1]; + } + + return $data; + } + + /** + * Asserts that none of the keys outside the allow list reached a user. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @param string $password_hash The password hash the user should still have, or an + * empty string when the user is new. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_keys_outside_the_allow_list_ignored( int $user_id, string $password_hash, string $context ): void { + $user = get_userdata( $user_id ); + + $this->assertInstanceOf( WP_User::class, $user, "{$context}: the user should exist." ); + $this->assertFalse( wp_check_password( 'uwt-chosen-password', $user->user_pass, $user_id ), "{$context}: the password from the input should not be set." ); + if ( '' !== $password_hash ) { + $this->assertSame( $password_hash, $user->user_pass, "{$context}: the password should not change." ); + } + $this->assertNotContains( 'administrator', $user->roles, "{$context}: the role from the input should not be given." ); + $this->assertFalse( $user->has_cap( 'manage_options' ), "{$context}: no capability from the input should be given." ); + $this->assertSame( array(), get_user_meta( $user_id, 'uwt_meta' ), "{$context}: no meta from the input should be stored." ); + $this->assertNotSame( 'uwt-key', $user->user_activation_key, "{$context}: the activation key from the input should not be stored." ); + } + + /** + * Returns profile attributes that are refused, with the error each gets. + * + * The users of the shared fixtures have the username `uwt_`, the email + * `uwt-@example.test` and the slug `uwt_`. + * + * @return array, code: string, param: string, message: string|null}> + * The `data`, the error code, the input path and the message, or null when + * the message is not fixed. + */ + public static function data_profile_attributes_refused(): array { + return array( + 'email of another user' => array( array( 'email' => 'uwt-editor@example.test' ), 'user_exists', 'data[email]', 'Sorry, that email address is already used!' ), + 'email of another user in another case' => array( array( 'email' => 'UWT-Editor@Example.TEST' ), 'user_exists', 'data[email]', 'Sorry, that email address is already used!' ), + 'name longer once stored' => array( array( 'name' => str_repeat( 'a', 249 ) . '&' ), 'user_invalid_attribute', 'data[name]', self::LONG_NAME_MESSAGE ), + 'email stored differently' => array( array( 'email' => 'uwt&stored@example.test' ), 'user_invalid_attribute', 'data[email]', 'Invalid email address.' ), + 'name with nothing left after sanitizing' => array( array( 'name' => '' ), 'user_invalid_attribute', 'data[name]', null ), + 'nickname with nothing left' => array( array( 'nickname' => ' ' ), 'user_invalid_attribute', 'data[nickname]', null ), + 'slug with nothing left' => array( array( 'slug' => '!!!' ), 'user_invalid_attribute', 'data[slug]', 'Invalid slug.' ), + 'slug of another user' => array( array( 'slug' => 'uwt_editor' ), 'user_invalid_attribute', 'data[slug]', 'Invalid slug.' ), + 'slug of 51 characters' => array( array( 'slug' => str_repeat( 'a', 51 ) ), 'user_invalid_attribute', 'data[slug]', null ), + 'url with nothing left' => array( array( 'url' => 'javascript:alert(1)' ), 'user_invalid_attribute', 'data[url]', null ), + 'url of 101 characters' => array( array( 'url' => 'https://example.test/' . str_repeat( 'a', 80 ) ), 'user_invalid_attribute', 'data[url]', null ), + ); + } + + /** + * Returns an email of 101 characters and a name of 251 characters, each with schema + * validation on and skipped. + * + * @return array, skip_validation: bool, param: string}> + * The `data`, whether to skip validation, and the input path. + */ + public static function data_values_over_the_length_limits(): array { + $email = array( 'email' => str_repeat( 'a', 88 ) . '@example.test' ); + $name = array( 'name' => str_repeat( 'a', 251 ) ); + + return array( + 'email of 101 characters' => array( $email, false, 'data[email]' ), + 'name of 251 characters' => array( $name, false, 'data[name]' ), + 'email of 101 characters, validation skipped' => array( $email, true, 'data[email]' ), + 'name of 251 characters, validation skipped' => array( $name, true, 'data[name]' ), + ); + } + + /** + * Asserts that a value over a length limit was refused: by the schema, or with the + * error about the value when schema validation was skipped. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param bool $skip_validation Whether schema validation was skipped. + * @param string $param The input path of the value. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_over_the_length_limit( $result, bool $skip_validation, string $param, string $context ): void { + if ( $skip_validation ) { + $this->assert_value_error( $result, 'user_invalid_attribute', $param, $context ); + } else { + $this->assert_invalid_input( $result, $context ); + } + } + + /** + * Returns text values with quotes and backslashes. + * + * @since 7.3.0 + * + * @return array The values, keyed by attribute. + */ + protected function get_quoted_values(): array { + return array( + 'name' => 'Sam O\'Neil "Q" \\ end', + 'first_name' => 'Sam \\ O\'Neil', + 'last_name' => 'O\'Neil "the \\ second"', + 'nickname' => '\'Q\' \\\\ "Sam"', + 'description' => 'Says "hi" and \'bye\' \\ with C:\\path', + ); + } + + /** + * Asserts that the text values with quotes and backslashes were stored as given. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_quoted_values_stored( int $user_id, string $context ): void { + $values = $this->get_quoted_values(); + $user = get_userdata( $user_id ); + + $this->assertSame( $values['name'], $user->display_name, "{$context}: the name should be stored as given." ); + foreach ( array( 'first_name', 'last_name', 'nickname', 'description' ) as $key ) { + $this->assertSame( $values[ $key ], get_user_meta( $user_id, $key, true ), "{$context}: the {$key} should be stored as given." ); + } + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserCreateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserCreateAbility.php new file mode 100644 index 0000000000000..94075a5c86c44 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserCreateAbility.php @@ -0,0 +1,1176 @@ + $data Optional. More attributes. Default empty array. + * @return array The input. + */ + private function create_input( string $username, array $data = array() ): array { + return array( + 'data' => array_merge( + array( + 'username' => $username, + 'email' => "{$username}@example.test", + ), + $data + ), + ); + } + + /** + * Asserts that no user with the given username exists. + * + * @since 7.3.0 + * + * @param string $username The username. + * @param string $context What the call was, for the assertion messages. + */ + private function assert_no_user( string $username, string $context ): void { + $this->assertFalse( get_user_by( 'login', $username ), "{$context}: no user should be created." ); + } + + /** + * The ability is registered in the user category with its label and annotations. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_registers_the_ability(): void { + $this->assert_registration( 'Create User', false, false ); + } + + /** + * The input schema takes the attributes in `data`, with the username and the email + * required, and the fields of core/users-query. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_input_schema(): void { + $this->register_abilities(); + + $this->assertTrue( wp_has_ability( self::ABILITY ), 'The create ability should be registered.' ); + + $expected = array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'data' ), + 'properties' => array( + 'data' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'username', 'email' ), + 'properties' => array_merge( + array( + 'username' => array( + 'type' => 'string', + 'minLength' => 1, + ), + ), + $this->get_profile_property_schemas() + ), + ), + 'fields' => wp_get_ability( 'core/users-query' )->get_input_schema()['properties']['fields'], + ), + ); + + $this->assertSame( $this->normalize_schema( $expected ), $this->normalize_schema( wp_get_ability( self::ABILITY )->get_input_schema() ) ); + } + + /** + * The output schema is the core/users-query user item. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_output_schema(): void { + $this->assert_output_schema_is_the_query_item(); + } + + /** + * A user is created with the given attributes and roles, and the output holds + * exactly the requested fields. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_creates_a_user_with_chosen_fields(): void { + $this->login_as( 'manager' ); + $this->register_abilities(); + + $fields = array( 'name', 'slug', 'username', 'email', 'registered', 'roles' ); + $result = $this->run_ability( + array( + 'data' => array( + 'username' => 'uwtmcarter', + 'email' => 'm.carter@example.test', + 'name' => 'Maya Carter', + 'first_name' => 'Maya', + 'last_name' => 'Carter', + 'roles' => array( 'editor' ), + ), + 'fields' => $fields, + ) + ); + + $user_id = $this->assert_user_item( $result, $fields, 'Creating an editor' ); + $user = get_userdata( $user_id ); + + $this->assertSameSets( array_merge( array( 'id' ), $fields ), array_keys( $result ), 'The output should hold exactly the requested fields and the ID.' ); + $this->assertSame( 'uwtmcarter', $user->user_login, 'The username should be stored.' ); + $this->assertSame( 'm.carter@example.test', $user->user_email, 'The email should be stored.' ); + $this->assertSame( 'Maya Carter', $user->display_name, 'The name should be stored.' ); + $this->assertSame( 'Maya', $user->first_name, 'The first name should be stored.' ); + $this->assertSame( 'Carter', $user->last_name, 'The last name should be stored.' ); + $this->assertSame( array( 'editor' ), $result['roles'], 'The output should show the editor role.' ); + $this->assertSame( array( 'editor' ), array_values( $user->roles ), 'The user should be an editor only.' ); + } + + /** + * The minimum input gives the default fields, takes the name, nickname and slug from + * the username, gives the default role, sends the two mails without the password, + * and sets a generated password. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_creates_a_user_from_the_minimum_input(): void { + update_option( 'default_role', 'author' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->create_input( 'uwtjdoe' ) ); + $user_id = $this->assert_user_item( $result, array(), 'Creating a user from the minimum input' ); + $user = get_userdata( $user_id ); + + $this->assertSameSets( self::DEFAULT_FIELDS, array_keys( $result ), 'The output should hold the default fields.' ); + $this->assertSame( 'uwtjdoe', $user->display_name, 'The name should be the username.' ); + $this->assertSame( 'uwtjdoe', $user->nickname, 'The nickname should be the username.' ); + $this->assertSame( 'uwtjdoe', $user->user_nicename, 'The slug should be the username.' ); + + if ( is_multisite() ) { + $this->assertTrue( is_user_member_of_blog( $user_id ), 'The user should be a member of the current site.' ); + $this->assertSame( array(), array_values( $user->roles ), 'The user should have no role on multisite.' ); + } else { + $this->assertSame( array( 'author' ), array_values( $user->roles ), 'The user should have the default role.' ); + } + + $this->assertNotEmpty( $this->generated_passwords, 'A password of 24 characters should be generated.' ); + $this->assertTrue( wp_check_password( end( $this->generated_passwords ), $user->user_pass, $user_id ), 'The generated password should be the stored one.' ); + $this->assert_password_not_leaked( $result, 'Creating a user from the minimum input' ); + + $site = $this->get_mail_site_name(); + $mails = $this->get_mails(); + $this->assertSameSets( array( "[{$site}] New User Registration", "[{$site}] Login Details" ), wp_list_pluck( $mails, 'subject' ), 'Exactly the notice and the login details should be sent.' ); + + foreach ( $mails as $mail ) { + if ( "[{$site}] New User Registration" === $mail['subject'] ) { + $this->assertSame( array( strtolower( get_option( 'admin_email' ) ) ), $mail['to'], 'The notice should go to the site admin email.' ); + $this->assertStringContainsString( 'uwtjdoe', $mail['body'], 'The notice should hold the username.' ); + $this->assertStringContainsString( 'uwtjdoe@example.test', $mail['body'], 'The notice should hold the email.' ); + } else { + $this->assertSame( array( 'uwtjdoe@example.test' ), $mail['to'], 'The login details should go to the new user.' ); + $this->assertStringContainsString( 'uwtjdoe', $mail['body'], 'The login details should hold the username.' ); + $this->assertStringContainsString( 'action=rp', $mail['body'], 'The login details should link to setting a password.' ); + } + } + } + + /** + * On multisite the network admin also gets Core's notice when it is on. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + */ + public function test_sends_the_network_notice_when_it_is_on(): void { + update_site_option( 'registrationnotification', 'yes' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->create_input( 'uwtnotice' ) ); + + $this->assertIsArray( $result, 'The user should be created.' ); + + $site = $this->get_mail_site_name(); + $subjects = wp_list_pluck( $this->get_mails(), 'subject' ); + $this->assertSameSets( array( "[{$site}] New User Registration", "[{$site}] Login Details", 'New User Registration: uwtnotice' ), $subjects, 'The network notice should be sent as well.' ); + $this->assert_password_not_leaked( $result, 'Creating a user with the network notice on' ); + } + + /** + * The user ends with exactly the given roles, in the given order, also when they are + * sent as a comma-separated string. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_role_lists + * + * @param list|string $sent The roles as sent. + * @param list $roles The roles the user should hold. + */ + public function test_gives_the_roles_in_order( $sent, array $roles ): void { + $this->login_as( 'manager' ); + $this->register_abilities(); + + $result = $this->run_ability( + array( + 'data' => array( + 'username' => 'uwtroles', + 'email' => 'uwtroles@example.test', + 'roles' => $sent, + ), + 'fields' => array( 'roles' ), + ) + ); + + $this->assertIsArray( $result, 'The user should be created.' ); + $this->assertSame( $roles, $result['roles'], 'The output should show the roles in order.' ); + $this->assertSame( $roles, array_values( get_userdata( $result['id'] )->roles ), 'The user should hold exactly the roles, in order.' ); + } + + /** + * Returns lists of roles. + * + * @return array|string, roles: list}> The roles as + * sent and as held. + */ + public static function data_role_lists(): array { + return array( + 'one role' => array( array( 'editor' ), array( 'editor' ) ), + 'two roles' => array( array( 'author', 'editor' ), array( 'author', 'editor' ) ), + 'three roles' => array( array( 'subscriber', 'contributor', 'author' ), array( 'subscriber', 'contributor', 'author' ) ), + 'comma-separated roles' => array( 'subscriber,contributor,author', array( 'subscriber', 'contributor', 'author' ) ), + ); + } + + /** + * A caller without `create_users` is refused by the permission check, and gets the + * schema error for invalid input. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_callers_without_create_users + * + * @param string $caller The caller, as a fixture name, or empty when logged out. + */ + public function test_refuses_callers_without_create_users( string $caller ): void { + $this->login_as( $caller ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_refused( $this->run_ability( $this->create_input( 'uwtrefused' ) ), 'Creating without create_users' ); + $this->assert_unchanged( $before, 'Creating without create_users' ); + + $this->assert_invalid_input( $this->run_ability( array( 'data' => array( 'username' => 'uwtrefused' ) ) ), 'Creating without create_users and without an email' ); + } + + /** + * Returns callers without `create_users`. + * + * @return array The callers. + */ + public static function data_callers_without_create_users(): array { + return array( + 'editor' => array( 'editor' ), + 'author' => array( 'author' ), + 'contributor' => array( 'contributor' ), + 'subscriber' => array( 'subscriber' ), + 'promoter' => array( 'promoter' ), + 'logged out' => array( '' ), + ); + } + + /** + * On multisite a site administrator cannot create users while the network does not + * let site administrators add users. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + */ + public function test_refuses_a_site_administrator_while_the_network_does_not_let_them_add_users(): void { + update_site_option( 'add_new_users', 0 ); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_refused( $this->run_ability( $this->create_input( 'uwtsiteadmin' ) ), 'A site administrator creating a user' ); + $this->assert_unchanged( $before, 'A site administrator creating a user' ); + } + + /** + * The callback checks `create_users` again, whatever the input holds. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_callers_and_inputs_behind_the_gate + * + * @param string $caller The caller, as a fixture name, or empty when logged out. + * @param array $data The `data`. + */ + public function test_checks_create_users_again( string $caller, array $data ): void { + $callbacks = $this->get_ability_callbacks(); + $this->login_as( $caller ); + + $before = $this->snapshot(); + + $this->assert_core_error( $callbacks['execute_callback']( array( 'data' => $data ) ), 'user_cannot_create', 'Creating behind the gate' ); + $this->assert_unchanged( $before, 'Creating behind the gate' ); + } + + /** + * Returns callers without `create_users` and inputs. + * + * @return array}> The callers and `data`. + */ + public static function data_callers_and_inputs_behind_the_gate(): array { + $valid = array( + 'username' => 'uwtbehind', + 'email' => 'uwtbehind@example.test', + ); + $invalid = array( + 'username' => 'uwt_editor', + 'email' => 'not-an-email', + 'roles' => array( 'administrator' ), + ); + + return array( + 'subscriber, valid input' => array( 'subscriber', $valid ), + 'subscriber, invalid input' => array( 'subscriber', $invalid ), + 'logged out, valid input' => array( '', $valid ), + 'logged out, invalid input' => array( '', $invalid ), + ); + } + + /** + * A role that was removed after the ability was registered is refused. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_refuses_a_role_removed_after_registration(): void { + add_role( 'uwt_gone', 'Gone', array( 'read' => true ) ); + $this->login_as( 'manager' ); + $this->register_abilities(); + remove_role( 'uwt_gone' ); + + $before = $this->snapshot(); + + $this->assert_value_error( + $this->run_ability( $this->create_input( 'uwtgone', array( 'roles' => array( 'uwt_gone' ) ) ) ), + 'user_invalid_attribute', + 'data[roles]', + 'Creating with a removed role', + 'The role uwt_gone does not exist.' + ); + $this->assert_unchanged( $before, 'Creating with a removed role' ); + } + + /** + * A role that is not editable is refused, also next to an editable one. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_roles_with_one_not_editable + * + * @param list $roles The roles; `editor` is not editable. + * @param bool $keyed Whether the filter keeps the key of `editor` with an + * empty entry instead of removing it. + */ + public function test_refuses_a_role_that_is_not_editable( array $roles, bool $keyed ): void { + add_filter( + 'editable_roles', + static function ( $roles ) use ( $keyed ) { + if ( $keyed ) { + $roles['editor'] = false; + } else { + unset( $roles['editor'] ); + } + return $roles; + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( $this->run_ability( $this->create_input( 'uwtnoteditable', array( 'roles' => $roles ) ) ), 'user_cannot_assign_role', 'Creating with a role that is not editable' ); + $this->assert_unchanged( $before, 'Creating with a role that is not editable' ); + } + + /** + * Returns role lists that hold `editor`. + * + * @return array, keyed: bool}> The roles, and whether + * the entry is kept empty. + */ + public static function data_roles_with_one_not_editable(): array { + return array( + 'only the role' => array( array( 'editor' ), false ), + 'after another' => array( array( 'author', 'editor' ), false ), + 'before another' => array( array( 'editor', 'author' ), false ), + 'entry set to false' => array( array( 'editor' ), true ), + 'entry false, after another' => array( array( 'author', 'editor' ), true ), + ); + } + + /** + * Attributes that cannot be applied are refused before the save or the signup + * validation runs. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_attributes_refused_on_create + * + * @param array $data The attributes. + * @param string $code The error code. + * @param string $param The input path. + * @param string|null $message The message, or null when it is not fixed. + * @param bool $accept Optional. Whether a filter accepts every username. Default false. + */ + public function test_refuses_attributes( array $data, string $code, string $param, ?string $message, bool $accept = false ): void { + add_filter( + 'illegal_user_logins', + static function () { + return array( 'uwtnope' ); + } + ); + if ( $accept ) { + add_filter( 'validate_username', '__return_true' ); + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + if ( self::LONG_NAME_MESSAGE === $message ) { + $message = $this->get_long_name_message( $this->create_input( 'uwtrefused', array( 'name' => str_repeat( 'a', 251 ) ) ) ); + } + + $before = $this->snapshot(); + + $this->watch_filter( 'pre_user_login' ); + $this->watch_filter( 'wpmu_validate_user_signup' ); + + $this->assert_value_error( $this->run_ability( $this->create_input( 'uwtrefused', $data ) ), $code, $param, 'Creating with a refused attribute', $message ); + $this->assert_unchanged( $before, 'Creating with a refused attribute' ); + $this->assert_filter_not_run( 'pre_user_login', 'Creating with a refused attribute' ); + $this->assert_filter_not_run( 'wpmu_validate_user_signup', 'Creating with a refused attribute' ); + } + + /** + * Returns attributes refused on create. + * + * @return array, 1: string, 2: string, 3: string|null, 4?: bool}> + * The attributes, the error code, the input path, the message, and whether a + * filter accepts every username. + */ + public static function data_attributes_refused_on_create(): array { + return array_merge( + array( + 'username changed by sanitizing' => array( array( 'username' => 'uwt new!' ), 'user_invalid_attribute', 'data[username]', null ), + 'username changed by sanitizing, accepted by a filter' => array( array( 'username' => 'uwtnew!' ), 'user_invalid_attribute', 'data[username]', null, true ), + 'illegal username' => array( array( 'username' => 'uwtnope' ), 'user_invalid_attribute', 'data[username]', null ), + 'illegal username in another case' => array( array( 'username' => 'UWTNOPE' ), 'user_invalid_attribute', 'data[username]', null ), + 'username of 61 characters' => array( array( 'username' => str_repeat( 'a', 61 ) ), 'user_invalid_attribute', 'data[username]', null ), + 'username of another user' => array( array( 'username' => 'uwt_editor' ), 'user_exists', 'data[username]', 'Sorry, that username already exists!' ), + ), + self::data_profile_attributes_refused() + ); + } + + /** + * An email of 101 characters and a name of 251 characters are refused by the schema, + * and with the error about the value when validation is skipped, before the save or + * the signup validation runs. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_values_over_the_length_limits + * + * @param array $data The attribute. + * @param bool $skip_validation Whether to skip schema validation. + * @param string $param The input path. + */ + public function test_refuses_values_over_the_length_limits( array $data, bool $skip_validation, string $param ): void { + if ( $skip_validation ) { + $this->skip_input_validation(); + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->watch_filter( 'pre_user_login' ); + $this->watch_filter( 'wpmu_validate_user_signup' ); + + $this->assert_over_the_length_limit( $this->run_ability( $this->create_input( 'uwtlong', $data ) ), $skip_validation, $param, 'Creating with a value over the length limit' ); + $this->assert_unchanged( $before, 'Creating with a value over the length limit' ); + $this->assert_filter_not_run( 'pre_user_login', 'Creating with a value over the length limit' ); + $this->assert_filter_not_run( 'wpmu_validate_user_signup', 'Creating with a value over the length limit' ); + } + + /** + * The role checks run before the attribute checks, and the attribute checks run in + * order; the first failure is the error. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_inputs_with_two_failures + * + * @param array $data The attributes. + * @param string $code The error code. + * @param string|null $param The input path, or null for an error without one. + * @param string|null $message The message, or null when it is not fixed. + */ + public function test_reports_the_first_failing_check( array $data, string $code, ?string $param, ?string $message ): void { + add_filter( + 'editable_roles', + static function ( $roles ) { + unset( $roles['editor'] ); + return $roles; + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + $result = $this->run_ability( $this->create_input( 'uwtorder', $data ) ); + + if ( null === $param ) { + $this->assert_core_error( $result, $code, 'Creating with two failures' ); + } else { + $this->assert_value_error( $result, $code, $param, 'Creating with two failures', $message ); + } + $this->assert_unchanged( $before, 'Creating with two failures' ); + } + + /** + * Returns attributes with two failures, and the first one. + * + * @return array, code: string, param: string|null, message: string|null}> + * The attributes, the error code, the input path and the message. + */ + public static function data_inputs_with_two_failures(): array { + return array( + 'role before username' => array( + array( + 'username' => 'uwt_editor', + 'roles' => array( 'editor' ), + ), + 'user_cannot_assign_role', + null, + null, + ), + 'username before email' => array( + array( + 'username' => 'uwt_editor', + 'email' => 'uwt-author@example.test', + ), + 'user_exists', + 'data[username]', + 'Sorry, that username already exists!', + ), + 'email before name' => array( + array( + 'email' => 'uwt-author@example.test', + 'name' => str_repeat( 'a', 249 ) . '&', + ), + 'user_exists', + 'data[email]', + 'Sorry, that email address is already used!', + ), + 'name before nickname' => array( + array( + 'name' => str_repeat( 'a', 249 ) . '&', + 'nickname' => '', + ), + 'user_invalid_attribute', + 'data[name]', + null, + ), + 'nickname before slug' => array( + array( + 'nickname' => '', + 'slug' => '!!!', + ), + 'user_invalid_attribute', + 'data[nickname]', + null, + ), + 'slug before url' => array( + array( + 'slug' => '!!!', + 'url' => 'javascript:alert(1)', + ), + 'user_invalid_attribute', + 'data[slug]', + 'Invalid slug.', + ), + ); + } + + /** + * Values at the length limits are accepted and stored. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_accepts_values_at_the_length_limits(): void { + $data = array( + 'username' => str_repeat( 'a', 60 ), + 'email' => str_repeat( 'b', 87 ) . '@example.test', + 'name' => str_repeat( 'c', 250 ), + 'slug' => str_repeat( 'd', 50 ), + 'url' => 'https://example.test/' . str_repeat( 'e', 79 ), + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $result = $this->run_ability( array( 'data' => $data ) ); + + $this->assertIsArray( $result, 'Values at the limits should be accepted.' ); + + $user = get_userdata( $result['id'] ); + $this->assertSame( $data['username'], $user->user_login, 'The username of 60 characters should be stored.' ); + $this->assertSame( $data['email'], $user->user_email, 'The email of 100 characters should be stored.' ); + $this->assertSame( $data['name'], $user->display_name, 'The name of 250 characters should be stored.' ); + $this->assertSame( $data['slug'], $user->user_nicename, 'The slug of 50 characters should be stored.' ); + $this->assertSame( $data['url'], $user->user_url, 'The URL of 100 characters should be stored.' ); + } + + /** + * Quotes and backslashes in text values are stored as given. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_stores_quotes_and_backslashes(): void { + $this->login_as( 'manager' ); + $this->register_abilities(); + + $fields = array( 'name', 'description', 'first_name', 'last_name', 'nickname' ); + $result = $this->run_ability( + array_merge( + $this->create_input( 'uwtquotes', $this->get_quoted_values() ), + array( 'fields' => $fields ) + ) + ); + + $user_id = $this->assert_user_item( $result, $fields, 'Creating with quotes and backslashes' ); + $this->assert_quoted_values_stored( $user_id, 'Creating with quotes and backslashes' ); + } + + /** + * On multisite a site administrator who may add users reads back the public fields + * of the new user only. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + */ + public function test_site_administrator_reads_back_public_fields(): void { + update_site_option( 'add_new_users', 1 ); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $result = $this->run_ability( + array_merge( + $this->create_input( 'uwtsiteadded' ), + array( 'fields' => array( 'name', 'slug', 'username', 'email', 'roles', 'registered' ) ) + ) + ); + + $this->assertIsArray( $result, 'The site administrator should create the user.' ); + $this->assertSameSets( array( 'id', 'name', 'slug' ), array_keys( $result ), 'Only the public fields should be returned.' ); + $this->assertInstanceOf( WP_User::class, get_user_by( 'login', 'uwtsiteadded' ), 'The user should be created.' ); + } + + /** + * A caller who may create users but neither edit nor list them reads back the ID only. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_caller_without_list_users_reads_back_the_id_only(): void { + if ( is_multisite() ) { + update_site_option( 'add_new_users', 1 ); + } + + $this->login_as( 'creator' ); + $this->register_abilities(); + + $result = $this->run_ability( + array_merge( + $this->create_input( 'uwtcreated' ), + array( 'fields' => array( 'name', 'username', 'email' ) ) + ) + ); + + $user = get_user_by( 'login', 'uwtcreated' ); + + $this->assertInstanceOf( WP_User::class, $user, 'The user should be created.' ); + $this->assertSame( array( 'id' => $user->ID ), $result, 'The output should hold the ID only.' ); + } + + /** + * On multisite the new user becomes a member of the current site only. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + */ + public function test_adds_the_user_to_the_current_site_only(): void { + $this->login_as( 'manager' ); + $this->register_abilities(); + + $main_id = $this->run_ability( $this->create_input( 'uwtmainsite' ) )['id'] ?? 0; + + switch_to_blog( self::$site_id ); + $sub_id = $this->run_ability( $this->create_input( 'uwtsubsite' ) )['id'] ?? 0; + restore_current_blog(); + + $this->assertTrue( is_user_member_of_blog( $main_id, get_current_blog_id() ), 'A user created on the main site should be a member of it.' ); + $this->assertFalse( is_user_member_of_blog( $main_id, self::$site_id ), 'A user created on the main site should not be a member of the other site.' ); + $this->assertTrue( is_user_member_of_blog( $sub_id, self::$site_id ), 'A user created on the other site should be a member of it.' ); + $this->assertFalse( is_user_member_of_blog( $sub_id, get_current_blog_id() ), 'A user created on the other site should not be a member of the main site.' ); + } + + /** + * On multisite what Core's signup validation refuses is refused with its message, + * before the save runs. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + * + * @dataProvider data_signups_refused + * + * @param string $username The username. + * @param string $email The email. + * @param string $core_code The code of Core's error to take the message from. + * @param string $param The input path. + */ + public function test_refuses_what_core_signup_validation_refuses( string $username, string $email, string $core_code, string $param ): void { + update_site_option( 'banned_email_domains', array( 'banned.test' ) ); + add_filter( + 'wpmu_validate_user_signup', + static function ( $result ) { + if ( 'uwtfiltered' === $result['user_name'] ) { + $result['errors']->add( 'uwt_refused', 'Refused by a filter.' ); + } + return $result; + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $expected = wpmu_validate_user_signup( $username, $email )['errors']->get_error_message( $core_code ); + $this->assertNotSame( '', $expected, 'Core should refuse the signup.' ); + + $before = $this->snapshot(); + + $this->watch_filter( 'pre_user_login' ); + + $this->assert_value_error( + $this->run_ability( + array( + 'data' => array( + 'username' => $username, + 'email' => $email, + ), + ) + ), + 'user_invalid_attribute', + $param, + 'Creating what signup validation refuses', + $expected + ); + $this->assert_unchanged( $before, 'Creating what signup validation refuses' ); + $this->assert_filter_not_run( 'pre_user_login', 'Creating what signup validation refuses' ); + } + + /** + * Returns signups that Core refuses. + * + * @return array + * The username, the email, Core's code and the input path. + */ + public static function data_signups_refused(): array { + return array( + 'username with a dash' => array( 'uwt-dash1', 'uwt-dash1@example.test', 'user_name', 'data[username]' ), + 'banned email domain' => array( 'uwtbanned', 'uwtbanned@banned.test', 'user_email', 'data[email]' ), + 'username before email' => array( 'uwt-dash2', 'uwt-dash2@banned.test', 'user_name', 'data[username]' ), + 'error added by a filter' => array( 'uwtfiltered', 'uwtfiltered@example.test', 'uwt_refused', 'data' ), + ); + } + + /** + * On multisite, when adding the new user to the site fails, the user is deleted again + * and the error is returned. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + * + * @dataProvider data_refusals_of_adding_to_the_site + * + * @param WP_Error|false $refusal The value of the filter. + * @param string $code The error code. + * @param string $message The message. + * @param int $status The error status. + */ + public function test_deletes_the_user_when_adding_to_the_site_fails( $refusal, string $code, string $message, int $status ): void { + update_site_option( 'registrationnotification', 'yes' ); + add_filter( + 'can_add_user_to_blog', + static function () use ( $refusal ) { + return $refusal; + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + $result = $this->run_ability( $this->create_input( 'uwtnotadded' ) ); + + $this->assert_error( $result, $code, $status, 'Creating while adding to the site fails' ); + $this->assertSame( $message, $result->get_error_message(), 'The message of the first error should be kept.' ); + $this->assert_no_user( 'uwtnotadded', 'Creating while adding to the site fails' ); + + $after = $this->snapshot(); + $this->assertSame( array_diff_key( $before, array( 'mail' => true ) ), array_diff_key( $after, array( 'mail' => true ) ), 'Nothing else should change.' ); + $this->assertSame( array(), array_diff( $after['mail'], array( 'New User Registration: uwtnotadded' ) ), 'No mail but the network notice should be sent.' ); + } + + /** + * Returns values of the `can_add_user_to_blog` filter that refuse. + * + * @return array + * The value, the error code, the message and the status. + */ + public static function data_refusals_of_adding_to_the_site(): array { + return array( + 'error' => array( new WP_Error( 'uwt_not_added', 'Not added by a filter.' ), 'uwt_not_added', 'Not added by a filter.', 500 ), + 'error with status' => array( new WP_Error( 'uwt_forbidden', 'Forbidden by a filter.', array( 'status' => 403 ) ), 'uwt_forbidden', 'Forbidden by a filter.', 403 ), + 'false' => array( false, 'user_cannot_be_added', 'User cannot be added to this site.', 500 ), + ); + } + + /** + * A save that fails refuses the call, and nothing is created or mailed. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_failing_saves + * + * @param string $hook The filter. + * @param callable $callback The filter callback. + * @param string $single_site_code The error code on single site. + * @param int $single_site_status The error status on single site. + */ + public function test_refuses_a_failing_save( string $hook, callable $callback, string $single_site_code, int $single_site_status ): void { + add_filter( $hook, $callback ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + $result = $this->run_ability( $this->create_input( 'uwtfailing', array( 'roles' => array( 'editor' ) ) ) ); + + if ( is_multisite() ) { + $this->assert_core_error( $result, 'user_create_failed', 'Creating with a failing save' ); + } elseif ( 'user_invalid_attribute' === $single_site_code ) { + $this->assert_value_error( $result, $single_site_code, 'data[username]', 'Creating with a failing save' ); + } else { + $this->assert_error( $result, $single_site_code, $single_site_status, 'Creating with a failing save' ); + } + + $this->assert_unchanged( $before, 'Creating with a failing save' ); + } + + /** + * Returns filters that make the save fail. + * + * @return array + * The filter, its callback and the error on single site. + */ + public static function data_failing_saves(): array { + return array( + 'empty username' => array( 'pre_user_login', '__return_empty_string', 'user_invalid_attribute', 400 ), + 'empty data' => array( 'wp_pre_insert_user_data', '__return_empty_array', 'empty_data', 500 ), + ); + } + + /** + * A mail that cannot be sent does not change the result. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_succeeds_when_a_mail_cannot_be_sent(): void { + add_filter( 'pre_wp_mail', '__return_false' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->create_input( 'uwtnomail' ) ); + + $this->assertIsArray( $result, 'The create should succeed.' ); + $this->assertInstanceOf( WP_User::class, get_user_by( 'login', 'uwtnomail' ), 'The user should be created.' ); + } + + /** + * Input that the schema refuses gets the schema error, and nothing changes. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_inputs_the_schema_refuses + * + * @param array $input The input. + */ + public function test_refuses_input_the_schema_refuses( array $input ): void { + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_invalid_input( $this->run_ability( $input ), 'Creating with input the schema refuses' ); + $this->assert_unchanged( $before, 'Creating with input the schema refuses' ); + } + + /** + * Returns inputs the schema refuses. + * + * @return array}> The inputs. + */ + public static function data_inputs_the_schema_refuses(): array { + $valid = array( + 'username' => 'uwtschema', + 'email' => 'uwtschema@example.test', + ); + + $rows = array( + 'no data' => array( array() ), + 'data not an object' => array( array( 'data' => 'uwtschema' ) ), + 'no username' => array( array( 'data' => array( 'email' => 'uwtschema@example.test' ) ) ), + 'no email' => array( array( 'data' => array( 'username' => 'uwtschema' ) ) ), + 'empty username' => array( array( 'data' => array_merge( $valid, array( 'username' => '' ) ) ) ), + 'empty name' => array( array( 'data' => array_merge( $valid, array( 'name' => '' ) ) ) ), + 'empty nickname' => array( array( 'data' => array_merge( $valid, array( 'nickname' => '' ) ) ) ), + 'empty slug' => array( array( 'data' => array_merge( $valid, array( 'slug' => '' ) ) ) ), + 'invalid email' => array( array( 'data' => array_merge( $valid, array( 'email' => 'not-an-email' ) ) ) ), + 'name not a string' => array( array( 'data' => array_merge( $valid, array( 'name' => 5 ) ) ) ), + 'locale not installed' => array( array( 'data' => array_merge( $valid, array( 'locale' => 'klingon' ) ) ) ), + 'empty roles' => array( array( 'data' => array_merge( $valid, array( 'roles' => array() ) ) ) ), + 'unregistered role' => array( array( 'data' => array_merge( $valid, array( 'roles' => array( 'ilovesteak' ) ) ) ) ), + 'repeated role' => array( array( 'data' => array_merge( $valid, array( 'roles' => array( 'editor', 'editor' ) ) ) ) ), + 'empty roles string' => array( array( 'data' => array_merge( $valid, array( 'roles' => '' ) ) ) ), + 'unknown field' => array( + array( + 'data' => $valid, + 'fields' => array( 'password' ), + ), + ), + 'unknown key' => array( + array( + 'data' => $valid, + 'id' => 156, + ), + ), + ); + + foreach ( self::data_keys_outside_the_allow_list() as $name => $row ) { + $rows[ "data with {$name}" ] = array( array( 'data' => array_merge( $valid, array( $row[0] => $row[1] ) ) ) ); + } + + return $rows; + } + + /** + * With schema validation skipped, the callback refuses what the schema would. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_inputs_checked_when_validation_is_skipped + * + * @param array $data The `data`. + * @param string $param The input path. + * @param string|null $message The message, or null when it is not fixed. + */ + public function test_checks_input_when_validation_is_skipped( array $data, string $param, ?string $message ): void { + $this->skip_input_validation(); + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_value_error( $this->run_ability( array( 'data' => $data ) ), 'user_invalid_attribute', $param, 'Creating without validation', $message ); + $this->assert_unchanged( $before, 'Creating without validation' ); + } + + /** + * Returns `data` that only the callback can refuse once validation is skipped. + * + * @return array, param: string, message: string|null}> + * The `data`, the input path and the message. + */ + public static function data_inputs_checked_when_validation_is_skipped(): array { + $valid = array( + 'username' => 'uwtskipped', + 'email' => 'uwtskipped@example.test', + ); + + return array( + 'no username' => array( array( 'email' => 'uwtskipped@example.test' ), 'data[username]', null ), + 'no email' => array( array( 'username' => 'uwtskipped' ), 'data[email]', null ), + 'empty roles' => array( array_merge( $valid, array( 'roles' => array() ) ), 'data[roles]', null ), + 'unregistered role' => array( array_merge( $valid, array( 'roles' => array( 'uwt_unregistered' ) ) ), 'data[roles]', 'The role uwt_unregistered does not exist.' ), + 'invalid email' => array( array_merge( $valid, array( 'email' => 'not-an-email' ) ), 'data[email]', null ), + 'locale not installed' => array( array_merge( $valid, array( 'locale' => 'klingon' ) ), 'data[locale]', null ), + ); + } + + /** + * Keys outside the attributes never reach the save, when validation is skipped and + * when the callback is called directly. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_ways_past_the_schema + * + * @param bool $direct Whether to call the callback directly. + */ + public function test_ignores_keys_outside_the_allow_list( bool $direct ): void { + $callbacks = $this->get_ability_callbacks(); + $this->login_as( 'manager' ); + + $fields = array( + 'user_login' => 'uwtsentlogin', + 'user_nicename' => 'uwt-sent-slug', + 'user_registered' => '2001-02-03 04:05:06', + 'display_name' => 'Sent Display Name', + ); + $input = $this->create_input( 'uwtallowlist', array_merge( $this->get_keys_outside_the_allow_list(), $fields ) ); + $start = time(); + if ( $direct ) { + $result = $callbacks['execute_callback']( $input ); + } else { + $this->skip_input_validation(); + $result = $this->run_ability( $input ); + } + + $this->assertIsArray( $result, 'The attributes should be applied.' ); + $this->assert_keys_outside_the_allow_list_ignored( $result['id'], '', 'Creating with keys outside the attributes' ); + + $user = get_userdata( $result['id'] ); + $this->assertSame( 'uwtallowlist', $user->user_login, 'The login should be the username.' ); + $this->assertSame( 'uwtallowlist', $user->user_nicename, 'The slug should be the one derived from the username.' ); + $this->assertSame( 'uwtallowlist', $user->display_name, 'The display name should be the one given without a name.' ); + $this->assertFalse( get_user_by( 'login', 'uwtsentlogin' ), 'No user should have the login sent as a key.' ); + $this->assertGreaterThanOrEqual( $start - 1, strtotime( $user->user_registered . ' UTC' ), 'The registration date should be now, not the one sent.' ); + $this->assertLessThanOrEqual( time() + 1, strtotime( $user->user_registered . ' UTC' ), 'The registration date should not be in the future.' ); + } + + /** + * Returns the ways past the schema. + * + * @return array Whether to call the callback directly. + */ + public static function data_ways_past_the_schema(): array { + return array( + 'validation skipped' => array( false ), + 'direct call' => array( true ), + ); + } + + /** + * Core's user hooks fire as the caller, and the hooks of the other ways of creating + * users do not. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_fires_core_hooks_only(): void { + $fired = array(); + foreach ( array( 'rest_pre_insert_user', 'rest_insert_user', 'rest_after_insert_user', 'rest_prepare_user', 'edit_user_created_user' ) as $hook ) { + add_filter( + $hook, + static function ( $value ) use ( &$fired, $hook ) { + $fired[] = $hook; + return $value; + } + ); + } + + $current_users = array(); + add_action( + 'user_register', + static function () use ( &$current_users ) { + $current_users[] = get_current_user_id(); + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertIsArray( $this->run_ability( $this->create_input( 'uwthooks' ) ), 'The user should be created.' ); + $this->assertSame( array( self::$user_ids['manager'] ), $current_users, 'The user_register action should fire once, as the caller.' ); + $this->assertSame( array(), $fired, 'No hook of the other ways of creating users should fire.' ); + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserDeleteAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserDeleteAbility.php new file mode 100644 index 0000000000000..6945da5922ef6 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserDeleteAbility.php @@ -0,0 +1,967 @@ + The input. + */ + private function delete_input( $user_id, $reassign ): array { + $input = array( 'where' => array( 'id' => $user_id ) ); + if ( null !== $reassign ) { + $input['reassign'] = $reassign; + } + + return $input; + } + + /** + * Creates a user who authored a published post and owns a link. + * + * @since 7.3.0 + * + * @param string $login The username. + * @return array{user: int, post: int, link: int} The IDs of the user, the post and the link. + */ + private function create_target_with_content( string $login ): array { + $user_id = $this->create_target( $login ); + + return array( + 'user' => $user_id, + 'post' => self::factory()->post->create( + array( + 'post_author' => $user_id, + 'post_status' => 'publish', + ) + ), + 'link' => (int) wp_insert_link( + array( + 'link_url' => 'https://example.test/', + 'link_name' => 'UWT link', + 'link_owner' => $user_id, + ) + ), + ); + } + + /** + * Returns the author and status of a post, read from the database. + * + * @since 7.3.0 + * + * @param int $post_id The post ID. + * @return array{author: int, status: string}|null The author and status, or null when the post is gone. + */ + private function get_stored_post( int $post_id ): ?array { + global $wpdb; + + $row = $wpdb->get_row( $wpdb->prepare( "SELECT post_author, post_status FROM {$wpdb->posts} WHERE ID = %d", $post_id ), ARRAY_A ); + + return null === $row ? null : array( + 'author' => (int) $row['post_author'], + 'status' => $row['post_status'], + ); + } + + /** + * Returns the owner of a link, read from the database. + * + * @since 7.3.0 + * + * @param int $link_id The link ID. + * @return int|null The owner, or null when the link is gone. + */ + private function get_stored_link_owner( int $link_id ): ?int { + global $wpdb; + + $owner = $wpdb->get_var( $wpdb->prepare( "SELECT link_owner FROM {$wpdb->links} WHERE link_id = %d", $link_id ) ); + + return null === $owner ? null : (int) $owner; + } + + /** + * Returns whether a user row exists, read from the database. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @return bool Whether the user exists. + */ + private function user_row_exists( int $user_id ): bool { + global $wpdb; + + return '1' === (string) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->users} WHERE ID = %d", $user_id ) ); + } + + /** + * Returns the outcome of a successful call on this kind of install. + * + * @since 7.3.0 + * + * @return array{outcome: string} The output. + */ + private function get_success_output(): array { + return array( 'outcome' => is_multisite() ? 'removed' : 'deleted' ); + } + + /** + * Asserts that a user was deleted, or on multisite removed from the current site only. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @param string $context What the call was, for the assertion messages. + */ + private function assert_user_gone( int $user_id, string $context ): void { + if ( is_multisite() ) { + $this->assertFalse( is_user_member_of_blog( $user_id, get_current_blog_id() ), "{$context}: the user should no longer be a member of the site." ); + $this->assertTrue( $this->user_row_exists( $user_id ), "{$context}: the account should stay." ); + } else { + $this->assertFalse( $this->user_row_exists( $user_id ), "{$context}: the user should be deleted." ); + } + } + + /** + * The ability is registered in the user category with its label and annotations. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_registers_the_ability(): void { + $this->assert_registration( 'Delete User', true, false ); + } + + /** + * The input schema takes `where` with the ID and a required `reassign`. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_input_schema(): void { + $this->register_abilities(); + + $this->assertTrue( wp_has_ability( self::ABILITY ), 'The delete ability should be registered.' ); + + $expected = array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'where', 'reassign' ), + 'properties' => array( + 'where' => $this->get_where_schema(), + 'reassign' => array( + 'type' => array( 'integer', 'boolean' ), + 'minimum' => 1, + ), + ), + ); + + $this->assertSame( $this->normalize_schema( $expected ), $this->normalize_schema( wp_get_ability( self::ABILITY )->get_input_schema() ) ); + } + + /** + * The output schema is an object with the outcome only. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_output_schema(): void { + $this->register_abilities(); + + $this->assertTrue( wp_has_ability( self::ABILITY ), 'The delete ability should be registered.' ); + + $expected = array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'outcome' ), + 'properties' => array( + 'outcome' => array( 'type' => 'string' ), + ), + ); + + $this->assertSame( $this->normalize_schema( $expected ), $this->normalize_schema( wp_get_ability( self::ABILITY )->get_output_schema() ) ); + } + + /** + * The user is deleted, or on multisite removed from the current site, and a second + * call finds no user. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_deletes_the_user_once(): void { + $user_id = $this->create_target( 'uwtgone' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertSame( $this->get_success_output(), $this->run_ability( $this->delete_input( $user_id, false ) ), 'The output should give the outcome.' ); + $this->assert_user_gone( $user_id, 'Deleting a user' ); + $this->assertSame( array(), $this->get_mails(), 'No mail should be sent.' ); + + $this->assert_core_error( $this->run_ability( $this->delete_input( $user_id, false ) ), 'user_not_found', 'Deleting the same user again' ); + } + + /** + * Without reassignment the posts of a deleted user go to the trash and their links + * are deleted; on multisite, where the user is only removed, they keep their author. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_no_reassignment + * + * @param mixed $reassign The reassign value. + */ + public function test_deletes_without_reassigning( $reassign ): void { + $target = $this->create_target_with_content( 'uwtnoreassign' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertSame( $this->get_success_output(), $this->run_ability( $this->delete_input( $target['user'], $reassign ) ), 'The user should be deleted.' ); + $this->assert_user_gone( $target['user'], 'Deleting without reassigning' ); + + if ( is_multisite() ) { + $this->assertSame( + array( + 'author' => $target['user'], + 'status' => 'publish', + ), + $this->get_stored_post( $target['post'] ), + 'The post should keep its author.' + ); + $this->assertSame( $target['user'], $this->get_stored_link_owner( $target['link'] ), 'The link should keep its owner.' ); + } else { + $this->assertSame( 'trash', $this->get_stored_post( $target['post'] )['status'] ?? null, 'The post should go to the trash.' ); + $this->assertNull( $this->get_stored_link_owner( $target['link'] ), 'The link should be deleted.' ); + } + } + + /** + * Returns the values that reassign nothing. + * + * @return array The reassign values. + */ + public static function data_no_reassignment(): array { + return array( + 'false' => array( false ), + 'false as text' => array( 'false' ), + ); + } + + /** + * Without reassignment, on a single site, a page goes to the trash, a post that is + * already in the trash and an attachment are deleted permanently, and a pattern stays + * with its author. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-excluded + * + * @dataProvider data_content_deleted_with_its_author + * + * @param string $post_type The post type. + * @param string $post_status The post status. + * @param string|null $status The status afterwards, or null when the post is + * deleted permanently. + */ + public function test_deletes_content_by_its_kind_without_reassigning( string $post_type, string $post_status, ?string $status ): void { + $user_id = $this->create_target( 'uwtcontent' ); + $post_id = self::factory()->post->create( + array( + 'post_author' => $user_id, + 'post_type' => $post_type, + 'post_status' => $post_status, + ) + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertSame( + array( + 'author' => $user_id, + 'status' => $post_status, + ), + $this->get_stored_post( $post_id ), + 'The content should be stored for the user before the call.' + ); + $this->assertSame( array( 'outcome' => 'deleted' ), $this->run_ability( $this->delete_input( $user_id, false ) ), 'The user should be deleted.' ); + $this->assertFalse( $this->user_row_exists( $user_id ), 'The user row should be gone.' ); + + $stored = $this->get_stored_post( $post_id ); + + if ( null === $status ) { + $this->assertNull( $stored, 'The content should be deleted permanently.' ); + } elseif ( 'trash' === $status ) { + $this->assertSame( 'trash', $stored['status'] ?? null, 'The content should go to the trash.' ); + } else { + $this->assertSame( + array( + 'author' => $user_id, + 'status' => $status, + ), + $stored, + 'The content should stay as it is, with its author.' + ); + } + } + + /** + * Returns kinds of content, and what becomes of each when its author is deleted. + * + * @return array + * The post type, the post status, and the status afterwards. + */ + public static function data_content_deleted_with_its_author(): array { + return array( + 'page' => array( 'page', 'publish', 'trash' ), + 'post in the trash' => array( 'post', 'trash', null ), + 'attachment' => array( 'attachment', 'inherit', null ), + 'pattern' => array( 'wp_block', 'publish', 'publish' ), + ); + } + + /** + * The posts and links of a deleted user go to the user given in `reassign`, given as + * a number or as text; on multisite, the posts of the current site. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_reassign_ids + * + * @param string $heir The user to reassign to, as a fixture name, or `first` for user 1. + * @param bool $as_text Whether to send the ID as text. + */ + public function test_reassigns_posts_and_links( string $heir, bool $as_text ): void { + $heir_id = 'first' === $heir ? 1 : self::$user_ids[ $heir ]; + $target = $this->create_target_with_content( 'uwtreassign' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertSame( $this->get_success_output(), $this->run_ability( $this->delete_input( $target['user'], $as_text ? (string) $heir_id : $heir_id ) ), 'The user should be deleted.' ); + $this->assert_user_gone( $target['user'], 'Deleting with reassignment' ); + $this->assertSame( + array( + 'author' => $heir_id, + 'status' => 'publish', + ), + $this->get_stored_post( $target['post'] ), + 'The post should belong to the user it was reassigned to.' + ); + $this->assertSame( $heir_id, $this->get_stored_link_owner( $target['link'] ), 'The link should belong to the user it was reassigned to.' ); + } + + /** + * Returns the users to reassign to. + * + * @return array The user, and whether to + * send the ID as text. + */ + public static function data_reassign_ids(): array { + return array( + 'editor' => array( 'editor', false ), + 'editor, ID as text' => array( 'editor', true ), + 'user one' => array( 'first', false ), + 'user one, ID as text' => array( 'first', true ), + ); + } + + /** + * Every value that names no usable user to reassign to gives the same error, and + * nothing changes. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_unusable_reassign_values + * + * @param mixed $reassign The reassign value; `missing`, `target` and `outsider` + * stand for an ID of no user, the target and a user of + * another site, and null sends none. + * @param bool $skip_validation Whether to skip schema validation. + */ + public function test_refuses_an_unusable_reassign_value( $reassign, bool $skip_validation ): void { + $target = $this->create_target_with_content( 'uwtbadreassign' ); + + $placeholders = array( + 'missing' => self::MISSING_ID, + 'target' => $target['user'], + 'outsider' => self::$user_ids['outsider'] ?? 0, + ); + if ( is_string( $reassign ) && isset( $placeholders[ $reassign ] ) ) { + $reassign = $placeholders[ $reassign ]; + } + + $input = $this->delete_input( $target['user'], $reassign ); + if ( null === $reassign && $skip_validation ) { + $input['reassign'] = null; + } + if ( $skip_validation ) { + $this->skip_input_validation(); + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + $result = $this->run_ability( $input ); + + $message = self::ERRORS['user_invalid_reassign'][1]; + $this->assert_value_error( $result, 'user_invalid_reassign', 'reassign', 'Deleting with an unusable reassign value', $message ); + $this->assertSame( + array( + 'status' => 400, + 'params' => array( 'reassign' => $message ), + ), + $result->get_error_data(), + 'The error data should be the same for every unusable value.' + ); + $this->assert_unchanged( $before, 'Deleting with an unusable reassign value' ); + } + + /** + * Returns reassign values that name no usable user. + * + * @return array The value, and + * whether to skip validation. + */ + public static function data_unusable_reassign_values(): array { + $rows = array( + 'true' => array( true, false ), + 'true as text' => array( 'true', false ), + 'ID of no user' => array( 'missing', false ), + 'the user being deleted' => array( 'target', false ), + 'null, validation skipped' => array( null, true ), + 'zero, validation skipped' => array( 0, true ), + 'negative, validation skipped' => array( -1, true ), + ); + + if ( is_multisite() ) { + $rows['user of another site'] = array( 'outsider', false ); + } + + return $rows; + } + + /** + * With validation skipped, input without `reassign` gives the reassign error. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_refuses_a_missing_reassign_when_validation_is_skipped(): void { + $user_id = $this->create_target( 'uwtnoreassignkey' ); + + $this->skip_input_validation(); + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_value_error( $this->run_ability( $this->delete_input( $user_id, null ) ), 'user_invalid_reassign', 'reassign', 'Deleting without reassign', self::ERRORS['user_invalid_reassign'][1] ); + $this->assert_unchanged( $before, 'Deleting without reassign' ); + } + + /** + * Input the schema refuses changes nothing. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_inputs_the_schema_refuses + * + * @param array $input The input, where the ID `target` stands for the user to delete. + */ + public function test_refuses_input_the_schema_refuses( array $input ): void { + $user_id = $this->create_target( 'uwtschema' ); + if ( isset( $input['where']['id'] ) && 'target' === $input['where']['id'] ) { + $input['where']['id'] = $user_id; + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_invalid_input( $this->run_ability( $input ), 'Deleting with input the schema refuses' ); + $this->assert_unchanged( $before, 'Deleting with input the schema refuses' ); + } + + /** + * Returns inputs the schema refuses; the ID `target` stands for the user to delete. + * + * @return array}> The inputs. + */ + public static function data_inputs_the_schema_refuses(): array { + $where = array( 'id' => 'target' ); + $rows = array( + 'no where' => array( array( 'reassign' => false ) ), + 'no reassign' => array( array( 'where' => $where ) ), + 'ID of zero' => array( + array( + 'where' => array( 'id' => 0 ), + 'reassign' => false, + ), + ), + 'unknown key' => array( + array( + 'where' => $where, + 'reassign' => false, + 'force' => true, + ), + ), + ); + + $values = array( + 'zero' => 0, + 'zero as text' => '0', + 'empty text' => '', + 'negative' => -1, + 'fraction' => 7.5, + 'text' => 'abc', + 'null' => null, + 'list' => array( 1 ), + ); + foreach ( $values as $label => $value ) { + $rows[ "reassign {$label}" ] = array( + array( + 'where' => $where, + 'reassign' => $value, + ), + ); + } + + return $rows; + } + + /** + * A caller without the capability to delete users is refused, and nothing changes. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_callers_without_the_capability + * + * @param string $caller The caller, as a fixture name, or an empty string to log out. + */ + public function test_refuses_callers_without_the_capability( string $caller ): void { + $user_id = $this->create_target( 'uwtgate' ); + + $this->login_as( $caller ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_refused( $this->run_ability( $this->delete_input( $user_id, false ) ), 'Deleting without the capability' ); + $this->assert_unchanged( $before, 'Deleting without the capability' ); + } + + /** + * Returns callers who may not delete users. + * + * @return array The caller. + */ + public static function data_callers_without_the_capability(): array { + return array( + 'editor' => array( 'editor' ), + 'author' => array( 'author' ), + 'contributor' => array( 'contributor' ), + 'subscriber' => array( 'subscriber' ), + 'promoter' => array( 'promoter' ), + 'logged out' => array( '' ), + ); + } + + /** + * The callback checks the capability again, with a status that tells a logged-out + * caller apart. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_callers_behind_the_gate + * + * @param string $caller The caller, as a fixture name, or an empty string to log out. + */ + public function test_checks_the_capability_again( string $caller ): void { + $user_id = $this->create_target( 'uwtgateagain' ); + $callbacks = $this->get_ability_callbacks(); + $this->login_as( $caller ); + + $before = $this->snapshot(); + + $this->assert_core_error( $callbacks['execute_callback']( $this->delete_input( $user_id, false ) ), 'user_cannot_delete', 'Deleting behind the gate' ); + $this->assert_unchanged( $before, 'Deleting behind the gate' ); + } + + /** + * Returns callers who reach the callback without the capability. + * + * @return array The caller. + */ + public static function data_callers_behind_the_gate(): array { + return array( + 'subscriber' => array( 'subscriber' ), + 'logged out' => array( '' ), + ); + } + + /** + * The callback checks the capability to delete users apart from the capability on + * the target: a caller granted only the capability on the target is refused. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_checks_the_capability_apart_from_the_one_on_the_user(): void { + $target = $this->create_target_with_content( 'uwtgrantedtarget' ); + $user_id = $target['user']; + $callbacks = $this->get_ability_callbacks(); + + add_filter( + 'map_meta_cap', + static function ( array $caps, string $cap, int $caller_id, array $args ) use ( $user_id ): array { + if ( ( is_multisite() ? 'remove_user' : 'delete_user' ) === $cap && (int) ( $args[0] ?? 0 ) === $user_id ) { + return array( 'exist' ); + } + + return $caps; + }, + 10, + 4 + ); + + $this->login_as( 'subscriber' ); + + $this->assertTrue( current_user_can( is_multisite() ? 'remove_user' : 'delete_user', $user_id ), 'The subscriber should hold the capability on the target.' ); + $this->assertFalse( current_user_can( is_multisite() ? 'remove_users' : 'delete_users' ), 'The subscriber should not hold the capability to delete users.' ); + + $before = $this->snapshot(); + + $this->assert_core_error( $callbacks['execute_callback']( $this->delete_input( $user_id, false ) ), 'user_cannot_delete', 'Deleting with the capability on the target only' ); + $this->assert_unchanged( $before, 'Deleting with the capability on the target only' ); + $this->assertTrue( is_multisite() ? is_user_member_of_blog( $user_id, get_current_blog_id() ) : $this->user_row_exists( $user_id ), 'The target should stay.' ); + $this->assertSame( 'publish', $this->get_stored_post( $target['post'] )['status'] ?? null, 'The post should not be trashed.' ); + } + + /** + * An ID that no user has is the not-found error. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_ids_of_no_user + * + * @param mixed $id The ID. + * @param bool $skip_validation Whether to skip schema validation. + */ + public function test_reports_a_missing_user( $id, bool $skip_validation ): void { + if ( $skip_validation ) { + $this->skip_input_validation(); + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( $this->run_ability( $this->delete_input( $id, false ) ), 'user_not_found', 'Deleting a user that does not exist' ); + $this->assert_unchanged( $before, 'Deleting a user that does not exist' ); + } + + /** + * Returns IDs that name no user. + * + * @return array The ID, and whether + * to skip validation. + */ + public static function data_ids_of_no_user(): array { + return array( + 'missing ID' => array( self::MISSING_ID, false ), + 'zero, validation skipped' => array( 0, true ), + 'negative, validation skipped' => array( -1, true ), + ); + } + + /** + * A capability filter that denies deleting the target is respected. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_respects_a_denied_capability_for_the_user(): void { + $user_id = $this->create_target( 'uwtdenied' ); + + add_filter( + 'map_meta_cap', + static function ( array $caps, string $cap, int $caller_id, array $args ) use ( $user_id ): array { + if ( in_array( $cap, array( 'delete_user', 'remove_user' ), true ) && (int) ( $args[0] ?? 0 ) === $user_id ) { + return array( 'do_not_allow' ); + } + + return $caps; + }, + 10, + 4 + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( $this->run_ability( $this->delete_input( $user_id, false ) ), 'user_cannot_delete', 'Deleting a user the capability filter protects' ); + $this->assert_unchanged( $before, 'Deleting a user the capability filter protects' ); + } + + /** + * On a single site the last administrator may delete themself. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-excluded + */ + public function test_last_administrator_deletes_themself(): void { + ( new WP_User( 1 ) )->set_role( 'editor' ); + ( new WP_User( self::$user_ids['administrator'] ) )->set_role( 'editor' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertSame( array( 'outcome' => 'deleted' ), $this->run_ability( $this->delete_input( self::$user_ids['manager'], false ) ), 'The administrator should delete themself.' ); + $this->assertFalse( $this->user_row_exists( self::$user_ids['manager'] ), 'The administrator should be deleted.' ); + } + + /** + * On multisite only a super admin may remove themself from the site. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + * + * @dataProvider data_callers_removing_themselves + * + * @param string $caller The caller, as a fixture name. + * @param bool $allowed Whether the caller may remove themself. + */ + public function test_removing_yourself_on_multisite( string $caller, bool $allowed ): void { + $user_id = self::$user_ids[ $caller ]; + + $this->login_as( $caller ); + $this->register_abilities(); + + $before = $this->snapshot(); + $result = $this->run_ability( $this->delete_input( $user_id, false ) ); + + if ( $allowed ) { + $this->assertSame( array( 'outcome' => 'removed' ), $result, 'The super admin should remove themself.' ); + $this->assert_user_gone( $user_id, 'A super admin removing themself' ); + } else { + $this->assert_core_error( $result, 'user_cannot_delete', 'A site administrator removing themself' ); + $this->assert_unchanged( $before, 'A site administrator removing themself' ); + } + } + + /** + * Returns callers who remove themselves. + * + * @return array The caller, and whether + * they may. + */ + public static function data_callers_removing_themselves(): array { + return array( + 'site administrator' => array( 'administrator', false ), + 'super admin' => array( 'manager', true ), + ); + } + + /** + * On multisite a site administrator removes a super admin from the site only: the + * account, the super admin status and the other memberships stay. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + */ + public function test_site_administrator_removes_a_super_admin(): void { + $user_id = $this->create_target( 'uwtsuper', array( 'role' => 'administrator' ) ); + grant_super_admin( $user_id ); + add_user_to_blog( self::$site_id, $user_id, 'editor' ); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $this->assertSame( array( 'outcome' => 'removed' ), $this->run_ability( $this->delete_input( $user_id, false ) ), 'The super admin should be removed from the site.' ); + $this->assert_user_gone( $user_id, 'Removing a super admin' ); + $this->assertTrue( is_super_admin( $user_id ), 'The user should stay a super admin.' ); + $this->assertTrue( is_user_member_of_blog( $user_id, self::$site_id ), 'The user should stay a member of the other site.' ); + + revoke_super_admin( $user_id ); + } + + /** + * On multisite a user who is not a member of the current site is not found, for + * every caller. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + * + * @dataProvider data_callers_and_users_of_another_site + * + * @param string $caller The caller, as a fixture name. + * @param string $target The target, as a fixture name. + */ + public function test_reports_a_user_of_another_site( string $caller, string $target ): void { + $this->login_as( $caller ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( $this->run_ability( $this->delete_input( self::$user_ids[ $target ], false ) ), 'user_not_found', 'Deleting a user of another site' ); + $this->assert_unchanged( $before, 'Deleting a user of another site' ); + } + + /** + * Returns callers and users who are not members of the current site. + * + * @return array The caller and the target. + */ + public static function data_callers_and_users_of_another_site(): array { + return array( + 'super admin' => array( 'manager', 'outsider' ), + 'super admin removing oneself' => array( 'outside_super_admin', 'outside_super_admin' ), + 'site administrator' => array( 'administrator', 'outsider' ), + ); + } + + /** + * A user that is still stored after the deletion is the delete error. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-excluded + */ + public function test_reports_a_user_row_that_was_not_deleted(): void { + global $wpdb; + + $user_id = $this->create_target( 'uwtstuck' ); + $users = $wpdb->users; + + add_filter( + 'query', + static function ( string $query ) use ( $users, $user_id ): string { + if ( preg_match( '/^DELETE FROM `?' . preg_quote( $users, '/' ) . '`? WHERE `?ID`? = \'?' . $user_id . '\'?$/', trim( $query ) ) ) { + return 'SELECT 1'; + } + + return $query; + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assert_core_error( $this->run_ability( $this->delete_input( $user_id, false ) ), 'user_delete_failed', 'Deleting a user whose row stays' ); + $this->assertTrue( $this->user_row_exists( $user_id ), 'The user should still exist.' ); + } + + /** + * On multisite a user who is still a member after the removal is the delete error. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + */ + public function test_reports_a_membership_that_was_not_removed(): void { + global $wpdb; + + $user_id = $this->create_target( 'uwtstuckmember' ); + $meta_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT umeta_id FROM {$wpdb->usermeta} WHERE user_id = %d AND meta_key = %s", $user_id, $wpdb->get_blog_prefix() . 'capabilities' ) ); + $blocked = "DELETE FROM {$wpdb->usermeta} WHERE umeta_id IN( {$meta_id} )"; + + $this->assertGreaterThan( 0, $meta_id, 'The user should have capabilities on the site.' ); + + add_filter( + 'query', + static function ( string $query ) use ( $blocked ): string { + return trim( $query ) === $blocked ? 'SELECT 1' : $query; + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assert_core_error( $this->run_ability( $this->delete_input( $user_id, false ) ), 'user_delete_failed', 'Removing a user whose membership stays' ); + $this->assertTrue( is_user_member_of_blog( $user_id, get_current_blog_id() ), 'The user should still be a member.' ); + } + + /** + * Core's user hook fires once, as the caller, and the hook of the other ways of + * deleting users does not. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_fires_core_hooks_only(): void { + $user_id = $this->create_target( 'uwthooks' ); + + $other = 0; + add_action( + 'rest_delete_user', + static function () use ( &$other ) { + ++$other; + } + ); + + $current_users = array(); + add_action( + is_multisite() ? 'remove_user_from_blog' : 'delete_user', + static function () use ( &$current_users ) { + $current_users[] = get_current_user_id(); + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertSame( $this->get_success_output(), $this->run_ability( $this->delete_input( $user_id, false ) ), 'The user should be deleted.' ); + $this->assertSame( array( self::$user_ids['manager'] ), $current_users, 'The core action should fire once, as the caller.' ); + $this->assertSame( 0, $other, 'The hook of the other ways of deleting users should not fire.' ); + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserUpdateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserUpdateAbility.php new file mode 100644 index 0000000000000..afc334a33e968 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserUpdateAbility.php @@ -0,0 +1,1301 @@ + $data The attributes. + * @param list|null $fields Optional. The fields, or null to send none. Default null. + * @return array The input. + */ + private function update_input( int $user_id, array $data, ?array $fields = null ): array { + $input = array( + 'where' => array( 'id' => $user_id ), + 'data' => $data, + ); + if ( null !== $fields ) { + $input['fields'] = $fields; + } + + return $input; + } + + /** + * Returns the roles of a user, read from the database. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @return list The roles. + */ + private function get_stored_roles( int $user_id ): array { + return array_values( ( new WP_User( $user_id ) )->roles ); + } + + /** + * The ability is registered in the user category with its label and annotations. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_registers_the_ability(): void { + $this->assert_registration( 'Update User', false, true ); + } + + /** + * The input schema takes `where` with the ID, the attributes in `data` without the + * username, and the fields of core/users-query. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_input_schema(): void { + $this->register_abilities(); + + $this->assertTrue( wp_has_ability( self::ABILITY ), 'The update ability should be registered.' ); + + $expected = array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'where', 'data' ), + 'properties' => array( + 'where' => $this->get_where_schema(), + 'data' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => $this->get_profile_property_schemas(), + ), + 'fields' => wp_get_ability( 'core/users-query' )->get_input_schema()['properties']['fields'], + ), + ); + + $this->assertSame( $this->normalize_schema( $expected ), $this->normalize_schema( wp_get_ability( self::ABILITY )->get_input_schema() ) ); + } + + /** + * The output schema is the core/users-query user item. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_output_schema(): void { + $this->assert_output_schema_is_the_query_item(); + } + + /** + * The roles and the biography are changed, and the output shows the new state. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_updates_roles_and_description(): void { + $user_id = $this->create_target( 'uwtmaya', array( 'role' => 'editor' ) ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $fields = array( 'name', 'description', 'roles' ); + $result = $this->run_ability( + $this->update_input( + $user_id, + array( + 'roles' => array( 'author' ), + 'description' => 'Writes about hardware.', + ), + $fields + ) + ); + + $this->assert_user_item( $result, $fields, 'Changing the roles and the biography' ); + $this->assertSameSets( array( 'id', 'name', 'description', 'roles' ), array_keys( $result ), 'The output should hold exactly the requested fields and the ID.' ); + $this->assertSame( array( 'author' ), $result['roles'], 'The output should show the new role.' ); + $this->assertSame( 'Writes about hardware.', $result['description'], 'The output should show the new biography.' ); + $this->assertSame( array( 'author' ), $this->get_stored_roles( $user_id ), 'The user should be an author only.' ); + } + + /** + * Every attribute is stored, the output shows the stored user, and the username and + * password stay. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_updates_every_attribute(): void { + $user_id = $this->create_target( 'uwtevery' ); + $before = get_userdata( $user_id ); + $hash = $before->user_pass; + + $data = array( + 'email' => 'uwt-every-new@example.test', + 'name' => 'Every Attribute', + 'first_name' => 'Every', + 'last_name' => 'Attribute', + 'nickname' => 'every', + 'slug' => 'every-attribute', + 'description' => 'A plain biography.', + 'url' => 'https://example.test/every', + 'locale' => 'de_DE', + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->update_input( $user_id, $data, self::ALL_FIELDS ) ); + + $this->assert_user_item( $result, self::ALL_FIELDS, 'Changing every attribute' ); + + $user = get_userdata( $user_id ); + $this->assertSame( $data['email'], $user->user_email, 'The email should be stored.' ); + $this->assertSame( $data['name'], $user->display_name, 'The name should be stored.' ); + $this->assertSame( $data['first_name'], $user->first_name, 'The first name should be stored.' ); + $this->assertSame( $data['last_name'], $user->last_name, 'The last name should be stored.' ); + $this->assertSame( $data['nickname'], $user->nickname, 'The nickname should be stored.' ); + $this->assertSame( $data['slug'], $user->user_nicename, 'The slug should be stored.' ); + $this->assertSame( $data['description'], $user->description, 'The biography should be stored.' ); + $this->assertSame( $data['url'], $user->user_url, 'The URL should be stored.' ); + $this->assertSame( 'de_DE', get_user_meta( $user_id, 'locale', true ), 'The locale should be stored.' ); + $this->assertSame( 'uwtevery', $user->user_login, 'The username should stay.' ); + $this->assertSame( $hash, $user->user_pass, 'The password should stay.' ); + $this->assertSame( array( 'author' ), $this->get_stored_roles( $user_id ), 'The roles should stay.' ); + } + + /** + * The previous address is told about a changed email only, also when only the + * letter case changed, and no password mail is sent. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_email_changes + * + * @param array $data The attributes. + * @param bool $mail_expected Whether the previous address gets a mail. + */ + public function test_mails_the_previous_address_when_the_email_changes( array $data, bool $mail_expected ): void { + $user_id = $this->create_target( 'uwtmail' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertIsArray( $this->run_ability( $this->update_input( $user_id, $data ) ), 'The update should succeed.' ); + + if ( isset( $data['email'] ) ) { + $this->assertSame( $data['email'], get_userdata( $user_id )->user_email, 'The email should be stored as sent.' ); + } + + $mails = $this->get_mails(); + $expected = array(); + if ( $mail_expected ) { + $expected[] = array( + 'to' => array( 'uwtmail@example.test' ), + 'subject' => '[' . $this->get_mail_site_name() . '] Email Changed', + ); + } + + $this->assertSame( + $expected, + array_map( + static function ( $mail ) { + return array( + 'to' => $mail['to'], + 'subject' => $mail['subject'], + ); + }, + $mails + ), + 'Only the change of the email should be mailed, to the previous address.' + ); + } + + /** + * Returns updates with and without a change of the email. + * + * @return array, mail_expected: bool}> + * The attributes, and whether a mail is expected. + */ + public static function data_email_changes(): array { + return array( + 'email left out' => array( array( 'name' => 'Mail Target' ), false ), + 'same email' => array( array( 'email' => 'uwtmail@example.test' ), false ), + 'letter case changed' => array( array( 'email' => 'UwtMail@Example.test' ), true ), + 'new email' => array( array( 'email' => 'uwtmail-new@example.test' ), true ), + ); + } + + /** + * The roles are replaced by exactly the given ones, in order, also when they equal + * the current ones, without a profile save. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_role_replacements + * + * @param list $current The current roles. + * @param list $roles The roles sent. + */ + public function test_replaces_the_roles( array $current, array $roles ): void { + $user_id = $this->create_target( 'uwtroles', array( 'role' => array_shift( $current ) ) ); + foreach ( $current as $role ) { + get_userdata( $user_id )->add_role( $role ); + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $profile_updates = did_action( 'profile_update' ); + $result = $this->run_ability( $this->update_input( $user_id, array( 'roles' => $roles ), array( 'roles' ) ) ); + + $this->assertIsArray( $result, 'The roles should be replaced.' ); + $this->assertSame( $roles, $result['roles'], 'The output should show the roles in order.' ); + $this->assertSame( $roles, $this->get_stored_roles( $user_id ), 'The user should hold exactly the roles, in order.' ); + $this->assertSame( $profile_updates, did_action( 'profile_update' ), 'No profile save should run.' ); + $this->assertSame( array(), $this->get_mails(), 'No mail should be sent.' ); + } + + /** + * Returns current roles and new roles. + * + * @return array, roles: list}> The roles. + */ + public static function data_role_replacements(): array { + return array( + 'one role for another' => array( array( 'administrator' ), array( 'editor' ) ), + 'one role for two' => array( array( 'administrator' ), array( 'author', 'editor' ) ), + 'the same role' => array( array( 'author' ), array( 'author' ) ), + 'reversed order' => array( array( 'author', 'editor' ), array( 'editor', 'author' ) ), + ); + } + + /** + * Nobody logged in is refused by the permission check, and by the callback with a + * 401 before the user is looked up, whatever `data` holds. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_updates_while_logged_out + * + * @param bool $existing Whether the target exists. + * @param array $data The attributes. + */ + public function test_refuses_logged_out_callers( bool $existing, array $data ): void { + $user_id = $existing ? self::$user_ids['author'] : self::MISSING_ID; + $callbacks = $this->get_ability_callbacks(); + $this->login_as( '' ); + + $before = $this->snapshot(); + + $this->assert_refused( $this->run_ability( $this->update_input( $user_id, $data ) ), 'Updating while logged out' ); + $this->assert_core_error( $callbacks['execute_callback']( $this->update_input( $user_id, $data ) ), 'user_cannot_edit', 'Updating while logged out behind the gate' ); + $this->assert_unchanged( $before, 'Updating while logged out' ); + } + + /** + * Returns updates of a logged-out caller. + * + * @return array}> Whether the + * target exists, and the attributes. + */ + public static function data_updates_while_logged_out(): array { + return array( + 'profile' => array( true, array( 'name' => 'Logged Out' ) ), + 'roles' => array( true, array( 'roles' => array( 'editor' ) ) ), + 'invalid attribute' => array( true, array( 'name' => str_repeat( 'a', 249 ) . '&' ) ), + 'missing user' => array( false, array( 'name' => 'Logged Out' ) ), + ); + } + + /** + * An ID that no user has is the not-found error. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_ids_of_no_user + * + * @param mixed $id The ID. + * @param bool $skip_validation Whether to skip schema validation. + */ + public function test_reports_a_missing_user( $id, bool $skip_validation ): void { + if ( $skip_validation ) { + $this->skip_input_validation(); + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( + $this->run_ability( + array( + 'where' => array( 'id' => $id ), + 'data' => array( 'name' => 'Nobody' ), + ) + ), + 'user_not_found', + 'Updating a user that does not exist' + ); + $this->assert_unchanged( $before, 'Updating a user that does not exist' ); + } + + /** + * Returns IDs that name no user. + * + * @return array The ID, and whether + * to skip validation. + */ + public static function data_ids_of_no_user(): array { + return array( + 'missing ID' => array( self::MISSING_ID, false ), + 'zero, validation skipped' => array( 0, true ), + 'negative ID, validation skipped' => array( -1, true ), + ); + } + + /** + * On multisite a user who is not a member of the current site is not found, for + * every caller. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + * + * @dataProvider data_callers_and_users_of_another_site + * + * @param string $caller The caller, as a fixture name. + * @param string $target The target, as a fixture name. + * @param array $data The attributes. + */ + public function test_reports_a_user_of_another_site( string $caller, string $target, array $data ): void { + $this->login_as( $caller ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( $this->run_ability( $this->update_input( self::$user_ids[ $target ], $data ) ), 'user_not_found', 'Updating a user of another site' ); + $this->assert_unchanged( $before, 'Updating a user of another site' ); + } + + /** + * Returns callers and users who are not members of the current site. + * + * @return array}> + * The caller, the target and the attributes. + */ + public static function data_callers_and_users_of_another_site(): array { + return array( + 'site administrator, profile' => array( 'administrator', 'outsider', array( 'first_name' => 'Other' ) ), + 'super admin, profile' => array( 'manager', 'outsider', array( 'first_name' => 'Other' ) ), + 'super admin, roles' => array( 'manager', 'outsider', array( 'roles' => array( 'editor' ) ) ), + 'super admin updating oneself' => array( 'outside_super_admin', 'outside_super_admin', array( 'first_name' => 'Self' ) ), + ); + } + + /** + * A caller without the capability the keys of `data` need is refused before + * anything else is checked. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_updates_without_the_capability + * + * @param string $caller The caller, as a fixture name. + * @param bool $own Whether the caller updates themself. + * @param array $data The attributes. + * @param string $code The error code. + */ + public function test_refuses_callers_without_the_capability( string $caller, bool $own, array $data, string $code ): void { + $user_id = $own ? self::$user_ids[ $caller ] : $this->create_target( 'uwtcapability' ); + + $this->login_as( $caller ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( $this->run_ability( $this->update_input( $user_id, $data ) ), $code, 'Updating without the capability' ); + $this->assert_unchanged( $before, 'Updating without the capability' ); + } + + /** + * Returns updates the caller may not make. + * + * @return array, code: string}> + * The caller, whether the target is the caller, the attributes and the error code. + */ + public static function data_updates_without_the_capability(): array { + $profile = array( 'name' => 'Not Allowed' ); + $roles = array( 'roles' => array( 'editor' ) ); + + return array( + 'editor, profile' => array( 'editor', false, $profile, 'user_cannot_edit' ), + 'author, profile' => array( 'author', false, $profile, 'user_cannot_edit' ), + 'contributor, profile' => array( 'contributor', false, $profile, 'user_cannot_edit' ), + 'subscriber, profile' => array( 'subscriber', false, $profile, 'user_cannot_edit' ), + 'promoter, profile' => array( 'promoter', false, $profile, 'user_cannot_edit' ), + 'lister and promoter, profile' => array( 'lister_promoter', false, $profile, 'user_cannot_edit' ), + 'editor, roles' => array( 'editor', false, $roles, 'user_cannot_edit_roles' ), + 'author, roles' => array( 'author', false, $roles, 'user_cannot_edit_roles' ), + 'contributor, roles' => array( 'contributor', false, $roles, 'user_cannot_edit_roles' ), + 'subscriber, roles' => array( 'subscriber', false, $roles, 'user_cannot_edit_roles' ), + 'editor, roles and profile' => array( 'editor', false, array_merge( $roles, $profile ), 'user_cannot_edit_roles' ), + 'promoter, roles and profile' => array( 'promoter', false, array_merge( $roles, $profile ), 'user_cannot_edit' ), + 'editor, invalid attribute' => array( 'editor', false, array( 'name' => str_repeat( 'a', 249 ) . '&' ), 'user_cannot_edit' ), + 'editor giving themself a role' => array( 'editor', true, array( 'roles' => array( 'administrator' ) ), 'user_cannot_edit_roles' ), + 'subscriber changing own roles' => array( 'subscriber', true, $roles, 'user_cannot_edit_roles' ), + ); + } + + /** + * An editor changes the letter case of their own email, which applies at once, but + * cannot take the email of another user in another case. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_editor_updates_their_own_email(): void { + $editor_id = self::$user_ids['editor']; + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->update_input( $editor_id, array( 'email' => 'UWT-Editor@example.test' ), array( 'email' ) ) ); + + $this->assertSame( + array( + 'id' => $editor_id, + 'email' => 'UWT-Editor@example.test', + ), + $result, + 'The output should show the new email.' + ); + $this->assertSame( 'UWT-Editor@example.test', get_userdata( $editor_id )->user_email, 'The new email should apply at once.' ); + + reset_phpmailer_instance(); + $before = $this->snapshot(); + + $this->assert_value_error( + $this->run_ability( $this->update_input( $editor_id, array( 'email' => 'UWT-AUTHOR@example.test' ) ) ), + 'user_exists', + 'data[email]', + 'Taking the email of another user in another case', + 'Sorry, that email address is already used!' + ); + $this->assert_unchanged( $before, 'Taking the email of another user in another case' ); + } + + /** + * An administrator who is not a super admin cannot give themself a role without + * `edit_users`, also next to a role with it. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_own_roles_without_edit_users + * + * @param list $roles The roles. + */ + public function test_refuses_lowering_your_own_role( array $roles ): void { + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( $this->run_ability( $this->update_input( self::$user_ids['administrator'], array( 'roles' => $roles ) ) ), 'user_cannot_assign_role', 'Lowering your own role' ); + $this->assert_unchanged( $before, 'Lowering your own role' ); + } + + /** + * Returns own roles that hold one without `edit_users`. + * + * @return array}> The roles. + */ + public static function data_own_roles_without_edit_users(): array { + return array( + 'editor' => array( array( 'editor' ) ), + 'administrator and editor' => array( array( 'administrator', 'editor' ) ), + 'subscriber' => array( array( 'subscriber' ) ), + ); + } + + /** + * An administrator who is not a super admin keeps their own role when they set it + * again, since it lets them edit users. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_administrator_sets_their_own_role_again(): void { + $user_id = self::$user_ids['administrator']; + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + if ( is_multisite() ) { + $this->assertFalse( is_super_admin( $user_id ), 'The administrator should not be a super admin.' ); + } + + $result = $this->run_ability( $this->update_input( $user_id, array( 'roles' => array( 'administrator' ) ), array( 'roles' ) ) ); + + $this->assertSame( + array( + 'id' => $user_id, + 'roles' => array( 'administrator' ), + ), + $result, + 'The output should show the role.' + ); + $this->assertSame( array( 'administrator' ), $this->get_stored_roles( $user_id ), 'The administrator should hold exactly the administrator role.' ); + } + + /** + * On multisite a super admin can lower their own role. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + */ + public function test_super_admin_lowers_their_own_role(): void { + $user_id = $this->create_target( 'uwtownrole', array( 'role' => 'administrator' ) ); + grant_super_admin( $user_id ); + + wp_set_current_user( $user_id ); + $this->register_abilities(); + + $result = $this->run_ability( $this->update_input( $user_id, array( 'roles' => array( 'editor' ) ), array( 'roles' ) ) ); + + $this->assertSame( + array( + 'id' => $user_id, + 'roles' => array( 'editor' ), + ), + $result, + 'The output should show the new role.' + ); + $this->assertSame( array( 'editor' ), $this->get_stored_roles( $user_id ), 'The super admin should be an editor of the site.' ); + } + + /** + * A role that is not editable is refused. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_ways_a_role_is_not_editable + * + * @param bool $keyed Whether the filter keeps the key of `editor` with an empty entry + * instead of removing it. + */ + public function test_refuses_a_role_that_is_not_editable( bool $keyed ): void { + add_filter( + 'editable_roles', + static function ( $roles ) use ( $keyed ) { + if ( $keyed ) { + $roles['editor'] = false; + } else { + unset( $roles['editor'] ); + } + return $roles; + } + ); + + $user_id = $this->create_target( 'uwtnoteditable' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_core_error( $this->run_ability( $this->update_input( $user_id, array( 'roles' => array( 'author', 'editor' ) ) ) ), 'user_cannot_assign_role', 'Giving a role that is not editable' ); + $this->assert_unchanged( $before, 'Giving a role that is not editable' ); + } + + /** + * Returns the ways a filter makes `editor` not editable. + * + * @return array Whether the entry is kept empty. + */ + public static function data_ways_a_role_is_not_editable(): array { + return array( + 'role removed' => array( false ), + 'entry set to false' => array( true ), + ); + } + + /** + * A role that was removed after the ability was registered is refused. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_refuses_a_role_removed_after_registration(): void { + $user_id = $this->create_target( 'uwtgone' ); + + add_role( 'uwt_gone', 'Gone', array( 'read' => true ) ); + $this->login_as( 'manager' ); + $this->register_abilities(); + remove_role( 'uwt_gone' ); + + $before = $this->snapshot(); + + $this->assert_value_error( + $this->run_ability( $this->update_input( $user_id, array( 'roles' => array( 'uwt_gone' ) ) ) ), + 'user_invalid_attribute', + 'data[roles]', + 'Giving a removed role', + 'The role uwt_gone does not exist.' + ); + $this->assert_unchanged( $before, 'Giving a removed role' ); + } + + /** + * Attributes that cannot be applied are refused before the save runs. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_profile_attributes_refused + * + * @param array $data The attributes. + * @param string $code The error code. + * @param string $param The input path. + * @param string|null $message The message, or null when it is not fixed. + */ + public function test_refuses_attributes( array $data, string $code, string $param, ?string $message ): void { + $user_id = $this->create_target( 'uwtrefused' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + if ( self::LONG_NAME_MESSAGE === $message ) { + $message = $this->get_long_name_message( $this->update_input( $user_id, array( 'name' => str_repeat( 'a', 251 ) ) ) ); + } + + $before = $this->snapshot(); + + $this->watch_filter( 'pre_user_login' ); + + $this->assert_value_error( $this->run_ability( $this->update_input( $user_id, $data ) ), $code, $param, 'Updating with a refused attribute', $message ); + $this->assert_unchanged( $before, 'Updating with a refused attribute' ); + $this->assert_filter_not_run( 'pre_user_login', 'Updating with a refused attribute' ); + } + + /** + * An email of 101 characters and a name of 251 characters are refused by the schema, + * and with the error about the value when validation is skipped, before the save runs. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_values_over_the_length_limits + * + * @param array $data The attribute. + * @param bool $skip_validation Whether to skip schema validation. + * @param string $param The input path. + */ + public function test_refuses_values_over_the_length_limits( array $data, bool $skip_validation, string $param ): void { + $user_id = $this->create_target( 'uwtlong' ); + + if ( $skip_validation ) { + $this->skip_input_validation(); + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->watch_filter( 'pre_user_login' ); + $this->watch_filter( 'wpmu_validate_user_signup' ); + + $this->assert_over_the_length_limit( $this->run_ability( $this->update_input( $user_id, $data ) ), $skip_validation, $param, 'Updating with a value over the length limit' ); + $this->assert_unchanged( $before, 'Updating with a value over the length limit' ); + $this->assert_filter_not_run( 'pre_user_login', 'Updating with a value over the length limit' ); + $this->assert_filter_not_run( 'wpmu_validate_user_signup', 'Updating with a value over the length limit' ); + } + + /** + * An email of 100 characters and a name of 250 characters are accepted and stored. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_accepts_values_at_the_length_limits(): void { + $user_id = $this->create_target( 'uwtlimits' ); + $data = array( + 'email' => str_repeat( 'b', 87 ) . '@example.test', + 'name' => str_repeat( 'c', 250 ), + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertIsArray( $this->run_ability( $this->update_input( $user_id, $data ) ), 'Values at the limits should be accepted.' ); + + $user = get_userdata( $user_id ); + $this->assertSame( $data['email'], $user->user_email, 'The email of 100 characters should be stored.' ); + $this->assertSame( $data['name'], $user->display_name, 'The name of 250 characters should be stored.' ); + } + + /** + * Quotes and backslashes in text values are stored as given. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_stores_quotes_and_backslashes(): void { + $user_id = $this->create_target( 'uwtquotes' ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $fields = array( 'name', 'description', 'first_name', 'last_name', 'nickname' ); + $this->assert_user_item( $this->run_ability( $this->update_input( $user_id, $this->get_quoted_values(), $fields ) ), $fields, 'Updating with quotes and backslashes' ); + $this->assert_quoted_values_stored( $user_id, 'Updating with quotes and backslashes' ); + } + + /** + * The locale is stored, and the output shows the locale the user gets. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_locales + * + * @param string $locale The locale. + */ + public function test_sets_the_locale( string $locale ): void { + $user_id = $this->create_target( 'uwtlocale', array( 'locale' => 'es_ES' ) ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->update_input( $user_id, array( 'locale' => $locale ), array( 'locale' ) ) ); + + $this->assertSame( $locale, get_user_meta( $user_id, 'locale', true ), 'The locale should be stored.' ); + $this->assertSame( + array( + 'id' => $user_id, + 'locale' => get_user_locale( $user_id ), + ), + $result, + 'The output should show the locale of the user.' + ); + } + + /** + * Returns locales that can be set. + * + * @return array The locales. + */ + public static function data_locales(): array { + return array( + 'site locale' => array( '' ), + 'English' => array( 'en_US' ), + 'installed language' => array( 'de_DE' ), + ); + } + + /** + * An empty URL clears the URL, and the user's own slug can be sent again. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_clears_the_url_and_keeps_the_slug(): void { + $user_id = $this->create_target( 'uwtsameslug', array( 'user_url' => 'https://example.test/old' ) ); + $slug = get_userdata( $user_id )->user_nicename; + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $first = $this->run_ability( + $this->update_input( + $user_id, + array( + 'url' => '', + 'slug' => $slug, + ), + array( 'url', 'slug' ) + ) + ); + $second = $this->run_ability( $this->update_input( $user_id, array( 'slug' => $slug ), array( 'url', 'slug' ) ) ); + + $expected = array( + 'id' => $user_id, + 'url' => '', + 'slug' => $slug, + ); + $this->assertSame( $expected, $first, 'The first update should clear the URL and keep the slug.' ); + $this->assertSame( $expected, $second, 'The same slug should be accepted a second time.' ); + $this->assertSame( '', get_userdata( $user_id )->user_url, 'The URL should be cleared.' ); + } + + /** + * A caller who may only change roles reads back the ID only, or the public fields + * when they may list users. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_callers_who_may_only_change_roles + * + * @param string $caller The caller, as a fixture name. + * @param list $keys The keys of the output. + */ + public function test_output_of_callers_who_may_only_change_roles( string $caller, array $keys ): void { + $user_id = $this->create_target( 'uwtpromoted' ); + + $this->login_as( $caller ); + $this->register_abilities(); + + $result = $this->run_ability( $this->update_input( $user_id, array( 'roles' => array( 'editor' ) ), array( 'name', 'slug', 'username', 'email', 'roles' ) ) ); + + $this->assertIsArray( $result, 'The roles should be changed.' ); + $this->assertSameSets( $keys, array_keys( $result ), 'Only the fields the caller may read should be returned.' ); + $this->assertSame( $user_id, $result['id'], 'The output should hold the ID.' ); + $this->assertSame( array( 'editor' ), $this->get_stored_roles( $user_id ), 'The user should be an editor.' ); + } + + /** + * Returns callers who may change roles but not edit users. + * + * @return array}> The caller and the keys of the output. + */ + public static function data_callers_who_may_only_change_roles(): array { + return array( + 'promoter' => array( 'promoter', array( 'id' ) ), + 'lister and promoter' => array( 'lister_promoter', array( 'id', 'name', 'slug' ) ), + ); + } + + /** + * On multisite a site administrator changes the roles of a super admin and reads + * back the public fields only. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + */ + public function test_site_administrator_changes_roles_of_a_super_admin(): void { + $user_id = $this->create_target( 'uwtsuperroles', array( 'role' => 'administrator' ) ); + grant_super_admin( $user_id ); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->update_input( $user_id, array( 'roles' => array( 'editor' ) ), array( 'name', 'username', 'roles' ) ) ); + + $this->assertIsArray( $result, 'The roles should be changed.' ); + $this->assertSameSets( array( 'id', 'name' ), array_keys( $result ), 'Only the public fields should be returned.' ); + $this->assertSame( array( 'editor' ), $this->get_stored_roles( $user_id ), 'The super admin should be an editor of the site.' ); + $this->assertTrue( is_super_admin( $user_id ), 'The user should stay a super admin.' ); + } + + /** + * On multisite profile attributes of another member need the network capability, + * and those of a super admin need a super admin. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @group ms-required + * + * @dataProvider data_profile_changes_on_multisite + * + * @param string $caller The caller, as a fixture name. + * @param bool $super_admin Whether the target is a super admin. + * @param bool $allowed Whether the change is allowed. + */ + public function test_profile_changes_on_multisite( string $caller, bool $super_admin, bool $allowed ): void { + $user_id = $this->create_target( 'uwtnetwork' ); + if ( $super_admin ) { + grant_super_admin( $user_id ); + } + + $this->login_as( $caller ); + $this->register_abilities(); + + $before = $this->snapshot(); + $result = $this->run_ability( $this->update_input( $user_id, array( 'first_name' => 'Changed' ) ) ); + + if ( $allowed ) { + $this->assertIsArray( $result, 'The change should be allowed.' ); + $this->assertSame( 'Changed', get_userdata( $user_id )->first_name, 'The first name should be stored.' ); + } else { + $this->assert_core_error( $result, 'user_cannot_edit', 'Changing a profile without the network capability' ); + $this->assert_unchanged( $before, 'Changing a profile without the network capability' ); + } + } + + /** + * Returns profile changes on multisite. + * + * @return array + * The caller, whether the target is a super admin, and whether it is allowed. + */ + public static function data_profile_changes_on_multisite(): array { + return array( + 'site administrator, member' => array( 'administrator', false, false ), + 'site administrator, super admin' => array( 'administrator', true, false ), + 'network user editor, super admin' => array( 'network_editor', true, false ), + 'network user editor, member' => array( 'network_editor', false, true ), + 'super admin, super admin' => array( 'manager', true, true ), + ); + } + + /** + * A save that fails refuses the call, and the roles stay. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_failing_saves + * + * @param string $hook The filter. + * @param callable $callback The filter callback. + * @param string $code The error code. + */ + public function test_refuses_a_failing_save( string $hook, callable $callback, string $code ): void { + $user_id = $this->create_target( 'uwtfailing' ); + add_filter( $hook, $callback ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_error( + $this->run_ability( + $this->update_input( + $user_id, + array( + 'name' => 'Failing', + 'roles' => array( 'editor' ), + ) + ) + ), + $code, + 500, + 'Updating with a failing save' + ); + $this->assert_unchanged( $before, 'Updating with a failing save' ); + $this->assertSame( array( 'author' ), $this->get_stored_roles( $user_id ), 'The roles should stay.' ); + } + + /** + * Returns filters that make the save fail. + * + * @return array The filter, + * its callback and the error code. + */ + public static function data_failing_saves(): array { + return array( + 'empty username' => array( 'pre_user_login', '__return_empty_string', 'empty_user_login' ), + 'empty data' => array( 'wp_pre_insert_user_data', '__return_empty_array', 'empty_data' ), + ); + } + + /** + * Input that the schema refuses gets the schema error, and nothing changes. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_inputs_the_schema_refuses + * + * @param array $input The input, where `where.id` 0 stands for the target. + */ + public function test_refuses_input_the_schema_refuses( array $input ): void { + $user_id = $this->create_target( 'uwtschema' ); + if ( isset( $input['where']['id'] ) && 'target' === $input['where']['id'] ) { + $input['where']['id'] = $user_id; + } + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_invalid_input( $this->run_ability( $input ), 'Updating with input the schema refuses' ); + $this->assert_unchanged( $before, 'Updating with input the schema refuses' ); + } + + /** + * Returns inputs the schema refuses; the ID `target` stands for the user to update. + * + * @return array}> The inputs. + */ + public static function data_inputs_the_schema_refuses(): array { + $where = array( 'id' => 'target' ); + $rows = array( + 'no where' => array( array( 'data' => array( 'name' => 'Schema' ) ) ), + 'no data' => array( array( 'where' => $where ) ), + 'empty data' => array( + array( + 'where' => $where, + 'data' => array(), + ), + ), + 'ID of zero' => array( + array( + 'where' => array( 'id' => 0 ), + 'data' => array( 'name' => 'Schema' ), + ), + ), + 'ID as text' => array( + array( + 'where' => array( 'id' => 'abc' ), + 'data' => array( 'name' => 'Schema' ), + ), + ), + 'unknown where key' => array( + array( + 'where' => array( + 'id' => 'target', + 'slug' => 'uwtschema', + ), + 'data' => array( 'name' => 'Schema' ), + ), + ), + 'username' => array( + array( + 'where' => $where, + 'data' => array( 'username' => 'uwtrenamed' ), + ), + ), + 'empty name' => array( + array( + 'where' => $where, + 'data' => array( 'name' => '' ), + ), + ), + 'invalid email' => array( + array( + 'where' => $where, + 'data' => array( 'email' => 'not-an-email' ), + ), + ), + 'locale not installed' => array( + array( + 'where' => $where, + 'data' => array( 'locale' => 'klingon' ), + ), + ), + 'empty roles' => array( + array( + 'where' => $where, + 'data' => array( 'roles' => array() ), + ), + ), + 'unregistered role' => array( + array( + 'where' => $where, + 'data' => array( 'roles' => array( 'BeSharp' ) ), + ), + ), + 'repeated role' => array( + array( + 'where' => $where, + 'data' => array( 'roles' => array( 'editor', 'editor' ) ), + ), + ), + 'unknown field' => array( + array( + 'where' => $where, + 'data' => array( 'name' => 'Schema' ), + 'fields' => array( 'password' ), + ), + ), + ); + + foreach ( self::data_keys_outside_the_allow_list() as $name => $row ) { + $rows[ "data with {$name}" ] = array( + array( + 'where' => $where, + 'data' => array( $row[0] => $row[1] ), + ), + ); + } + + return $rows; + } + + /** + * With schema validation skipped, the callback refuses what the schema would. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_inputs_checked_when_validation_is_skipped + * + * @param array $data The attributes. + * @param string $param The input path. + * @param string|null $message The message, or null when it is not fixed. + */ + public function test_checks_input_when_validation_is_skipped( array $data, string $param, ?string $message ): void { + $user_id = $this->create_target( 'uwtskipped' ); + + $this->skip_input_validation(); + $this->login_as( 'manager' ); + $this->register_abilities(); + + $before = $this->snapshot(); + + $this->assert_value_error( $this->run_ability( $this->update_input( $user_id, $data ) ), 'user_invalid_attribute', $param, 'Updating without validation', $message ); + $this->assert_unchanged( $before, 'Updating without validation' ); + } + + /** + * Returns attributes that only the callback can refuse once validation is skipped. + * + * @return array, param: string, message: string|null}> + * The attributes, the input path and the message. + */ + public static function data_inputs_checked_when_validation_is_skipped(): array { + return array( + 'no attributes' => array( array(), 'data', null ), + 'only unknown keys' => array( array( 'password' => 'uwt-chosen-password' ), 'data', null ), + 'empty roles' => array( array( 'roles' => array() ), 'data[roles]', null ), + 'unregistered role' => array( array( 'roles' => array( 'uwt_unregistered' ) ), 'data[roles]', 'The role uwt_unregistered does not exist.' ), + 'invalid email' => array( array( 'email' => 'not-an-email' ), 'data[email]', null ), + 'locale not installed' => array( array( 'locale' => 'klingon' ), 'data[locale]', null ), + ); + } + + /** + * Keys outside the attributes never reach the save, when validation is skipped and + * when the callback is called directly; the username and password stay. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_ways_past_the_schema + * + * @param bool $direct Whether to call the callback directly. + */ + public function test_ignores_keys_outside_the_allow_list( bool $direct ): void { + $user_id = $this->create_target( 'uwtallowlist' ); + $stored = get_userdata( $user_id ); + $hash = $stored->user_pass; + $callbacks = $this->get_ability_callbacks(); + $this->login_as( 'manager' ); + + $saved_logins = array(); + add_filter( + 'wp_pre_insert_user_data', + static function ( $data, $update, $id, $userdata ) use ( &$saved_logins ) { + $saved_logins[] = $userdata['user_login'] ?? null; + return $data; + }, + 10, + 4 + ); + + $fields = array( + 'username' => 'uwtrenamed', + 'user_login' => 'uwtsentlogin', + 'user_nicename' => 'uwt-sent-slug', + 'user_registered' => '2001-02-03 04:05:06', + 'display_name' => 'Sent Display Name', + ); + $input = $this->update_input( $user_id, array_merge( array( 'first_name' => 'Allowed' ), $this->get_keys_outside_the_allow_list(), $fields ) ); + if ( $direct ) { + $result = $callbacks['execute_callback']( $input ); + } else { + $this->skip_input_validation(); + $result = $this->run_ability( $input ); + } + + $this->assertIsArray( $result, 'The attributes should be applied.' ); + + $user = get_userdata( $user_id ); + $this->assertSame( 'Allowed', $user->first_name, 'The first name should be stored.' ); + $this->assertSame( $stored->user_login, $user->user_login, 'The username should stay.' ); + $this->assertSame( $stored->user_nicename, $user->user_nicename, 'The slug should stay.' ); + $this->assertSame( $stored->user_registered, $user->user_registered, 'The registration date should stay.' ); + $this->assertSame( $stored->display_name, $user->display_name, 'The display name should stay.' ); + $this->assertSame( array( $stored->user_login ), array_unique( $saved_logins ), 'The save should receive the stored login.' ); + $this->assertSame( array( 'author' ), $this->get_stored_roles( $user_id ), 'The roles should stay.' ); + $this->assert_keys_outside_the_allow_list_ignored( $user_id, $hash, 'Updating with keys outside the attributes' ); + } + + /** + * Returns the ways past the schema. + * + * @return array Whether to call the callback directly. + */ + public static function data_ways_past_the_schema(): array { + return array( + 'validation skipped' => array( false ), + 'direct call' => array( true ), + ); + } + + /** + * Core's user hooks fire as the caller, and the hooks of the other ways of updating + * users do not. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_fires_core_hooks_only(): void { + $user_id = $this->create_target( 'uwthooks' ); + + $fired = array(); + foreach ( array( 'rest_pre_insert_user', 'rest_insert_user', 'rest_after_insert_user', 'rest_prepare_user' ) as $hook ) { + add_filter( + $hook, + static function ( $value ) use ( &$fired, $hook ) { + $fired[] = $hook; + return $value; + } + ); + } + + $current_users = array(); + add_action( + 'profile_update', + static function () use ( &$current_users ) { + $current_users[] = get_current_user_id(); + } + ); + + $this->login_as( 'manager' ); + $this->register_abilities(); + + $this->assertIsArray( $this->run_ability( $this->update_input( $user_id, array( 'name' => 'Hooked' ) ) ), 'The user should be updated.' ); + $this->assertSame( array( self::$user_ids['manager'] ), $current_users, 'The profile_update action should fire once, as the caller.' ); + $this->assertSame( array(), $fired, 'No hook of the other ways of updating users should fire.' ); + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreUsersAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreUsersAbility.php index 671db3381ec3b..241aff03e4df8 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreUsersAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreUsersAbility.php @@ -167,8 +167,10 @@ public static function wpTearDownAfterClass(): void { * @since 7.2.0 */ private function register_ability(): void { - if ( wp_has_ability( 'core/users-query' ) ) { - wp_unregister_ability( 'core/users-query' ); + foreach ( array( 'core/users-query', 'core/user-create', 'core/user-update', 'core/user-delete' ) as $ability_name ) { + if ( wp_has_ability( $ability_name ) ) { + wp_unregister_ability( $ability_name ); + } } global $wp_current_filter; diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesUsersController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesUsersController.php index d9755d9e2c58e..b88c2d10eb3b1 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesUsersController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesUsersController.php @@ -33,6 +33,20 @@ class Tests_REST_API_WpRestAbilitiesUsersController extends WP_UnitTestCase { */ protected static $subscriber_id; + /** + * Administrator user ID, a super admin on multisite. + * + * @var int + */ + protected static $manager_id; + + /** + * Editor user ID. + * + * @var int + */ + protected static $editor_id; + /** * The run route for the core/users-query ability. * @@ -40,6 +54,27 @@ class Tests_REST_API_WpRestAbilitiesUsersController extends WP_UnitTestCase { */ const RUN_ROUTE = '/wp-abilities/v1/abilities/core/users-query/run'; + /** + * The run route for the core/user-create ability. + * + * @var string + */ + const CREATE_ROUTE = '/wp-abilities/v1/abilities/core/user-create/run'; + + /** + * The run route for the core/user-update ability. + * + * @var string + */ + const UPDATE_ROUTE = '/wp-abilities/v1/abilities/core/user-update/run'; + + /** + * The run route for the core/user-delete ability. + * + * @var string + */ + const DELETE_ROUTE = '/wp-abilities/v1/abilities/core/user-delete/run'; + /** * Sets up users and registers the core abilities. * @@ -50,6 +85,12 @@ class Tests_REST_API_WpRestAbilitiesUsersController extends WP_UnitTestCase { public static function wpSetUpBeforeClass( $factory ): void { self::$admin_id = $factory->user->create( array( 'role' => 'administrator' ) ); self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + self::$manager_id = $factory->user->create( array( 'role' => 'administrator' ) ); + self::$editor_id = $factory->user->create( array( 'role' => 'editor' ) ); + + if ( is_multisite() ) { + grant_super_admin( self::$manager_id ); + } remove_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); remove_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); @@ -83,6 +124,10 @@ public static function wpSetUpBeforeClass( $factory ): void { * @since 7.2.0 */ public static function wpTearDownAfterClass(): void { + if ( is_multisite() ) { + revoke_super_admin( self::$manager_id ); + } + foreach ( wp_get_abilities() as $ability ) { wp_unregister_ability( $ability->get_name() ); } @@ -461,4 +506,371 @@ public function test_has_published_posts_accepts_the_string_true(): void { $this->assertSame( 200, $response->get_status(), 'The string "true" should be accepted for has_published_posts.' ); $this->assertSame( array( $author_id ), wp_list_pluck( $data['items'], 'id' ), 'Only the included user with a published post should be returned.' ); } + + /** + * Builds a run request: a POST request carries the input in a JSON body, and other + * requests carry it in the query string. + * + * @param string $method The HTTP method. + * @param string $route The run route. + * @param mixed $input The ability input, or null to send none. + * @return WP_REST_Request The request. + */ + private function write_request( string $method, string $route, $input ): WP_REST_Request { + $request = new WP_REST_Request( $method, $route ); + $params = null === $input ? array() : array( 'input' => $input ); + + if ( 'POST' === $method ) { + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( wp_json_encode( $params ) ); + } else { + $request->set_query_params( $params ); + } + + return $request; + } + + /** + * Creates an author with a published post. + * + * @param string $login The username. + * @return array{user: int, post: int} The IDs of the user and the post. + */ + private function create_author_with_post( string $login ): array { + $user_id = self::factory()->user->create( + array( + 'role' => 'author', + 'user_login' => $login, + 'user_email' => "{$login}@example.test", + ) + ); + + return array( + 'user' => $user_id, + 'post' => self::factory()->post->create( + array( + 'post_author' => $user_id, + 'post_status' => 'publish', + ) + ), + ); + } + + /** + * A user is created through the run route with a POST request. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_creates_a_user_with_a_post_request(): void { + wp_set_current_user( self::$manager_id ); + + $response = $this->server->dispatch( + $this->write_request( + 'POST', + self::CREATE_ROUTE, + array( + 'data' => array( + 'username' => 'uwtruncreated', + 'email' => 'uwt-run-created@example.test', + ), + 'fields' => array( 'id', 'username' ), + ) + ) + ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status(), 'Creating a user should succeed.' ); + $this->assertSame( 'uwtruncreated', $data['username'] ?? null, 'The output should hold the new username.' ); + $this->assertSame( $data['id'] ?? null, get_user_by( 'login', 'uwtruncreated' )->ID ?? 0, 'The output ID should be the new user.' ); + } + + /** + * A user is updated through the run route with a POST request. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_updates_a_user_with_a_post_request(): void { + $user_id = self::factory()->user->create( array( 'role' => 'author' ) ); + wp_set_current_user( self::$manager_id ); + + $response = $this->server->dispatch( + $this->write_request( + 'POST', + self::UPDATE_ROUTE, + array( + 'where' => array( 'id' => $user_id ), + 'data' => array( 'name' => 'Updated By Run' ), + ) + ) + ); + + $this->assertSame( 200, $response->get_status(), 'Updating a user should succeed.' ); + $this->assertSame( $user_id, $response->get_data()['id'] ?? null, 'The output should hold the user ID.' ); + $this->assertSame( 'Updated By Run', get_userdata( $user_id )->display_name, 'The name should be stored.' ); + } + + /** + * A user is deleted through the run route with a POST request that carries the input + * in its body. + * + * @ticket XXXXX + * @since 7.3.0 + */ + public function test_deletes_a_user_with_a_post_request(): void { + $user_id = self::factory()->user->create( array( 'role' => 'author' ) ); + wp_set_current_user( self::$manager_id ); + + $response = $this->server->dispatch( + $this->write_request( + 'POST', + self::DELETE_ROUTE, + array( + 'where' => array( 'id' => $user_id ), + 'reassign' => false, + ) + ) + ); + + $this->assertSame( 200, $response->get_status(), 'Deleting a user should succeed.' ); + $this->assertSame( array( 'outcome' => is_multisite() ? 'removed' : 'deleted' ), $response->get_data(), 'The output should give the outcome.' ); + $this->assertFalse( is_user_member_of_blog( $user_id, get_current_blog_id() ), 'The user should be gone from the site.' ); + } + + /** + * Each user write ability takes POST requests only: a GET request and a DELETE + * request, with the input in the query string, are refused. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_wrong_methods + * + * @param string $method The HTTP method. + * @param string $route The run route. + */ + public function test_wrong_method_returns_405( string $method, string $route ): void { + $user_id = self::factory()->user->create( array( 'role' => 'author' ) ); + wp_set_current_user( self::$manager_id ); + + $inputs = array( + self::CREATE_ROUTE => array( + 'data' => array( + 'username' => 'uwtrunmethod', + 'email' => 'uwt-run-method@example.test', + ), + ), + self::UPDATE_ROUTE => array( + 'where' => array( 'id' => $user_id ), + 'data' => array( 'name' => 'Wrong Method' ), + ), + self::DELETE_ROUTE => array( + 'where' => array( 'id' => (string) $user_id ), + 'reassign' => 'false', + ), + ); + + $response = $this->server->dispatch( $this->write_request( $method, $route, $inputs[ $route ] ) ); + + $this->assertSame( 405, $response->get_status(), 'The method should be refused.' ); + $this->assertSame( 'rest_ability_invalid_method', $response->get_data()['code'] ?? null, 'The error should identify the invalid HTTP method.' ); + $this->assertFalse( get_user_by( 'login', 'uwtrunmethod' ), 'No user should be created.' ); + $this->assertSame( 'author', get_userdata( $user_id )->roles[0] ?? null, 'The user should stay.' ); + $this->assertNotSame( 'Wrong Method', get_userdata( $user_id )->display_name, 'The user should not be updated.' ); + } + + /** + * Returns HTTP methods the user write abilities do not take. + * + * @return array The method and the route. + */ + public static function data_wrong_methods(): array { + return array( + 'create with GET' => array( 'GET', self::CREATE_ROUTE ), + 'create with DELETE' => array( 'DELETE', self::CREATE_ROUTE ), + 'update with GET' => array( 'GET', self::UPDATE_ROUTE ), + 'update with DELETE' => array( 'DELETE', self::UPDATE_ROUTE ), + 'delete with GET' => array( 'GET', self::DELETE_ROUTE ), + 'delete with DELETE' => array( 'DELETE', self::DELETE_ROUTE ), + ); + } + + /** + * Refused calls of the user write abilities carry their status. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_refused_calls + * + * @param string $route The run route. + * @param string $caller The caller: `manager`, `editor`, `subscriber`, or an empty string to log out. + * @param string $input_name The input to send. + * @param int $status The expected status. + * @param string|null $code The expected error code, or null for any. + */ + public function test_refused_calls_carry_their_status( string $route, string $caller, string $input_name, int $status, ?string $code ): void { + $user_id = self::factory()->user->create( + array( + 'role' => 'author', + 'user_login' => 'uwtruntaken', + 'user_email' => 'uwt-run-taken@example.test', + ) + ); + $callers = array( + '' => 0, + 'manager' => self::$manager_id, + 'editor' => self::$editor_id, + 'subscriber' => self::$subscriber_id, + ); + $inputs = array( + 'new user' => array( + 'data' => array( + 'username' => 'uwtrunrefused', + 'email' => 'uwt-run-refused@example.test', + ), + ), + 'no email' => array( 'data' => array( 'username' => 'uwtrunrefused' ) ), + 'taken username' => array( + 'data' => array( + 'username' => 'uwtruntaken', + 'email' => 'uwt-run-other@example.test', + ), + ), + 'missing user' => array( + 'where' => array( 'id' => 987654321 ), + 'data' => array( 'name' => 'Refused' ), + ), + 'author' => array( + 'where' => array( 'id' => $user_id ), + 'data' => array( 'name' => 'Refused' ), + ), + 'delete author' => array( + 'where' => array( 'id' => $user_id ), + 'reassign' => false, + ), + 'reassign true' => array( + 'where' => array( 'id' => $user_id ), + 'reassign' => 'true', + ), + ); + + wp_set_current_user( $callers[ $caller ] ); + + $response = $this->server->dispatch( $this->write_request( 'POST', $route, $inputs[ $input_name ] ) ); + + $this->assertSame( $status, $response->get_status(), "The call should be refused with status {$status}." ); + if ( null !== $code ) { + $this->assertSame( $code, $response->get_data()['code'] ?? null, "The error code should be {$code}." ); + } + $this->assertFalse( get_user_by( 'login', 'uwtrunrefused' ), 'No user should be created.' ); + $this->assertSame( 'uwtruntaken', get_userdata( $user_id )->user_login ?? null, 'The author should stay.' ); + $this->assertNotSame( 'Refused', get_userdata( $user_id )->display_name, 'The author should not be updated.' ); + } + + /** + * Returns calls of the user write abilities that are refused. + * + * @return array + * The route, the caller, the input, the status and the error code. + */ + public static function data_refused_calls(): array { + return array( + 'create while logged out' => array( self::CREATE_ROUTE, '', 'new user', 401, 'rest_ability_cannot_execute' ), + 'create by a subscriber' => array( self::CREATE_ROUTE, 'subscriber', 'new user', 403, 'rest_ability_cannot_execute' ), + 'create with invalid input' => array( self::CREATE_ROUTE, 'manager', 'no email', 400, null ), + 'create with a taken username' => array( self::CREATE_ROUTE, 'manager', 'taken username', 400, 'user_exists' ), + 'update of a missing user' => array( self::UPDATE_ROUTE, 'manager', 'missing user', 404, 'user_not_found' ), + 'update of another user' => array( self::UPDATE_ROUTE, 'editor', 'author', 403, 'user_cannot_edit' ), + 'delete by a subscriber' => array( self::DELETE_ROUTE, 'subscriber', 'delete author', 403, 'rest_ability_cannot_execute' ), + 'delete with reassign true text' => array( self::DELETE_ROUTE, 'manager', 'reassign true', 400, 'user_invalid_reassign' ), + ); + } + + /** + * A POST request carries `reassign` in its JSON body with its type: false and a user + * ID are taken, as a boolean or an integer and as a string, and every other value is + * refused without deleting anything. + * + * @ticket XXXXX + * @since 7.3.0 + * + * @dataProvider data_reassign_values_in_the_body + * + * @param mixed $reassign The reassign value; `heir` stands for the editor's ID, + * `heir as text` for that ID as a string, and `absent` + * sends none. + * @param string|null $owner Who owns the post afterwards: `heir`, `first` for user 1, + * `nobody` when no one is reassigned, or null when refused. + * @param string|null $code The expected error code, or null when the user is deleted. + */ + public function test_delete_takes_reassign_from_the_json_body( $reassign, ?string $owner, ?string $code ): void { + $target = $this->create_author_with_post( 'uwt_run_reassign' ); + $input = array( 'where' => array( 'id' => $target['user'] ) ); + + if ( 'heir' === $reassign ) { + $input['reassign'] = self::$editor_id; + } elseif ( 'heir as text' === $reassign ) { + $input['reassign'] = (string) self::$editor_id; + } elseif ( 'absent' !== $reassign ) { + $input['reassign'] = $reassign; + } + + wp_set_current_user( self::$manager_id ); + + $response = $this->server->dispatch( $this->write_request( 'POST', self::DELETE_ROUTE, $input ) ); + $post = get_post( $target['post'] ); + + if ( null === $owner ) { + $this->assertSame( 400, $response->get_status(), 'The reassign value should be refused.' ); + $this->assertSame( $code, $response->get_data()['code'] ?? null, "The error code should be {$code}." ); + $this->assertTrue( is_user_member_of_blog( $target['user'], get_current_blog_id() ), 'The user should stay.' ); + $this->assertSame( $target['user'], (int) $post->post_author, 'The post should keep its author.' ); + $this->assertSame( 'publish', $post->post_status, 'The post should stay published.' ); + return; + } + + $this->assertSame( 200, $response->get_status(), 'The user should be deleted.' ); + + $owners = array( + 'heir' => self::$editor_id, + 'first' => 1, + 'nobody' => $target['user'], + ); + if ( 'nobody' === $owner && ! is_multisite() ) { + $this->assertSame( 'trash', $post->post_status, 'The post should go to the trash.' ); + } else { + $this->assertSame( $owners[ $owner ], (int) $post->post_author, 'The post should belong to the expected user.' ); + $this->assertSame( 'publish', $post->post_status, 'The post should stay published.' ); + } + } + + /** + * Returns reassign values as a JSON body carries them. + * + * @return array + * The value, who owns the post afterwards, and the error code. + */ + public static function data_reassign_values_in_the_body(): array { + return array( + 'false' => array( false, 'nobody', null ), + 'false as text' => array( 'false', 'nobody', null ), + 'ID' => array( 'heir', 'heir', null ), + 'ID as text' => array( 'heir as text', 'heir', null ), + 'one' => array( 1, 'first', null ), + 'one as text' => array( '1', 'first', null ), + 'true' => array( true, null, 'user_invalid_reassign' ), + 'true as text' => array( 'true', null, 'user_invalid_reassign' ), + 'zero' => array( 0, null, 'ability_invalid_input' ), + 'zero as text' => array( '0', null, 'ability_invalid_input' ), + 'empty' => array( '', null, 'ability_invalid_input' ), + 'negative' => array( -1, null, 'ability_invalid_input' ), + 'fraction' => array( 7.5, null, 'ability_invalid_input' ), + 'text' => array( 'abc', null, 'ability_invalid_input' ), + 'null' => array( null, null, 'ability_invalid_input' ), + 'list' => array( array( 1 ), null, 'ability_invalid_input' ), + 'absent' => array( 'absent', null, 'ability_invalid_input' ), + ); + } } From 5ae8a09a6003608abb94aab56fb174e8d2d6ffcd Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Tue, 17 Nov 2026 22:47:42 +0000 Subject: [PATCH 2/2] Abilities API: Add the ticket number to the user write ability tests. Replace the `@ticket` placeholder in the tests of `core/user-create`, `core/user-update` and `core/user-delete` with 66720. See #66720. --- .../wpRegisterCoreUserCreateAbility.php | 56 ++++++++--------- .../wpRegisterCoreUserDeleteAbility.php | 44 ++++++------- .../wpRegisterCoreUserUpdateAbility.php | 62 +++++++++---------- .../wpRestAbilitiesUsersController.php | 12 ++-- 4 files changed, 87 insertions(+), 87 deletions(-) diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserCreateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserCreateAbility.php index 94075a5c86c44..1aee08684d1bb 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserCreateAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserCreateAbility.php @@ -58,7 +58,7 @@ private function assert_no_user( string $username, string $context ): void { /** * The ability is registered in the user category with its label and annotations. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_registers_the_ability(): void { @@ -69,7 +69,7 @@ public function test_registers_the_ability(): void { * The input schema takes the attributes in `data`, with the username and the email * required, and the fields of core/users-query. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_input_schema(): void { @@ -106,7 +106,7 @@ public function test_input_schema(): void { /** * The output schema is the core/users-query user item. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_output_schema(): void { @@ -117,7 +117,7 @@ public function test_output_schema(): void { * A user is created with the given attributes and roles, and the output holds * exactly the requested fields. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_creates_a_user_with_chosen_fields(): void { @@ -157,7 +157,7 @@ public function test_creates_a_user_with_chosen_fields(): void { * the username, gives the default role, sends the two mails without the password, * and sets a generated password. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_creates_a_user_from_the_minimum_input(): void { @@ -206,7 +206,7 @@ public function test_creates_a_user_from_the_minimum_input(): void { /** * On multisite the network admin also gets Core's notice when it is on. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -231,7 +231,7 @@ public function test_sends_the_network_notice_when_it_is_on(): void { * The user ends with exactly the given roles, in the given order, also when they are * sent as a comma-separated string. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_role_lists @@ -278,7 +278,7 @@ public static function data_role_lists(): array { * A caller without `create_users` is refused by the permission check, and gets the * schema error for invalid input. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_callers_without_create_users @@ -317,7 +317,7 @@ public static function data_callers_without_create_users(): array { * On multisite a site administrator cannot create users while the network does not * let site administrators add users. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -337,7 +337,7 @@ public function test_refuses_a_site_administrator_while_the_network_does_not_let /** * The callback checks `create_users` again, whatever the input holds. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_callers_and_inputs_behind_the_gate @@ -382,7 +382,7 @@ public static function data_callers_and_inputs_behind_the_gate(): array { /** * A role that was removed after the ability was registered is refused. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_refuses_a_role_removed_after_registration(): void { @@ -406,7 +406,7 @@ public function test_refuses_a_role_removed_after_registration(): void { /** * A role that is not editable is refused, also next to an editable one. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_roles_with_one_not_editable @@ -457,7 +457,7 @@ public static function data_roles_with_one_not_editable(): array { * Attributes that cannot be applied are refused before the save or the signup * validation runs. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_attributes_refused_on_create @@ -523,7 +523,7 @@ public static function data_attributes_refused_on_create(): array { * and with the error about the value when validation is skipped, before the save or * the signup validation runs. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_values_over_the_length_limits @@ -555,7 +555,7 @@ public function test_refuses_values_over_the_length_limits( array $data, bool $s * The role checks run before the attribute checks, and the attribute checks run in * order; the first failure is the error. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_inputs_with_two_failures @@ -656,7 +656,7 @@ public static function data_inputs_with_two_failures(): array { /** * Values at the length limits are accepted and stored. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_accepts_values_at_the_length_limits(): void { @@ -686,7 +686,7 @@ public function test_accepts_values_at_the_length_limits(): void { /** * Quotes and backslashes in text values are stored as given. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_stores_quotes_and_backslashes(): void { @@ -709,7 +709,7 @@ public function test_stores_quotes_and_backslashes(): void { * On multisite a site administrator who may add users reads back the public fields * of the new user only. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -735,7 +735,7 @@ public function test_site_administrator_reads_back_public_fields(): void { /** * A caller who may create users but neither edit nor list them reads back the ID only. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_caller_without_list_users_reads_back_the_id_only(): void { @@ -762,7 +762,7 @@ public function test_caller_without_list_users_reads_back_the_id_only(): void { /** * On multisite the new user becomes a member of the current site only. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -787,7 +787,7 @@ public function test_adds_the_user_to_the_current_site_only(): void { * On multisite what Core's signup validation refuses is refused with its message, * before the save runs. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -858,7 +858,7 @@ public static function data_signups_refused(): array { * On multisite, when adding the new user to the site fails, the user is deleted again * and the error is returned. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -911,7 +911,7 @@ public static function data_refusals_of_adding_to_the_site(): array { /** * A save that fails refuses the call, and nothing is created or mailed. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_failing_saves @@ -957,7 +957,7 @@ public static function data_failing_saves(): array { /** * A mail that cannot be sent does not change the result. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_succeeds_when_a_mail_cannot_be_sent(): void { @@ -975,7 +975,7 @@ public function test_succeeds_when_a_mail_cannot_be_sent(): void { /** * Input that the schema refuses gets the schema error, and nothing changes. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_inputs_the_schema_refuses @@ -1043,7 +1043,7 @@ public static function data_inputs_the_schema_refuses(): array { /** * With schema validation skipped, the callback refuses what the schema would. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_inputs_checked_when_validation_is_skipped @@ -1089,7 +1089,7 @@ public static function data_inputs_checked_when_validation_is_skipped(): array { * Keys outside the attributes never reach the save, when validation is skipped and * when the callback is called directly. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_ways_past_the_schema @@ -1143,7 +1143,7 @@ public static function data_ways_past_the_schema(): array { * Core's user hooks fire as the caller, and the hooks of the other ways of creating * users do not. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_fires_core_hooks_only(): void { diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserDeleteAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserDeleteAbility.php index 6945da5922ef6..6ce9e19cac4cc 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserDeleteAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserDeleteAbility.php @@ -149,7 +149,7 @@ private function assert_user_gone( int $user_id, string $context ): void { /** * The ability is registered in the user category with its label and annotations. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_registers_the_ability(): void { @@ -159,7 +159,7 @@ public function test_registers_the_ability(): void { /** * The input schema takes `where` with the ID and a required `reassign`. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_input_schema(): void { @@ -186,7 +186,7 @@ public function test_input_schema(): void { /** * The output schema is an object with the outcome only. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_output_schema(): void { @@ -210,7 +210,7 @@ public function test_output_schema(): void { * The user is deleted, or on multisite removed from the current site, and a second * call finds no user. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_deletes_the_user_once(): void { @@ -230,7 +230,7 @@ public function test_deletes_the_user_once(): void { * Without reassignment the posts of a deleted user go to the trash and their links * are deleted; on multisite, where the user is only removed, they keep their author. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_no_reassignment @@ -279,7 +279,7 @@ public static function data_no_reassignment(): array { * already in the trash and an attachment are deleted permanently, and a pattern stays * with its author. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-excluded @@ -352,7 +352,7 @@ public static function data_content_deleted_with_its_author(): array { * The posts and links of a deleted user go to the user given in `reassign`, given as * a number or as text; on multisite, the posts of the current site. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_reassign_ids @@ -399,7 +399,7 @@ public static function data_reassign_ids(): array { * Every value that names no usable user to reassign to gives the same error, and * nothing changes. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_unusable_reassign_values @@ -475,7 +475,7 @@ public static function data_unusable_reassign_values(): array { /** * With validation skipped, input without `reassign` gives the reassign error. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_refuses_a_missing_reassign_when_validation_is_skipped(): void { @@ -494,7 +494,7 @@ public function test_refuses_a_missing_reassign_when_validation_is_skipped(): vo /** * Input the schema refuses changes nothing. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_inputs_the_schema_refuses @@ -566,7 +566,7 @@ public static function data_inputs_the_schema_refuses(): array { /** * A caller without the capability to delete users is refused, and nothing changes. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_callers_without_the_capability @@ -605,7 +605,7 @@ public static function data_callers_without_the_capability(): array { * The callback checks the capability again, with a status that tells a logged-out * caller apart. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_callers_behind_the_gate @@ -639,7 +639,7 @@ public static function data_callers_behind_the_gate(): array { * The callback checks the capability to delete users apart from the capability on * the target: a caller granted only the capability on the target is refused. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_checks_the_capability_apart_from_the_one_on_the_user(): void { @@ -676,7 +676,7 @@ static function ( array $caps, string $cap, int $caller_id, array $args ) use ( /** * An ID that no user has is the not-found error. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_ids_of_no_user @@ -715,7 +715,7 @@ public static function data_ids_of_no_user(): array { /** * A capability filter that denies deleting the target is respected. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_respects_a_denied_capability_for_the_user(): void { @@ -746,7 +746,7 @@ static function ( array $caps, string $cap, int $caller_id, array $args ) use ( /** * On a single site the last administrator may delete themself. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-excluded @@ -765,7 +765,7 @@ public function test_last_administrator_deletes_themself(): void { /** * On multisite only a super admin may remove themself from the site. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -810,7 +810,7 @@ public static function data_callers_removing_themselves(): array { * On multisite a site administrator removes a super admin from the site only: the * account, the super admin status and the other memberships stay. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -835,7 +835,7 @@ public function test_site_administrator_removes_a_super_admin(): void { * On multisite a user who is not a member of the current site is not found, for * every caller. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -871,7 +871,7 @@ public static function data_callers_and_users_of_another_site(): array { /** * A user that is still stored after the deletion is the delete error. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-excluded @@ -903,7 +903,7 @@ static function ( string $query ) use ( $users, $user_id ): string { /** * On multisite a user who is still a member after the removal is the delete error. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -935,7 +935,7 @@ static function ( string $query ) use ( $blocked ): string { * Core's user hook fires once, as the caller, and the hook of the other ways of * deleting users does not. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_fires_core_hooks_only(): void { diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserUpdateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserUpdateAbility.php index afc334a33e968..3c405f0225d2b 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreUserUpdateAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreUserUpdateAbility.php @@ -59,7 +59,7 @@ private function get_stored_roles( int $user_id ): array { /** * The ability is registered in the user category with its label and annotations. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_registers_the_ability(): void { @@ -70,7 +70,7 @@ public function test_registers_the_ability(): void { * The input schema takes `where` with the ID, the attributes in `data` without the * username, and the fields of core/users-query. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_input_schema(): void { @@ -100,7 +100,7 @@ public function test_input_schema(): void { /** * The output schema is the core/users-query user item. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_output_schema(): void { @@ -110,7 +110,7 @@ public function test_output_schema(): void { /** * The roles and the biography are changed, and the output shows the new state. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_updates_roles_and_description(): void { @@ -142,7 +142,7 @@ public function test_updates_roles_and_description(): void { * Every attribute is stored, the output shows the stored user, and the username and * password stay. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_updates_every_attribute(): void { @@ -188,7 +188,7 @@ public function test_updates_every_attribute(): void { * The previous address is told about a changed email only, also when only the * letter case changed, and no password mail is sent. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_email_changes @@ -251,7 +251,7 @@ public static function data_email_changes(): array { * The roles are replaced by exactly the given ones, in order, also when they equal * the current ones, without a profile save. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_role_replacements @@ -296,7 +296,7 @@ public static function data_role_replacements(): array { * Nobody logged in is refused by the permission check, and by the callback with a * 401 before the user is looked up, whatever `data` holds. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_updates_while_logged_out @@ -334,7 +334,7 @@ public static function data_updates_while_logged_out(): array { /** * An ID that no user has is the not-found error. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_ids_of_no_user @@ -383,7 +383,7 @@ public static function data_ids_of_no_user(): array { * On multisite a user who is not a member of the current site is not found, for * every caller. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -423,7 +423,7 @@ public static function data_callers_and_users_of_another_site(): array { * A caller without the capability the keys of `data` need is refused before * anything else is checked. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_updates_without_the_capability @@ -478,7 +478,7 @@ public static function data_updates_without_the_capability(): array { * An editor changes the letter case of their own email, which applies at once, but * cannot take the email of another user in another case. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_editor_updates_their_own_email(): void { @@ -516,7 +516,7 @@ public function test_editor_updates_their_own_email(): void { * An administrator who is not a super admin cannot give themself a role without * `edit_users`, also next to a role with it. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_own_roles_without_edit_users @@ -550,7 +550,7 @@ public static function data_own_roles_without_edit_users(): array { * An administrator who is not a super admin keeps their own role when they set it * again, since it lets them edit users. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_administrator_sets_their_own_role_again(): void { @@ -579,7 +579,7 @@ public function test_administrator_sets_their_own_role_again(): void { /** * On multisite a super admin can lower their own role. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -607,7 +607,7 @@ public function test_super_admin_lowers_their_own_role(): void { /** * A role that is not editable is refused. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_ways_a_role_is_not_editable @@ -654,7 +654,7 @@ public static function data_ways_a_role_is_not_editable(): array { /** * A role that was removed after the ability was registered is refused. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_refuses_a_role_removed_after_registration(): void { @@ -680,7 +680,7 @@ public function test_refuses_a_role_removed_after_registration(): void { /** * Attributes that cannot be applied are refused before the save runs. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_profile_attributes_refused @@ -713,7 +713,7 @@ public function test_refuses_attributes( array $data, string $code, string $para * An email of 101 characters and a name of 251 characters are refused by the schema, * and with the error about the value when validation is skipped, before the save runs. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_values_over_the_length_limits @@ -746,7 +746,7 @@ public function test_refuses_values_over_the_length_limits( array $data, bool $s /** * An email of 100 characters and a name of 250 characters are accepted and stored. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_accepts_values_at_the_length_limits(): void { @@ -769,7 +769,7 @@ public function test_accepts_values_at_the_length_limits(): void { /** * Quotes and backslashes in text values are stored as given. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_stores_quotes_and_backslashes(): void { @@ -786,7 +786,7 @@ public function test_stores_quotes_and_backslashes(): void { /** * The locale is stored, and the output shows the locale the user gets. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_locales @@ -828,7 +828,7 @@ public static function data_locales(): array { /** * An empty URL clears the URL, and the user's own slug can be sent again. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_clears_the_url_and_keeps_the_slug(): void { @@ -864,7 +864,7 @@ public function test_clears_the_url_and_keeps_the_slug(): void { * A caller who may only change roles reads back the ID only, or the public fields * when they may list users. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_callers_who_may_only_change_roles @@ -902,7 +902,7 @@ public static function data_callers_who_may_only_change_roles(): array { * On multisite a site administrator changes the roles of a super admin and reads * back the public fields only. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -926,7 +926,7 @@ public function test_site_administrator_changes_roles_of_a_super_admin(): void { * On multisite profile attributes of another member need the network capability, * and those of a super admin need a super admin. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @group ms-required @@ -977,7 +977,7 @@ public static function data_profile_changes_on_multisite(): array { /** * A save that fails refuses the call, and the roles stay. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_failing_saves @@ -1029,7 +1029,7 @@ public static function data_failing_saves(): array { /** * Input that the schema refuses gets the schema error, and nothing changes. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_inputs_the_schema_refuses @@ -1154,7 +1154,7 @@ public static function data_inputs_the_schema_refuses(): array { /** * With schema validation skipped, the callback refuses what the schema would. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_inputs_checked_when_validation_is_skipped @@ -1197,7 +1197,7 @@ public static function data_inputs_checked_when_validation_is_skipped(): array { * Keys outside the attributes never reach the save, when validation is skipped and * when the callback is called directly; the username and password stay. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_ways_past_the_schema @@ -1266,7 +1266,7 @@ public static function data_ways_past_the_schema(): array { * Core's user hooks fire as the caller, and the hooks of the other ways of updating * users do not. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_fires_core_hooks_only(): void { diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesUsersController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesUsersController.php index b88c2d10eb3b1..2023be9c1b44e 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesUsersController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesUsersController.php @@ -559,7 +559,7 @@ private function create_author_with_post( string $login ): array { /** * A user is created through the run route with a POST request. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_creates_a_user_with_a_post_request(): void { @@ -588,7 +588,7 @@ public function test_creates_a_user_with_a_post_request(): void { /** * A user is updated through the run route with a POST request. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_updates_a_user_with_a_post_request(): void { @@ -615,7 +615,7 @@ public function test_updates_a_user_with_a_post_request(): void { * A user is deleted through the run route with a POST request that carries the input * in its body. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 */ public function test_deletes_a_user_with_a_post_request(): void { @@ -642,7 +642,7 @@ public function test_deletes_a_user_with_a_post_request(): void { * Each user write ability takes POST requests only: a GET request and a DELETE * request, with the input in the query string, are refused. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_wrong_methods @@ -699,7 +699,7 @@ public static function data_wrong_methods(): array { /** * Refused calls of the user write abilities carry their status. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_refused_calls @@ -793,7 +793,7 @@ public static function data_refused_calls(): array { * ID are taken, as a boolean or an integer and as a string, and every other value is * refused without deleting anything. * - * @ticket XXXXX + * @ticket 66720 * @since 7.3.0 * * @dataProvider data_reassign_values_in_the_body