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