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        'analytics'                     => array( 'capability' => 'manage_options' ),
123        'stats'                         => array(
124            'capability' => 'view_stats',
125            'writes'     => array( 'stats/referrers/spam/' ),
126        ),
127        'wordads'                       => array( 'capability' => 'activate_wordads' ),
128        'subscribers'                   => array( 'capability' => 'view_stats' ),
129        'site-has-never-published-post' => array( 'capability' => 'view_stats' ),
130        'jetpack-stats'                 => array( 'capability' => 'view_stats' ),
131        'jetpack-stats-dashboard'       => array(
132            'capability' => 'view_stats',
133            'writes'     => array( 'jetpack-stats-dashboard/' ),
134            'cache_bust' => true,
135        ),
136        'commercial-classification'     => array(
137            'capability' => 'view_stats',
138            'writes'     => array( 'commercial-classification' ),
139        ),
140        'upgrades'                      => array(
141            'capability' => 'view_stats',
142            'path'       => '/upgrades?site=%d',
143        ),
144        'posts'                         => array(
145            'capability'      => 'view_stats',
146            // Only a post's public likers and approved replies — never post content
147            // (the blog token could otherwise read private posts for any view_stats user).
148            'pattern'         => '[0-9]+/(?:likes|replies)',
149            // Both endpoints serve public data without credentials, while likes
150            // rejects blog-token auth; forward the constrained group unsigned,
151            // mirroring stats-admin's Odyssey proxy for likes.
152            'unauthenticated' => true,
153        ),
154    );
155
156    /**
157     * Constructor.
158     */
159    public function __construct() {
160        $this->namespace = self::SLUG . '/v1';
161    }
162
163    /**
164     * Hook the controller's routes onto rest_api_init, and register its cache prefix with the
165     * stats package's transient cleanup cron.
166     *
167     * @return void
168     */
169    public static function register(): void {
170        $controller = new self();
171        add_action( 'rest_api_init', array( $controller, 'register_routes' ) );
172        add_filter( 'jetpack_stats_transient_cleanup_prefixes', array( $controller, 'register_transient_cleanup_prefix' ) );
173    }
174
175    /**
176     * Register the proxy cache prefix with the stats package's transient cleanup cron, so expired
177     * proxy transients are swept on sites without a persistent object cache (where WordPress's lazy
178     * GC never reaches the rarely re-read, param-keyed entries). The coupling is loose: the filter
179     * is just a hook name, so if the stats package isn't loaded it never fires and nothing breaks.
180     *
181     * Appends only when handed a valid array; a non-array (from a misbehaving upstream filter) is
182     * returned untouched so the stats consumer's own fall-back-to-defaults normalization still runs
183     * instead of being masked into dropping the default stats prefix.
184     *
185     * @param mixed $prefixes Transient prefixes the stats cleanup cron will sweep.
186     *
187     * @return mixed
188     */
189    public function register_transient_cleanup_prefix( $prefixes ) {
190        if ( is_array( $prefixes ) ) {
191            $prefixes[] = self::CACHE_PREFIX;
192        }
193
194        return $prefixes;
195    }
196
197    /**
198     * Register the agnostic data proxy route.
199     *
200     * @return void
201     */
202    public function register_routes(): void {
203        // proxy/v<version>/<prefix>/<subpath> — the `proxy/` segment marks a transparent WPCOM
204        // pass-through (local endpoints live elsewhere under the namespace), the version is part
205        // of the path (matching WPCOM's own `rest/v1.1` / `wpcom/v2` structure), and the prefix
206        // allowlist is anchored into the route.
207        register_rest_route(
208            $this->namespace,
209            '/proxy/v(?P<version>[0-9]+(?:\.[0-9]+)?)/(?P<endpoint>' . $this->allowed_endpoint_pattern() . ')',
210            array(
211                'methods'             => WP_REST_Server::READABLE . ',' . WP_REST_Server::EDITABLE,
212                'callback'            => array( $this, 'handle_data_request' ),
213                'permission_callback' => array( $this, 'check_data_permission' ),
214                'args'                => array(
215                    'endpoint' => array(
216                        'type'              => 'string',
217                        'required'          => true,
218                        'validate_callback' => array( $this, 'validate_data_endpoint' ),
219                    ),
220                    'version'  => array(
221                        'description'       => __( 'WPCOM API version to forward to (e.g. 1.1, 1.2, 2).', 'jetpack-premium-analytics' ),
222                        'type'              => 'string',
223                        'required'          => true,
224                        'validate_callback' => array( $this, 'validate_version' ),
225                    ),
226                ),
227            )
228        );
229    }
230
231    /**
232     * Regex alternation of the allowed endpoints, used to anchor the data route: each
233     * {@see PREFIX_CONFIG} key followed by its `pattern`-constrained sub-path when set, or any
234     * sub-path otherwise.
235     *
236     * @return string
237     */
238    private function allowed_endpoint_pattern(): string {
239        $alternatives = array();
240
241        foreach ( self::PREFIX_CONFIG as $prefix => $config ) {
242            $suffix         = isset( $config['pattern'] ) ? '/' . $config['pattern'] : '(?:/.*)?';
243            $alternatives[] = preg_quote( $prefix, '#' ) . $suffix;
244        }
245
246        return '(?:' . implode( '|', $alternatives ) . ')';
247    }
248
249    /**
250     * The {@see PREFIX_CONFIG} entry for an endpoint's top-level prefix, or null if not allowed.
251     *
252     * @param string $endpoint The endpoint value (`get_param('endpoint')`).
253     *
254     * @return array<string, mixed>|null
255     */
256    private function config_for( string $endpoint ): ?array {
257        $prefix = strtolower( explode( '/', $endpoint )[0] );
258
259        return self::PREFIX_CONFIG[ $prefix ] ?? null;
260    }
261
262    /**
263     * Permission for the data proxy: the prefix's configured capability grants access, and
264     * `manage_options` always does (so `analytics`, whose capability is `manage_options`, stays
265     * admin-only). The capability comes from {@see PREFIX_CONFIG}.
266     *
267     * @param WP_REST_Request $request Request object.
268     *
269     * @return bool
270     */
271    public function check_data_permission( WP_REST_Request $request ): bool {
272        $config = $this->config_for( (string) $request->get_param( 'endpoint' ) );
273        if ( null === $config ) {
274            return false;
275        }
276
277        // Fall back to `do_not_allow` so a config entry missing `capability` fails closed.
278        $capability = $config['capability'] ?? 'do_not_allow';
279
280        // phpcs:ignore WordPress.WP.Capabilities.Unknown -- capability is from the PREFIX_CONFIG allowlist.
281        return current_user_can( 'manage_options' ) || current_user_can( $capability );
282    }
283
284    /**
285     * Confine a data endpoint to a relative sub-path under an allowed prefix, rejecting traversal
286     * (`..`) and schemes (`:`). Commas are permitted since stats sub-paths legitimately contain
287     * them (UTM params).
288     *
289     * The prefix is re-checked here, not just in the route regex: WP's `get_param()` prefers
290     * GET/JSON/POST over the URL route capture, so a caller could otherwise shadow the matched
291     * `endpoint` with `?endpoint=…` and escape the allowlist. This runs against the same
292     * `get_param()` value the handler forwards, so it closes the hole whichever source wins.
293     *
294     * @param mixed $value Raw endpoint param.
295     *
296     * @return bool
297     */
298    public function validate_data_endpoint( $value ): bool {
299        $value = (string) $value;
300
301        if ( str_contains( $value, '..' ) ) {
302            return false;
303        }
304
305        if ( ! preg_match( '#^[\w.,/-]+$#', $value ) ) {
306            return false;
307        }
308
309        $config = $this->config_for( $value );
310        if ( null === $config ) {
311            return false;
312        }
313
314        // A prefix with a fixed `path` (e.g. site-less `upgrades`) takes no sub-path, so reject
315        // `<prefix>/<anything>` — build_data_path() ignores sub-paths there and would mis-route.
316        if ( isset( $config['path'] ) ) {
317            $prefix = strtolower( explode( '/', $value )[0] );
318            if ( $prefix !== rtrim( strtolower( $value ), '/' ) ) {
319                return false;
320            }
321        }
322
323        // A `pattern`-constrained prefix only exposes matching sub-paths. Re-checked here, not
324        // just in the route regex, because `get_param()` can be shadowed with `?endpoint=`.
325        if ( isset( $config['pattern'] ) ) {
326            $prefix = strtolower( explode( '/', $value )[0] );
327            if ( ! preg_match( '#^' . preg_quote( $prefix, '#' ) . '/' . $config['pattern'] . '$#i', rtrim( $value, '/' ) ) ) {
328                return false;
329            }
330        }
331
332        return true;
333    }
334
335    /**
336     * A WPCOM API version is one or two dot-separated numbers (e.g. `2`, `1.1`).
337     *
338     * @param mixed $value Raw version param.
339     *
340     * @return bool
341     */
342    public function validate_version( $value ): bool {
343        return (bool) preg_match( '#^[0-9]+(\.[0-9]+)?$#', (string) $value );
344    }
345
346    /**
347     * Proxy a data request to its WPCOM endpoint, at the caller-chosen API version.
348     *
349     * @param WP_REST_Request $request Request object.
350     *
351     * @return WP_REST_Response|WP_Error
352     */
353    public function handle_data_request( WP_REST_Request $request ) {
354        $endpoint = (string) $request->get_param( 'endpoint' );
355        $method   = strtoupper( $request->get_method() );
356
357        // Reads are open across the allowed prefixes; only POST may mutate, and only the
358        // few endpoints on the write allowlist. Everything else is rejected locally.
359        if ( 'GET' !== $method && ! ( 'POST' === $method && $this->is_write_allowed( $endpoint ) ) ) {
360            return new WP_Error(
361                'rest_read_only',
362                __( 'This endpoint is read-only.', 'jetpack-premium-analytics' ),
363                array( 'status' => 405 )
364            );
365        }
366
367        $version = (string) $request->get_param( 'version' );
368
369        $config = $this->config_for( $endpoint );
370
371        return $this->forward(
372            $request,
373            $this->build_data_path( $endpoint ),
374            array(
375                'version'         => $version,
376                'base'            => $this->base_for_version( $version ),
377                'bust_on_write'   => $this->busts_cache( $endpoint ),
378                'unauthenticated' => ! empty( $config['unauthenticated'] ),
379            )
380        );
381    }
382
383    /**
384     * The WPCOM API base for a version: v2 lives under `wpcom`, v1.x under `rest`. Derived from
385     * the major component so dotted forms (e.g. `2.0`) map correctly.
386     *
387     * @param string $version WPCOM API version.
388     *
389     * @return string
390     */
391    private function base_for_version( string $version ): string {
392        return 2 === (int) $version ? 'wpcom' : 'rest';
393    }
394
395    /**
396     * Build the WPCOM path for a data endpoint.
397     *
398     * @param string $endpoint The validated, allowed sub-path.
399     *
400     * @return string
401     */
402    private function build_data_path( string $endpoint ): string {
403        $site_id = (int) Jetpack_Options::get_option( 'id' );
404
405        // A prefix with a fixed `path` (e.g. site-less `upgrades`) is not scoped under /sites/<id>/.
406        $config = $this->config_for( $endpoint );
407        if ( null !== $config && isset( $config['path'] ) ) {
408            return sprintf( $config['path'], $site_id );
409        }
410
411        return sprintf( '/sites/%d/%s', $site_id, $endpoint );
412    }
413
414    /**
415     * Whether a non-GET method may be forwarded for this endpoint, per the prefix's `writes`.
416     * A `writes` entry ending in `/` matches that sub-path prefix; otherwise it matches exactly.
417     *
418     * @param string $endpoint The validated sub-path.
419     *
420     * @return bool
421     */
422    private function is_write_allowed( string $endpoint ): bool {
423        $endpoint = strtolower( $endpoint );
424        $config   = $this->config_for( $endpoint );
425
426        foreach ( $config['writes'] ?? array() as $matcher ) {
427            $matcher = strtolower( $matcher );
428            $matches = str_ends_with( $matcher, '/' )
429                ? str_starts_with( $endpoint, $matcher )
430                : $endpoint === $matcher;
431            if ( $matches ) {
432                return true;
433            }
434        }
435
436        return false;
437    }
438
439    /**
440     * Whether a successful write to this endpoint should invalidate the matching read cache.
441     *
442     * @param string $endpoint The validated sub-path.
443     *
444     * @return bool
445     */
446    private function busts_cache( string $endpoint ): bool {
447        $config = $this->config_for( $endpoint );
448
449        return ! empty( $config['cache_bust'] );
450    }
451
452    /**
453     * Serve a cached payload when available, otherwise forward to WPCOM and cache the result.
454     *
455     * @param WP_REST_Request      $request    Request object.
456     * @param string               $wpcom_path WPCOM path without the forwarded query string.
457     * @param array<string, mixed> $opts       version | base | bust_on_write | cache overrides.
458     *
459     * @return WP_REST_Response|WP_Error
460     */
461    private function forward( WP_REST_Request $request, string $wpcom_path, array $opts ) {
462        $version   = $opts['version'] ?? '2';
463        $base      = $opts['base'] ?? 'wpcom';
464        $method    = strtoupper( $request->get_method() );
465        $is_read   = 'GET' === $method;
466        $cacheable = $is_read
467            && ( $opts['cache'] ?? true )
468            && null === $request->get_param( 'force_refresh' );
469
470        $cache_key = $cacheable ? $this->cache_key_for( $wpcom_path, $version, $base, $this->get_forwarded_params( $request ) ) : null;
471        if ( null !== $cache_key ) {
472            $cached = get_transient( $cache_key );
473            if ( false !== $cached ) {
474                return $this->build_response( $cached );
475            }
476        }
477
478        // Unsigned forwards need no tokens — only the blog id baked into the path —
479        // so they skip the connection gate (its blog-token requirement) entirely.
480        if ( ! empty( $opts['unauthenticated'] ) && $is_read ) {
481            $response = $this->request_unauthenticated( $request, $wpcom_path, $version, $base );
482            if ( is_wp_error( $response ) ) {
483                return $response;
484            }
485
486            return $this->cache_and_build_response( $response, $cache_key );
487        }
488
489        if ( ! ( new Manager( self::SLUG ) )->is_connected() ) {
490            return new WP_Error(
491                'no_connection',
492                __( 'Please connect Jetpack to load your data.', 'jetpack-premium-analytics' ),
493                array( 'status' => 403 )
494            );
495        }
496
497        $args = array(
498            'method'  => $method,
499            'timeout' => self::API_TIMEOUT,
500        );
501        $body = null;
502        if ( ! $is_read ) {
503            $body            = $request->get_body();
504            $args['headers'] = array( 'Content-Type' => 'application/json' );
505        }
506
507        try {
508            $response = Client::wpcom_json_api_request_as_blog(
509                $this->append_forwarded_params( $request, $wpcom_path ),
510                $version,
511                $args,
512                $body,
513                $base
514            );
515        } catch ( \Exception $e ) {
516            return new WP_Error(
517                'api_error',
518                __( 'Error processing the request.', 'jetpack-premium-analytics' ),
519                array( 'status' => 500 )
520            );
521        }
522
523        if ( is_wp_error( $response ) ) {
524            return new WP_Error(
525                'api_error',
526                __( 'Error communicating with the data service.', 'jetpack-premium-analytics' ),
527                array( 'status' => 500 )
528            );
529        }
530
531        $this->maybe_bust_read_cache( $response, ! $is_read, $opts, $wpcom_path, $version, $base );
532
533        return $this->cache_and_build_response( $response, $cache_key );
534    }
535
536    /**
537     * Forward a read to WPCOM without signing, for `unauthenticated` endpoint groups. Mirrors
538     * stats-admin's Odyssey proxy (`get_single_post_likes()`): the target endpoint rejects
539     * blog-token auth but serves public data to credential-less requests. Private posts/sites
540     * return WPCOM's own restricted error — the same limitation Odyssey has.
541     *
542     * @param WP_REST_Request $request    Request object.
543     * @param string          $wpcom_path WPCOM path without the forwarded query string.
544     * @param string          $version    WPCOM API version.
545     * @param string          $base       WPCOM API base (`rest` or `wpcom`).
546     *
547     * @return array|WP_Error Raw HTTP response, or an error.
548     */
549    private function request_unauthenticated( WP_REST_Request $request, string $wpcom_path, string $version, string $base ) {
550        // The path embeds the blog id; without one the request would target site 0.
551        if ( ! (int) Jetpack_Options::get_option( 'id' ) ) {
552            return new WP_Error(
553                'no_connection',
554                __( 'Please connect Jetpack to load your data.', 'jetpack-premium-analytics' ),
555                array( 'status' => 403 )
556            );
557        }
558
559        $api_base = Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' );
560        if ( empty( $api_base ) ) {
561            $api_base = 'https://public-api.wordpress.com';
562        }
563
564        $response = wp_remote_get(
565            sprintf( '%s/%s/v%s%s', $api_base, $base, $version, $this->append_forwarded_params( $request, $wpcom_path ) ),
566            array( 'timeout' => self::API_TIMEOUT )
567        );
568
569        if ( is_wp_error( $response ) ) {
570            return new WP_Error(
571                'api_error',
572                __( 'Error communicating with the data service.', 'jetpack-premium-analytics' ),
573                array( 'status' => 500 )
574            );
575        }
576
577        return $response;
578    }
579
580    /**
581     * Mirror stats-admin: a successful write invalidates the matching (param-less) read cache, so
582     * the next GET reflects the change instead of serving the cached pre-write value. It busts only
583     * when the request was a write, the prefix opted in (`bust_on_write`), and WPCOM returned 200.
584     *
585     * This is a pure function of the response and route context — it takes the raw client response
586     * rather than reaching out to WPCOM itself, so the full bust decision is unit-testable without
587     * a live connection.
588     *
589     * @param array                $http_response Raw response from the Jetpack client.
590     * @param bool                 $is_write      Whether the request used a write (non-GET) method.
591     * @param array<string, mixed> $opts          Forwarding opts (reads `bust_on_write`).
592     * @param string               $wpcom_path    WPCOM path without the forwarded query string.
593     * @param string               $version       WPCOM API version.
594     * @param string               $base          WPCOM API base.
595     *
596     * @return void
597     */
598    private function maybe_bust_read_cache( array $http_response, bool $is_write, array $opts, string $wpcom_path, string $version, string $base ): void {
599        if ( ! $is_write || empty( $opts['bust_on_write'] ) ) {
600            return;
601        }
602
603        if ( 200 !== (int) wp_remote_retrieve_response_code( $http_response ) ) {
604            return;
605        }
606
607        delete_transient( $this->cache_key_for( $wpcom_path, $version, $base, array() ) );
608    }
609
610    /**
611     * Cache a successful (200) response when a cache key is given, and return it to the caller.
612     *
613     * @param array       $http_response Raw response from the Jetpack client.
614     * @param string|null $cache_key     Transient key, or null to skip caching.
615     *
616     * @return WP_REST_Response|WP_Error
617     */
618    private function cache_and_build_response( array $http_response, ?string $cache_key ) {
619        $status = (int) wp_remote_retrieve_response_code( $http_response );
620        $data   = json_decode( wp_remote_retrieve_body( $http_response ), false );
621
622        // A 200 with an undecodable body means the upstream is degraded; don't cache garbage.
623        if ( 200 === $status && null === $data && JSON_ERROR_NONE !== json_last_error() ) {
624            return new WP_Error(
625                'api_error',
626                __( 'The data service returned an unreadable response.', 'jetpack-premium-analytics' ),
627                array( 'status' => 502 )
628            );
629        }
630
631        $payload = array(
632            'data'    => $data,
633            'status'  => $status,
634            'headers' => $this->extract_forwarded_headers( wp_remote_retrieve_headers( $http_response ) ),
635        );
636
637        if ( null !== $cache_key && 200 === $status ) {
638            set_transient( $cache_key, $payload, self::CACHE_TTL );
639        }
640
641        return $this->build_response( $payload );
642    }
643
644    /**
645     * Rebuild a WP_REST_Response from a cached or freshly fetched payload.
646     *
647     * @param array $payload Stored payload with data, status, and headers.
648     *
649     * @return WP_REST_Response
650     */
651    private function build_response( array $payload ): WP_REST_Response {
652        $response = new WP_REST_Response( $payload['data'], (int) $payload['status'] );
653
654        foreach ( (array) $payload['headers'] as $name => $value ) {
655            $response->header( $name, $value );
656        }
657
658        return $response;
659    }
660
661    /**
662     * Keep only the response headers the dashboard needs (pagination totals).
663     *
664     * @param mixed $headers Response headers as returned by the HTTP API.
665     *
666     * @return array<string, string>
667     */
668    private function extract_forwarded_headers( $headers ): array {
669        if ( $headers instanceof \ArrayAccess || is_array( $headers ) ) {
670            $forwarded = array();
671            foreach ( self::FORWARDED_HEADERS as $name ) {
672                if ( isset( $headers[ $name ] ) ) {
673                    $forwarded[ $name ] = (string) $headers[ $name ];
674                }
675            }
676            return $forwarded;
677        }
678
679        return array();
680    }
681
682    /**
683     * Append the forwarded query params to a WPCOM path, choosing the right separator.
684     *
685     * @param WP_REST_Request $request    Request object.
686     * @param string          $wpcom_path WPCOM path that may already carry a query string.
687     *
688     * @return string
689     */
690    private function append_forwarded_params( WP_REST_Request $request, string $wpcom_path ): string {
691        $params = $this->get_forwarded_params( $request );
692        if ( empty( $params ) ) {
693            return $wpcom_path;
694        }
695
696        $separator = str_contains( $wpcom_path, '?' ) ? '&' : '?';
697
698        return $wpcom_path . $separator . http_build_query( $params );
699    }
700
701    /**
702     * Query params to forward to WPCOM, minus the WordPress routing params, the proxy's own
703     * control params (`endpoint`, `version`, `force_refresh` — which a caller could also pass as
704     * query params since `get_param()` prefers GET), and `site` (the proxy pins the site itself,
705     * so a caller-supplied `site` must not reach the `upgrades` query string). Dropping the
706     * control params also keeps them out of the cache key.
707     *
708     * @param WP_REST_Request $request Request object.
709     *
710     * @return array
711     */
712    private function get_forwarded_params( WP_REST_Request $request ): array {
713        $params = $request->get_query_params();
714        unset( $params['rest_route'], $params['_locale'], $params['site'], $params['endpoint'], $params['version'], $params['force_refresh'] );
715
716        return is_array( $params ) ? $params : array();
717    }
718
719    /**
720     * Transient key for a target path + API version/base + forwarded params (order-independent).
721     * Version and base are part of the key so the same path at different versions doesn't collide.
722     *
723     * @param string $wpcom_path WPCOM path without the forwarded query string.
724     * @param string $version    WPCOM API version.
725     * @param string $base       WPCOM API base.
726     * @param array  $params     Forwarded query params.
727     *
728     * @return string
729     */
730    private function cache_key_for( string $wpcom_path, string $version, string $base, array $params ): string {
731        ksort( $params );
732        $signature = implode( '|', array( $wpcom_path, $version, $base, (string) wp_json_encode( $params, JSON_UNESCAPED_SLASHES ) ) );
733
734        return self::CACHE_PREFIX . md5( $signature );
735    }
736}