Make WordPress Core

Opened 9 months ago

Closed 8 months ago

Last modified 3 months ago

#64804 closed defect (bug) (fixed)

REST API: Add finalize endpoint to `WP_REST_Attachments_Controller` for client-side media processing

Reported by: adamsilverstein Owned by: adamsilverstein
Priority: normal Milestone: 7.0
Component: REST API Version: 7.0
Severity: normal Keywords: has-patch has-unit-tests dev-reviewed
Cc: Focuses:

Description (last modified by westonruter)

When client-side media processing is active, the editor handles image resizing, thumbnail generation, and format conversion in the browser using WebAssembly. This bypasses the wp_generate_attachment_metadata filter that normally fires during wp_generate_attachment_metadata() in wp-admin/includes/image.php.

Many plugins rely on this filter to post-process uploads — for example, adding watermarks, syncing to a CDN, generating custom image sizes, or updating external indexes. When client-side processing is active, these plugins silently stop working because the filter never fires.

Proposed solution

Add a POST /wp/v2/media/{id}/finalize REST API endpoint to WP_REST_Attachments_Controller. This endpoint:

  1. Retrieves the current attachment metadata
  2. Re-applies the wp_generate_attachment_metadata filter with context 'update'
  3. Saves the (potentially modified) metadata back
  4. Returns the updated attachment object

The endpoint is only registered when wp_is_client_side_media_processing_enabled() returns true, so it has zero impact on sites not using client-side processing.

How it works

The client-side media pipeline calls this endpoint after all operations (upload, thumbnail sideloads, scaled image sideload) are complete. No new hooks are needed — the existing wp_generate_attachment_metadata filter is reused. Plugins that already hook into this filter will work without modification; they can distinguish client-side finalization by checking the $context parameter:

<?php
add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id, $context ) {
    if ( 'update' === $context ) {
        // Called from finalize endpoint after client-side processing.
        my_plugin_process_attachment( $attachment_id, $metadata );
    }
    return $metadata;
}, 10, 3 );

Permissions

The endpoint reuses edit_media_item_permissions_check(), consistent with the existing sideload and edit endpoints. A user must have permission to edit the attachment.

Change History (15)

This ticket was mentioned in ​PR #11168 on ​WordPress/wordpress-develop by ​@adamsilverstein.


9 months ago
#1

  • Keywords has-unit-tests added

## Summary

  • Adds a POST /wp/v2/media/{id}/finalize REST API endpoint to WP_REST_Attachments_Controller
  • The endpoint triggers the wp_generate_attachment_metadata filter with context 'update' after client-side media processing completes
  • Ensures server-side plugins (watermarking, CDN sync, custom sizes, etc.) can post-process attachments when client-side processing is active
  • Only registered when wp_is_client_side_media_processing_enabled() returns true

## Context

When client-side media processing handles image uploads (resizing, thumbnail generation, format conversion), server-side WordPress hooks like wp_generate_attachment_metadata are bypassed. This endpoint is called after all client-side operations (upload, thumbnail generation, sideloads) are complete, re-triggering the filter so plugins continue to work.

### Hook usage example

add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id, $context ) {
  // $context is 'update' when called from the finalize endpoint.
  if ( 'update' === $context ) {
    // Add watermark, sync to CDN, generate custom sizes, etc.
    my_plugin_process_attachment( $attachment_id, $metadata );
  }
  return $metadata;
}, 10, 3 );

## Changes

File Change
class-wp-rest-attachments-controller.php Add finalize route registration, finalize_item_permissions_check(), and finalize_item() methods
rest-attachments-controller.php (tests) Add tests for finalize endpoint (success, auth required, invalid ID)
rest-schema-setup.php Add finalize route to expected routes list
wp-api-generated.js Add finalize route to API fixtures

## Test plan

  • [ ] Verify finalize endpoint returns 200 with valid attachment
  • [ ] Verify wp_generate_attachment_metadata filter fires with context 'update'
  • [ ] Verify 401 when not authenticated
  • [ ] Verify 404 for invalid attachment ID
  • [ ] Run full REST API test suite

## Related

#2 @westonruter
9 months ago

  • Description modified (diff)

#3 @westonruter
9 months ago

@adamsilverstein Would it not make sense to just call wp_generate_attachment_metadata() after each image size is sideloaded? That way the metadata will be sure to be created even when no finalize request is made (e.g. the client goes offline). Or is the concern that re-generating the metadata each time would cause relevant plugins to do redundant work?

#4 @adamsilverstein
9 months ago

My main goal is to match the existing core hook behavior which I believe means firing once at the end of the process. Some plugins may expect all sub sizes to be in place. Worth reviewing how plugins actually use this hook.

#5 @divyeshpatel01
8 months ago

Tested the patch on WordPress trunk.

Applied the patch and verified that the new /wp/v2/media/{id}/finalize endpoint works correctly.

Confirmed that the wp_generate_attachment_metadata filter is trigger with context 'update'.

Unit tests pass and functionality works as expected.

#6 @adamsilverstein
8 months ago

  • Keywords commit added

#7 @adamsilverstein
8 months ago

  • Owner set to adamsilverstein
  • Resolution → fixed
  • Status new → closed

In 61982:

REST API: Add finalize endpoint to WP_REST_Attachments_Controller.

Introduce a POST /wp/v2/media/{id}/finalize REST API endpoint that re-triggers the wp_generate_attachment_metadata filter with context 'update' after client-side media processing completes. This ensures server-side plugins (watermarking, CDN sync, custom sizes, etc.) can post-process attachments when client-side processing is active.

The endpoint reuses edit_media_item_permissions_check for authorization and is only registered when wp_is_client_side_media_processing_enabled() returns true.

See ​https://github.com/WordPress/gutenberg/pull/74913.
See ​https://github.com/WordPress/gutenberg/issues/74358.

Props adamsilverstein, westonruter, mukesh27, divyeshpatel01.
Fixes #64804.

This ticket was mentioned in ​PR #12508 on ​WordPress/wordpress-develop by ​@adamsilverstein.


4 months ago
#8

Core backport of the server-side changes in ​https://github.com/WordPress/gutenberg/pull/80218.

On the client-side media processing path no server-side WP_Image_Editor is instantiated, so the image_strip_meta and image_max_bit_depth filters never influence generated images (see the hooks audit in ​https://github.com/WordPress/gutenberg/issues/80210 and follow-up ​https://github.com/WordPress/gutenberg/issues/80216).

This exposes the filtered values of both hooks on the REST API index inside the existing client-side media processing block in WP_REST_Server::get_index() (alongside image_size_threshold), so the client encoder can honor them:

  • image_strip_meta (bool): when a plugin disables stripping, the client keeps all metadata on generated sub-sizes instead of stripping everything except color profiles.
  • image_max_bit_depth (int): caps the bit depth of client-generated images (relevant for 10/12-bit HDR AVIF sub-sizes). Since the server never decodes the image on this path, the filter is applied with 16 as both the value and the current depth; plugins lowering the cap still take effect.

The client-side consumption of these values ships via the Gutenberg package updates (@wordpress/vips, @wordpress/upload-media, editor settings plumbing) in ​https://github.com/WordPress/gutenberg/pull/80218.

Trac ticket: to be filed (see #64804 for the client-side media processing feature).

​@adamsilverstein commented on ​PR #12508:


4 months ago
#9

Upstream PR has merged, this should be ready.

#10 @adamsilverstein
3 months ago

In 63200:

REST API: Bind finalize sub-size file names to their sideload.

Fix an issue where the finalize endpoint stored the sub-size file names a client sent without confirming a sideloaded image had produced them for that attachment. Those names are later resolved against the attachment's upload directory and read or deleted, so finalize could record a file the upload never created. To address this, the sideload endpoint now records each name it generates under a _wp_sideloaded_file post meta key, and the finalize endpoint accepts a name only when:

  1. a prior sideload recorded it in post meta,
  2. it is the attachment's own attached file, or
  3. it is already stored in the attachment's metadata.

Anything else returns a rest_invalid_sub_size_file error (HTTP 400) before any metadata is written. Sideloads are also pinned to the attachment's own subdirectory via the upload_dir filter, so names are in the directory they later resolve against. Finalize stays safe to repeat: a name already in the attachment's metadata is accepted again.

Follow-up to r61982, r62609.

Reviewed by westonruter.

Props westonruter.
See #64804.

#11 @wildworks
3 months ago

  • Keywords dev-feedback added; commit removed

Reopening #64804 to request backporting [63200] to 7.1 branch

#12 @wildworks
3 months ago

@andrewserong, if you have time, could you check if it's okay to backport r63200 to 7.1?

#13 @andrewserong
3 months ago

  • Keywords dev-reviewed added; dev-feedback removed

Thanks for the ping @wildworks, yes, I've looked over the commit and I think this is good to backport to 7.1.

#14 @wildworks
3 months ago

@andrewserong Thanks for the review! I'll be committing [63200] to the 7.1 branch.

#15 @wildworks
3 months ago

In 63203:

REST API: Bind finalize sub-size file names to their sideload.

Fix an issue where the finalize endpoint stored the sub-size file names a client sent without confirming a sideloaded image had produced them for that attachment. Those names are later resolved against the attachment's upload directory and read or deleted, so finalize could record a file the upload never created. To address this, the sideload endpoint now records each name it generates under a _wp_sideloaded_file post meta key, and the finalize endpoint accepts a name only when:

a prior sideload recorded it in post meta,
it is the attachment's own attached file, or
it is already stored in the attachment's metadata.
Anything else returns a rest_invalid_sub_size_file error (HTTP 400) before any metadata is written. Sideloads are also pinned to the attachment's own subdirectory via the upload_dir filter, so names are in the directory they later resolve against. Finalize stays safe to repeat: a name already in the attachment's metadata is accepted again.

Follow-up to r61982, r62609.

Reviewed by andrewserong.
Merges [63200] to the 7.1 branch.

Props westonruter.
See #64804.

Note: See TracTickets for help on using tickets.