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