Opened 2 months ago
Closed 2 months ago
#66008 closed defect (bug) (fixed)
unregister_post_type() corrupts the $post_type_meta_caps registry for still-registered post types
| Reported by: | westonruter | Owned by: | westonruter |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.2 |
| Component: | Posts, Post Types | Version: | 4.5 |
| Severity: | normal | Keywords: | has-patch has-unit-tests |
| Cc: | Focuses: |
Description
This issue was discovered while working to fix an error identified by PHPStan.
The unregister_post_type() function removes entries from the global $post_type_meta_caps registry by subtracting every value of the post type's own $cap object. Because that registry is a flat, global map keyed by custom capability name and shared by every post type that resolves to the same name, the subtraction deletes mappings that other, still-registered post types depend on.
The offending code is in WP_Post_Type::remove_rewrite_rules() (class-wp-post-type.php:822-825):
<?php // Remove registered custom meta capabilities. foreach ( $this->cap as $cap ) { unset( $post_type_meta_caps[ $cap ] ); }
The registry is populated by _post_type_meta_capabilities() (post.php:2093-2101), which is far more selective:
<?php foreach ( $capabilities as $core => $custom ) { if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ), true ) ) { $post_type_meta_caps[ $custom ] = $core; } }
...and which only runs at all when map_meta_cap is true (post.php:2076-2078).
The mismatch between the two produces three distinct defects.
1. No ownership tracking: post types sharing a capability_type clobber each other
Two post types registered with the same capability_type resolve to the same meta capability names, so they write the same keys. Unregistering either one deletes the mapping the other still needs.
This is user-visible. With book and magazine both using capability_type => 'publication' and map_meta_cap => true, unregistering book alone leaves magazine registered but breaks capability mapping for its posts.
Once the mapping is gone, map_meta_cap() falls through the default: branch (capabilities.php:839-844) and returns the meta capability verbatim as though it were a primitive. Nobody is granted that primitive, so the check fails closed and the post's own author loses edit access.
Failing closed is the lucky case. A site that has granted the meta capability name to a role directly, which is a common enough mistake, gets the inverse: the ownership and post-status checks (edit_others_*, edit_published_*, edit_private_*) silently disappear from the mapping and the capability becomes unconditional.
2. Removal is unconditional while registration is not
_post_type_meta_capabilities() is only called when map_meta_cap is true, but the removal loop runs for every post type. A post type registered with map_meta_cap => false contributes nothing to the registry, yet still deletes on unregistration. With the default capability_type of post, its $cap->edit_post is literally edit_post, so it wipes core's own entries:
register_post_type( 'gadget', array( 'map_meta_cap' => false ) ); // contributes nothing unregister_post_type( 'gadget' ); // => edit_post, read_post and delete_post are all now missing from $post_type_meta_caps
3. Primitive capabilities are treated as meta capabilities
The loop passes every value in $this->cap to unset(), not just the three meta capabilities that _post_type_meta_capabilities() registers. A post type whose primitive capability value happens to equal another post type's meta capability name will delete it:
register_post_type( 'tome', array( 'capability_type' => 'tome', 'map_meta_cap' => true ) ); register_post_type( 'shelf', array( 'map_meta_cap' => false, 'capabilities' => array( 'edit_posts' => 'edit_tome' ) ) ); unregister_post_type( 'shelf' ); // => edit_tome is missing, while 'tome' is still registered
Steps to reproduce
Save as repro.php and run with wp eval-file repro.php --skip-plugins --skip-themes, or using the built-in wordpress-develop Docker env with repo.php placed in the repo-root: npm --silent run env:cli -- eval-file /var/www/repro.php --skip-plugins --skip-themes.
<?php global $post_type_meta_caps; function _repro_show( $keys ) { global $post_type_meta_caps; $out = array(); foreach ( (array) $keys as $k ) { $out[ $k ] = isset( $post_type_meta_caps[ $k ] ) ? $post_type_meta_caps[ $k ] : '(missing)'; } var_export( $out ); echo "\n"; } echo "==== 1. Post types sharing a capability_type clobber each other ====\n"; register_post_type( 'book', array( 'capability_type' => 'publication', 'map_meta_cap' => true ) ); register_post_type( 'magazine', array( 'capability_type' => 'publication', 'map_meta_cap' => true ) ); echo 'before: '; _repro_show( array( 'edit_publication', 'read_publication', 'delete_publication' ) ); unregister_post_type( 'book' ); echo "after unregister('book'), 'magazine' still registered: "; _repro_show( array( 'edit_publication', 'read_publication', 'delete_publication' ) ); echo "\n---- user-visible effect ----\n"; $uid = wp_insert_user( array( 'user_login' => 'owner' . wp_rand(), 'user_pass' => 'x', 'role' => 'author' ) ); $u = new WP_User( $uid ); foreach ( array( 'edit_publications', 'edit_published_publications', 'publish_publications' ) as $c ) { $u->add_cap( $c ); } $post_id = wp_insert_post( array( 'post_type' => 'magazine', 'post_title' => 'M', 'post_status' => 'publish', 'post_author' => $uid ) ); echo 'owner can edit their own published magazine: '; var_export( user_can( $uid, 'edit_publication', $post_id ) ); // false -- was true before unregister('book') echo "\nmap_meta_cap( 'edit_publication' ): "; var_export( map_meta_cap( 'edit_publication', $uid, $post_id ) ); // array( 'edit_publication' ) -- no longer mapped echo "\n"; wp_delete_post( $post_id, true ); wp_delete_user( $uid ); unregister_post_type( 'magazine' ); echo "\n==== 2. A map_meta_cap=false post type removes entries it never registered ====\n"; _post_type_meta_capabilities( array( 'edit_post' => 'edit_post', 'read_post' => 'read_post', 'delete_post' => 'delete_post' ) ); echo 'before: '; _repro_show( array( 'edit_post', 'read_post', 'delete_post' ) ); register_post_type( 'gadget', array( 'map_meta_cap' => false ) ); unregister_post_type( 'gadget' ); echo "after register+unregister('gadget'): "; _repro_show( array( 'edit_post', 'read_post', 'delete_post' ) ); echo "\n==== 3. Primitive caps are treated as meta caps ====\n"; register_post_type( 'tome', array( 'capability_type' => 'tome', 'map_meta_cap' => true ) ); register_post_type( 'shelf', array( 'map_meta_cap' => false, 'capabilities' => array( 'edit_posts' => 'edit_tome' ) ) ); echo 'before: '; _repro_show( array( 'edit_tome' ) ); unregister_post_type( 'shelf' ); echo "after unregister('shelf'), 'tome' still registered: "; _repro_show( array( 'edit_tome' ) );
Actual vs Expected
-
.txt
old new 7 7 'delete_publication' => 'delete_post', 8 8 ) 9 9 after unregister('book'), 'magazine' still registered: array ( 10 'edit_publication' => ' (missing)',11 'read_publication' => ' (missing)',12 'delete_publication' => ' (missing)',10 'edit_publication' => 'edit_post', 11 'read_publication' => 'read_post', 12 'delete_publication' => 'delete_post', 13 13 ) 14 14 15 15 ---- user-visible effect ---- 16 owner can edit their own published magazine: false16 owner can edit their own published magazine: true 17 17 map_meta_cap( 'edit_publication' ): array ( 18 0 => 'edit_publi cation',18 0 => 'edit_published_publications', 19 19 ) 20 20 21 21 ==== 2. A map_meta_cap=false post type removes entries it never registered ==== … … 25 25 'delete_post' => 'delete_post', 26 26 ) 27 27 after register+unregister('gadget'): array ( 28 'edit_post' => ' (missing)',29 'read_post' => ' (missing)',30 'delete_post' => ' (missing)',28 'edit_post' => 'edit_post', 29 'read_post' => 'read_post', 30 'delete_post' => 'delete_post', 31 31 ) 32 32 33 33 ==== 3. Primitive caps are treated as meta caps ==== … … 35 35 'edit_tome' => 'edit_post', 36 36 ) 37 37 after unregister('shelf'), 'tome' still registered: array ( 38 'edit_tome' => ' (missing)',38 'edit_tome' => 'edit_post', 39 39 )
History
The registry was introduced in r15890 (#14122, 3.1) as part of the first pass at map_meta_cap() support for custom post types. _post_type_meta_capabilities() held it in a static $meta_caps and doubled as its own accessor:
<?php function _post_type_meta_capabilities( $capabilities = null ) { static $meta_caps = array(); if ( null === $capabilities ) return $meta_caps; foreach ( $capabilities as $core => $custom ) { if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) ) $meta_caps[ $custom ] = $core; } }
r36316 (#14761, 4.5) introduced unregister_post_type(). The same changeset replaced the static with the $post_type_meta_caps global, which removed the accessor branch, and added the subtraction loop to the new function. Nothing reconciled the two halves: the writer had always been selective about which capabilities it stored and under what conditions, while the new remover was not. The docblock was left describing an accessor that no longer existed, which is the state it stayed in until this ticket.
r37890 (#36217, 4.6) introduced WP_Post_Type and moved the loop out of unregister_post_type() into WP_Post_Type::remove_rewrite_rules(), where it has sat unchanged since. That move matters on its own: capability bookkeeping ended up inside a method named for rewrite rules. Anyone auditing capability handling greps capabilities.php and map_meta_cap(), not a rewrite method, which is a large part of why the code has survived three rounds of unrelated cleanup.
Proposed fix
Subtraction cannot work against a shared registry: an entry may be owed to any number of registered post types, and nothing records which ones. Rather than reference-count the entries, rebuild the list from the post types that remain.
That means taking the cleanup out of WP_Post_Type::remove_rewrite_rules() entirely, leaving that method to do only what its name says, and rebuilding in unregister_post_type() once the post type has been removed from $wp_post_types. Rebuilding rather than subtracting fixes all three defects at once, because it inherits the writer's own rules instead of trying to invert them: entries are written only for post types with map_meta_cap => true (2), only for the three meta capabilities (3), and an entry shared by several post types survives as long as any one of them is still registered (1).
One thing to watch for in any implementation: remove_rewrite_rules() is called several lines before the post type is unset from $wp_post_types, so a rebuild performed from inside that method would still see the post type it is removing.
Removing the loop also empties tests/phpstan/baselines/foreach.nonIterable.neon, so that baseline file and its includes entry in phpstan.neon.dist can be deleted in the same change.
_post_type_meta_capabilities() itself still carries the vestiges of r36316 described above, and they are worth correcting alongside: the summary describes a return value that no longer exists, $capabilities still defaults to null, and @param string[] leaves the keys untyped when the body clearly wants a map.
See the pull request for the patch and its test coverage.
Notes
Core's own post types are _builtin and cannot be unregistered, so the blast radius is limited to post types registered by plugins and themes, which is precisely where dynamic registration and unregistration happens (test teardown, switch_to_blog(), feature toggles, plugin deactivation routines).
How this was found. The loop carries a foreach.nonIterable PHPStan baseline entry. It came to light while reviewing a proposal to silence that entry with a type cast, which turned out to leave the underlying logic untouched. See the PR for that discussion.
A related typing problem will be addressed as part of #64898: WP_Post_Type::$cap is a bare stdClass and so carries no property types, which puts the capability names beyond the reach of static analysis no matter how the property is documented. Addressing that most likely calls for a PHPStan extension.
🤖 Claude Code Opus 5 was used in the preparation of this ticket.
Change History (2)
This ticket was mentioned in PR #13342 on WordPress/wordpress-develop by @westonruter.
2 months ago
#1
- Keywords has-patch has-unit-tests added
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
unregister_post_type()removes entries from the global$post_type_meta_capslist by subtracting every value of the post type's own$capobject. That list is keyed by *custom* capability name and is shared by every post type resolving to the same name, so the subtraction deletes mappings that other, still-registered post types depend on.Once a mapping is gone,
map_meta_cap()stops translating the meta capability into contextual primitives and returns it verbatim. The ownership and post-status checks (edit_others_*,edit_published_*,edit_private_*) do not become stricter, they disappear from the result entirely, so a post's own author can lose edit access to it.The full analysis, including three distinct defects and a reproduction script, is in Core-66008.
## The fix
Subtraction cannot work against a shared list: an entry may be owed to any number of registered post types, and nothing records which ones. Rather than reference-count the entries, the list is rebuilt from the post types that remain.
The cleanup is removed from
WP_Post_Type::remove_rewrite_rules()entirely, leaving that method to do only what its name says, and the rebuild happens inunregister_post_type()once the post type has been removed from$wp_post_types. Placement matters:remove_rewrite_rules()is called several lines *before* thatunset(), so a rebuild performed from inside it would still see the post type being removed.Rebuilding rather than subtracting fixes all three defects at once, because it inherits the rules of
_post_type_meta_capabilities()instead of trying to invert them. Entries are written only for post types withmap_meta_cap => true, only for the three meta capabilities, and an entry shared by several post types survives as long as any one of them is still registered.Removing the loop also empties
tests/phpstan/baselines/foreach.nonIterable.neon, so that baseline and itsincludesentry inphpstan.neon.distare deleted here too. This supersedes #13079, which proposed silencing that baseline entry with a type cast.## Tests
Four tests in
tests/phpunit/tests/post/types.php, one per defect plus a functional one. Each was confirmed to fail before the fix, on an assertion *after* the unregistration rather than during setup:1) ..._retains_meta_capabilities_shared_with_another_post_type Undefined array key "read_publication" 2) ..._retains_meta_capabilities_when_not_mapping_meta_caps Undefined array key "read_post" 3) ..._retains_meta_capabilities_matching_primitive_capabilities Undefined array key "edit_book" 4) ..._retains_meta_capability_mapping_for_another_post_type - 0 => 'edit_published_publications' + 0 => 'edit_publication'--group post(951 tests) and--group capabilities(789 tests) both pass.## Notes for review
The
$capabilitiesmap handed to_post_type_meta_capabilities()comes fromWP_Post_Type::$cap, a barestdClassthat carries no property types. PHPStan typesget_object_vars()on any object asarray<mixed>regardless of how the object is documented, so the call reports anargument.typeerror at higher rule levels even though the values are always strings at runtime. Narrowing the map at runtime or relaxing what the function documents would both be worse; typing$capwell enough for the analyzer to follow is separate work, tracked in Core-64898.WP_Post_Type::remove_rewrite_rules()is public, so moving the cleanup out of it is technically a behavior change for any caller invoking it directly. A search of public GitHub forremove_rewrite_rules()returns only vendored copies of core's ownpost.php,taxonomy.phpand the two class files, with no third-party call sites at all.Some accompanying documentation fixes to
_post_type_meta_capabilities(), each in its own commit: r36316 removed the branch that returned the list when the function was called with no arguments, but left behind thenulldefault and a summary describing that return value.Trac ticket: Core-66008
Trac ticket: Core-65817
## Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Opus 5
Used for: Investigating the defect and its history, drafting the fix and its tests, and drafting the Trac ticket. The approach, the final implementation and the tests were reviewed, revised and are owned by me.