Opened 2 months ago
Closed 2 months ago
#66032 closed defect (bug) (fixed)
Updating a template via the REST API can cause an uncaught fatal error in the templates controller
| Reported by: | ramonopoly | Owned by: | ramonopoly |
|---|---|---|---|
| Priority: | low | Milestone: | 7.2 |
| Component: | REST API | Version: | 7.0 |
| Severity: | normal | Keywords: | has-patch has-unit-tests |
| Cc: | Focuses: |
Description
A ticket to trac the syncing of Gutenberg PR https://github.com/WordPress/gutenberg/pull/82374
Updating a template via the REST API can cause an uncaught fatal error in the templates controller:
Attempt to assign property "content" on null
WP_REST_Templates_Controller::update_item() refetches the template with get_block_template() after writing changes and passes the result to prepare_item_for_response() without checking it. When the refetch returns null — observed in production at line 423; also reachable on the revert path, which force-deletes the post before refetching (line 380) — prepare_item_for_response() fatals reading and assigning $item->content.
Reproduce via the revert path:
POST /wp/v2/templateswith{"slug": "db-only", "title": "T"}(no theme file for the slug).PUT /wp/v2/templates/<theme>//db-onlywith{"source": "theme"}— the post is force-deleted, then the request 500s with the fatal.
Suggested fix: return rest_template_not_found from prepare_item_for_response() for a null template.
Change History (2)
This ticket was mentioned in PR #13375 on WordPress/wordpress-develop by @ramonopoly.
2 months ago
#1
- Keywords has-patch has-unit-tests added
Backports the guard from https://github.com/WordPress/gutenberg/pull/82374.
## What
Prevents an uncaught fatal error (
Attempt to assign property "content" on null) inWP_REST_Templates_Controller::prepare_item_for_response()when it receives anulltemplate.## Why
WP_REST_Templates_Controller::update_item()passes itsget_block_template()refetches toprepare_item_for_response()without checking them, both after writing an update and on its revert-to-theme path, which force-deletes the template's post before checking that a theme or plugin version of the template exists. When a refetch returnsnull, the method fatals reading$item->content.## What changed
prepare_item_for_response()returns arest_template_not_foundWP_Error(404) when the template isnull, instead of crashing.prepare_item_for_response( null, ... )directly, the exact condition that fatals on trunk. Without the guard the call fatals and the run aborts, so the test can only pass through the guard.## Manual testing
The revert path is the easiest way to reach the fatal:
POST /wp/v2/templateswith{ "slug": "db-only", "title": "T", "content": "" }.PUT /wp/v2/templates/<theme>//db-onlywith{ "source": "theme" }.rest_template_not_found.