Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.36% covered (success)
90.36%
75 / 83
66.67% covered (warning)
66.67%
6 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Rest_Controller
91.36% covered (success)
91.36%
74 / 81
66.67% covered (warning)
66.67%
6 / 9
38.93
0.00% covered (danger)
0.00%
0 / 1
 register_routes
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 permission_check
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 get_blog_id_or_error
37.50% covered (danger)
37.50%
3 / 8
0.00% covered (danger)
0.00%
0 / 1
2.98
 named_types
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 request_names_no_types
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 transport_error
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 upstream_error
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 upstream_reason
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
15
 clip_reason
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
1<?php
2/**
3 * REST controller for the modernized Backup dashboard.
4 *
5 * @package automattic/jetpack-backup-plugin
6 */
7
8namespace Automattic\Jetpack\Backup\V0005\REST;
9
10use Automattic\Jetpack\Backup\V0005\Jetpack_Backup;
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Jetpack_Options;
13use WP_Error;
14use WP_REST_Request;
15
16if ( ! defined( 'ABSPATH' ) ) {
17    exit( 0 );
18}
19
20/**
21 * Registers REST routes that back the modernized dashboard.
22 *
23 * Each bridge class declares its routes via `register_routes()` and uses
24 * the shared `permission_check()` helper for the `manage_options` gate.
25 * Routes only register when `is_modernized()` is true, so the
26 * legacy plugin is byte-identical when it is false.
27 */
28class Rest_Controller {
29
30    /**
31     * Every category WPCOM's rewind endpoints recognize in a `types` map.
32     *
33     * The first six are the whole-site checklist the Restore and Download
34     * screens render.
35     *
36     * `paths` covers the granular *download* shape only — `types: { paths:
37     * true }`, paired with `include_path_list` / `exclude_path_list`.
38     * Nothing sends it yet (C3), but leaving it out would make the file
39     * browser's granular download fail closed with a confusing 400 the day
40     * it is wired up.
41     *
42     * It does not carry over to granular *restore*, whatever that ends up
43     * spelling: the v1 route took `types: 'paths'` as a bare string, which
44     * is not a map at all and would never reach this allowlist. Granular
45     * restore has to establish its own shape against the v2 route before
46     * anything here can claim to cover it.
47     *
48     * This list has to grow if VaultPress adds a category. WPCOM's own
49     * route deliberately does not allowlist, so that it stays open to new
50     * types; we can afford to be stricter because we also own the UI that
51     * produces the values, and here a value that names nothing is the
52     * dangerous case rather than merely a useless one.
53     *
54     * @var string[]
55     */
56    private const CATEGORIES = array(
57        'themes',
58        'plugins',
59        'roots',
60        'contents',
61        'sqls',
62        'uploads',
63        'paths',
64    );
65
66    /**
67     * Hook entry point. Registers all bridge routes if `is_modernized()` is true.
68     *
69     * @return void
70     */
71    public static function register_routes() {
72        if ( ! Jetpack_Backup::is_modernized() ) {
73            return;
74        }
75
76        Capabilities_Bridge::register_routes();
77        Activity_Log_Bridge::register_routes();
78        Backup_Sizes_Bridge::register_routes();
79        File_Browser_Bridge::register_routes();
80        Download_Bridge::register_routes();
81        Restore_Bridge::register_routes();
82        Schedule_Bridge::register_routes();
83        Retention_Bridge::register_routes();
84    }
85
86    /**
87     * Permission check shared by every modernized-dashboard route.
88     *
89     * Mirrors the activity-log package's pattern: `manage_options` is
90     * necessary but not sufficient — every bridge eventually proxies a
91     * WPCOM endpoint that's user-gated, so a site admin who isn't
92     * personally WPCOM-linked needs a clearer error than the opaque
93     * "Only Administrators can query…" WPCOM returns.
94     *
95     * @return bool|WP_Error True when the current user can call the bridges, WP_Error otherwise.
96     */
97    public static function permission_check() {
98        if ( ! current_user_can( 'manage_options' ) ) {
99            return false;
100        }
101
102        if ( ! ( new Connection_Manager() )->is_user_connected() ) {
103            return new WP_Error(
104                'user_not_connected',
105                __( 'Your WordPress.com account is not connected to this site.', 'jetpack-backup-pkg' ),
106                array( 'status' => 403 )
107            );
108        }
109
110        return true;
111    }
112
113    /**
114     * Returns the site's WPCOM blog id, or a `not_connected` WP_Error
115     * when the site hasn't been registered yet. Shared across the bridges
116     * so the `sprintf( '/sites/%d/…', $blog_id )` upstream path is never
117     * built with an empty id.
118     *
119     * @return int|WP_Error Blog id, or WP_Error when not connected.
120     */
121    public static function get_blog_id_or_error() {
122        $blog_id = (int) Jetpack_Options::get_option( 'id' );
123        if ( ! $blog_id ) {
124            return new WP_Error(
125                'not_connected',
126                __( 'This site is not connected to Jetpack.', 'jetpack-backup-pkg' ),
127                array( 'status' => 412 )
128            );
129        }
130        return $blog_id;
131    }
132
133    /**
134     * Rebuild a restore/download `types` parameter as a named map.
135     *
136     * The PHP counterpart of the client's `requireTypes`, and the reason
137     * it exists here rather than being trusted from the request: WordPress
138     * validates `'type' => 'object'` with `rest_is_object()`, which is
139     * `is_array()`. A JSON list therefore passes validation and arrives as
140     * a PHP list, whose numeric keys WPCOM reads as category names. The
141     * route schema rejects the realistic version of that, but only because
142     * the members fail a boolean check — shape itself is never asserted —
143     * so the guarantee is made here, where the payload is actually built.
144     *
145     * Only known categories with a truthy value survive, and every
146     * surviving value is normalized to `true`. Values are read with
147     * `rest_sanitize_boolean()` so a form-encoded `"false"` or `"0"` means
148     * skip rather than select.
149     *
150     * Unknown keys are dropped rather than forwarded, which is what makes
151     * `request_names_no_types()` a total guard: without it a payload naming
152     * only categories WPCOM does not recognize would satisfy the guard and
153     * be sent on, and what WPCOM does with a `types` that matches nothing
154     * is not characterized. Dropping them means such a payload names
155     * nothing, and is refused. The realistic way to get there is not an
156     * attacker — an admin who can craft the request can already omit
157     * `types` for a whole-site operation — but a future client-side typo:
158     * renaming a checklist key `sqls` to `sql` would otherwise go through
159     * silently.
160     *
161     * @param mixed $types Raw `types` parameter from the request.
162     * @return array<string, true> Named types, empty when none are selected.
163     */
164    public static function named_types( $types ) {
165        if ( ! is_array( $types ) && ! is_object( $types ) ) {
166            return array();
167        }
168
169        $named = array();
170        foreach ( (array) $types as $key => $value ) {
171            if ( in_array( $key, self::CATEGORIES, true ) && rest_sanitize_boolean( $value ) ) {
172                $named[ $key ] = true;
173            }
174        }
175        return $named;
176    }
177
178    /**
179     * Whether the request supplied a `types` parameter that names no category.
180     *
181     * The distinction this draws is the whole point of the helper, and it
182     * is the opposite of what it looks like. An **absent** `types` is a
183     * valid, deliberate request for every category — WPCOM's contract is
184     * "omit it for everything" — so the mutations leave the key out for a
185     * whole-site restore or a full archive. A **supplied** `types` that
186     * survives into nothing is the other thing entirely: the caller tried
187     * to name categories and named none, and forwarding that as an
188     * omission would quietly upgrade "restore nothing" into "restore
189     * everything", against a live site.
190     *
191     * It takes the request rather than the value because the value cannot
192     * answer the question. `{"types": null}` is supplied and names nothing,
193     * but arrives as the same `null` an omitted key does — and the schema
194     * never sees it, since `WP_REST_Request::has_valid_params()` skips
195     * `validate_callback` for a null param. `has_param()` is the only thing
196     * that knows the key was on the wire.
197     *
198     * Nothing upstream catches it on both routes. The v2 restore route
199     * rejects a `types` naming nothing, but `/rewind/downloads` does not,
200     * so the guarantee has to be made here for the pair to behave alike.
201     *
202     * @param WP_REST_Request $request The REST request.
203     * @return bool True when the caller supplied a `types` that names no category.
204     */
205    public static function request_names_no_types( WP_REST_Request $request ) {
206        if ( ! $request->has_param( 'types' ) ) {
207            return false;
208        }
209
210        return ! self::named_types( $request->get_param( 'types' ) );
211    }
212
213    /**
214     * Convert a transport-level failure into a bridge error.
215     *
216     * `Client::wpcom_json_api_request_as_*` answers with a `WP_Error` when
217     * the request never reached WPCOM at all — DNS, TLS, or the cURL
218     * timeout behind JETPACK-2173's "cURL error 28". Returning that error
219     * unchanged hands cURL's own text to the browser, where the dashboard
220     * renders the message verbatim in a notice; it also carries no
221     * `status`, so core answers 500 for what is really a reachability
222     * problem rather than a server fault.
223     *
224     * The raw text is preserved under `transport` rather than discarded.
225     * It is the only part a support agent can act on, and it is the same
226     * reason the non-200 branches forward WPCOM's status instead of
227     * flattening it.
228     *
229     * Always 502: telling a timeout from a refused connection would mean
230     * matching on cURL's English message text, and no caller reads the
231     * difference.
232     *
233     * @param WP_Error $error Transport error from the HTTP client.
234     * @param string   $code  Bridge error code for the operation that failed.
235     * @return WP_Error
236     */
237    public static function transport_error( WP_Error $error, $code ) {
238        return new WP_Error(
239            $code,
240            __( 'Could not reach WordPress.com. Check your connection and try again.', 'jetpack-backup-pkg' ),
241            array(
242                'status'    => 502,
243                'transport' => array(
244                    'code'    => $error->get_error_code(),
245                    'message' => $error->get_error_message(),
246                ),
247            )
248        );
249    }
250
251    /**
252     * Longest either half of a forwarded upstream reason may be.
253     *
254     * Neither field is bounded upstream and both travel to the browser on
255     * every failed request, so a VaultPress stack trace in `message` would
256     * otherwise be copied out verbatim.
257     *
258     * @var int
259     */
260    private const REASON_MAX_LENGTH = 200;
261
262    /**
263     * Convert a non-200 answer from WordPress.com into a bridge error.
264     *
265     * The counterpart of `transport_error()`, for the failure where the
266     * request did arrive and WordPress.com refused it. Every bridge used to
267     * spell this branch out for itself, and every spelling threw away the
268     * only part that says *why*: a plan problem and an expired token both
269     * reached a support agent as `restore_initiate_failed` / "Could not
270     * start the backup restore.", distinguishable only by a status code.
271     *
272     * WordPress.com's own reason is preserved under `wpcom`, deliberately
273     * shaped like `transport_error()`'s `transport` key. The client decides
274     * what to do with it: `failureMessage()` in `_helpers.ts` maps the
275     * codes whose meaning is the code itself, and *renders* the message for
276     * the ones — `rewind_error`, `authorization_required` — where one code
277     * spans several unrelated situations and only the sentence tells them
278     * apart.
279     *
280     * That the message can reach a reader is why the flattening and the
281     * 200-character clip below are not housekeeping. They are the whole
282     * reason it is safe to render, so do not relax them. It stays a plain
283     * string all the way out; the client escapes it by rendering it as
284     * React children.
285     *
286     * Only those two fields are forwarded, never the body — an error body
287     * is unbounded and can echo the request that produced it.
288     *
289     * The status is clamped to the failure range rather than merely tested
290     * for truthiness, and that is load-bearing. The retrieval helper hands
291     * back whatever the transport put there, and its callers must cast
292     * before comparing — a numeric-string `'200'` fails `200 !==
293     * $status_code`, which routed a perfectly good response into the
294     * failure branch. Every status comparison in this package casts now —
295     * bridges and legacy routes alike — so this function should no longer
296     * be reachable with a success code; the clamp stays because "should
297     * not" is not "cannot", and the cost of being wrong is one-sided.
298     * Forwarding a 200 would set `data.status` to 200, WordPress would
299     * serve the error envelope as HTTP 200, `apiFetch` would resolve
300     * instead of rejecting, and `apiCall()` would never throw — so a failed
301     * restore would run the mutation's `onSuccess` and report a restore
302     * that never started. A visible failure becoming an invisible false
303     * success is the worst outcome available on a destructive operation, so
304     * anything outside 4xx/5xx becomes a 500.
305     *
306     * The same clamp is what keeps junk out. `(int)` is a total function:
307     * `'2 Bad'` is 2, `3.7` is 3, `true` is 1, and a zero must never reach
308     * a `WP_Error` at all, because core hands the status to
309     * `status_header()` and a zero there emits an invalid status line.
310     *
311     * What the cast does buy, and the reason it is here rather than an
312     * `is_int()` test, is that a genuine `'404'` from a transport that
313     * reports statuses as strings now travels as 404 instead of being
314     * flattened to 500. The client is literal about the type too:
315     * `isAmbiguousFailure()` only reads a status that is already a number.
316     *
317     * @param array|\WP_Error $response The wp_remote_* response. Non-200 by the time it gets here.
318     * @param string          $code     Bridge error code for the operation that failed.
319     * @param string          $message  Translated message for the reader.
320     * @return WP_Error
321     */
322    public static function upstream_error( $response, $code, $message ) {
323        $status_code = (int) wp_remote_retrieve_response_code( $response );
324
325        $data = array( 'status' => $status_code >= 400 && $status_code <= 599 ? $status_code : 500 );
326
327        $reason = self::upstream_reason( wp_remote_retrieve_body( $response ) );
328        if ( ! empty( $reason ) ) {
329            $data['wpcom'] = $reason;
330        }
331
332        return new WP_Error( $code, $message, $data );
333    }
334
335    /**
336     * Read WordPress.com's own reason out of a response body.
337     *
338     * Three shapes have to be read here and they disagree about where the
339     * reason lives. A wpcom/v2 route serializes a `WP_Error` as `{ code,
340     * message, data }`. The older v1 envelope names that same token `error`
341     * and keeps prose beside it in `message`. And the restore endpoint's
342     * own `{ ok: false, error }` body puts VaultPress's sentence directly
343     * in `error`, with no token anywhere.
344     *
345     * So `error` is sometimes a token and sometimes a sentence, and the
346     * only thing separating them is shape: a `WP_Error` code has no
347     * whitespace in it, and a VaultPress refusal is a sentence. Sorting on
348     * that is what keeps the two halves honest. The client matches `code`
349     * against a list of codes it knows, so a sentence landing there would
350     * become a key that can never match — the reason lost again, in a
351     * quieter way.
352     *
353     * Sorting is all it does, though: nothing is ever discarded. When
354     * `error` holds a sentence *and* `message` holds another — which is
355     * what a VaultPress refusal wrapped in a generic envelope looks like —
356     * both are kept, `error` first, because that is the specific half. An
357     * earlier revision promoted `error` only when `message` was empty, and
358     * so threw away the specific reason in exactly the shape this function
359     * exists to read.
360     *
361     * `/u` on the whitespace test is not cosmetic. Without it `\s` is
362     * ASCII-only, so a sentence spaced with U+00A0 has "no whitespace" and
363     * lands in `code` — the precise outcome the sort is here to prevent.
364     *
365     * @param string|array $body Raw response body, or one already decoded.
366     * @return array<string, string> `code` and/or `message`; empty when the body names no reason.
367     */
368    public static function upstream_reason( $body ) {
369        $decoded = is_array( $body ) ? $body : json_decode( (string) $body, true );
370        if ( ! is_array( $decoded ) ) {
371            return array();
372        }
373
374        $token = '';
375        foreach ( array( 'code', 'error' ) as $key ) {
376            if ( isset( $decoded[ $key ] ) && is_string( $decoded[ $key ] ) && '' !== trim( $decoded[ $key ] ) ) {
377                $token = trim( $decoded[ $key ] );
378                break;
379            }
380        }
381
382        $prose = isset( $decoded['message'] ) && is_string( $decoded['message'] ) ? trim( $decoded['message'] ) : '';
383
384        $reason    = array();
385        $sentences = array();
386
387        if ( '' !== $token && ! preg_match( '/\s/u', $token ) ) {
388            $reason['code'] = self::clip_reason( $token );
389        } elseif ( '' !== $token ) {
390            $sentences[] = $token;
391        }
392
393        // Guarded against the duplicate rather than assumed away: some
394        // envelopes repeat the same text in both keys, and joining it to
395        // itself would say everything twice inside a budget meant for one.
396        if ( '' !== $prose && ! in_array( $prose, $sentences, true ) ) {
397            $sentences[] = $prose;
398        }
399
400        if ( ! empty( $sentences ) ) {
401            $reason['message'] = self::clip_reason( implode( ' ', $sentences ) );
402        }
403
404        return $reason;
405    }
406
407    /**
408     * Flatten and shorten one half of an upstream reason.
409     *
410     * Newlines go first so a multi-line upstream message cannot spend the
411     * whole budget on indentation before it says anything.
412     *
413     * `mb_substr()` rather than `substr()`, and the reason is mostly not
414     * the exotic one. A byte-wise cut spends the budget in bytes, so a
415     * reason written in a script that costs three bytes a character keeps
416     * a third of what it was allotted — 67 characters of 200, in the test
417     * that pins this. The encoding damage is the smaller half: the cut
418     * lands inside a character and leaves the field invalid UTF-8, which
419     * `wp_json_encode()` does not reject — its sanity check silently
420     * rewrites the broken bytes, so the reason arrives with a `?` on the
421     * end and nothing anywhere says why.
422     *
423     * The flatten runs in Unicode mode so a non-breaking or ideographic
424     * space collapses like any other, which also means it returns null on
425     * invalid UTF-8. The ASCII pass stands behind it so the bound is still
426     * enforced in that case. Unreachable in practice — every string that
427     * gets here came out of a `json_decode()`, which refuses invalid
428     * UTF-8 outright — but a silent null would turn the whole reason into
429     * an empty string, which is a poor way to find out.
430     *
431     * @param string $value Raw upstream text.
432     * @return string
433     */
434    private static function clip_reason( $value ) {
435        $flattened = preg_replace( '/\s+/u', ' ', $value );
436        if ( null === $flattened ) {
437            $flattened = preg_replace( '/\s+/', ' ', $value );
438        }
439
440        $value = trim( (string) $flattened );
441
442        if ( mb_strlen( $value, 'UTF-8' ) <= self::REASON_MAX_LENGTH ) {
443            return $value;
444        }
445
446        return rtrim( mb_substr( $value, 0, self::REASON_MAX_LENGTH, 'UTF-8' ) ) . '…';
447    }
448}