Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.38% covered (warning)
85.38%
181 / 212
91.30% covered (success)
91.30%
21 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Api_Proxy_Controller
85.38% covered (warning)
85.38%
181 / 212
91.30% covered (success)
91.30%
21 / 23
92.59
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 register_transient_cleanup_prefix
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 register_routes
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
1
 allowed_endpoint_pattern
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 config_for
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 check_data_permission
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 validate_data_endpoint
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
8
 validate_version
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle_data_request
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 base_for_version
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 build_data_path
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 is_write_allowed
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 busts_cache
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 forward
44.23% covered (danger)
44.23%
23 / 52
0.00% covered (danger)
0.00%
0 / 1
42.31
 request_unauthenticated
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 maybe_bust_read_cache
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 cache_and_build_response
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
6
 build_response
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 extract_forwarded_headers
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
5.58
 append_forwarded_params
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 get_forwarded_params
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 cache_key_for
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * REST controller that proxies dashboard data-layer requests to the WPCOM analytics API.
4 *
5 * @package automattic/jetpack-premium-analytics
6 */
7
8namespace Automattic\Jetpack\PremiumAnalytics\REST;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Connection\Manager;
12use Automattic\Jetpack\Constants;
13use Jetpack_Options;
14use WP_Error;
15use WP_REST_Controller;
16use WP_REST_Request;
17use WP_REST_Response;
18use WP_REST_Server;
19
20/**
21 * Forwards an authenticated dashboard request to the WPCOM endpoint for the connected
22 * site's blog ID, caches the successful response in a short-lived transient, and returns
23 * it. Lets the extracted frontend's data layer talk to WPCOM without each call leaving the
24 * WordPress origin.
25 *
26 * One agnostic route serves the whole pass-through surface (analytics + the re-exposed
27 * `stats-admin` endpoints), minus the blog ID in the URL:
28 *
29 *     proxy/v<version>/<prefix>/<subpath>   e.g. proxy/v1.1/wordads/earnings
30 *
31 * The `proxy/` segment marks a transparent WPCOM forward (future local endpoints live
32 * elsewhere under the namespace). Rather than registering each endpoint, it accepts any
33 * sub-path under an allowed top-level prefix (see {@see PREFIX_CONFIG}); the caller picks the
34 * WPCOM API `version` in the path (the base is derived: v2 → wpcom, v1.x → rest). The proxy
35 * stays endpoint-agnostic while the prefix allowlist + write-method policy keep the blast
36 * radius of the blog token bounded.
37 */
38class Api_Proxy_Controller extends WP_REST_Controller {
39
40    /**
41     * Package slug. Also the cache-key prefix (see SLUG-derived CACHE_PREFIX) — the only
42     * piece the source pulled from its dropped Utilities trait.
43     */
44    private const SLUG = 'jetpack-premium-analytics';
45
46    /**
47     * Transient key prefix, derived from the package slug.
48     *
49     * @var string
50     */
51    private const CACHE_PREFIX = self::SLUG . '_proxy_';
52
53    /**
54     * How long a successful response stays cached.
55     *
56     * @var int
57     */
58    private const CACHE_TTL = 5 * MINUTE_IN_SECONDS;
59
60    /**
61     * Timeout for the outbound WPCOM request, in seconds.
62     *
63     * @var int
64     */
65    private const API_TIMEOUT = 20;
66
67    /**
68     * Response headers worth forwarding back to the dashboard.
69     *
70     * @var string[]
71     */
72    private const FORWARDED_HEADERS = array( 'x-wp-total', 'x-wp-totalpages' );
73
74    /**
75     * Per-prefix configuration — the single source of truth for every proxied endpoint group.
76     * The route regex, permission check, write gate, cache-busting, and path builder all read
77     * from this table, so an endpoint group is defined here and nowhere else.
78     *
79     * The keys double as the security boundary: a request is only routed (and the blog token only
80     * forwarded) if its first path segment is a key here — so the proxy can never be driven
81     * against the whole WPCOM site API. Keep keys lowercase; they are matched case-insensitively.
82     *
83     * A request maps to `proxy/v<version>/<key>/<sub-path>` →
84     * `/sites/<blog-id>/<key>/<sub-path>` (the caller chooses `<version>`; the base is derived).
85     *
86     * Fields per entry:
87     *  - `capability` (string, required) Capability granting access. `manage_options` is always
88     *                  also accepted, so a value of `manage_options` means "admins only". A
89     *                  missing/unknown value fails closed (denies).
90     *  - `writes`     (string[], optional) Sub-paths reachable with POST (the only write verb).
91     *                  Each matcher: trailing `/` = that sub-path and anything under it; no
92     *                  trailing `/` = that exact endpoint only. Omit for a read-only group.
93     *  - `cache_bust` (bool, optional) If true, a successful POST clears the matching read cache.
94     *                  Only meaningful alongside `writes`.
95     *  - `path`       (string, optional) printf template (`%d` = blog id) for groups NOT under
96     *                  `/sites/<id>/` (e.g. `upgrades` → `/upgrades?site=%d`). A group with a
97     *                  fixed `path` takes no sub-path. Omit for the normal `/sites/<id>/<key>/…`.
98     *  - `pattern`    (string, optional) Regex the sub-path (after `<key>/`) must fully match,
99     *                  for groups where only specific endpoints are safe to expose (e.g. `posts`
100     *                  → only `<id>/likes` and `<id>/replies`, never post content). Anchored on both ends and
101     *                  enforced in the route regex AND in `validate_data_endpoint()` (the route
102     *                  capture can be shadowed with `?endpoint=`). Omit to allow the whole group.
103     *  - `unauthenticated` (bool, optional) Forward reads WITHOUT signing (plain HTTP, like
104     *                  stats-admin's Odyssey proxy does for post likes). For WPCOM endpoints
105     *                  that reject blog-token auth but serve public data without credentials.
106     *                  Reads only; the group's `capability` still gates the local request.
107     *
108     * Maintaining endpoints (this table is the only edit needed for a pass-through endpoint):
109     *  - ADD a group:   add a key with at least `capability`. Reads work immediately at
110     *                   `proxy/v<version>/<key>/<sub-path>`. The frontend picks the WPCOM version.
111     *  - ALLOW writes:  add `writes` (and `cache_bust` if a write should freshen a cached read).
112     *  - CHANGE access: edit `capability` (e.g. tighten a group to `manage_options`).
113     *  - REMOVE a group: delete its key — the route stops matching it and it 404s.
114     *  - Cover it with a row in `data_endpoint_matrix()` (capability / writable / WPCOM path).
115     *  - NOTE: this is for transparent WPCOM forwards only. Endpoints needing local processing
116     *    (DB reads, body rewrites, the Notices class, …) are NOT proxied — they get their own
117     *    routes outside `proxy/`; do not add them here.
118     *
119     * @var array<string, array<string, mixed>>
120     */
121    private const PREFIX_CONFIG = array(
122        // Gated like WooCommerce's own Analytics screens, which shop managers can read;
123        // woocommerce-analytics made the same move away from manage_options (WOOA7S-551).
124        'analytics'                     => array( 'capability' => 'view_woocommerce_reports' ),
125        'stats'                         => array(
126            'capability' => 'view_stats',
127            'writes'     => array( 'stats/referrers/spam/' ),
128        ),
129        'wordads'                       => array( 'capability' => 'activate_wordads' ),
130        'subscribers'                   => array( 'capability' => 'view_stats' ),
131        'site-has-never-published-post' => array( 'capability' => 'view_stats' ),
132        'jetpack-stats'                 => array( 'capability' => 'view_stats' ),
133        'jetpack-stats-dashboard'       => array(
134            'capability' => 'view_stats',
135            'writes'     => array( 'jetpack-stats-dashboard/' ),
136            'cache_bust' => true,
137        ),
138        'commercial-classification'     => array(
139            'capability' => 'view_stats',
140            'writes'     => array( 'commercial-classification' ),
141        ),
142        'upgrades'                      => array(
143            'capability' => 'view_stats',
144            'path'       => '/upgrades?site=%d',
145        ),
146        'posts'                         => array(
147            'capability'      => 'view_stats',
148            // Only a post's public likers and approved replies — never post content
149            // (the blog token could otherwise read private posts for any view_stats user).
150            'pattern'         => '[0-9]+/(?:likes|replies)',
151            // Both endpoints serve public data without credentials, while likes
152            // rejects blog-token auth; forward the constrained group unsigned,
153            // mirroring stats-admin's Odyssey proxy for likes.
154            'unauthenticated' => true,
155        ),
156    );
157
158    /**
159     * Constructor.
160     */
161    public function __construct() {
162        $this->namespace = self::SLUG . '/v1';
163    }
164
165    /**
166     * Hook the controller's routes onto rest_api_init, and register its cache prefix with the
167     * stats package's transient cleanup cron.
168     *
169     * @return void
170     */
171    public static function register(): void {
172        $controller = new self();
173        add_action( 'rest_api_init', array( $controller, 'register_routes' ) );
174        add_filter( 'jetpack_stats_transient_cleanup_prefixes', array( $controller, 'register_transient_cleanup_prefix' ) );
175    }
176
177    /**
178     * Register the proxy cache prefix with the stats package's transient cleanup cron, so expired
179     * proxy transients are swept on sites without a persistent object cache (where WordPress's lazy
180     * GC never reaches the rarely re-read, param-keyed entries). The coupling is loose: the filter
181     * is just a hook name, so if the stats package isn't loaded it never fires and nothing breaks.
182     *
183     * Appends only when handed a valid array; a non-array (from a misbehaving upstream filter) is
184     * returned untouched so the stats consumer's own fall-back-to-defaults normalization still runs
185     * instead of being masked into dropping the default stats prefix.
186     *
187     * @param mixed $prefixes Transient prefixes the stats cleanup cron will sweep.
188     *
189     * @return mixed
190     */
191    public function register_transient_cleanup_prefix( $prefixes ) {
192        if ( is_array( $prefixes ) ) {
193            $prefixes[] = self::CACHE_PREFIX;
194        }
195
196        return $prefixes;
197    }
198
199    /**
200     * Register the agnostic data proxy route.
201     *
202     * @return void
203     */
204    public function register_routes(): void {
205        // proxy/v<version>/<prefix>/<subpath> — the `proxy/` segment marks a transparent WPCOM
206        // pass-through (local endpoints live elsewhere under the namespace), the version is part
207        // of the path (matching WPCOM's own `rest/v1.1` / `wpcom/v2` structure), and the prefix
208        // allowlist is anchored into the route.
209        register_rest_route(
210            $this->namespace,
211            '/proxy/v(?P<version>[0-9]+(?:\.[0-9]+)?)/(?P<endpoint>' . $this->allowed_endpoint_pattern() . ')',
212            array(
213                'methods'             => WP_REST_Server::READABLE . ',' . WP_REST_Server::EDITABLE,
214                'callback'            => array( $this, 'handle_data_request' ),
215                'permission_callback' => array( $this, 'check_data_permission' ),
216                'args'                => array(
217                    'endpoint' => array(
218                        'type'              => 'string',
219                        'required'          => true,
220                        'validate_callback' => array( $this, 'validate_data_endpoint' ),
221                    ),
222                    'version'  => array(
223                        'description'       => __( 'WPCOM API version to forward to (e.g. 1.1, 1.2, 2).', 'jetpack-premium-analytics-pkg' ),
224                        'type'              => 'string',
225                        'required'          => true,
226                        'validate_callback' => array( $this, 'validate_version' ),
227                    ),
228                ),
229            )
230        );
231    }
232
233    /**
234     * Regex alternation of the allowed endpoints, used to anchor the data route: each
235     * {@see PREFIX_CONFIG} key followed by its `pattern`-constrained sub-path when set, or any
236     * sub-path otherwise.
237     *
238     * @return string
239     */
240    private function allowed_endpoint_pattern(): string {
241        $alternatives = array();
242
243        foreach ( self::PREFIX_CONFIG as $prefix => $config ) {
244            $suffix         = isset( $config['pattern'] ) ? '/' . $config['pattern'] : '(?:/.*)?';
245            $alternatives[] = preg_quote( $prefix, '#' ) . $suffix;
246        }
247
248        return '(?:' . implode( '|', $alternatives ) . ')';
249    }
250
251    /**
252     * The {@see PREFIX_CONFIG} entry for an endpoint's top-level prefix, or null if not allowed.
253     *
254     * @param string $endpoint The endpoint value (`get_param('endpoint')`).
255     *
256     * @return array<string, mixed>|null
257     */
258    private function config_for( string $endpoint ): ?array {
259        $prefix = strtolower( explode( '/', $endpoint )[0] );
260
261        return self::PREFIX_CONFIG[ $prefix ] ?? null;
262    }
263
264    /**
265     * Permission for the data proxy: the prefix's configured capability grants access, and
266     * `manage_options` always does (so `analytics`, whose capability is `manage_options`, stays
267     * admin-only). The capability comes from {@see PREFIX_CONFIG}.
268     *
269     * @param WP_REST_Request $request Request object.
270     *
271     * @return bool
272     */
273    public function check_data_permission( WP_REST_Request $request ): bool {
274        $config = $this->config_for( (string) $request->get_param( 'endpoint' ) );
275        if ( null === $config ) {
276            return false;
277        }
278
279        // Fall back to `do_not_allow` so a config entry missing `capability` fails closed.
280        $capability = $config['capability'] ?? 'do_not_allow';
281
282        // phpcs:ignore WordPress.WP.Capabilities.Unknown -- capability is from the PREFIX_CONFIG allowlist.
283        return current_user_can( 'manage_options' ) || current_user_can( $capability );
284    }
285
286    /**
287     * Confine a data endpoint to a relative sub-path under an allowed prefix, rejecting traversal
288     * (`..`) and schemes (`:`). Commas are permitted since stats sub-paths legitimately contain
289     * them (UTM params).
290     *
291     * The prefix is re-checked here, not just in the route regex: WP's `get_param()` prefers
292     * GET/JSON/POST over the URL route capture, so a caller could otherwise shadow the matched
293     * `endpoint` with `?endpoint=…` and escape the allowlist. This runs against the same
294     * `get_param()` value the handler forwards, so it closes the hole whichever source wins.
295     *
296     * @param mixed $value Raw endpoint param.
297     *
298     * @return bool
299     */
300    public function validate_data_endpoint( $value ): bool {
301        $value = (string) $value;
302
303        if ( str_contains( $value, '..' ) ) {
304            return false;
305        }
306
307        if ( ! preg_match( '#^[\w.,/-]+$#', $value ) ) {
308            return false;
309        }
310
311        $config = $this->config_for( $value );
312        if ( null === $config ) {
313            return false;
314        }
315
316        // A prefix with a fixed `path` (e.g. site-less `upgrades`) takes no sub-path, so reject
317        // `<prefix>/<anything>` — build_data_path() ignores sub-paths there and would mis-route.
318        if ( isset( $config['path'] ) ) {
319            $prefix = strtolower( explode( '/', $value )[0] );
320            if ( $prefix !== rtrim( strtolower( $value ), '/' ) ) {
321                return false;
322            }
323        }
324
325        // A `pattern`-constrained prefix only exposes matching sub-paths. Re-checked here, not
326        // just in the route regex, because `get_param()` can be shadowed with `?endpoint=`.
327        if ( isset( $config['pattern'] ) ) {
328            $prefix = strtolower( explode( '/', $value )[0] );
329            if ( ! preg_match( '#^' . preg_quote( $prefix, '#' ) . '/' . $config['pattern'] . '$#i', rtrim( $value, '/' ) ) ) {
330                return false;
331            }
332        }
333
334        return true;
335    }
336
337    /**
338     * A WPCOM API version is one or two dot-separated numbers (e.g. `2`, `1.1`).
339     *
340     * @param mixed $value Raw version param.
341     *
342     * @return bool
343     */
344    public function validate_version( $value ): bool {
345        return (bool) preg_match( '#^[0-9]+(\.[0-9]+)?$#', (string) $value );
346    }
347
348    /**
349     * Proxy a data request to its WPCOM endpoint, at the caller-chosen API version.
350     *
351     * @param WP_REST_Request $request Request object.
352     *
353     * @return WP_REST_Response|WP_Error
354     */
355    public function handle_data_request( WP_REST_Request $request ) {
356        $endpoint = (string) $request->get_param( 'endpoint' );
357        $method   = strtoupper( $request->get_method() );
358
359        // Reads are open across the allowed prefixes; only POST may mutate, and only the
360        // few endpoints on the write allowlist. Everything else is rejected locally.
361        if ( 'GET' !== $method && ! ( 'POST' === $method && $this->is_write_allowed( $endpoint ) ) ) {
362            return new WP_Error(
363                'rest_read_only',
364                __( 'This endpoint is read-only.', 'jetpack-premium-analytics-pkg' ),
365                array( 'status' => 405 )
366            );
367        }
368
369        $version = (string) $request->get_param( 'version' );
370
371        $config = $this->config_for( $endpoint );
372
373        return $this->forward(
374            $request,
375            $this->build_data_path( $endpoint ),
376            array(
377                'version'         => $version,
378                'base'            => $this->base_for_version( $version ),
379                'bust_on_write'   => $this->busts_cache( $endpoint ),
380                'unauthenticated' => ! empty( $config['unauthenticated'] ),
381            )
382        );
383    }
384
385    /**
386     * The WPCOM API base for a version: v2 lives under `wpcom`, v1.x under `rest`. Derived from
387     * the major component so dotted forms (e.g. `2.0`) map correctly.
388     *
389     * @param string $version WPCOM API version.
390     *
391     * @return string
392     */
393    private function base_for_version( string $version ): string {
394        return 2 === (int) $version ? 'wpcom' : 'rest';
395    }
396
397    /**
398     * Build the WPCOM path for a data endpoint.
399     *
400     * @param string $endpoint The validated, allowed sub-path.
401     *
402     * @return string
403     */
404    private function build_data_path( string $endpoint ): string {
405        $site_id = (int) Jetpack_Options::get_option( 'id' );
406
407        // A prefix with a fixed `path` (e.g. site-less `upgrades`) is not scoped under /sites/<id>/.
408        $config = $this->config_for( $endpoint );
409        if ( null !== $config && isset( $config['path'] ) ) {
410            return sprintf( $config['path'], $site_id );
411        }
412
413        return sprintf( '/sites/%d/%s', $site_id, $endpoint );
414    }
415
416    /**
417     * Whether a non-GET method may be forwarded for this endpoint, per the prefix's `writes`.
418     * A `writes` entry ending in `/` matches that sub-path prefix; otherwise it matches exactly.
419     *
420     * @param string $endpoint The validated sub-path.
421     *
422     * @return bool
423     */
424    private function is_write_allowed( string $endpoint ): bool {
425        $endpoint = strtolower( $endpoint );
426        $config   = $this->config_for( $endpoint );
427
428        foreach ( $config['writes'] ?? array() as $matcher ) {
429            $matcher = strtolower( $matcher );
430            $matches = str_ends_with( $matcher, '/' )
431                ? str_starts_with( $endpoint, $matcher )
432                : $endpoint === $matcher;
433            if ( $matches ) {
434                return true;
435            }
436        }
437
438        return false;
439    }
440
441    /**
442     * Whether a successful write to this endpoint should invalidate the matching read cache.
443     *
444     * @param string $endpoint The validated sub-path.
445     *
446     * @return bool
447     */
448    private function busts_cache( string $endpoint ): bool {
449        $config = $this->config_for( $endpoint );
450
451        return ! empty( $config['cache_bust'] );
452    }
453
454    /**
455     * Serve a cached payload when available, otherwise forward to WPCOM and cache the result.
456     *
457     * @param WP_REST_Request      $request    Request object.
458     * @param string               $wpcom_path WPCOM path without the forwarded query string.
459     * @param array<string, mixed> $opts       version | base | bust_on_write | cache overrides.
460     *
461     * @return WP_REST_Response|WP_Error
462     */
463    private function forward( WP_REST_Request $request, string $wpcom_path, array $opts ) {
464        $version   = $opts['version'] ?? '2';
465        $base      = $opts['base'] ?? 'wpcom';
466        $method    = strtoupper( $request->get_method() );
467        $is_read   = 'GET' === $method;
468        $cacheable = $is_read
469            && ( $opts['cache'] ?? true )
470            && null === $request->get_param( 'force_refresh' );
471
472        $cache_key = $cacheable ? $this->cache_key_for( $wpcom_path, $version, $base, $this->get_forwarded_params( $request ) ) : null;
473        if ( null !== $cache_key ) {
474            $cached = get_transient( $cache_key );
475            if ( false !== $cached ) {
476                return $this->build_response( $cached );
477            }
478        }
479
480        // Unsigned forwards need no tokens — only the blog id baked into the path —
481        // so they skip the connection gate (its blog-token requirement) entirely.
482        if ( ! empty( $opts['unauthenticated'] ) && $is_read ) {
483            $response = $this->request_unauthenticated( $request, $wpcom_path, $version, $base );
484            if ( is_wp_error( $response ) ) {
485                return $response;
486            }
487
488            return $this->cache_and_build_response( $response, $cache_key );
489        }
490
491        if ( ! ( new Manager( self::SLUG ) )->is_connected() ) {
492            return new WP_Error(
493                'no_connection',
494                __( 'Please connect Jetpack to load your data.', 'jetpack-premium-analytics-pkg' ),
495                array( 'status' => 403 )
496            );
497        }
498
499        $args = array(
500            'method'  => $method,
501            'timeout' => self::API_TIMEOUT,
502        );
503        $body = null;
504        if ( ! $is_read ) {
505            $body            = $request->get_body();
506            $args['headers'] = array( 'Content-Type' => 'application/json' );
507        }
508
509        try {
510            $response = Client::wpcom_json_api_request_as_blog(
511                $this->append_forwarded_params( $request, $wpcom_path ),
512                $version,
513                $args,
514                $body,
515                $base
516            );
517        } catch ( \Exception $e ) {
518            return new WP_Error(
519                'api_error',
520                __( 'Error processing the request.', 'jetpack-premium-analytics-pkg' ),
521                array( 'status' => 500 )
522            );
523        }
524
525        if ( is_wp_error( $response ) ) {
526            return new WP_Error(
527                'api_error',
528                __( 'Error communicating with the data service.', 'jetpack-premium-analytics-pkg' ),
529                array( 'status' => 500 )
530            );
531        }
532
533        $this->maybe_bust_read_cache( $response, ! $is_read, $opts, $wpcom_path, $version, $base );
534
535        return $this->cache_and_build_response( $response, $cache_key );
536    }
537
538    /**
539     * Forward a read to WPCOM without signing, for `unauthenticated` endpoint groups. Mirrors
540     * stats-admin's Odyssey proxy (`get_single_post_likes()`): the target endpoint rejects
541     * blog-token auth but serves public data to credential-less requests. Private posts/sites
542     * return WPCOM's own restricted error — the same limitation Odyssey has.
543     *
544     * @param WP_REST_Request $request    Request object.
545     * @param string          $wpcom_path WPCOM path without the forwarded query string.
546     * @param string          $version    WPCOM API version.
547     * @param string          $base       WPCOM API base (`rest` or `wpcom`).
548     *
549     * @return array|WP_Error Raw HTTP response, or an error.
550     */
551    private function request_unauthenticated( WP_REST_Request $request, string $wpcom_path, string $version, string $base ) {
552        // The path embeds the blog id; without one the request would target site 0.
553        if ( ! (int) Jetpack_Options::get_option( 'id' ) ) {
554            return new WP_Error(
555                'no_connection',
556                __( 'Please connect Jetpack to load your data.', 'jetpack-premium-analytics-pkg' ),
557                array( 'status' => 403 )
558            );
559        }
560
561        $api_base = Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' );
562        if ( empty( $api_base ) ) {
563            $api_base = 'https://public-api.wordpress.com';
564        }
565
566        $response = wp_remote_get(
567            sprintf( '%s/%s/v%s%s', $api_base, $base, $version, $this->append_forwarded_params( $request, $wpcom_path ) ),
568            array( 'timeout' => self::API_TIMEOUT )
569        );
570
571        if ( is_wp_error( $response ) ) {
572            return new WP_Error(
573                'api_error',
574                __( 'Error communicating with the data service.', 'jetpack-premium-analytics-pkg' ),
575                array( 'status' => 500 )
576            );
577        }
578
579        return $response;
580    }
581
582    /**
583     * Mirror stats-admin: a successful write invalidates the matching (param-less) read cache, so
584     * the next GET reflects the change instead of serving the cached pre-write value. It busts only
585     * when the request was a write, the prefix opted in (`bust_on_write`), and WPCOM returned 200.
586     *
587     * This is a pure function of the response and route context — it takes the raw client response
588     * rather than reaching out to WPCOM itself, so the full bust decision is unit-testable without
589     * a live connection.
590     *
591     * @param array                $http_response Raw response from the Jetpack client.
592     * @param bool                 $is_write      Whether the request used a write (non-GET) method.
593     * @param array<string, mixed> $opts          Forwarding opts (reads `bust_on_write`).
594     * @param string               $wpcom_path    WPCOM path without the forwarded query string.
595     * @param string               $version       WPCOM API version.
596     * @param string               $base          WPCOM API base.
597     *
598     * @return void
599     */
600    private function maybe_bust_read_cache( array $http_response, bool $is_write, array $opts, string $wpcom_path, string $version, string $base ): void {
601        if ( ! $is_write || empty( $opts['bust_on_write'] ) ) {
602            return;
603        }
604
605        if ( 200 !== (int) wp_remote_retrieve_response_code( $http_response ) ) {
606            return;
607        }
608
609        delete_transient( $this->cache_key_for( $wpcom_path, $version, $base, array() ) );
610    }
611
612    /**
613     * Cache a successful (200) response when a cache key is given, and return it to the caller.
614     *
615     * @param array       $http_response Raw response from the Jetpack client.
616     * @param string|null $cache_key     Transient key, or null to skip caching.
617     *
618     * @return WP_REST_Response|WP_Error
619     */
620    private function cache_and_build_response( array $http_response, ?string $cache_key ) {
621        $status = (int) wp_remote_retrieve_response_code( $http_response );
622        $data   = json_decode( wp_remote_retrieve_body( $http_response ), false );
623
624        // A 200 with an undecodable body means the upstream is degraded; don't cache garbage.
625        if ( 200 === $status && null === $data && JSON_ERROR_NONE !== json_last_error() ) {
626            return new WP_Error(
627                'api_error',
628                __( 'The data service returned an unreadable response.', 'jetpack-premium-analytics-pkg' ),
629                array( 'status' => 502 )
630            );
631        }
632
633        $payload = array(
634            'data'    => $data,
635            'status'  => $status,
636            'headers' => $this->extract_forwarded_headers( wp_remote_retrieve_headers( $http_response ) ),
637        );
638
639        if ( null !== $cache_key && 200 === $status ) {
640            set_transient( $cache_key, $payload, self::CACHE_TTL );
641        }
642
643        return $this->build_response( $payload );
644    }
645
646    /**
647     * Rebuild a WP_REST_Response from a cached or freshly fetched payload.
648     *
649     * @param array $payload Stored payload with data, status, and headers.
650     *
651     * @return WP_REST_Response
652     */
653    private function build_response( array $payload ): WP_REST_Response {
654        $response = new WP_REST_Response( $payload['data'], (int) $payload['status'] );
655
656        foreach ( (array) $payload['headers'] as $name => $value ) {
657            $response->header( $name, $value );
658        }
659
660        return $response;
661    }
662
663    /**
664     * Keep only the response headers the dashboard needs (pagination totals).
665     *
666     * @param mixed $headers Response headers as returned by the HTTP API.
667     *
668     * @return array<string, string>
669     */
670    private function extract_forwarded_headers( $headers ): array {
671        if ( $headers instanceof \ArrayAccess || is_array( $headers ) ) {
672            $forwarded = array();
673            foreach ( self::FORWARDED_HEADERS as $name ) {
674                if ( isset( $headers[ $name ] ) ) {
675                    $forwarded[ $name ] = (string) $headers[ $name ];
676                }
677            }
678            return $forwarded;
679        }
680
681        return array();
682    }
683
684    /**
685     * Append the forwarded query params to a WPCOM path, choosing the right separator.
686     *
687     * @param WP_REST_Request $request    Request object.
688     * @param string          $wpcom_path WPCOM path that may already carry a query string.
689     *
690     * @return string
691     */
692    private function append_forwarded_params( WP_REST_Request $request, string $wpcom_path ): string {
693        $params = $this->get_forwarded_params( $request );
694        if ( empty( $params ) ) {
695            return $wpcom_path;
696        }
697
698        $separator = str_contains( $wpcom_path, '?' ) ? '&' : '?';
699
700        return $wpcom_path . $separator . http_build_query( $params );
701    }
702
703    /**
704     * Query params to forward to WPCOM, minus the WordPress routing params, the proxy's own
705     * control params (`endpoint`, `version`, `force_refresh` — which a caller could also pass as
706     * query params since `get_param()` prefers GET), and `site` (the proxy pins the site itself,
707     * so a caller-supplied `site` must not reach the `upgrades` query string). Dropping the
708     * control params also keeps them out of the cache key.
709     *
710     * @param WP_REST_Request $request Request object.
711     *
712     * @return array
713     */
714    private function get_forwarded_params( WP_REST_Request $request ): array {
715        $params = $request->get_query_params();
716        unset( $params['rest_route'], $params['_locale'], $params['site'], $params['endpoint'], $params['version'], $params['force_refresh'] );
717
718        return is_array( $params ) ? $params : array();
719    }
720
721    /**
722     * Transient key for a target path + API version/base + forwarded params (order-independent).
723     * Version and base are part of the key so the same path at different versions doesn't collide.
724     *
725     * @param string $wpcom_path WPCOM path without the forwarded query string.
726     * @param string $version    WPCOM API version.
727     * @param string $base       WPCOM API base.
728     * @param array  $params     Forwarded query params.
729     *
730     * @return string
731     */
732    private function cache_key_for( string $wpcom_path, string $version, string $base, array $params ): string {
733        ksort( $params );
734        $signature = implode( '|', array( $wpcom_path, $version, $base, (string) wp_json_encode( $params, JSON_UNESCAPED_SLASHES ) ) );
735
736        return self::CACHE_PREFIX . md5( $signature );
737    }
738}