Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
96.77% |
180 / 186 |
|
95.83% |
23 / 24 |
CRAP | |
0.00% |
0 / 1 |
| Proxy_Controller | |
96.77% |
180 / 186 |
|
95.83% |
23 / 24 |
66 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
1 | |||
| register_hooks | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| register_transient_cleanup_prefix | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| register_routes | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
1 | |||
| allowed_endpoint_pattern | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| config_for | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| check_data_permission | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| validate_data_endpoint | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
8 | |||
| validate_version | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| handle_data_request | |
100.00% |
19 / 19 |
|
100.00% |
1 / 1 |
4 | |||
| base_for_version | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| build_data_path | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| is_write_allowed | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
4 | |||
| busts_cache | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| forward | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
6 | |||
| request | |
82.86% |
29 / 35 |
|
0.00% |
0 / 1 |
5.13 | |||
| prepare_body | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| extract_forwarded_headers | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| maybe_bust_read_cache | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
4 | |||
| cache_and_build_response | |
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
6 | |||
| build_response | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| append_forwarded_params | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| get_forwarded_params | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| cache_key_for | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * REST controller that proxies allowlisted requests to the WordPress.com API. |
| 4 | * |
| 5 | * @package automattic/jetpack-connection |
| 6 | */ |
| 7 | |
| 8 | namespace Automattic\Jetpack\Connection; |
| 9 | |
| 10 | use Jetpack_Options; |
| 11 | use WP_Error; |
| 12 | use WP_REST_Controller; |
| 13 | use WP_REST_Request; |
| 14 | use WP_REST_Response; |
| 15 | use WP_REST_Server; |
| 16 | |
| 17 | /** |
| 18 | * Forwards an allowlisted request to the WordPress.com endpoint of the connected site, |
| 19 | * signed as the blog, caches a successful read in a short-lived transient, and returns it. |
| 20 | * |
| 21 | * One route serves every allowed endpoint, with the WordPress.com API version in the path: |
| 22 | * |
| 23 | * <namespace>/proxy/v<version>/<prefix>/<sub-path> e.g. proxy/v1.1/stats/video-plays |
| 24 | * |
| 25 | * The product owning the route declares the prefixes it exposes (see {@see __construct()}); |
| 26 | * the blog token is never forwarded outside that table. A product with needs beyond the |
| 27 | * table overrides {@see request()}, {@see prepare_body()} or {@see extract_forwarded_headers()}. |
| 28 | * |
| 29 | * @since $$next-version$$ |
| 30 | */ |
| 31 | class Proxy_Controller extends WP_REST_Controller { |
| 32 | |
| 33 | /** |
| 34 | * Per-prefix configuration, the single source of truth for every proxied endpoint group. |
| 35 | * |
| 36 | * @var array<string, array<string, mixed>> |
| 37 | */ |
| 38 | protected $prefix_config; |
| 39 | |
| 40 | /** |
| 41 | * Transient key prefix. |
| 42 | * |
| 43 | * @var string |
| 44 | */ |
| 45 | protected $cache_prefix; |
| 46 | |
| 47 | /** |
| 48 | * Plugin slug handed to the connection manager, or null for the default. |
| 49 | * |
| 50 | * @var string|null |
| 51 | */ |
| 52 | protected $connection_slug; |
| 53 | |
| 54 | /** |
| 55 | * How long a successful response stays cached, in seconds. |
| 56 | * |
| 57 | * @var int |
| 58 | */ |
| 59 | protected $cache_ttl; |
| 60 | |
| 61 | /** |
| 62 | * Timeout for the outbound WordPress.com request, in seconds. |
| 63 | * |
| 64 | * @var int |
| 65 | */ |
| 66 | protected $api_timeout; |
| 67 | |
| 68 | /** |
| 69 | * Constructor. |
| 70 | * |
| 71 | * The prefix table keys double as the security boundary: a request is only routed, and the |
| 72 | * blog token only forwarded, if its first path segment is a key. Keys are lowercase; they are |
| 73 | * matched case-insensitively. A request maps to `proxy/v<version>/<key>/<sub-path>` → |
| 74 | * `/sites/<blog-id>/<key>/<sub-path>`, and the caller chooses the version. |
| 75 | * |
| 76 | * Fields per entry: |
| 77 | * - `capability` (string, required) Capability granting access. `manage_options` is always |
| 78 | * also accepted. A missing value fails closed. |
| 79 | * - `writes` (string[], optional) Sub-paths reachable with POST, the only write verb. A |
| 80 | * matcher ending in `/` covers that sub-path and anything under it; otherwise |
| 81 | * it covers that exact endpoint. Omit for a read-only group. |
| 82 | * - `cache_bust` (bool, optional) If true, a successful POST clears the matching read cache. |
| 83 | * - `path` (string, optional) printf template (`%d` = blog id) for a group NOT under |
| 84 | * `/sites/<id>/`, e.g. `/upgrades?site=%d`. Such a group takes no sub-path. |
| 85 | * - `pattern` (string, optional) Regex the sub-path must fully match, for a group where |
| 86 | * only specific endpoints are safe to expose. Anchored on both ends and |
| 87 | * enforced in the route regex AND when the param is validated, because the |
| 88 | * route capture can be shadowed with `?endpoint=`. |
| 89 | * |
| 90 | * @param string $rest_namespace REST namespace the route lives in. |
| 91 | * @param array<string, array<string, mixed>> $prefix_config The prefix table described above. |
| 92 | * @param string $cache_prefix Transient key prefix, unique to the product. |
| 93 | * @param array<string, mixed> $options `connection_slug`, `cache_ttl` (seconds), `api_timeout` (seconds). |
| 94 | */ |
| 95 | public function __construct( string $rest_namespace, array $prefix_config, string $cache_prefix, array $options = array() ) { |
| 96 | $this->namespace = $rest_namespace; |
| 97 | $this->rest_base = 'proxy'; |
| 98 | $this->prefix_config = $prefix_config; |
| 99 | $this->cache_prefix = $cache_prefix; |
| 100 | $this->connection_slug = $options['connection_slug'] ?? null; |
| 101 | $this->cache_ttl = (int) ( $options['cache_ttl'] ?? 5 * MINUTE_IN_SECONDS ); |
| 102 | $this->api_timeout = (int) ( $options['api_timeout'] ?? 20 ); |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * Hook the route onto `rest_api_init`, and the cache prefix onto the Stats package's |
| 107 | * transient cleanup cron. |
| 108 | * |
| 109 | * @return void |
| 110 | */ |
| 111 | public function register_hooks(): void { |
| 112 | add_action( 'rest_api_init', array( $this, 'register_routes' ) ); |
| 113 | add_filter( 'jetpack_stats_transient_cleanup_prefixes', array( $this, 'register_transient_cleanup_prefix' ) ); |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * Register the cache prefix with the Stats package's transient cleanup cron, which sweeps |
| 118 | * expired entries on sites without a persistent object cache. The coupling is a hook name: |
| 119 | * without the Stats package the filter never fires. |
| 120 | * |
| 121 | * A non-array is returned untouched so the cleanup's own defaults still apply. |
| 122 | * |
| 123 | * @param mixed $prefixes Transient prefixes the cleanup cron will sweep. |
| 124 | * @return mixed |
| 125 | */ |
| 126 | public function register_transient_cleanup_prefix( $prefixes ) { |
| 127 | if ( is_array( $prefixes ) ) { |
| 128 | $prefixes[] = $this->cache_prefix; |
| 129 | } |
| 130 | |
| 131 | return $prefixes; |
| 132 | } |
| 133 | |
| 134 | /** |
| 135 | * Register the proxy route, anchored to the prefix table. |
| 136 | * |
| 137 | * @return void |
| 138 | */ |
| 139 | public function register_routes(): void { |
| 140 | register_rest_route( |
| 141 | $this->namespace, |
| 142 | '/' . $this->rest_base . '/v(?P<version>[0-9]+(?:\.[0-9]+)?)/(?P<endpoint>' . $this->allowed_endpoint_pattern() . ')', |
| 143 | array( |
| 144 | 'methods' => WP_REST_Server::READABLE . ',' . WP_REST_Server::EDITABLE, |
| 145 | 'callback' => array( $this, 'handle_data_request' ), |
| 146 | 'permission_callback' => array( $this, 'check_data_permission' ), |
| 147 | 'args' => array( |
| 148 | 'endpoint' => array( |
| 149 | 'type' => 'string', |
| 150 | 'required' => true, |
| 151 | 'validate_callback' => array( $this, 'validate_data_endpoint' ), |
| 152 | ), |
| 153 | 'version' => array( |
| 154 | 'description' => __( 'WordPress.com API version to forward to (e.g. 1.1, 1.2, 2).', 'jetpack-connection' ), |
| 155 | 'type' => 'string', |
| 156 | 'required' => true, |
| 157 | 'validate_callback' => array( $this, 'validate_version' ), |
| 158 | ), |
| 159 | ), |
| 160 | ) |
| 161 | ); |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Regex alternation of the allowed endpoints: each prefix followed by its `pattern`-constrained |
| 166 | * sub-path when set, or any sub-path otherwise. |
| 167 | * |
| 168 | * @return string |
| 169 | */ |
| 170 | protected function allowed_endpoint_pattern(): string { |
| 171 | $alternatives = array(); |
| 172 | |
| 173 | foreach ( $this->prefix_config as $prefix => $config ) { |
| 174 | $suffix = isset( $config['pattern'] ) ? '/' . $config['pattern'] : '(?:/.*)?'; |
| 175 | $alternatives[] = preg_quote( $prefix, '#' ) . $suffix; |
| 176 | } |
| 177 | |
| 178 | return '(?:' . implode( '|', $alternatives ) . ')'; |
| 179 | } |
| 180 | |
| 181 | /** |
| 182 | * The prefix table entry for an endpoint's top-level prefix, or null if not allowed. |
| 183 | * |
| 184 | * @param string $endpoint The endpoint value (`get_param('endpoint')`). |
| 185 | * @return array<string, mixed>|null |
| 186 | */ |
| 187 | protected function config_for( string $endpoint ): ?array { |
| 188 | $prefix = strtolower( explode( '/', $endpoint )[0] ); |
| 189 | |
| 190 | return $this->prefix_config[ $prefix ] ?? null; |
| 191 | } |
| 192 | |
| 193 | /** |
| 194 | * Permission callback: the prefix's capability grants access, and `manage_options` always does. |
| 195 | * |
| 196 | * @param WP_REST_Request $request Request object. |
| 197 | * @return bool |
| 198 | */ |
| 199 | public function check_data_permission( WP_REST_Request $request ): bool { |
| 200 | $config = $this->config_for( (string) $request->get_param( 'endpoint' ) ); |
| 201 | if ( null === $config ) { |
| 202 | return false; |
| 203 | } |
| 204 | |
| 205 | // Fall back to `do_not_allow` so an entry missing `capability` fails closed. |
| 206 | $capability = $config['capability'] ?? 'do_not_allow'; |
| 207 | |
| 208 | // phpcs:ignore WordPress.WP.Capabilities.Unknown -- The capability comes from the prefix table. |
| 209 | return current_user_can( 'manage_options' ) || current_user_can( $capability ); |
| 210 | } |
| 211 | |
| 212 | /** |
| 213 | * Confine an endpoint to a relative sub-path under an allowed prefix, rejecting traversal |
| 214 | * (`..`) and schemes (`:`). Commas are permitted since stats sub-paths carry them (UTM params). |
| 215 | * |
| 216 | * The prefix is re-checked here, not just in the route regex: WP's `get_param()` prefers |
| 217 | * GET/JSON/POST over the URL capture, so a caller could otherwise shadow the matched `endpoint` |
| 218 | * with `?endpoint=…`. This runs against the same value the handler forwards. |
| 219 | * |
| 220 | * @param mixed $value Raw endpoint param. |
| 221 | * @return bool |
| 222 | */ |
| 223 | public function validate_data_endpoint( $value ): bool { |
| 224 | $value = (string) $value; |
| 225 | |
| 226 | if ( str_contains( $value, '..' ) ) { |
| 227 | return false; |
| 228 | } |
| 229 | |
| 230 | if ( ! preg_match( '#^[\w.,/-]+$#', $value ) ) { |
| 231 | return false; |
| 232 | } |
| 233 | |
| 234 | $config = $this->config_for( $value ); |
| 235 | if ( null === $config ) { |
| 236 | return false; |
| 237 | } |
| 238 | |
| 239 | $prefix = strtolower( explode( '/', $value )[0] ); |
| 240 | |
| 241 | // A prefix with a fixed `path` takes no sub-path: build_data_path() would mis-route it. |
| 242 | if ( isset( $config['path'] ) && $prefix !== rtrim( strtolower( $value ), '/' ) ) { |
| 243 | return false; |
| 244 | } |
| 245 | |
| 246 | if ( isset( $config['pattern'] ) && ! preg_match( '#^' . preg_quote( $prefix, '#' ) . '/' . $config['pattern'] . '$#i', rtrim( $value, '/' ) ) ) { |
| 247 | return false; |
| 248 | } |
| 249 | |
| 250 | return true; |
| 251 | } |
| 252 | |
| 253 | /** |
| 254 | * A WordPress.com API version is one or two dot-separated numbers (e.g. `2`, `1.1`). |
| 255 | * |
| 256 | * @param mixed $value Raw version param. |
| 257 | * @return bool |
| 258 | */ |
| 259 | public function validate_version( $value ): bool { |
| 260 | return (bool) preg_match( '#^[0-9]+(\.[0-9]+)?$#', (string) $value ); |
| 261 | } |
| 262 | |
| 263 | /** |
| 264 | * Proxy a request to its WordPress.com endpoint, at the caller-chosen API version. |
| 265 | * |
| 266 | * @param WP_REST_Request $request Request object. |
| 267 | * @return WP_REST_Response|WP_Error |
| 268 | */ |
| 269 | public function handle_data_request( WP_REST_Request $request ) { |
| 270 | $endpoint = (string) $request->get_param( 'endpoint' ); |
| 271 | $method = strtoupper( $request->get_method() ); |
| 272 | |
| 273 | // Reads are open across the allowed prefixes; only POST may mutate, and only on the |
| 274 | // write allowlist. Everything else is rejected locally. |
| 275 | if ( 'GET' !== $method && ! ( 'POST' === $method && $this->is_write_allowed( $endpoint ) ) ) { |
| 276 | return new WP_Error( |
| 277 | 'rest_read_only', |
| 278 | __( 'This endpoint is read-only.', 'jetpack-connection' ), |
| 279 | array( 'status' => 405 ) |
| 280 | ); |
| 281 | } |
| 282 | |
| 283 | $version = (string) $request->get_param( 'version' ); |
| 284 | |
| 285 | return $this->forward( |
| 286 | $request, |
| 287 | $this->build_data_path( $endpoint ), |
| 288 | array( |
| 289 | 'version' => $version, |
| 290 | 'base' => $this->base_for_version( $version ), |
| 291 | 'bust_on_write' => $this->busts_cache( $endpoint ), |
| 292 | 'config' => $this->config_for( $endpoint ) ?? array(), |
| 293 | ) |
| 294 | ); |
| 295 | } |
| 296 | |
| 297 | /** |
| 298 | * The WordPress.com API base for a version: v2 lives under `wpcom`, v1.x under `rest`. |
| 299 | * |
| 300 | * @param string $version WordPress.com API version. |
| 301 | * @return string |
| 302 | */ |
| 303 | protected function base_for_version( string $version ): string { |
| 304 | return 2 === (int) $version ? 'wpcom' : 'rest'; |
| 305 | } |
| 306 | |
| 307 | /** |
| 308 | * Build the WordPress.com path for an endpoint. |
| 309 | * |
| 310 | * @param string $endpoint The validated, allowed sub-path. |
| 311 | * @return string |
| 312 | */ |
| 313 | protected function build_data_path( string $endpoint ): string { |
| 314 | $site_id = (int) Jetpack_Options::get_option( 'id' ); |
| 315 | |
| 316 | $config = $this->config_for( $endpoint ); |
| 317 | if ( null !== $config && isset( $config['path'] ) ) { |
| 318 | return sprintf( $config['path'], $site_id ); |
| 319 | } |
| 320 | |
| 321 | return sprintf( '/sites/%d/%s', $site_id, $endpoint ); |
| 322 | } |
| 323 | |
| 324 | /** |
| 325 | * Whether a POST may be forwarded for this endpoint, per the prefix's `writes`. |
| 326 | * |
| 327 | * @param string $endpoint The validated sub-path. |
| 328 | * @return bool |
| 329 | */ |
| 330 | protected function is_write_allowed( string $endpoint ): bool { |
| 331 | $endpoint = strtolower( $endpoint ); |
| 332 | $config = $this->config_for( $endpoint ); |
| 333 | |
| 334 | foreach ( $config['writes'] ?? array() as $matcher ) { |
| 335 | $matcher = strtolower( $matcher ); |
| 336 | $matches = str_ends_with( $matcher, '/' ) |
| 337 | ? str_starts_with( $endpoint, $matcher ) |
| 338 | : $endpoint === $matcher; |
| 339 | if ( $matches ) { |
| 340 | return true; |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | return false; |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * Whether a successful write to this endpoint should invalidate the matching read cache. |
| 349 | * |
| 350 | * @param string $endpoint The validated sub-path. |
| 351 | * @return bool |
| 352 | */ |
| 353 | protected function busts_cache( string $endpoint ): bool { |
| 354 | $config = $this->config_for( $endpoint ); |
| 355 | |
| 356 | return ! empty( $config['cache_bust'] ); |
| 357 | } |
| 358 | |
| 359 | /** |
| 360 | * Serve a cached payload when available, otherwise forward to WordPress.com and cache the result. |
| 361 | * |
| 362 | * @param WP_REST_Request $request Request object. |
| 363 | * @param string $wpcom_path WordPress.com path without the forwarded query string. |
| 364 | * @param array<string, mixed> $opts `version`, `base`, `bust_on_write`, `config` (the prefix entry). |
| 365 | * @return WP_REST_Response|WP_Error |
| 366 | */ |
| 367 | protected function forward( WP_REST_Request $request, string $wpcom_path, array $opts ) { |
| 368 | $version = $opts['version'] ?? '2'; |
| 369 | $base = $opts['base'] ?? 'wpcom'; |
| 370 | $is_read = 'GET' === strtoupper( $request->get_method() ); |
| 371 | |
| 372 | $cache_key = $is_read && null === $request->get_param( 'force_refresh' ) |
| 373 | ? $this->cache_key_for( $wpcom_path, $version, $base, $this->get_forwarded_params( $request ) ) |
| 374 | : null; |
| 375 | if ( null !== $cache_key ) { |
| 376 | $cached = get_transient( $cache_key ); |
| 377 | if ( false !== $cached ) { |
| 378 | return $this->build_response( $cached ); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | $response = $this->request( $request, $wpcom_path, $opts ); |
| 383 | if ( is_wp_error( $response ) ) { |
| 384 | return $response; |
| 385 | } |
| 386 | |
| 387 | $this->maybe_bust_read_cache( $response, ! $is_read, $opts, $wpcom_path, $version, $base ); |
| 388 | |
| 389 | return $this->cache_and_build_response( $response, $cache_key ); |
| 390 | } |
| 391 | |
| 392 | /** |
| 393 | * Send the request to WordPress.com, signed as the blog. |
| 394 | * |
| 395 | * The transport seam: a product that must reach an endpoint another way, for a group its |
| 396 | * table marks, overrides this and falls back to the parent for the rest. |
| 397 | * |
| 398 | * @param WP_REST_Request $request Request object. |
| 399 | * @param string $wpcom_path WordPress.com path without the forwarded query string. |
| 400 | * @param array<string, mixed> $opts Forwarding opts, as passed to {@see forward()}. |
| 401 | * @return array|WP_Error Raw HTTP response, or an error. |
| 402 | */ |
| 403 | protected function request( WP_REST_Request $request, string $wpcom_path, array $opts ) { |
| 404 | if ( ! ( new Manager( $this->connection_slug ) )->is_connected() ) { |
| 405 | return new WP_Error( |
| 406 | 'no_connection', |
| 407 | __( 'Please connect Jetpack to load your data.', 'jetpack-connection' ), |
| 408 | array( 'status' => 403 ) |
| 409 | ); |
| 410 | } |
| 411 | |
| 412 | $method = strtoupper( $request->get_method() ); |
| 413 | $args = array( |
| 414 | 'method' => $method, |
| 415 | 'timeout' => $this->api_timeout, |
| 416 | ); |
| 417 | $body = null; |
| 418 | if ( 'GET' !== $method ) { |
| 419 | $body = $this->prepare_body( $request->get_body(), $opts ); |
| 420 | $args['headers'] = array( 'Content-Type' => 'application/json' ); |
| 421 | } |
| 422 | |
| 423 | try { |
| 424 | $response = Client::wpcom_json_api_request_as_blog( |
| 425 | $this->append_forwarded_params( $request, $wpcom_path ), |
| 426 | $opts['version'] ?? '2', |
| 427 | $args, |
| 428 | $body, |
| 429 | $opts['base'] ?? 'wpcom' |
| 430 | ); |
| 431 | } catch ( \Exception $e ) { |
| 432 | return new WP_Error( |
| 433 | 'api_error', |
| 434 | __( 'Error processing the request.', 'jetpack-connection' ), |
| 435 | array( 'status' => 500 ) |
| 436 | ); |
| 437 | } |
| 438 | |
| 439 | if ( is_wp_error( $response ) ) { |
| 440 | return new WP_Error( |
| 441 | 'api_error', |
| 442 | __( 'Error communicating with the data service.', 'jetpack-connection' ), |
| 443 | array( 'status' => 500 ) |
| 444 | ); |
| 445 | } |
| 446 | |
| 447 | return $response; |
| 448 | } |
| 449 | |
| 450 | /** |
| 451 | * The body to forward with a write. Forwarded untouched by default; a product that must |
| 452 | * rewrite a body for a group its table marks overrides this. |
| 453 | * |
| 454 | * @param string $body The incoming request body. |
| 455 | * @param array<string, mixed> $opts Forwarding opts, as passed to {@see forward()}. |
| 456 | * @return string |
| 457 | */ |
| 458 | protected function prepare_body( string $body, array $opts ): string { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- The seam's signature, for subclasses. |
| 459 | return $body; |
| 460 | } |
| 461 | |
| 462 | /** |
| 463 | * Response headers worth forwarding back to the client. None by default. |
| 464 | * |
| 465 | * @param mixed $headers Response headers as returned by the HTTP API. |
| 466 | * @return array<string, string> |
| 467 | */ |
| 468 | protected function extract_forwarded_headers( $headers ): array { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- The seam's signature, for subclasses. |
| 469 | return array(); |
| 470 | } |
| 471 | |
| 472 | /** |
| 473 | * A successful write invalidates the matching (param-less) read cache, so the next GET reflects |
| 474 | * the change. It busts only when the request was a write, the prefix opted in (`bust_on_write`), |
| 475 | * and WordPress.com returned 200. |
| 476 | * |
| 477 | * @param array $http_response Raw response from the Jetpack client. |
| 478 | * @param bool $is_write Whether the request used a write (non-GET) method. |
| 479 | * @param array<string, mixed> $opts Forwarding opts (reads `bust_on_write`). |
| 480 | * @param string $wpcom_path WordPress.com path without the forwarded query string. |
| 481 | * @param string $version WordPress.com API version. |
| 482 | * @param string $base WordPress.com API base. |
| 483 | * @return void |
| 484 | */ |
| 485 | protected function maybe_bust_read_cache( array $http_response, bool $is_write, array $opts, string $wpcom_path, string $version, string $base ): void { |
| 486 | if ( ! $is_write || empty( $opts['bust_on_write'] ) ) { |
| 487 | return; |
| 488 | } |
| 489 | |
| 490 | if ( 200 !== (int) wp_remote_retrieve_response_code( $http_response ) ) { |
| 491 | return; |
| 492 | } |
| 493 | |
| 494 | delete_transient( $this->cache_key_for( $wpcom_path, $version, $base, array() ) ); |
| 495 | } |
| 496 | |
| 497 | /** |
| 498 | * Cache a successful (200) response when a cache key is given, and return it to the caller. |
| 499 | * |
| 500 | * @param array $http_response Raw response from the Jetpack client. |
| 501 | * @param string|null $cache_key Transient key, or null to skip caching. |
| 502 | * @return WP_REST_Response|WP_Error |
| 503 | */ |
| 504 | protected function cache_and_build_response( array $http_response, ?string $cache_key ) { |
| 505 | $status = (int) wp_remote_retrieve_response_code( $http_response ); |
| 506 | $data = json_decode( wp_remote_retrieve_body( $http_response ), false ); |
| 507 | |
| 508 | // A 200 with an undecodable body means the upstream is degraded; don't cache garbage. |
| 509 | if ( 200 === $status && null === $data && JSON_ERROR_NONE !== json_last_error() ) { |
| 510 | return new WP_Error( |
| 511 | 'api_error', |
| 512 | __( 'The data service returned an unreadable response.', 'jetpack-connection' ), |
| 513 | array( 'status' => 502 ) |
| 514 | ); |
| 515 | } |
| 516 | |
| 517 | $payload = array( |
| 518 | 'data' => $data, |
| 519 | 'status' => $status, |
| 520 | 'headers' => $this->extract_forwarded_headers( wp_remote_retrieve_headers( $http_response ) ), |
| 521 | ); |
| 522 | |
| 523 | if ( null !== $cache_key && 200 === $status ) { |
| 524 | set_transient( $cache_key, $payload, $this->cache_ttl ); |
| 525 | } |
| 526 | |
| 527 | return $this->build_response( $payload ); |
| 528 | } |
| 529 | |
| 530 | /** |
| 531 | * Rebuild a WP_REST_Response from a cached or freshly fetched payload. |
| 532 | * |
| 533 | * @param array $payload Stored payload with data, status, and headers. |
| 534 | * @return WP_REST_Response |
| 535 | */ |
| 536 | protected function build_response( array $payload ): WP_REST_Response { |
| 537 | $response = new WP_REST_Response( $payload['data'], (int) $payload['status'] ); |
| 538 | |
| 539 | foreach ( (array) $payload['headers'] as $name => $value ) { |
| 540 | $response->header( $name, $value ); |
| 541 | } |
| 542 | |
| 543 | return $response; |
| 544 | } |
| 545 | |
| 546 | /** |
| 547 | * Append the forwarded query params to a WordPress.com path, choosing the right separator. |
| 548 | * |
| 549 | * @param WP_REST_Request $request Request object. |
| 550 | * @param string $wpcom_path WordPress.com path that may already carry a query string. |
| 551 | * @return string |
| 552 | */ |
| 553 | protected function append_forwarded_params( WP_REST_Request $request, string $wpcom_path ): string { |
| 554 | $params = $this->get_forwarded_params( $request ); |
| 555 | if ( empty( $params ) ) { |
| 556 | return $wpcom_path; |
| 557 | } |
| 558 | |
| 559 | $separator = str_contains( $wpcom_path, '?' ) ? '&' : '?'; |
| 560 | |
| 561 | return $wpcom_path . $separator . http_build_query( $params ); |
| 562 | } |
| 563 | |
| 564 | /** |
| 565 | * Query params to forward, minus the WordPress routing params, the proxy's own control params |
| 566 | * (`endpoint`, `version`, `force_refresh`, which a caller could also pass as query params) and |
| 567 | * `site`, since the proxy pins the site itself. Dropping them also keeps them out of the cache key. |
| 568 | * |
| 569 | * @param WP_REST_Request $request Request object. |
| 570 | * @return array |
| 571 | */ |
| 572 | protected function get_forwarded_params( WP_REST_Request $request ): array { |
| 573 | $params = $request->get_query_params(); |
| 574 | unset( $params['rest_route'], $params['_locale'], $params['site'], $params['endpoint'], $params['version'], $params['force_refresh'] ); |
| 575 | |
| 576 | return is_array( $params ) ? $params : array(); |
| 577 | } |
| 578 | |
| 579 | /** |
| 580 | * Transient key for a target path + API version/base + forwarded params, in any order. |
| 581 | * |
| 582 | * @param string $wpcom_path WordPress.com path without the forwarded query string. |
| 583 | * @param string $version WordPress.com API version. |
| 584 | * @param string $base WordPress.com API base. |
| 585 | * @param array $params Forwarded query params. |
| 586 | * @return string |
| 587 | */ |
| 588 | protected function cache_key_for( string $wpcom_path, string $version, string $base, array $params ): string { |
| 589 | ksort( $params ); |
| 590 | $signature = implode( '|', array( $wpcom_path, $version, $base, (string) wp_json_encode( $params, JSON_UNESCAPED_SLASHES ) ) ); |
| 591 | |
| 592 | return $this->cache_prefix . md5( $signature ); |
| 593 | } |
| 594 | } |