Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.49% covered (success)
95.49%
127 / 133
50.00% covered (danger)
50.00%
2 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
Restore_Bridge
96.95% covered (success)
96.95%
127 / 131
50.00% covered (danger)
50.00%
2 / 4
32
0.00% covered (danger)
0.00%
0 / 1
 register_routes
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
1
 initiate_restore
96.43% covered (success)
96.43%
54 / 56
0.00% covered (danger)
0.00%
0 / 1
12
 get_restore_status
92.59% covered (success)
92.59%
25 / 27
0.00% covered (danger)
0.00%
0 / 1
9.03
 project_status
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
10
1<?php
2/**
3 * Restore REST bridge — proxies wpcom/v2 /sites/{site}/rewind/restores.
4 *
5 * @package automattic/jetpack-backup-plugin
6 */
7
8namespace Automattic\Jetpack\Backup\V0005\REST;
9
10use Automattic\Jetpack\Connection\Client;
11use WP_Error;
12use WP_REST_Request;
13use WP_REST_Server;
14
15if ( ! defined( 'ABSPATH' ) ) {
16    exit( 0 );
17}
18
19/**
20 * Restore endpoints powering the Restore screen:
21 *   - POST /jetpack/v4/rewind/to/{rewindId}                     → initiate restore
22 *   - GET  /jetpack/v4/rewind/restore/{restoreId}/status        → poll status
23 */
24class Restore_Bridge {
25
26    /**
27     * Register routes.
28     *
29     * @return void
30     */
31    public static function register_routes() {
32        register_rest_route(
33            'jetpack/v4',
34            '/rewind/to/(?P<rewind_id>[A-Za-z0-9.\-]+)',
35            array(
36                'methods'             => WP_REST_Server::CREATABLE,
37                'callback'            => array( __CLASS__, 'initiate_restore' ),
38                'permission_callback' => array( Rest_Controller::class, 'permission_check' ),
39                'args'                => array(
40                    'rewind_id' => array(
41                        'type'     => 'string',
42                        'required' => true,
43                    ),
44                    'types'     => array(
45                        'type'                 => 'object',
46                        // See the download bridge: `object` alone accepts a
47                        // JSON list, because WordPress validates it with
48                        // `is_array()`.
49                        'additionalProperties' => array( 'type' => 'boolean' ),
50                    ),
51                ),
52            )
53        );
54
55        register_rest_route(
56            'jetpack/v4',
57            '/rewind/restore/(?P<restore_id>\d+)/status',
58            array(
59                'methods'             => WP_REST_Server::READABLE,
60                'callback'            => array( __CLASS__, 'get_restore_status' ),
61                'permission_callback' => array( Rest_Controller::class, 'permission_check' ),
62                'args'                => array(
63                    'restore_id' => array(
64                        'type'     => 'integer',
65                        'required' => true,
66                    ),
67                ),
68            )
69        );
70    }
71
72    /**
73     * Initiate a restore.
74     *
75     * Proxies POST wpcom/v2 /sites/{blog_id}/rewind/restores.
76     *
77     * This route exists because the v1 activity-log endpoint this used to
78     * call could never work from wp-admin: the v1 JSON API discards
79     * Jetpack user tokens by design, so `can_rewind()` evaluated an empty
80     * user and every request came back 401. The permission rule is the
81     * same on both — v1 simply had nobody logged in.
82     *
83     * Signed as the user, and that is not incidental: the guard upstream
84     * is `can_rewind()`, which needs `upload_files` and `delete_users`
85     * for a specific user id, so a bare blog token has no capabilities to
86     * evaluate and is rejected. It is also the right answer on its own
87     * terms — a restore is destructive and the activity log names the
88     * person who started it.
89     *
90     * @param WP_REST_Request $request The REST request.
91     * @return \WP_REST_Response|WP_Error
92     */
93    public static function initiate_restore( WP_REST_Request $request ) {
94        $blog_id = Rest_Controller::get_blog_id_or_error();
95        if ( is_wp_error( $blog_id ) ) {
96            return $blog_id;
97        }
98        $rewind_id = (string) $request->get_param( 'rewind_id' );
99        $types     = $request->get_param( 'types' );
100
101        // A supplied `types` that names nothing is refused rather than
102        // dropped, and this is the screen where that matters most: an
103        // absent `types` means every category upstream, so forwarding an
104        // empty selection as an omission would overwrite the live site
105        // with exactly the parts the caller excluded.
106        //
107        // The v2 route this now calls rejects it too, so there are two
108        // lines of defence — but this is the one that matters, since the
109        // other only fires after the request has left the site.
110        if ( Rest_Controller::request_names_no_types( $request ) ) {
111            return new WP_Error(
112                'no_types_selected',
113                __( 'Select at least one item to restore.', 'jetpack-backup-pkg' ),
114                array( 'status' => 400 )
115            );
116        }
117
118        // The rewind id travels in the body, in full. The decimal suffix is
119        // significant — it is passed straight to VaultPress as the backup's
120        // timestamp, and truncating it addresses a different backup than
121        // the reader picked. (`toIntRewindId` belongs to the file-browser
122        // URL family only, whose route regex really is `\d+`.)
123        $request_body = array(
124            'rewindId'     => $rewind_id,
125            // Optional upstream, and it now defaults to false — but both
126            // this dashboard and Calypso have always sent true, so omitting
127            // it would be a silent behaviour change for existing callers.
128            'force_rewind' => true,
129        );
130
131        // Absent when the caller named no categories at all, which is how
132        // a whole-site restore is spelled upstream. Rebuilt as a named map
133        // otherwise — the same contract the download bridge follows.
134        $named_types = Rest_Controller::named_types( $types );
135        if ( ! empty( $named_types ) ) {
136            $request_body['types'] = $named_types;
137        }
138
139        $response = Client::wpcom_json_api_request_as_user(
140            sprintf( '/sites/%d/rewind/restores', $blog_id ),
141            'v2',
142            array( 'method' => 'POST' ),
143            $request_body,
144            'wpcom'
145        );
146
147        if ( is_wp_error( $response ) ) {
148            return Rest_Controller::transport_error( $response, 'restore_initiate_failed' );
149        }
150
151        // Cast because `wp_remote_retrieve_response_code()` hands back
152        // whatever the transport put there, and a numeric string fails the
153        // strict comparison below. On this route that is the worst place to
154        // get it wrong: a restore WordPress.com accepted would be reported
155        // as a failure, and the reader would start a second one. The long
156        // version is on `Rest_Controller::upstream_error()`.
157        $status_code = (int) wp_remote_retrieve_response_code( $response );
158        if ( 200 !== $status_code ) {
159            return Rest_Controller::upstream_error(
160                $response,
161                'restore_initiate_failed',
162                __( 'Could not start the backup restore.', 'jetpack-backup-pkg' )
163            );
164        }
165
166        $decoded = json_decode( wp_remote_retrieve_body( $response ), true );
167        if ( ! is_array( $decoded ) ) {
168            $decoded = array();
169        }
170
171        // `ok` is the success signal, not the presence of an id.
172        //
173        // VaultPress does not reliably echo a restore id back — the
174        // underlying call's documented response is only `{ ok, error }` —
175        // so `restore_id: null` means "queued, id not known yet", which is
176        // a perfectly good outcome. Reading the id as the signal reported
177        // a successfully queued restore as a 500, and could not have
178        // distinguished the two cases anyway: `(int) null` and `(int) 0`
179        // are both `0`.
180        if ( empty( $decoded['ok'] ) ) {
181            $data = array( 'status' => 500 );
182
183            // The `error` beside it is the whole of what went wrong —
184            // "There is already a restore in progress" and its like — and
185            // it was being dropped on the floor, leaving a reader who
186            // cannot start a second restore with no way to learn why.
187            //
188            // It arrives as prose with no machine code beside it, which is
189            // why `upstream_reason()` sorts on shape rather than on which
190            // key a value came from. The v2 route usually turns this
191            // answer into a 500 `rewind_error` before it ever reaches us,
192            // so what this branch catches is the shape upstream does not.
193            $reason = Rest_Controller::upstream_reason( $decoded );
194            if ( ! empty( $reason ) ) {
195                $data['wpcom'] = $reason;
196            }
197
198            return new WP_Error(
199                'restore_initiate_failed',
200                __( 'Could not start the backup restore.', 'jetpack-backup-pkg' ),
201                $data
202            );
203        }
204
205        $restore_id_in = isset( $decoded['restore_id'] ) && null !== $decoded['restore_id']
206            ? (int) $decoded['restore_id']
207            : null;
208
209        return rest_ensure_response(
210            array(
211                // Null is meaningful here and the client branches on it:
212                // the restore is running, and its id has to be recovered
213                // from the restores collection before progress can be
214                // polled.
215                'id'        => $restore_id_in,
216                'rewind_id' => isset( $decoded['rewind_id'] ) ? (string) $decoded['rewind_id'] : $rewind_id,
217            )
218        );
219    }
220
221    /**
222     * WPCOM's restore statuses, mapped to the vocabulary the client uses.
223     *
224     * Two engines write this field and the v2 route serves whichever ran:
225     * a Rewind restore — which is every restore this package starts —
226     * reports `queued | running | finished | fail`, a legacy VaultPress one
227     * `success | success-with-errors | aborted`.
228     *
229     * The Rewind half comes from Calypso's typed contract for this same
230     * endpoint, not from the v1 endpoint's docblock: that list omits
231     * `finished`, so every successful restore once reported `unknown`.
232     *
233     * Mapped here rather than in the client for the same reason the
234     * download bridge derives its own status: the wire vocabulary is
235     * WPCOM's to change, and one place to change it is better than three
236     * string comparisons scattered through a state machine.
237     *
238     * `success-with-errors` is deliberately kept distinct instead of being
239     * folded into either neighbour. A restore that completed but not
240     * cleanly is neither a success the reader should walk away from nor a
241     * failure they should retry blindly.
242     *
243     * @var array<string, string>
244     */
245    private const STATUS_MAP = array(
246        'queued'              => 'queued',
247        'running'             => 'running',
248        'finished'            => 'finished',
249        'fail'                => 'failed',
250        'success'             => 'finished',
251        'success-with-errors' => 'finished-with-errors',
252        'aborted'             => 'aborted',
253    );
254
255    /**
256     * Poll restore status.
257     *
258     * Proxies GET wpcom/v2 /sites/{blog_id}/rewind/restores/{restore_id}.
259     *
260     * Signed `as_blog`, unlike its sibling. Starting a restore is
261     * user-attributed and needs a user token; *watching* one does not —
262     * this route falls through to `is_jetpack_authorized_for_site()`, the
263     * same check the already-registered `GET /jetpack/v4/restores` relies
264     * on. That is a real capability gain rather than a shortcut: progress
265     * now survives the initiating user's session and is visible to any
266     * admin, which is exactly the failure mode where someone closes the
267     * tab mid-restore and can never see the outcome again.
268     *
269     * @param WP_REST_Request $request The REST request.
270     * @return \WP_REST_Response|WP_Error
271     */
272    public static function get_restore_status( WP_REST_Request $request ) {
273        $blog_id = Rest_Controller::get_blog_id_or_error();
274        if ( is_wp_error( $blog_id ) ) {
275            return $blog_id;
276        }
277        $restore_id = (int) $request->get_param( 'restore_id' );
278
279        $response = Client::wpcom_json_api_request_as_blog(
280            sprintf( '/sites/%d/rewind/restores/%d', $blog_id, $restore_id ),
281            'v2',
282            array(),
283            null,
284            'wpcom'
285        );
286
287        if ( is_wp_error( $response ) ) {
288            return Rest_Controller::transport_error( $response, 'restore_status_fetch_failed' );
289        }
290
291        // Cast, as in `initiate_restore()`. Both branches below depend on
292        // it: an uncast `'404'` would miss the queued-restore carve-out as
293        // well as the success test, so the ordinary opening seconds of a
294        // restore would surface as an error.
295        $status_code = (int) wp_remote_retrieve_response_code( $response );
296
297        // A 404 is the normal first answer, not a failure. A restore that
298        // has just been queued is not visible to this route yet, and the
299        // id may not even exist on our side (see `initiate_restore`, where
300        // VaultPress can decline to echo one). Reporting it as an error
301        // would turn the ordinary opening seconds of every restore into a
302        // user-visible failure.
303        //
304        // Reported as `not-found` and never as `queued`, which upstream
305        // also returns: the client reads the two the same way on screen
306        // but must not treat "no record of it" as a sign of life.
307        //
308        // Safe to treat softly only because the upstream route now
309        // answers 502 for an unparseable VaultPress reply — before that, a
310        // 404 could quietly have meant "upstream is down".
311        if ( 404 === $status_code ) {
312            return rest_ensure_response( self::project_status( array(), $restore_id, 'not-found' ) );
313        }
314
315        if ( 200 !== $status_code ) {
316            return Rest_Controller::upstream_error(
317                $response,
318                'restore_status_fetch_failed',
319                __( 'Could not fetch restore progress.', 'jetpack-backup-pkg' )
320            );
321        }
322
323        $body = json_decode( wp_remote_retrieve_body( $response ), true );
324        // The v2 payload is flat. The old nested `restore_status` unwrap is
325        // kept because it is what makes the flat shape work too — the
326        // fallback branch is the live path now, not the defensive one.
327        $status = is_array( $body ) && isset( $body['restore_status'] ) && is_array( $body['restore_status'] )
328            ? $body['restore_status']
329            : ( is_array( $body ) ? $body : array() );
330
331        return rest_ensure_response( self::project_status( $status, $restore_id ) );
332    }
333
334    /**
335     * Shape a restore-status payload for the client.
336     *
337     * @param array       $status   Upstream status fields, possibly empty.
338     * @param int         $fallback Restore id to report when upstream names none.
339     * @param string|null $force    Status to report regardless of the payload.
340     * @return array
341     */
342    private static function project_status( array $status, $fallback, $force = null ) {
343        $raw = isset( $status['status'] ) ? (string) $status['status'] : '';
344
345        if ( null !== $force ) {
346            $mapped = $force;
347        } elseif ( '' === $raw ) {
348            // A record that arrived without a status is queued and has not
349            // started reporting. An empty payload is not a record, and
350            // calling it `queued` would claim upstream is holding a
351            // restore it never mentioned — enough to refuse the reader a
352            // new one. Tested on emptiness rather than on one key, so a
353            // record spelled with fields we do not read still counts.
354            $mapped = empty( $status ) ? 'not-found' : 'queued';
355        } else {
356            // Anything unrecognised is reported as such rather than
357            // guessed at. The client keeps polling through `unknown` under
358            // a bounded cap, so a status WPCOM adds later degrades into a
359            // slower answer instead of a frozen progress bar.
360            $mapped = self::STATUS_MAP[ $raw ] ?? 'unknown';
361        }
362
363        return array(
364            'id'         => isset( $status['restore_id'] ) ? (int) $status['restore_id'] : (int) $fallback,
365            'status'     => $mapped,
366            'progress'   => isset( $status['percent'] ) ? (float) $status['percent'] : 0,
367            'rewind_id'  => isset( $status['rewind_id'] ) ? (string) $status['rewind_id'] : '',
368            'error_code' => isset( $status['error_code'] ) ? (string) $status['error_code'] : '',
369            'message'    => isset( $status['message'] ) ? (string) $status['message'] : '',
370        );
371    }
372}