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