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