From 7fec177db68ba92bcc3b368696b2f6af22fbc17c Mon Sep 17 00:00:00 2001 From: Subodh Rajpopat Date: Thu, 22 Oct 2026 23:17:25 +0530 Subject: [PATCH 1/4] Keep media folders private to signed-in users, and apply the folder lock on every route Reading the media-folder terms over REST now needs a signed-in user who can write posts (edit_posts), so the gallery block's folder picker keeps working for Contributors. Creating, changing or deleting folders needs upload_files. The Media Library folder tree and the block editor run signed in, so they are unaffected. The folder lock is applied where a folder changes rather than by matching one route path: - The media-folder term routes carry the check on their own permission callbacks, so it holds however a request reaches them (letter case, ?rest_route=, batch requests). It reads the folder id the way the controller does. - The assign_term capability is refused for a locked folder, which covers the core media route's media-folder field. That route also refuses to take a file out of a locked folder, as the assign-folder route does. - A new folder cannot be created inside a locked folder on any route. - An upload that names a locked folder, or one inside it, still succeeds but is left unfiled. The lock check itself moves to Media_Folder_Utils so these paths share it. --- inc/classes/class-media-library-ajax.php | 7 + .../class-media-folder-utils.php | 39 ++ inc/classes/rest-api/class-media-library.php | 195 ++++-- .../taxonomies/class-media-folders.php | 72 +++ tests/bootstrap.php | 9 + tests/php/MediaFolderLockTest.php | 603 ++++++++++++++++++ tests/php/MediaUploadLockedFolderTest.php | 127 ++++ tests/stubs/class-wp-rest-request.php | 18 +- tests/stubs/media-folder-functions.php | 116 ++++ 9 files changed, 1119 insertions(+), 67 deletions(-) create mode 100644 tests/php/MediaFolderLockTest.php create mode 100644 tests/php/MediaUploadLockedFolderTest.php create mode 100644 tests/stubs/media-folder-functions.php diff --git a/inc/classes/class-media-library-ajax.php b/inc/classes/class-media-library-ajax.php index fa01d83059..8ea6f96e05 100644 --- a/inc/classes/class-media-library-ajax.php +++ b/inc/classes/class-media-library-ajax.php @@ -10,6 +10,7 @@ defined( 'ABSPATH' ) || exit; use RTGODAM\Inc\Traits\Singleton; +use RTGODAM\Inc\Media_Library\Media_Folder_Utils; /** * Class Media_Library @@ -637,6 +638,12 @@ public function add_media_library_taxonomy_on_media_upload( $attachment_id ) { return; } + // A locked folder, or one inside a locked folder, takes no new files. Leave the + // upload unfiled, as the assign-folder route refuses the same move. + if ( Media_Folder_Utils::get_instance()->is_folder_locked( $media_folder ) ) { + return; + } + // Assign the existing term. wp_set_object_terms( $attachment_id, (int) $media_folder, 'media-folder' ); } diff --git a/inc/classes/media-library/class-media-folder-utils.php b/inc/classes/media-library/class-media-folder-utils.php index 735b0424ce..c0cfe1342e 100644 --- a/inc/classes/media-library/class-media-folder-utils.php +++ b/inc/classes/media-library/class-media-folder-utils.php @@ -258,6 +258,45 @@ public function is_valid_folder( $folder_id ) { return ! is_wp_error( $term ) && ! empty( $term ); } + /** + * Whether a media folder is locked, directly or through an ancestor. + * + * Folder locking is protective: a locked folder shields itself AND all of its + * descendants from mutation. So a folder counts as locked if its own `locked` + * term-meta is truthy or if any of its ancestors' is. Client-side gating (React) + * is UX only; this is the authoritative server-side check. + * + * @since n.e.x.t + * + * @param int $folder_id Media folder term ID. + * @return bool True if the folder or one of its ancestors is locked. + */ + public function is_folder_locked( $folder_id ) { + $folder_id = (int) $folder_id; + + if ( $folder_id <= 0 ) { + return false; + } + + // The term itself plus every ancestor — a locked ancestor locks the branch. + $ids = array( $folder_id ); + $ancestors = get_ancestors( $folder_id, 'media-folder', 'taxonomy' ); + + if ( is_array( $ancestors ) ) { + $ids = array_merge( $ids, $ancestors ); + } + + foreach ( $ids as $id ) { + $locked_raw = get_term_meta( $id, 'locked', true ); + + if ( '1' === $locked_raw || 1 === $locked_raw || true === $locked_raw || 'true' === $locked_raw ) { + return true; + } + } + + return false; + } + /** * Get folder information with attachment count * diff --git a/inc/classes/rest-api/class-media-library.php b/inc/classes/rest-api/class-media-library.php index dc0ad11b87..3bb2026a34 100644 --- a/inc/classes/rest-api/class-media-library.php +++ b/inc/classes/rest-api/class-media-library.php @@ -39,17 +39,18 @@ class Media_Library extends Base { /** * Setup hooks. * - * Adds the base REST-route registration plus a server-side guard that enforces - * folder "locked" state on the NATIVE wp/v2/media-folder term endpoints (rename, - * delete, re-parent, create-under). Locking was previously enforced only in React, - * so a direct REST call could still mutate a locked folder. + * Adds the base REST-route registration plus the server-side rules for the NATIVE + * wp/v2/media-folder term endpoints: who may use them, and the folder "locked" state + * (rename, delete, re-parent, create-under). Locking was previously enforced only in + * React, so a direct REST call could still mutate a locked folder. * * @return void */ protected function setup_hooks() { parent::setup_hooks(); - add_filter( 'rest_pre_dispatch', array( $this, 'enforce_locked_media_folder' ), 10, 3 ); + add_filter( 'rest_endpoints', array( $this, 'guard_media_folder_routes' ) ); + add_filter( 'rest_pre_insert_attachment', array( $this, 'enforce_locked_folder_on_media_update' ), 10, 2 ); // Background builder for folder-ZIP downloads (see download_folder()). Runs via // Action Scheduler when available, otherwise WP-Cron — both invoke this hook. @@ -57,42 +58,91 @@ protected function setup_hooks() { } /** - * Reject mutating REST requests against locked media-folder terms. + * Put the media-folder term routes behind check_media_folder_request(). * - * Runs before dispatch on the native taxonomy routes: + * The check is attached to the routes' own permission callbacks rather than matched + * against the requested path, so it runs however the request reaches them (any letter + * case, `?rest_route=`, a batch request, an embed). + * + * @since n.e.x.t + * + * @param array $endpoints The registered REST routes, keyed by route. + * @return array The routes, with the media-folder handlers wrapped. + */ + public function guard_media_folder_routes( $endpoints ) { + $base = rest_get_route_for_taxonomy_items( Media_Folders::SLUG ); + + if ( '' === $base || ! is_array( $endpoints ) ) { + return $endpoints; + } + + foreach ( $endpoints as $route => $handlers ) { + // The collection route and the single-term route. + if ( $route !== $base && 0 !== strpos( $route, $base . '/' ) ) { + continue; + } + + foreach ( $handlers as $key => $handler ) { + // Route options such as `allow_batch` and `schema` sit beside the handlers. + if ( ! is_int( $key ) || ! is_array( $handler ) ) { + continue; + } + + $original = isset( $handler['permission_callback'] ) ? $handler['permission_callback'] : '__return_true'; + + $endpoints[ $route ][ $key ]['permission_callback'] = function ( $request ) use ( $original ) { + $allowed = $this->check_media_folder_request( $request ); + + return is_wp_error( $allowed ) ? $allowed : call_user_func( $original, $request ); + }; + } + } + + return $endpoints; + } + + /** + * Check a request to the native media-folder term routes, before the controller's own permission check. + * + * Reading folders needs `edit_posts` (the gallery block's folder picker runs for anyone + * who writes posts); every other verb needs `upload_files`. Then, on the mutating verbs: * - POST/PUT/PATCH /wp/v2/media-folder/{id} → rename / re-parent an existing folder * - DELETE /wp/v2/media-folder/{id} → delete an existing folder * - POST /wp/v2/media-folder → create a folder (blocked only when the * target parent is locked, i.e. populating it) - * Reads (GET) are always allowed — locking protects against modification, not viewing. + * Reads are always allowed once the user can write posts; locking protects against + * modification, not viewing. + * + * @since n.e.x.t * - * @param mixed $result Pre-dispatch result (non-null short-circuits the request). - * @param \WP_REST_Server $server Server instance (unused). * @param \WP_REST_Request $request The request being dispatched. - * @return mixed Original $result, or a 403 WP_Error when the target folder is locked. + * @return true|\WP_Error True to carry on to the controller's own check, or a WP_Error + * (401/403) when the user may not use the routes or the target + * folder is locked. */ - public function enforce_locked_media_folder( $result, $server, $request ) { - // Let an already short-circuited result (e.g. another plugin's error) stand. - if ( null !== $result ) { - return $result; - } + public function check_media_folder_request( $request ) { + $is_write = in_array( $request->get_method(), array( 'POST', 'PUT', 'PATCH', 'DELETE' ), true ); - // Only guard the native media-folder collection or a single term. - if ( ! preg_match( '#^/wp/v2/media-folder(?:/(\d+))?$#', $request->get_route(), $matches ) ) { - return $result; + // Anyone who writes posts can read folders (the gallery block's folder picker); changing them needs upload rights. + if ( ! current_user_can( $is_write ? 'upload_files' : 'edit_posts' ) ) { + return new \WP_Error( + 'rest_forbidden', + __( 'Sorry, you are not allowed to access media folders.', 'godam' ), + array( 'status' => rest_authorization_required_code() ) + ); } - // Only mutating verbs. - if ( ! in_array( $request->get_method(), array( 'POST', 'PUT', 'PATCH', 'DELETE' ), true ) ) { - return $result; + if ( ! $is_write ) { + return true; } - $term_id = isset( $matches[1] ) ? (int) $matches[1] : 0; + // Read the id the way the controller does: a body or query `id` outranks the one in the URL. + $term_id = (int) $request->get_param( 'id' ); // Renaming / re-parenting / deleting a locked folder (or a child of one). A // bookmark toggle is a personal flag rather than a modification of the folder's // protected content, so it is still allowed on a locked folder. - if ( $term_id > 0 && $this->is_folder_locked( $term_id ) && ! $this->is_bookmark_only_folder_update( $request, $term_id ) ) { + if ( $term_id > 0 && Media_Folder_Utils::get_instance()->is_folder_locked( $term_id ) && ! $this->is_bookmark_only_folder_update( $request, $term_id ) ) { return new \WP_Error( 'godam_folder_locked', __( 'This folder is locked and cannot be modified.', 'godam' ), @@ -104,7 +154,7 @@ public function enforce_locked_media_folder( $result, $server, $request ) { if ( 'DELETE' !== $request->get_method() ) { $new_parent = $request->get_param( 'parent' ); - if ( ! is_null( $new_parent ) && (int) $new_parent > 0 && $this->is_folder_locked( (int) $new_parent ) ) { + if ( ! is_null( $new_parent ) && (int) $new_parent > 0 && Media_Folder_Utils::get_instance()->is_folder_locked( (int) $new_parent ) ) { return new \WP_Error( 'godam_folder_locked', __( 'The destination folder is locked and cannot be modified.', 'godam' ), @@ -113,7 +163,57 @@ public function enforce_locked_media_folder( $result, $server, $request ) { } } - return $result; + return true; + } + + /** + * Refuse a core media update that takes a file out of a locked folder. + * + * Moving a file INTO a locked folder is already refused by the `assign_term` + * capability check (see Media_Folders::lock_folder_assignment()). Moving one OUT is + * not a capability check in core: the media route replaces the file's folders with the + * `media-folder` field it was sent, which empties the locked folder. Same rule as the + * assign-folder route. + * + * @since n.e.x.t + * + * @param \stdClass|\WP_Error $prepared_post The attachment about to be saved. + * @param \WP_REST_Request $request The request being dispatched. + * @return \stdClass|\WP_Error The attachment, or a 403 WP_Error when it would leave a locked folder. + */ + public function enforce_locked_folder_on_media_update( $prepared_post, $request ) { + // A new upload has no folder to leave; only an update carries an ID. + if ( is_wp_error( $prepared_post ) || empty( $prepared_post->ID ) ) { + return $prepared_post; + } + + $taxonomy = get_taxonomy( Media_Folders::SLUG ); + $rest_base = ( $taxonomy && ! empty( $taxonomy->rest_base ) ) ? $taxonomy->rest_base : Media_Folders::SLUG; + $requested = $request->get_param( $rest_base ); + + // The request does not touch the file's folders. + if ( null === $requested ) { + return $prepared_post; + } + + $requested = array_map( 'intval', (array) $requested ); + $current = wp_get_object_terms( (int) $prepared_post->ID, Media_Folders::SLUG, array( 'fields' => 'ids' ) ); + + if ( is_wp_error( $current ) ) { + return $prepared_post; + } + + foreach ( $current as $current_folder_id ) { + if ( ! in_array( (int) $current_folder_id, $requested, true ) && Media_Folder_Utils::get_instance()->is_folder_locked( $current_folder_id ) ) { + return new \WP_Error( + 'godam_folder_locked', + __( 'One or more attachments belong to a locked folder and cannot be moved.', 'godam' ), + array( 'status' => 403 ) + ); + } + } + + return $prepared_post; } /** @@ -910,7 +1010,7 @@ public function assign_images_to_folder( $request ) { if ( is_array( $current_folders ) ) { foreach ( $current_folders as $current_folder_id ) { - if ( (int) $current_folder_id !== (int) $folder_term_id && $this->is_folder_locked( $current_folder_id ) ) { + if ( (int) $current_folder_id !== (int) $folder_term_id && Media_Folder_Utils::get_instance()->is_folder_locked( $current_folder_id ) ) { return new \WP_Error( 'godam_folder_locked', __( 'One or more attachments belong to a locked folder and cannot be moved.', 'godam' ), @@ -947,7 +1047,7 @@ public function assign_images_to_folder( $request ) { } // Assigning attachments into a locked folder (or a child of one) populates it — reject. - if ( $this->is_folder_locked( $folder_term_id ) ) { + if ( Media_Folder_Utils::get_instance()->is_folder_locked( $folder_term_id ) ) { return new \WP_Error( 'godam_folder_locked', __( 'This folder is locked and cannot be modified.', 'godam' ), @@ -1752,7 +1852,7 @@ public function bulk_delete_folders( $request ) { // Reject the whole request if any target is locked (or a child of a locked folder), // so a direct API call can't delete a protected folder — and we never partially delete. foreach ( $folder_ids as $folder_id ) { - if ( is_numeric( $folder_id ) && (int) $folder_id > 0 && $this->is_folder_locked( $folder_id ) ) { + if ( is_numeric( $folder_id ) && (int) $folder_id > 0 && Media_Folder_Utils::get_instance()->is_folder_locked( $folder_id ) ) { return new \WP_Error( 'godam_folder_locked', __( 'One or more selected folders are locked and cannot be deleted.', 'godam' ), @@ -1819,43 +1919,6 @@ public function bulk_delete_folders( $request ) { } } - /** - * Whether a media-folder term is locked, directly or through an ancestor. - * - * Folder locking is protective: a locked folder shields itself AND all of its - * descendants from mutation. So a folder counts as locked if its own `locked` - * term-meta is truthy or if any of its ancestors' is. Client-side gating (React) - * is UX only; this is the authoritative server-side check. - * - * @param int $term_id Media-folder term ID. - * @return bool True if the folder or one of its ancestors is locked. - */ - private function is_folder_locked( $term_id ) { - $term_id = (int) $term_id; - - if ( $term_id <= 0 ) { - return false; - } - - // The term itself plus every ancestor — a locked ancestor locks the branch. - $ids = array( $term_id ); - $ancestors = get_ancestors( $term_id, 'media-folder', 'taxonomy' ); - - if ( is_array( $ancestors ) ) { - $ids = array_merge( $ids, $ancestors ); - } - - foreach ( $ids as $id ) { - $locked_raw = get_term_meta( $id, 'locked', true ); - - if ( '1' === $locked_raw || 1 === $locked_raw || true === $locked_raw || 'true' === $locked_raw ) { - return true; - } - } - - return false; - } - /** * Update meta status for multiple folders. * This is a helper method used by bulk_update_folder_lock_status and bulk_update_folder_bookmark_status. diff --git a/inc/classes/taxonomies/class-media-folders.php b/inc/classes/taxonomies/class-media-folders.php index 0fbca7d2e3..eeb276bbee 100644 --- a/inc/classes/taxonomies/class-media-folders.php +++ b/inc/classes/taxonomies/class-media-folders.php @@ -7,6 +7,8 @@ namespace RTGODAM\Inc\Taxonomies; +use RTGODAM\Inc\Media_Library\Media_Folder_Utils; + defined( 'ABSPATH' ) || exit; /** @@ -32,6 +34,76 @@ protected function setup_hooks() { parent::setup_hooks(); add_action( 'init', array( $this, 'register_term_meta' ) ); + + // The folder lock, applied where a folder is filled or created rather than on one route. + add_filter( 'map_meta_cap', array( $this, 'lock_folder_assignment' ), 10, 4 ); + add_filter( 'pre_insert_term', array( $this, 'lock_folder_creation' ), 10, 3 ); + } + + /** + * Refuse the `assign_term` capability for a locked folder. + * + * Core asks `assign_term` for each folder a request names before it files an attachment + * there (the media route's `media-folder` field is one such request), so a locked folder, + * or one inside a locked folder, takes no new files for any user. Same rule as the + * assign-folder route. + * + * @since n.e.x.t + * + * @param string[] $caps Primitive capabilities required of the user. + * @param string $cap Capability being checked. + * @param int $user_id The user ID. + * @param array $args Extra arguments; the first is the term ID for term capabilities. + * @return string[] The capabilities, with `do_not_allow` added for a locked folder. + */ + public function lock_folder_assignment( $caps, $cap, $user_id, $args ) { + if ( 'assign_term' !== $cap || empty( $args[0] ) ) { + return $caps; + } + + $term = get_term( (int) $args[0] ); + + if ( ! $term || is_wp_error( $term ) || static::SLUG !== $term->taxonomy ) { + return $caps; + } + + if ( Media_Folder_Utils::get_instance()->is_folder_locked( $term->term_id ) ) { + $caps[] = 'do_not_allow'; + } + + return $caps; + } + + /** + * Refuse a new folder inside a locked folder. + * + * Runs for every way a folder is created, so a locked folder gets no new child + * however the request arrives. + * + * @since n.e.x.t + * + * @param string|\WP_Error $term The term name to add, or a WP_Error from an earlier filter. + * @param string $taxonomy Taxonomy slug. + * @param array|string $args Arguments passed to wp_insert_term(). + * @return string|\WP_Error The term name, or a 403 WP_Error when the parent folder is locked. + */ + public function lock_folder_creation( $term, $taxonomy, $args ) { + if ( static::SLUG !== $taxonomy || is_wp_error( $term ) ) { + return $term; + } + + $args = wp_parse_args( $args ); + $parent = isset( $args['parent'] ) ? (int) $args['parent'] : 0; + + if ( $parent > 0 && Media_Folder_Utils::get_instance()->is_folder_locked( $parent ) ) { + return new \WP_Error( + 'godam_folder_locked', + __( 'The destination folder is locked and cannot be modified.', 'godam' ), + array( 'status' => 403 ) + ); + } + + return $term; } /** diff --git a/tests/bootstrap.php b/tests/bootstrap.php index d8bb9d7a75..8112cb892c 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -525,6 +525,15 @@ function wp_read_video_metadata( $file ) { // phpcs:ignore WordPress.NamingConve } } +// Loaded for MediaFolderLockTest: the folder lock check, the lock rules on the taxonomy +// and the media-folder REST route guard. Each file only declares a class, so requiring +// them runs no WP code. +require_once __DIR__ . '/stubs/media-folder-functions.php'; +require_once dirname( __DIR__ ) . '/inc/classes/media-library/class-media-folder-utils.php'; +require_once dirname( __DIR__ ) . '/inc/classes/taxonomies/class-base.php'; +require_once dirname( __DIR__ ) . '/inc/classes/taxonomies/class-media-folders.php'; +require_once dirname( __DIR__ ) . '/inc/classes/rest-api/class-media-library.php'; + // Helper functions under test (godam_is_supported_document). The file only // declares functions plus a few guarded define()s, so it is safe to load here. require_once dirname( __DIR__ ) . '/inc/helpers/custom-functions.php'; diff --git a/tests/php/MediaFolderLockTest.php b/tests/php/MediaFolderLockTest.php new file mode 100644 index 0000000000..956e475cbc --- /dev/null +++ b/tests/php/MediaFolderLockTest.php @@ -0,0 +1,603 @@ + self::AUTHOR_CAPS, + 'user' => array( 'name' => 'Author' ), + 'terms' => array( + self::OPEN => $this->term( self::OPEN, 0, 'Open' ), + self::LOCKED => $this->term( self::LOCKED, 0, 'Locked' ), + self::CHILD => $this->term( self::CHILD, self::LOCKED, 'Child' ), + self::GRANDCHILD => $this->term( self::GRANDCHILD, self::CHILD, 'Grandchild' ), + self::OTHER => $this->term( self::OTHER, 0, 'Other' ), + 99 => $this->term( 99, 0, 'A category', 'category' ), + ), + 'term_meta' => array( + // Only the top folder carries the lock; the rest are locked through it. + self::LOCKED => array( 'locked' => '1' ), + ), + 'object_terms' => array( + self::IN_LOCKED => array( self::LOCKED ), + self::IN_CHILD => array( self::CHILD ), + self::IN_OPEN => array( self::OPEN ), + ), + ); + } + + /** + * Clear the stubs. + * + * @return void + */ + protected function tearDown(): void { + unset( $GLOBALS['rtgodam_stub'] ); + $GLOBALS['rtgodam_hooks'] = array(); + parent::tearDown(); + } + + /** + * A stubbed term. + * + * @param int $id Term ID. + * @param int $parent_id Parent term ID. + * @param string $name Name. + * @param string $taxonomy Taxonomy slug. + * @return object + */ + private function term( $id, $parent_id, $name, $taxonomy = 'media-folder' ) { + return (object) array( + 'term_id' => $id, + 'taxonomy' => $taxonomy, + 'parent' => $parent_id, + 'name' => $name, + 'slug' => strtolower( $name ), + 'description' => '', + ); + } + + /** + * The REST controller, built without its constructor (which would register routes). + * + * @return Media_Library + */ + private function rest() { + return ( new \ReflectionClass( Media_Library::class ) )->newInstanceWithoutConstructor(); + } + + /** + * The taxonomy, built without its constructor. + * + * @return Media_Folders + */ + private function taxonomy() { + return ( new \ReflectionClass( Media_Folders::class ) )->newInstanceWithoutConstructor(); + } + + /** + * A request to the media-folder routes. A null argument leaves that param out. + * + * @param string $method HTTP method. + * @param int|null $id Folder ID, in the URL or the body. + * @param string|null $name New name. + * @param int|null $parent_id New parent folder. + * @param array|null $meta Term meta, such as `bookmark` and `locked`. + * @return \WP_REST_Request + */ + private function folder_request( $method, $id = null, $name = null, $parent_id = null, $meta = null ) { + $params = array_filter( + array( + 'id' => $id, + 'name' => $name, + 'parent' => $parent_id, + 'meta' => $meta, + ), + static function ( $value ) { + return null !== $value; + } + ); + + return new \WP_REST_Request( $params, $method ); + } + + /** + * The request the folder menu sends to bookmark the locked folder: the whole folder, sent back. + * + * @param string $name Name to send. + * @param int $parent_id Parent to send. + * @param array $meta Term meta to send. + * @return \WP_REST_Request + */ + private function whole_folder_request( $name, $parent_id, $meta ) { + return new \WP_REST_Request( + array( + 'id' => self::LOCKED, + 'name' => $name, + 'slug' => 'locked', + 'description' => '', + 'parent' => $parent_id, + 'meta' => $meta, + ), + 'POST' + ); + } + + /** + * Call the permission callback the guard puts on a route handler. + * + * @param \WP_REST_Request $request The request. + * @param array $spy Filled with the arguments of each call to the original check. + * @param mixed $original What the route's own permission check answers. + * @return mixed + */ + private function permission( $request, &$spy = array(), $original = true ) { + $route = '/wp/v2/media-folder/(?P[\d]+)'; + $endpoints = array( + $route => array( + array( + 'methods' => 'POST, PUT, PATCH', + 'permission_callback' => static function ( $request ) use ( &$spy, $original ) { + $spy[] = $request; + return $original; + }, + ), + ), + ); + + $guarded = $this->rest()->guard_media_folder_routes( $endpoints ); + + return call_user_func( $guarded[ $route ][0]['permission_callback'], $request ); + } + + /** + * Whether a value is the folder-locked refusal. + * + * @param mixed $value Value to test. + * @return bool + */ + private function is_locked_error( $value ) { + return $value instanceof \WP_Error && 'godam_folder_locked' === $value->get_error_code() && array( 'status' => 403 ) === $value->get_error_data(); + } + + /** + * Every way the plugin has stored a lock reads as locked, and nothing else does. + * + * @dataProvider lock_values + * + * @param mixed $stored Stored `locked` term meta. + * @param bool $locked Whether the folder reads as locked. + * @return void + */ + public function test_lock_meta_values( $stored, $locked ) { + $GLOBALS['rtgodam_stub']['term_meta'] = array( + self::OPEN => array( 'locked' => $stored ), + ); + + $this->assertSame( $locked, Media_Folder_Utils::get_instance()->is_folder_locked( self::OPEN ) ); + } + + /** + * @return array + */ + public function lock_values() { + return array( + 'string one' => array( '1', true ), + 'int one' => array( 1, true ), + 'true' => array( true, true ), + 'string true' => array( 'true', true ), + 'empty string' => array( '', false ), + 'string zero' => array( '0', false ), + 'int zero' => array( 0, false ), + 'false' => array( false, false ), + 'string false' => array( 'false', false ), + ); + } + + /** + * A locked folder shields everything inside it, and nothing outside it. + * + * @return void + */ + public function test_a_locked_folder_locks_its_descendants() { + $utils = Media_Folder_Utils::get_instance(); + + $this->assertTrue( $utils->is_folder_locked( self::LOCKED ) ); + $this->assertTrue( $utils->is_folder_locked( self::CHILD ) ); + $this->assertTrue( $utils->is_folder_locked( self::GRANDCHILD ) ); + $this->assertFalse( $utils->is_folder_locked( self::OPEN ) ); + $this->assertFalse( $utils->is_folder_locked( self::OTHER ) ); + $this->assertFalse( $utils->is_folder_locked( 0 ) ); + $this->assertFalse( $utils->is_folder_locked( -4 ) ); + } + + /** + * The taxonomy registers its two lock rules. + * + * @return void + */ + public function test_taxonomy_registers_the_lock_rules() { + $taxonomy = $this->taxonomy(); + $setup = new \ReflectionMethod( Media_Folders::class, 'setup_hooks' ); + $setup->setAccessible( true ); + $setup->invoke( $taxonomy ); + + $this->assertTrue( has_action( 'map_meta_cap', array( $taxonomy, 'lock_folder_assignment' ) ) ); + $this->assertTrue( has_action( 'pre_insert_term', array( $taxonomy, 'lock_folder_creation' ) ) ); + } + + /** + * Filing a file in a locked folder, or one inside it, is refused for every user. + * + * @return void + */ + public function test_assigning_to_a_locked_folder_is_refused() { + foreach ( array( self::LOCKED, self::CHILD, self::GRANDCHILD ) as $folder ) { + $caps = $this->taxonomy()->lock_folder_assignment( array( 'upload_files' ), 'assign_term', 1, array( $folder ) ); + + $this->assertSame( array( 'upload_files', 'do_not_allow' ), $caps, "Folder $folder" ); + } + } + + /** + * Open folders, other taxonomies and other capabilities are left as core mapped them. + * + * @return void + */ + public function test_the_assign_capability_is_untouched_elsewhere() { + $taxonomy = $this->taxonomy(); + $caps = array( 'upload_files' ); + + $this->assertSame( $caps, $taxonomy->lock_folder_assignment( $caps, 'assign_term', 1, array( self::OPEN ) ) ); + $this->assertSame( $caps, $taxonomy->lock_folder_assignment( $caps, 'assign_term', 1, array( self::OTHER ) ) ); + $this->assertSame( $caps, $taxonomy->lock_folder_assignment( $caps, 'assign_term', 1, array( 99 ) ), 'A term of another taxonomy' ); + $this->assertSame( $caps, $taxonomy->lock_folder_assignment( $caps, 'assign_term', 1, array( 12345 ) ), 'A term that does not exist' ); + $this->assertSame( $caps, $taxonomy->lock_folder_assignment( $caps, 'assign_term', 1, array() ) ); + $this->assertSame( $caps, $taxonomy->lock_folder_assignment( $caps, 'edit_term', 1, array( self::LOCKED ) ) ); + $this->assertSame( $caps, $taxonomy->lock_folder_assignment( $caps, 'upload_files', 1, array() ) ); + } + + /** + * A folder cannot be created inside a locked folder or inside one of its descendants. + * + * @return void + */ + public function test_a_folder_cannot_be_created_inside_a_locked_folder() { + foreach ( array( self::LOCKED, self::CHILD, self::GRANDCHILD ) as $parent_id ) { + $result = $this->taxonomy()->lock_folder_creation( 'New', 'media-folder', array( 'parent' => $parent_id ) ); + + $this->assertTrue( $this->is_locked_error( $result ), "Parent $parent_id" ); + } + } + + /** + * Other new folders, other taxonomies and earlier errors pass through. + * + * @return void + */ + public function test_other_new_terms_pass_through() { + $taxonomy = $this->taxonomy(); + + $this->assertSame( 'New', $taxonomy->lock_folder_creation( 'New', 'media-folder', array( 'parent' => self::OPEN ) ) ); + $this->assertSame( 'New', $taxonomy->lock_folder_creation( 'New', 'media-folder', array() ) ); + $this->assertSame( 'New', $taxonomy->lock_folder_creation( 'New', 'media-folder', array( 'parent' => 0 ) ) ); + $this->assertSame( 'New', $taxonomy->lock_folder_creation( 'New', 'media-folder', array( 'parent' => -1 ) ) ); + $this->assertSame( 'New', $taxonomy->lock_folder_creation( 'New', 'category', array( 'parent' => self::LOCKED ) ) ); + + $earlier = new \WP_Error( 'other_plugin', 'Refused earlier' ); + $this->assertSame( $earlier, $taxonomy->lock_folder_creation( $earlier, 'media-folder', array( 'parent' => self::LOCKED ) ) ); + } + + /** + * The guard wraps the collection and single-term routes, and nothing else. + * + * @return void + */ + public function test_the_guard_wraps_only_the_media_folder_routes() { + $original = static function () { + return true; + }; + $handler = array( + 'methods' => 'GET', + 'callback' => '__return_true', + 'permission_callback' => $original, + ); + $single = '/wp/v2/media-folder/(?P[\d]+)'; + $endpoints = array( + '/wp/v2/media-folder' => array( $handler, $handler ), + $single => array( + $handler, + 'allow_batch' => array( 'v1' => true ), + ), + '/wp/v2/media' => array( $handler ), + '/wp/v2/media-folders-sibling' => array( $handler ), + '/wp/v2/categories' => array( $handler ), + ); + + $guarded = $this->rest()->guard_media_folder_routes( $endpoints ); + + $this->assertNotSame( $original, $guarded['/wp/v2/media-folder'][0]['permission_callback'] ); + $this->assertNotSame( $original, $guarded['/wp/v2/media-folder'][1]['permission_callback'] ); + $this->assertNotSame( $original, $guarded[ $single ][0]['permission_callback'] ); + $this->assertSame( array( 'v1' => true ), $guarded[ $single ]['allow_batch'], 'Route options are kept' ); + $this->assertSame( $endpoints['/wp/v2/media'], $guarded['/wp/v2/media'] ); + $this->assertSame( $endpoints['/wp/v2/media-folders-sibling'], $guarded['/wp/v2/media-folders-sibling'] ); + $this->assertSame( $endpoints['/wp/v2/categories'], $guarded['/wp/v2/categories'] ); + } + + /** + * A visitor who is not signed in is refused with a 401, and the route's own check never runs. + * + * @return void + */ + public function test_a_logged_out_visitor_is_refused() { + unset( $GLOBALS['rtgodam_stub']['user'] ); + $GLOBALS['rtgodam_stub']['caps'] = array(); + + foreach ( array( 'GET', 'POST', 'DELETE' ) as $method ) { + $spy = array(); + $result = $this->permission( $this->folder_request( $method, self::OPEN ), $spy ); + + $this->assertInstanceOf( \WP_Error::class, $result, $method ); + $this->assertSame( 'rest_forbidden', $result->get_error_code(), $method ); + $this->assertSame( array( 'status' => 401 ), $result->get_error_data(), $method ); + $this->assertSame( array(), $spy, 'The route check must not run for a refused request' ); + } + } + + /** + * A signed-in user who writes posts (a Contributor) reads folders, for the gallery block's + * folder picker, but cannot change them without upload rights. + * + * @return void + */ + public function test_a_contributor_reads_folders_but_cannot_change_them() { + $GLOBALS['rtgodam_stub']['caps'] = array( 'read', 'edit_posts' ); + + $spy = array(); + $this->assertTrue( $this->permission( $this->folder_request( 'GET', self::OPEN ), $spy ) ); + $this->assertCount( 1, $spy ); + + foreach ( array( 'POST', 'DELETE' ) as $method ) { + $spy = array(); + $result = $this->permission( $this->folder_request( $method, self::OPEN ), $spy ); + + $this->assertInstanceOf( \WP_Error::class, $result, $method ); + $this->assertSame( array( 'status' => 403 ), $result->get_error_data(), $method ); + $this->assertSame( array(), $spy, $method ); + } + } + + /** + * A signed-in user who cannot write posts (a Subscriber) is refused with a 403. + * + * @return void + */ + public function test_a_subscriber_is_refused() { + $GLOBALS['rtgodam_stub']['caps'] = array( 'read' ); + + $spy = array(); + $result = $this->permission( $this->folder_request( 'GET', self::OPEN ), $spy ); + + $this->assertInstanceOf( \WP_Error::class, $result ); + $this->assertSame( array( 'status' => 403 ), $result->get_error_data() ); + $this->assertSame( array(), $spy ); + } + + /** + * Anyone who can upload files reads folders, locked ones included, and the route's own answer stands. + * + * @return void + */ + public function test_an_uploader_reads_folders_and_the_route_check_decides() { + foreach ( array( self::OPEN, self::LOCKED, self::CHILD ) as $folder ) { + $spy = array(); + + $this->assertTrue( $this->permission( $this->folder_request( 'GET', $folder ), $spy ), "Folder $folder" ); + $this->assertCount( 1, $spy ); + } + + $denied = new \WP_Error( 'rest_cannot_update', 'The route said no' ); + $this->assertSame( $denied, $this->permission( $this->folder_request( 'POST', self::OPEN ), $spy, $denied ) ); + } + + /** + * A locked folder, or one inside it, cannot be changed by any of the mutating verbs. + * + * @return void + */ + public function test_a_locked_folder_cannot_be_modified() { + foreach ( array( self::LOCKED, self::CHILD, self::GRANDCHILD ) as $folder ) { + foreach ( array( 'POST', 'PUT', 'PATCH', 'DELETE' ) as $method ) { + $spy = array(); + $result = $this->permission( $this->folder_request( $method, $folder, 'Renamed' ), $spy ); + + $this->assertTrue( $this->is_locked_error( $result ), "$method on $folder" ); + $this->assertSame( array(), $spy, 'The route check must not run for a refused request' ); + } + } + } + + /** + * The id is read the way the controller reads it, so a body id naming a locked folder is caught. + * + * @return void + */ + public function test_the_id_the_controller_acts_on_is_the_one_checked() { + // The controller reads `$request['id']`, where a body or query value outranks the URL's. + $result = $this->permission( $this->folder_request( 'POST', self::LOCKED, 'Hijacked' ) ); + + $this->assertTrue( $this->is_locked_error( $result ) ); + } + + /** + * Moving a folder into a locked folder, or creating one there, is refused. + * + * @return void + */ + public function test_nothing_is_added_to_a_locked_folder() { + $moved = $this->permission( $this->folder_request( 'POST', self::OPEN, null, self::LOCKED ) ); + $this->assertTrue( $this->is_locked_error( $moved ), 'Move an open folder in' ); + + $created = $this->permission( $this->folder_request( 'POST', null, 'New', self::CHILD ) ); + $this->assertTrue( $this->is_locked_error( $created ), 'Create a folder in' ); + } + + /** + * Open folders keep working: rename, move, create and delete reach the route's own check. + * + * @return void + */ + public function test_open_folders_are_unaffected() { + $requests = array( + 'rename' => $this->folder_request( 'POST', self::OPEN, 'Renamed' ), + 'move' => $this->folder_request( 'POST', self::OPEN, null, self::OTHER ), + 'to top' => $this->folder_request( 'POST', self::OPEN, null, 0 ), + 'create' => $this->folder_request( 'POST', null, 'New', self::OPEN ), + 'delete' => $this->folder_request( 'DELETE', self::OPEN ), + ); + + foreach ( $requests as $name => $request ) { + $this->assertTrue( $this->permission( $request ), $name ); + } + } + + /** + * Bookmarking a locked folder, as the folder menu does, is still allowed; changing the lock is not. + * + * @return void + */ + public function test_bookmarking_a_locked_folder_is_allowed_but_not_changing_it() { + $bookmark = $this->permission( $this->whole_folder_request( 'Locked', 0, array( 'bookmark' => true ) ) ); + $this->assertTrue( $bookmark, 'Bookmark with the whole folder sent back' ); + + $only_meta = $this->permission( $this->folder_request( 'POST', self::LOCKED, null, null, array( 'bookmark' => true ) ) ); + $this->assertTrue( $only_meta, 'Bookmark alone' ); + + $unlock = $this->permission( $this->whole_folder_request( 'Locked', 0, array( 'locked' => false ) ) ); + $this->assertTrue( $this->is_locked_error( $unlock ), 'Unlock' ); + + $renamed = $this->permission( $this->whole_folder_request( 'Renamed', 0, array( 'bookmark' => true ) ) ); + $this->assertTrue( $this->is_locked_error( $renamed ), 'Rename with a bookmark' ); + + $moved = $this->permission( $this->whole_folder_request( 'Locked', self::OPEN, array( 'bookmark' => true ) ) ); + $this->assertTrue( $this->is_locked_error( $moved ), 'Move with a bookmark' ); + } + + /** + * A core media update that takes a file out of a locked folder is refused. + * + * @return void + */ + public function test_a_file_cannot_leave_a_locked_folder() { + $cases = array( + 'to no folder' => array( self::IN_LOCKED, array() ), + 'to another folder' => array( self::IN_LOCKED, array( self::OTHER ) ), + 'from a locked child' => array( self::IN_CHILD, array( self::OPEN ) ), + 'as string ids' => array( self::IN_LOCKED, array( (string) self::OTHER ) ), + 'to a folder, not a list' => array( self::IN_LOCKED, self::OTHER ), + ); + + foreach ( $cases as $name => $case ) { + list( $attachment, $folders ) = $case; + + $result = $this->rest()->enforce_locked_folder_on_media_update( + (object) array( 'ID' => $attachment ), + new \WP_REST_Request( array( 'media-folder' => $folders ), 'POST' ) + ); + + $this->assertTrue( $this->is_locked_error( $result ), $name ); + } + } + + /** + * Other core media updates are left alone. + * + * @return void + */ + public function test_other_media_updates_pass_through() { + $rest = $this->rest(); + $request = static function ( $params ) { + return new \WP_REST_Request( $params, 'POST' ); + }; + + $in_locked = (object) array( 'ID' => self::IN_LOCKED ); + $in_open = (object) array( 'ID' => self::IN_OPEN ); + $new = (object) array( 'post_title' => 'New' ); + + $this->assertSame( $in_locked, $rest->enforce_locked_folder_on_media_update( $in_locked, $request( array( 'title' => 'Renamed' ) ) ), 'A request that does not name folders' ); + $this->assertSame( $in_open, $rest->enforce_locked_folder_on_media_update( $in_open, $request( array( 'media-folder' => array( self::OTHER ) ) ) ), 'A file leaving an open folder' ); + $this->assertSame( $in_open, $rest->enforce_locked_folder_on_media_update( $in_open, $request( array( 'media-folder' => array() ) ) ), 'A file taken out of every folder' ); + $this->assertSame( $in_locked, $rest->enforce_locked_folder_on_media_update( $in_locked, $request( array( 'media-folder' => array( self::LOCKED ) ) ) ), 'Naming the folder it is already in leaves it there; the assign capability decides that case' ); + $this->assertSame( $new, $rest->enforce_locked_folder_on_media_update( $new, $request( array( 'media-folder' => array( self::OPEN ) ) ) ), 'A new upload has no folder to leave' ); + + $earlier = new \WP_Error( 'rest_invalid_param', 'Refused earlier' ); + $this->assertSame( $earlier, $rest->enforce_locked_folder_on_media_update( $earlier, $request( array( 'media-folder' => array() ) ) ) ); + } +} diff --git a/tests/php/MediaUploadLockedFolderTest.php b/tests/php/MediaUploadLockedFolderTest.php new file mode 100644 index 0000000000..7dcda8cd66 --- /dev/null +++ b/tests/php/MediaUploadLockedFolderTest.php @@ -0,0 +1,127 @@ + $id, + 'taxonomy' => 'media-folder', + 'parent' => $parent_id, + ); + }; + + $GLOBALS['rtgodam_stub'] = array( + 'terms' => array( + self::OPEN => $folder( self::OPEN, 0 ), + self::LOCKED => $folder( self::LOCKED, 0 ), + self::CHILD => $folder( self::CHILD, self::LOCKED ), + self::GRANDCHILD => $folder( self::GRANDCHILD, self::CHILD ), + ), + 'term_meta' => array( self::LOCKED => array( 'locked' => '1' ) ), + 'nonce_valid' => true, + 'assigned' => array(), + ); + + $_REQUEST = array( '_wpnonce' => 'media-form-nonce' ); + + // phpcs:disable Squiz.PHP.Eval.Discouraged -- test-only stubs, isolated process. + eval( 'function wp_verify_nonce( $nonce, $action = -1 ) { return ! empty( $GLOBALS["rtgodam_stub"]["nonce_valid"] ); }' ); + eval( 'function wp_unslash( $value ) { return $value; }' ); + eval( 'function wp_set_object_terms( $object_id, $terms, $taxonomy ) { $GLOBALS["rtgodam_stub"]["assigned"][] = array( $object_id, $terms, $taxonomy ); return array(); }' ); + // phpcs:enable Squiz.PHP.Eval.Discouraged + } + + /** + * Run the upload handler for a request that names $folder. + * + * @param mixed $folder Value of the `media-folder` request field. + * @return array The files filed so far: array( attachment, term, taxonomy ) per call. + */ + private function upload_into( $folder ) { + $_REQUEST['media-folder'] = $folder; + + $ajax = ( new \ReflectionClass( Media_Library_Ajax::class ) )->newInstanceWithoutConstructor(); + $ajax->add_media_library_taxonomy_on_media_upload( self::ATTACHMENT ); + + return $GLOBALS['rtgodam_stub']['assigned']; + } + + /** + * An upload that names an open folder is filed there. + * + * @return void + */ + public function test_an_upload_is_filed_in_an_open_folder() { + $this->assertSame( + array( array( self::ATTACHMENT, self::OPEN, 'media-folder' ) ), + $this->upload_into( (string) self::OPEN ) + ); + } + + /** + * An upload that names a locked folder, or one inside it, is not filed there. + * + * @return void + */ + public function test_an_upload_is_not_filed_in_a_locked_folder() { + foreach ( array( self::LOCKED, self::CHILD, self::GRANDCHILD ) as $folder ) { + $this->assertSame( array(), $this->upload_into( (string) $folder ), "Folder $folder" ); + } + } + + /** + * The checks that were there before the lock still leave an upload unfiled. + * + * @return void + */ + public function test_an_upload_is_not_filed_without_a_valid_folder_and_nonce() { + $this->assertSame( array(), $this->upload_into( '0' ), 'No folder' ); + $this->assertSame( array(), $this->upload_into( '-3' ), 'Negative id' ); + $this->assertSame( array(), $this->upload_into( '404' ), 'A folder that does not exist' ); + + $GLOBALS['rtgodam_stub']['nonce_valid'] = false; + $this->assertSame( array(), $this->upload_into( (string) self::OPEN ), 'Without a valid nonce' ); + } +} diff --git a/tests/stubs/class-wp-rest-request.php b/tests/stubs/class-wp-rest-request.php index 158e0a511e..6cdcaaeafa 100644 --- a/tests/stubs/class-wp-rest-request.php +++ b/tests/stubs/class-wp-rest-request.php @@ -23,11 +23,27 @@ class WP_REST_Request { */ private $params; + /** + * HTTP method. + * + * @var string + */ + private $method; + /** * @param array $params Request params. + * @param string $method HTTP method. */ - public function __construct( array $params = array() ) { + public function __construct( array $params = array(), $method = 'GET' ) { $this->params = $params; + $this->method = $method; + } + + /** + * @return string The HTTP method. + */ + public function get_method() { + return $this->method; } /** diff --git a/tests/stubs/media-folder-functions.php b/tests/stubs/media-folder-functions.php new file mode 100644 index 0000000000..1786d68394 --- /dev/null +++ b/tests/stubs/media-folder-functions.php @@ -0,0 +1,116 @@ + object( term_id, taxonomy, parent, name, slug, description ); + * - `term_meta` term id => array( meta key => value ); + * - `object_terms` object id => list of term ids; + * - `user` set for a signed-in user, unset for a logged-out visitor. + * + * All guarded so a real WP test bootstrap that already defines these wins. + * + * @package GoDAM + */ + +if ( ! function_exists( 'get_term' ) ) { + + /** + * @param int $term_id Term ID. + * @param string $taxonomy Taxonomy the term must belong to; any when empty. + * @return object|null The stubbed term, or null when there is none. + */ + function get_term( $term_id, $taxonomy = '' ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- stub mirroring the WP function. + $term = $GLOBALS['rtgodam_stub']['terms'][ (int) $term_id ] ?? null; + + if ( $term && '' !== $taxonomy && $taxonomy !== $term->taxonomy ) { + return null; + } + + return $term; + } +} + +if ( ! function_exists( 'get_term_meta' ) ) { + + /** + * @param int $term_id Term ID. + * @param string $key Meta key. + * @param bool $single Ignored; always single-value semantics. + * @return mixed The stubbed value, or '' when there is none. + */ + function get_term_meta( $term_id, $key = '', $single = false ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound, Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- stub mirroring the WP function. + $meta = $GLOBALS['rtgodam_stub']['term_meta'][ (int) $term_id ] ?? array(); + + return array_key_exists( $key, $meta ) ? $meta[ $key ] : ''; + } +} + +if ( ! function_exists( 'get_ancestors' ) ) { + + /** + * @param int $object_id Term ID. + * @param string $object_type Ignored. + * @param string $resource_type Ignored. + * @return int[] Parent IDs, nearest first. + */ + function get_ancestors( $object_id, $object_type = '', $resource_type = '' ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound, Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- stub mirroring the WP function. + $ancestors = array(); + $term = get_term( $object_id ); + + while ( $term && $term->parent > 0 && ! in_array( (int) $term->parent, $ancestors, true ) ) { + $ancestors[] = (int) $term->parent; + $term = get_term( $term->parent ); + } + + return $ancestors; + } +} + +if ( ! function_exists( 'wp_get_object_terms' ) ) { + + /** + * @param int $object_id Object ID. + * @param string|array $taxonomy Ignored. + * @param array $args Ignored; term IDs are always returned. + * @return int[] + */ + function wp_get_object_terms( $object_id, $taxonomy = '', $args = array() ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound, Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- stub mirroring the WP function. + return $GLOBALS['rtgodam_stub']['object_terms'][ (int) $object_id ] ?? array(); + } +} + +if ( ! function_exists( 'get_taxonomy' ) ) { + + /** + * @param string $taxonomy Taxonomy slug. + * @return object The taxonomy, with its REST base set to its slug. + */ + function get_taxonomy( $taxonomy ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- stub mirroring the WP function. + return (object) array( + 'name' => $taxonomy, + 'rest_base' => $taxonomy, + ); + } +} + +if ( ! function_exists( 'rest_get_route_for_taxonomy_items' ) ) { + + /** + * @param string $taxonomy Taxonomy slug. + * @return string The core namespace plus the slug, as core builds it. + */ + function rest_get_route_for_taxonomy_items( $taxonomy ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- stub mirroring the WP function. + return '/wp/v2/' . $taxonomy; + } +} + +if ( ! function_exists( 'rest_authorization_required_code' ) ) { + + /** + * @return int 403 for a signed-in user, 401 for a visitor. + */ + function rest_authorization_required_code() { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- stub mirroring the WP function. + return is_user_logged_in() ? 403 : 401; + } +} From 18edf5aa454e26b81e3cbb57ce3f87b46ba60290 Mon Sep 17 00:00:00 2001 From: Subodh Rajpopat Date: Fri, 23 Oct 2026 15:01:34 +0530 Subject: [PATCH 2/4] Check the media folder capability with a fixed capability name per verb --- inc/classes/rest-api/class-media-library.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/inc/classes/rest-api/class-media-library.php b/inc/classes/rest-api/class-media-library.php index 3bb2026a34..fe8e61b8c2 100644 --- a/inc/classes/rest-api/class-media-library.php +++ b/inc/classes/rest-api/class-media-library.php @@ -124,7 +124,9 @@ public function check_media_folder_request( $request ) { $is_write = in_array( $request->get_method(), array( 'POST', 'PUT', 'PATCH', 'DELETE' ), true ); // Anyone who writes posts can read folders (the gallery block's folder picker); changing them needs upload rights. - if ( ! current_user_can( $is_write ? 'upload_files' : 'edit_posts' ) ) { + $can_use_route = $is_write ? current_user_can( 'upload_files' ) : current_user_can( 'edit_posts' ); + + if ( ! $can_use_route ) { return new \WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to access media folders.', 'godam' ), From f05e596239e396936ec526fb5f5d9b3d50bf11a7 Mon Sep 17 00:00:00 2001 From: Subodh Rajpopat Date: Mon, 26 Oct 2026 10:56:03 +0530 Subject: [PATCH 3/4] Keep media folder names out of the post classes shown to visitors Core adds a media-folder- class for each folder an attachment is in, and the media route's class_list and attachment pages show those classes to logged-out visitors. Folder slugs are folder names, so leave the taxonomy out of the post classes. --- .../taxonomies/class-media-folders.php | 21 +++++++++++++++++ tests/php/MediaFolderLockTest.php | 23 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/inc/classes/taxonomies/class-media-folders.php b/inc/classes/taxonomies/class-media-folders.php index eeb276bbee..a234da9064 100644 --- a/inc/classes/taxonomies/class-media-folders.php +++ b/inc/classes/taxonomies/class-media-folders.php @@ -38,6 +38,27 @@ protected function setup_hooks() { // The folder lock, applied where a folder is filled or created rather than on one route. add_filter( 'map_meta_cap', array( $this, 'lock_folder_assignment' ), 10, 4 ); add_filter( 'pre_insert_term', array( $this, 'lock_folder_creation' ), 10, 3 ); + + // Folder names are private, so keep them out of the post classes core shows to visitors. + add_filter( 'post_class_taxonomies', array( $this, 'hide_folders_from_post_classes' ) ); + } + + /** + * Leave media folders out of the post classes. + * + * Core adds a `media-folder-` class for each folder an attachment is in, and shows + * those classes to logged-out visitors in the media route's `class_list` and on attachment + * pages. Folder slugs are folder names, which only signed-in users may see. + * + * @since n.e.x.t + * + * @param string[] $taxonomies Taxonomies whose terms become post classes. + * @return string[] The taxonomies, without media folders. + */ + public function hide_folders_from_post_classes( $taxonomies ) { + unset( $taxonomies[ static::SLUG ] ); + + return $taxonomies; } /** diff --git a/tests/php/MediaFolderLockTest.php b/tests/php/MediaFolderLockTest.php index 956e475cbc..5cb9c087e4 100644 --- a/tests/php/MediaFolderLockTest.php +++ b/tests/php/MediaFolderLockTest.php @@ -28,6 +28,7 @@ * @covers \RTGODAM\Inc\Taxonomies\Media_Folders::setup_hooks * @covers \RTGODAM\Inc\Taxonomies\Media_Folders::lock_folder_assignment * @covers \RTGODAM\Inc\Taxonomies\Media_Folders::lock_folder_creation + * @covers \RTGODAM\Inc\Taxonomies\Media_Folders::hide_folders_from_post_classes * @covers \RTGODAM\Inc\REST_API\Media_Library::guard_media_folder_routes * @covers \RTGODAM\Inc\REST_API\Media_Library::check_media_folder_request * @covers \RTGODAM\Inc\REST_API\Media_Library::enforce_locked_folder_on_media_update @@ -290,6 +291,28 @@ public function test_taxonomy_registers_the_lock_rules() { $this->assertTrue( has_action( 'map_meta_cap', array( $taxonomy, 'lock_folder_assignment' ) ) ); $this->assertTrue( has_action( 'pre_insert_term', array( $taxonomy, 'lock_folder_creation' ) ) ); + $this->assertTrue( has_action( 'post_class_taxonomies', array( $taxonomy, 'hide_folders_from_post_classes' ) ) ); + } + + /** + * Folder names stay out of the post classes core shows to visitors. + * + * @return void + */ + public function test_folders_are_left_out_of_post_classes() { + $public = array( + 'category' => 'category', + 'media-folder' => 'media-folder', + 'post_tag' => 'post_tag', + ); + + $this->assertSame( + array( + 'category' => 'category', + 'post_tag' => 'post_tag', + ), + $this->taxonomy()->hide_folders_from_post_classes( $public ) + ); } /** From 74efc160d6f78c0008bb5774a36cbc81aea63e21 Mon Sep 17 00:00:00 2001 From: Subodh Rajpopat Date: Mon, 26 Oct 2026 11:13:11 +0530 Subject: [PATCH 4/4] Set @since to 2.5.1 for the hotfix release --- inc/classes/media-library/class-media-folder-utils.php | 2 +- inc/classes/rest-api/class-media-library.php | 6 +++--- inc/classes/taxonomies/class-media-folders.php | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/inc/classes/media-library/class-media-folder-utils.php b/inc/classes/media-library/class-media-folder-utils.php index c0cfe1342e..9e69059fb3 100644 --- a/inc/classes/media-library/class-media-folder-utils.php +++ b/inc/classes/media-library/class-media-folder-utils.php @@ -266,7 +266,7 @@ public function is_valid_folder( $folder_id ) { * term-meta is truthy or if any of its ancestors' is. Client-side gating (React) * is UX only; this is the authoritative server-side check. * - * @since n.e.x.t + * @since 2.5.1 * * @param int $folder_id Media folder term ID. * @return bool True if the folder or one of its ancestors is locked. diff --git a/inc/classes/rest-api/class-media-library.php b/inc/classes/rest-api/class-media-library.php index fe8e61b8c2..0b76222c0e 100644 --- a/inc/classes/rest-api/class-media-library.php +++ b/inc/classes/rest-api/class-media-library.php @@ -64,7 +64,7 @@ protected function setup_hooks() { * against the requested path, so it runs however the request reaches them (any letter * case, `?rest_route=`, a batch request, an embed). * - * @since n.e.x.t + * @since 2.5.1 * * @param array $endpoints The registered REST routes, keyed by route. * @return array The routes, with the media-folder handlers wrapped. @@ -113,7 +113,7 @@ public function guard_media_folder_routes( $endpoints ) { * Reads are always allowed once the user can write posts; locking protects against * modification, not viewing. * - * @since n.e.x.t + * @since 2.5.1 * * @param \WP_REST_Request $request The request being dispatched. * @return true|\WP_Error True to carry on to the controller's own check, or a WP_Error @@ -177,7 +177,7 @@ public function check_media_folder_request( $request ) { * `media-folder` field it was sent, which empties the locked folder. Same rule as the * assign-folder route. * - * @since n.e.x.t + * @since 2.5.1 * * @param \stdClass|\WP_Error $prepared_post The attachment about to be saved. * @param \WP_REST_Request $request The request being dispatched. diff --git a/inc/classes/taxonomies/class-media-folders.php b/inc/classes/taxonomies/class-media-folders.php index a234da9064..f3ab80e702 100644 --- a/inc/classes/taxonomies/class-media-folders.php +++ b/inc/classes/taxonomies/class-media-folders.php @@ -50,7 +50,7 @@ protected function setup_hooks() { * those classes to logged-out visitors in the media route's `class_list` and on attachment * pages. Folder slugs are folder names, which only signed-in users may see. * - * @since n.e.x.t + * @since 2.5.1 * * @param string[] $taxonomies Taxonomies whose terms become post classes. * @return string[] The taxonomies, without media folders. @@ -69,7 +69,7 @@ public function hide_folders_from_post_classes( $taxonomies ) { * or one inside a locked folder, takes no new files for any user. Same rule as the * assign-folder route. * - * @since n.e.x.t + * @since 2.5.1 * * @param string[] $caps Primitive capabilities required of the user. * @param string $cap Capability being checked. @@ -101,7 +101,7 @@ public function lock_folder_assignment( $caps, $cap, $user_id, $args ) { * Runs for every way a folder is created, so a locked folder gets no new child * however the request arrives. * - * @since n.e.x.t + * @since 2.5.1 * * @param string|\WP_Error $term The term name to add, or a WP_Error from an earlier filter. * @param string $taxonomy Taxonomy slug.