#66329 closed defect (bug) (fixed)
Revisions endpoint returns meta that isn't revisioned, so restoring a revision in the editor overwrites it
| Reported by: | dlocc | Owned by: | adamsilverstein |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.2 |
| Component: | REST API | Version: | 7.0 |
| Severity: | normal | Keywords: | has-patch has-unit-tests commit needs-dev-note |
| Cc: | Focuses: |
Description
Hey there! I'm report that the block editor's Visual Revisions, new in 7.0, restores a revision by reading it from the REST API and saving its title, excerpt, content and meta onto the post. The meta part is where it goes wrong.
WP_REST_Revisions_Controller returns every show_in_rest meta key registered for the parent post type, read from the revision ID. Only keys with revisions_enabled, or added with the wp_post_revision_meta_keys filter, are ever stored on a revision, so the rest come back as their default, or null when the default doesn't pass the key's schema. The editor then saves those over the post's real values.
Patterns hit this right away, since wp_pattern_sync_status isn't revisioned and only allows partial or unsynced:
- Restoring an unsynced pattern sends
null, which deletes the status, so the pattern quietly becomes synced. - Restoring a synced pattern fails with a 500: "The wp_pattern_sync_status property has an invalid stored value, and cannot be updated to null." The content is already saved by then, so the restore half works and the user sees an error.
On other post types it's silent. Restoring resets every non-revisioned show_in_rest key: strings become '', keys with a registered default get that default, and multi keys are deleted.
The classic revisions screen is fine, because wp_restore_post_revision() only restores the keys from wp_post_revision_meta_keys().
This was reported in Gutenberg as #84809, and @davidsword traced it to this endpoint. The editor can't tell which keys are revisioned, since revisions_enabled isn't exposed over REST, so the fix needs to happen here.
Steps to reproduce
- Register a meta key that isn't revisioned, for example in an mu-plugin:
<?php add_action( 'init', function () { register_post_meta( 'post', 'kept_meta', array( 'show_in_rest' => true, 'single' => true, 'type' => 'string', ) ); } );
- Create a post and update it a couple of times so it has revisions.
- Give it a value with
wp post meta update <ID> kept_meta hello. - With "Custom fields" turned off in the editor Preferences, so the editor uses Visual Revisions, open Revisions, move to an earlier revision, and click "Restore".
kept_metais now empty.
GET /wp/v2/posts/<ID>/revisions/<revision ID>?context=edit shows "kept_meta": "" even though nothing is stored on the revision. The steps for patterns are in the Gutenberg issue.
Proposed fix
Have the revisions endpoint only return, and only describe in its schema, the meta keys from wp_post_revision_meta_keys() for the parent post type. That matches what's stored on a revision and what the classic restore does, and the editor doesn't need a change. Autosave responses are built by the revisions controller, so they'd follow too, and autosaves only store revisioned keys anyway.
I have a patch with tests and will link the PR here.
Change History (16)
This ticket was mentioned in PR #14359 on WordPress/wordpress-develop by @dlocc.
4 weeks ago
#1
- Keywords has-patch has-unit-tests added
@talldanwp commented on PR #14359:
4 weeks ago
#3
I've added some extra reviewers (REST API component maintainers and contributors to https://core.trac.wordpress.org/ticket/20564)
@adamsilverstein commented on PR #14359:
3 weeks ago
#4
A plugin that writes meta onto revisions itself, without revisions_enabled or the filter, would stop seeing those keys in revision responses.
It might be worth seeing if there are any plugins expecting this behavior or trying anyway, https://veloria.dev/ is a good resource for this.
Adding them to wp_post_revision_meta_keys brings them back.
That would also have other consequences though. Might be fine?
@adamsilverstein commented on PR #14359:
3 weeks ago
#5
Thanks for tracking this down @DevinWalker, the restore approach makes sense to me and lines up nicely with wp_restore_post_revision_meta(). A couple of things look worth fixing before this goes in though.
_Claude reviewed the PR and verified each finding with throwaway PHPUnit tests:_
- Autosaving your own draft now drops meta from the response. When the author autosaves their own draft,
create_item()updates the parent post withwp_update_post()instead of creating an autosave, then returnsget_post( $post_id )through the revisions controller. The object is the live post, butWP_REST_Revision_Meta_Fieldsstill filters its meta, so non-revisioned keys disappear from the response.A test with a draft by the current user, a non-revisioned
kept_metaset tohello, and aPOST /wp/v2/posts/<id>/autosaves: the responseidis the post ID andkept_metais inmetaon the base commit, but missing with this PR. The value is still stored, only the response changes.
This matters for the editor: in
saveEntityRecord()(packages/core-data/src/actions.js), whenpersistedRecord.id === updatedRecord.idit replaces the stored record'smetawith the response'smeta. So after every draft autosave, the editor's copy of the post loses its non-revisioned meta. The new autosave test uses the editor-autosaving-someone-else's-post path, so it doesn't catch this.
One way to fix it is to only filter when the object really is a revision:
public function get_value( $object_id, $request ) { if ( 'revision' !== get_post_type( $object_id ) ) { $meta = new WP_REST_Post_Meta_Fields( $this->post_type ); return $meta->get_value( $object_id, $request ); } return parent::get_value( $object_id, $request ); }
With that in place the draft autosave test passes, along with all of
--group 66329and the full revisions and autosaves controller suites (118 tests).
array_flip()fatals if the filter returns a non-array.wp_post_revision_meta_keysis filterable, and a callback returningfalse(eg. to turn meta revisions off) now throwsTypeError: array_flip(): Argument #1 ($array) must be of type array, false givenon PHP 8, so every revision and autosave GET returns a 500. On the base commit the same request returns 200. Something likearray_flip( array_filter( (array) wp_post_revision_meta_keys( $this->post_type ), 'is_string' ) )guards it. Worth noting that_wp_preview_meta_filter()already has the same weakness within_array(), so this is more about not widening it.
- Minor: the autosave schema no longer matches what the endpoint accepts. The autosaves
metaschema now lists only revisioned keys (footnotes,rev_metain testing), while the POST args still come from the posts controller (footnotes,kept_meta,rev_meta), and on the draft path those extra keys really are saved. On the base commit the two matched. Probably fine to leave, but maybe worth a mention in the dev note alongside the plugin back compat item already in the description.Also checked and not issues: older revisions returning the default for a revisioned key that was never stored matches what
wp_restore_post_revision_meta()already does (delete, then copy), and callingwp_create_initial_post_meta()in the pattern test is safe since the test case unregisters all meta keys between tests.
What do you think about scoping the filter to revisions like that? Happy to help test once it's updated.
@dlocc commented on PR #14359:
3 weeks ago
#6
Thanks for the thorough review, @adamsilverstein… and nice catch on the draft autosave path.
- Autosaving your own draft now drops meta from the response.
Fixed with your suggestion. WP_REST_Revision_Meta_Fields::get_value() now reads the post's own meta when the object isn't a revision, and there's a new test for an author autosaving their own draft.
array_flip()fatals if the filter returns a non-array.
Fixed too, with the cast and is_string filter you suggested, plus a test that returns false from wp_post_revision_meta_keys.
- Minor: the autosave schema no longer matches what the endpoint accepts.
I added it to the back compat notes in the description so it makes it into the dev note.
- This only fixes 7.2 and later, but the bug goes back to 7.0, when Visual Revisions shipped.
Agreed. Happy to put up the Gutenberg compat PR in lib/compat/wordpress-7.2/ with the same revision check, and we can keep WordPress/gutenberg#84809 open until it lands.
On plugins that write meta onto revisions, I searched Veloria and found 21 that do it directly. The three biggest (MetForm, YayMail and Visual Composer) read those values back in their own code and, from what I can tell, don't register them for REST, so they shouldn't be affected. You're right that adding keys to wp_post_revision_meta_keys has other effects, since core then copies them on save and restores them from the classic screen. I think that's fine for anyone who wants them in the response, and I noted it in the description.
All of --group 66329, the revisions and autosaves controller tests, and --group restapi pass. Ready for another look when you have time.
@dlocc commented on PR #14359:
3 weeks ago
#8
The Gutenberg compat PR for 7.0 and 7.1 is up: WordPress/gutenberg#85509
@adamsilverstein commented on PR #14359:
2 weeks ago
#12
Draft dev note section for Trac #66329, to go in the 7.2 REST API roundup. The main action item is for plugins that write meta onto revisions.
_Claude read through the changeset and the review thread and drafted this:_
REST API: revision and autosave responses only include revisioned meta
Visual Revisions in the block editor (new in 7.0) restores a revision by reading it from the REST API and saving its
metaonto the post. Before 7.2,WP_REST_Revisions_Controllerreturned everyshow_in_restmeta key registered for the parent post type, read from the revision ID. Only revisioned keys are ever stored on a revision, so every other key came back as its registered default, ornullwhen the default did not pass the key's schema. The restore then wrote those values over the post's real meta.
The visible effects were:
- Restoring an unsynced pattern sent
nullforwp_pattern_sync_status, which deleted the status and made the pattern synced.- Restoring a synced pattern failed with a
rest_invalid_stored_valueerror after the content had already been saved.- On other post types, non-revisioned
show_in_restkeys were silently reset.The classic revisions screen was never affected, because
wp_restore_post_revision()only restores the keys fromwp_post_revision_meta_keys(). The editor cannot tell which keys are revisioned, sincerevisions_enabledis not exposed over REST, so the fix had to happen in the endpoint (#66329).
What changed in 7.2
The new
WP_REST_Revision_Meta_Fieldsclass, a subclass ofWP_REST_Post_Meta_Fields, limits a revision'smetaresponse and themetaproperty of the schema to the keys returned bywp_post_revision_meta_keys()for the parent post type.WP_REST_Revisions_Controlleruses it for its$metaproperty, so no editor change is needed. Keys registered with a customshow_in_restname are handled the same way.
- Autosave responses follow the same rules, because the revisions controller prepares them. Autosave requests still accept all of the parent post type's meta.
- When an author autosaves their own draft, the autosaves controller updates the post itself and returns it instead of an autosave. That response still includes all of the post's meta.
- Anything returned by the
wp_post_revision_meta_keysfilter that is not a string is ignored.What plugin developers should check
A meta key is revisioned when it is registered with
revisions_enabledset totrue, or when it is added with thewp_post_revision_meta_keysfilter.
register_post_meta( 'post', 'my_meta', array( 'show_in_rest' => true, 'single' => true, 'type' => 'string', 'revisions_enabled' => true, ) );
For meta that is registered elsewhere, or by code that cannot be changed, use the filter:
add_filter( 'wp_post_revision_meta_keys', static function ( array $keys ): array { $keys[] = 'my_meta'; return $keys; } );
- Plugins that write meta onto revisions directly, without either of the above, will no longer see those keys in REST revision and autosave responses. Adding the key to
wp_post_revision_meta_keysbrings it back. Note that this also makes the key part of what the classic screen restores, so it is worth confirming that is wanted.- Clients that read revision meta over REST should expect non-revisioned keys to be absent, rather than present with a default value. The
metaschema for revisions shrinks to match.- Code that subclasses or inspects the controller's
$metaproperty now finds aWP_REST_Revision_Meta_Fieldsinstance. It still extendsWP_REST_Post_Meta_Fields.For sites on the Gutenberg plugin
A compat change in Gutenberg (#85509, merged) applies the same filtering for sites running the plugin on WordPress 7.0 and 7.1.
Related: r64731, #14359, Gutenberg #84809.
Props to @dlocc, @davidsword, @talldanwp, @rachelbaker, @prasadkarmalkar, @umeshnevase and @adamsilverstein.
@adamsilverstein commented on PR #14359:
2 weeks ago
#13
Second part of the REST API dev note for 7.2, added here so the whole note lives on one PR. The revision meta section (#66329) is in the comment above, and the sections for #63982 and #46992 follow.
_Claude read both changesets and the ticket history, and drafted these sections:_
REST API: the comments endpoint accepts multiple statuses
The comments collection endpoint (
/wp/v2/comments) now accepts several statuses in one request.WP_Comment_Queryhas always supported an array of statuses, but the endpoint only accepted a single string, so clients that needed comments in more than one status, such as approved and pending notes, had to make a request for each (#63982).
/wp/v2/comments?status=approve,hold /wp/v2/comments?status[]=approve&status[]=holdSingle status requests work as before, and so does the
allstatus. The permission check is unchanged: unauthenticated requests may only use the defaultapprovestatus, and anything else, including a list that containsapprove, is rejected withrest_forbidden_paramunless the user canedit_posts.
What changed in 7.2
- The
statuscollection parameter is now anarrayof strings, with a default ofarray( 'approve' ), and the route's argument schema says so.- The new
WP_REST_Comments_Controller::sanitize_comment_statuses()accepts a string, a comma-separated list or an array. It sanitizes each value withsanitize_key, removes duplicates and drops empty values. A literal0is kept, because held comments are stored with acomment_approvedvalue of0.- No
enumof allowed values was added.WP_Comment_Querysupports custom comment statuses, so an enum limited to the registered statuses would have broken existing requests.What plugin developers should check
After sanitization,
$request['status']is always an array, and so isstatusin the arguments passed to therest_comment_queryfilter. Code that compared it to a string will no longer match:
// Before: only matches in 7.1 and earlier. if ( 'hold' === $request['status'] ) { // ... } // After: works in 7.1 and in 7.2. if ( in_array( 'hold', (array) $request['status'], true ) ) { // ... }
Clients and tools that read the route's argument schema will see
statusas an array rather than a string.
Related: r64494, #9870, Gutenberg #71271.
Props to @adamsilverstein, @westonruter, @swissspidy, @timothyblynjacobs, @mukesh27 and @wildworks.
REST API: new
rest_allowed_cors_methodsfilterWordPress 7.2 adds a
rest_allowed_cors_methodsfilter for theAccess-Control-Allow-Methodsheader that the REST API sends with cross-origin (CORS) requests. It also stops discarding anAccess-Control-Allow-Methodsvalue set on a REST response (#46992).
The problem
When a request carries an
Originheader,rest_send_cors_headers()sent a hardcoded list of methods:OPTIONS, GET, POST, PUT, PATCH, DELETE. There was no way to change that list short of unhookingrest_send_cors_headers()fromrest_pre_serve_requestand re-implementing it, or hooking in at a later priority and callingheader()directly. Both are fragile, and two plugins doing it will conflict.
Setting the header on the response through
rest_post_dispatch, the usual advice for changing REST response headers, did not work either.rest_send_cors_headers()runs after the response's own headers have been sent, and replaced whatever value the response set.
The two sibling CORS headers have had filters since 5.5:
rest_exposed_cors_headersforAccess-Control-Expose-Headersandrest_allowed_cors_headersforAccess-Control-Allow-Headers. This filter fills in the third.
The new filter
rest_allowed_cors_methodsfollows the same shape as its siblings. It receives the list of methods as an array, along with the request in context, and the result is joined into the header.
/** * @param string[] $allow_methods The list of HTTP methods to allow. * @param WP_REST_Request|null $request The request in context, if available. */ apply_filters( 'rest_allowed_cors_methods', $allow_methods, $request );
Since it is an array, plugins can add to or narrow the list without restating it, and several plugins can do so without stepping on each other.
Advertise an extra method, for example for a route that accepts
PROPFIND:
add_filter( 'rest_allowed_cors_methods', function ( array $methods ): array { $methods[] = 'PROPFIND'; return $methods; } );
Narrow the list for cross-origin requests to a read-only namespace:
add_filter( 'rest_allowed_cors_methods', function ( array $methods, ?WP_REST_Request $request ): array { if ( $request && str_starts_with( $request->get_route(), '/my-plugin/v1/public' ) ) { return array( 'OPTIONS', 'GET' ); } return $methods; }, 10, 2 );
Returning an empty array omits the
Access-Control-Allow-Methodsheader entirely. Entries that are not valid HTTP method tokens are dropped, and a callback that returns something other than an array or a string is ignored in favor of the unfiltered list.
Response values are no longer discarded
If a response sets its own
Access-Control-Allow-Methodsheader, for example fromrest_post_dispatch, that value is now used as the starting list passed to the filter instead of being overwritten by the default:
add_filter( 'rest_post_dispatch', function ( WP_HTTP_Response $response ): WP_HTTP_Response { $response->header( 'Access-Control-Allow-Methods', 'OPTIONS, GET' ); return $response; } );
The filter still runs after that, so a site always has the last word: a callback can keep the response's value, extend it, or replace it. If the response value names no valid methods, the default list is used.
Backward compatibility
The default output is unchanged. A site that neither sets the header on a response nor uses the filter sends the same
OPTIONS, GET, POST, PUT, PATCH, DELETElist as before.
rest_send_cors_headers()gains three optional parameters,$result,$requestand$server, and is now hooked torest_pre_serve_requestwith four accepted arguments. Existing calls with a single argument keep working, andremove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' )still removes it, since the priority is unchanged at 10. When serving a REST request, the CORS headers are now sent throughWP_REST_Server::send_header()rather than a directheader()call.
Edge case:
?_envelope=1With
_envelopeset, the response's headers are moved into the response body beforerest_send_cors_headers()runs, so a value set on the response is not seen and the filtered default is sent. The filter itself still applies.
Related: r64730, #13151, #57752 (the sibling filters gained the
$requestparameter in 6.3).
Props to @moonmeister, @sudar, @timothyblynjacobs, @aaemnnosttv and @westonruter.
@dlocc commented on PR #14359:
2 weeks ago
#15
Thanks for getting this committed, @adamsilverstein, and for wrapping up the last review items on WordPress/gutenberg#85509 as well - I appreciate it.
The dev note looks accurate to me. One small addition for the "What plugin developers should check" list: when a post type has no revisioned meta, a revision's meta is now an empty array ([]) instead of an object with each key's default.
@adamsilverstein commented on PR #14359:
2 weeks ago
#16
The dev note looks accurate to me. One small addition for the "What plugin developers should check" list: when a post type has no revisioned meta, a revision's
metais now an empty array ([]) instead of an object with each key's default.
Thanks, I'll make sure to include that change in the final version.
Visual Revisions in the block editor restores a revision by reading it from the REST API and saving its
metaonto the post. The revisions endpoint returns everyshow_in_restmeta key for the parent post type, read from the revision ID, but only revisioned keys are ever stored on a revision. Everything else comes back as its default, ornullwhen the default doesn't pass the key's schema, and the restore writes that over the post's real values.For patterns,
wp_pattern_sync_statuscomes backnull. Restoring an unsynced pattern deletes the status, so it becomes synced, and restoring a synced pattern fails with "The wp_pattern_sync_status property has an invalid stored value, and cannot be updated to null." after the content has already been saved. On other post types, any non-revisionedshow_in_restkey is quietly reset.Reported in Gutenberg as https://github.com/WordPress/gutenberg/issues/84809, where @davidsword traced it to this endpoint.
What changed
WP_REST_Revision_Meta_Fields, a smallWP_REST_Post_Meta_Fieldssubclass whoseget_registered_fields()only keeps the keys fromwp_post_revision_meta_keys()for the parent post type. That method is where meta keys get mapped to their REST names and schemas, soget_value()andget_field_schema()both follow it, including keys registered with a customshow_in_restname.WP_REST_Revisions_Controlleruses it for$this->meta, so a revision'smetaand themetaschema only include revisioned keys.This lines up with
wp_restore_post_revision(), which only restores those same keys, and the editor doesn't need a change.restoreRevisioncopies whatevermetathe revision has, so it now only sends revisioned keys back.Back compat
metais still there (an object, or[]when nothing is revisioned, same as before), it just stops including keys that were never stored on the revision.wp_post_revision_meta_keysfilter are still included.WP_REST_Autosaves_Controllerprepares its responses and schema through the revisions controller, so autosave responses follow too. Autosaves only store revisioned keys already increate_post_autosave(), and autosave requests are still validated against the parent post type's schema, so what clients can send doesn't change.$metaproperty is still documented asWP_REST_Post_Meta_Fields, so subclasses that use it keep working.metafrom their schema, so neither is affected.revisions_enabledor the filter, would stop seeing those keys in revision responses. Adding them towp_post_revision_meta_keysbrings them back.Testing
New tests in
tests/phpunit/tests/rest-api/rest-revisions-controller.php(9 cases) andtests/phpunit/tests/rest-api/rest-autosaves-controller.php(1 case), all in--group 66329. They cover single revisions, the collection, the schema, autosaves, the filter, custom REST names, and a restore done the same wayrestoreRevisiondoes it for a post and for synced, unsynced and partially synced patterns. The filter test passes on trunk too, since it checks that filtered keys aren't dropped.--group 66329--group restapi--group revisionThe
restapirun has 4 warnings (test_get_items_wdotorg_unavailable,test_create_item_wdotorg_unreachableand the twotest_format_validation_is_applied_if_missing_typetests). They're PHPUnit deprecation notices that show up on trunk too and aren't related to this change.tests/qunit/fixtures/wp-api-generated.jsis regenerated as part of the run. The fixture setup registers ameta_keythat isn't revisioned, so the revision and autosave fixtures now show"meta": []instead of{ "meta_key": "" }.PHPCS and PHPStan are clean on the changed files.
I also ran the restore the way the editor does it (
GETthe revision withcontext=edit, then save its content andmetato the post) against a local trunk install:kept_metaset tohellokept_metais''after restoringhellowp_pattern_sync_statusdeleted, pattern is syncedunsyncedrest_invalid_stored_value, content already restoredManual testing
wp post meta update <ID> kept_meta hello.kept_metais empty.kept_metais stillhello.Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5
Used for: Reproducing the bug, writing the fix and the PHPUnit tests, and drafting this description. I reviewed the code and the test results before opening this PR.