[ method, audit-api path under the * site, with `{id}` / `{artifact}` filled from the URL ]. * * @return array> */ public static function routes(): array { $id = '(?P' . self::ID_PATTERN . ')'; return array( '/widget-settings' => array( array( 'GET', '/widget-settings' ), array( 'PUT', '/widget-settings' ), ), '/statement' => array( array( 'GET', '/statement' ), array( 'POST', '/statement' ), ), '/statement/audit-options' => array( array( 'GET', '/statement/audit-options' ) ), '/statement/audit-snapshot' => array( array( 'GET', '/statement/audit-snapshot' ) ), '/statement/preview' => array( array( 'POST', '/statement/preview' ) ), '/statements/' . $id => array( array( 'GET', '/statements/{id}' ) ), '/statements/' . $id . '/generate' => array( array( 'POST', '/statements/{id}/generate' ) ), '/statements/' . $id . '/download/(?Phtml|pdf)' => array( array( 'GET', '/statements/{id}/download/{artifact}' ) ), // The Tracker screen (ACC-412). audit-api answers 404 // `endpoint_not_found` while it does not offer the Tracker, which // the bundle shows as a failed read. '/tracker' => array( array( 'GET', '/tracker' ) ), '/tracker/schedule' => array( array( 'PUT', '/tracker/schedule' ) ), ); } /** * `rest_api_init`: one `register_rest_route` per route, a handler per method. */ public static function register_routes(): void { foreach ( self::routes() as $route => $methods ) { $endpoints = array(); foreach ( $methods as $method ) { list( $verb, $upstream ) = $method; $endpoints[] = array( 'methods' => $verb, 'permission_callback' => array( __CLASS__, 'permission' ), 'callback' => static function ( WP_REST_Request $request ) use ( $verb, $upstream ) { return Accessibit_Rest::proxy( $request, $verb, $upstream ); }, ); } register_rest_route( self::NAMESPACE_V1, $route, $endpoints ); } } /** * An administrator of this site, from our own admin page. * * The messages here and in `proxy()` stay English: the bundle words a * refusal by its code, never by the server's sentence. * * Cookie authentication already refuses a request whose nonce is missing * (it is then logged out) or stale (`rest_cookie_invalid_nonce`). The nonce * is checked again here so the routes answer only to the admin page: an * application password authenticates without one, and nothing but that page * has any use for them. * * @param WP_REST_Request $request The request. * @return true|WP_Error */ public static function permission( WP_REST_Request $request ) { if ( ! current_user_can( 'manage_options' ) ) { return new WP_Error( 'rest_forbidden', 'Sorry, you are not allowed to do that.', array( 'status' => rest_authorization_required_code() ) ); } $nonce = (string) $request->get_header( 'X-WP-Nonce' ); if ( '' === $nonce || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { // Core's own code for a stale nonce, which the bundle turns into // "reload the page". return new WP_Error( 'rest_cookie_invalid_nonce', 'Cookie check failed', array( 'status' => 403 ) ); } return true; } /** * Forward one request to audit-api and answer with what it said. * * @param WP_REST_Request $request The incoming request. * @param string $method The HTTP verb to forward with. * @param string $upstream audit-api's path under the site. * @return WP_REST_Response|WP_Error */ public static function proxy( WP_REST_Request $request, string $method, string $upstream ) { // The admin screens mount the bundle only for a bound, current install; // this is the same refusal for a request that arrives anyway. A stale // binding is a database clone holding the original site's key, and // must not be able to change that site's widget or statement. if ( ! Accessibit_Settings::is_site_linked() || Accessibit_Settings::is_binding_stale() ) { return new WP_Error( 'accessibit_not_connected', 'This site is not connected to AccessiBit.', array( 'status' => 409 ) ); } $path = self::upstream_path( Accessibit_Settings::get_site_id(), $upstream, $request->get_url_params() ); $body = null; if ( 'GET' !== $method ) { $body = self::request_body( (string) $request->get_body() ); if ( null === $body ) { return new WP_Error( 'invalid_request', 'The body must be a JSON object', array( 'status' => 400 ) ); } } $client = Accessibit_Api_Client::from_settings(); /** * Seconds a write through the proxy may wait for AccessiBit. * * @param int $seconds `WRITE_TIMEOUT` by default. */ $write_timeout = (int) apply_filters( 'accessibit_rest_write_timeout', self::WRITE_TIMEOUT ); $result = $client->forward( $method, $path, $body, 'GET' === $method ? 0 : max( 1, $write_timeout ) ); // A widget save whose answer never came back may still have landed: // what is stored now says whether it did. if ( 0 === $result['status'] && 'PUT' === $method && '/widget-settings' === $upstream ) { // Briefly: the save has already waited WRITE_TIMEOUT. $current = $client->forward( 'GET', $path, null, self::RECOVERY_TIMEOUT ); $recovered = self::recovered_save( (string) $body, $current ); if ( null !== $recovered ) { $result = $recovered; } } $answer = self::answer( $result ); if ( null !== $answer['remember'] ) { self::remember_statement( $answer['remember'] ); } $response = new WP_REST_Response( $answer['body'], $answer['status'] ); // The answers are this site's settings, its statement and short-lived // download links: nothing a cache in between should keep. $response->header( 'Cache-Control', 'no-store' ); if ( '' !== $result['retry_after'] ) { $response->header( 'Retry-After', $result['retry_after'] ); } return $response; } /** * A lost widget save's answer, rebuilt from a read of what is stored, or * null when the read does not show this save. * * It shows it when the stored version is past the one the save was made * against and the stored settings are the ones sent. A version moved by * someone else's save has other settings, and stays a failure the page * reports — after which its next save meets the conflict it should. * * Pure, for the unit suite. * * @param string $sent The save's body, as forwarded. * @param array $current `forward()`'s result for a GET of the settings. * @return array|null A `forward()` result to answer with, or null. */ public static function recovered_save( string $sent, array $current ): ?array { if ( 200 !== (int) $current['status'] ) { return null; } $save = json_decode( $sent, true ); $stored = json_decode( (string) $current['body'], true ); if ( ! is_array( $save ) || ! is_array( $stored ) || ! isset( $stored['version'] ) || ! is_int( $stored['version'] ) ) { return null; } // Present, not merely null: a save without `expectedVersion` is one // audit-api refused (428), so nothing it sent can have landed. if ( ! array_key_exists( 'expectedVersion', $save ) || ! array_key_exists( 'settings', $save ) ) { return null; } $expected = $save['expectedVersion']; $advanced = null === $expected ? $stored['version'] > 0 : ( is_int( $expected ) && $stored['version'] > $expected ); // Strictly, in a key-order-free form. `==` would do the key order but // also PHP's loose casts, and on 7.4 `0 == "auto"` is true: settings that // differ could pass for this save. if ( ! $advanced || self::canonical( $stored['settings'] ?? null ) !== self::canonical( $save['settings'] ) ) { return null; } return $current; } /** * A decoded JSON value with every object's keys sorted, so two values * compare with `===` whatever order their keys came in. Lists keep their * order: in them it means something. * * @param mixed $value A value from `json_decode( …, true )`. * @return mixed */ private static function canonical( $value ) { if ( ! is_array( $value ) ) { return $value; } $is_list = array_keys( $value ) === range( 0, count( $value ) - 1 ); $out = array_map( array( __CLASS__, 'canonical' ), $value ); if ( ! $is_list ) { ksort( $out, SORT_STRING ); } return $out; } /** * The body to forward: the browser's JSON as it was sent, or null when it * is not an object. * * Forwarded verbatim rather than decoded into an array and encoded again. * A PHP array cannot tell `{}` from `[]`, so the round trip turned every * empty object in the widget settings or the statement into an empty * list. No body (a generation without `endTemporary`) is an empty object. * * Pure, for the unit suite. * * @param string $raw The request body. * @return string|null */ public static function request_body( string $raw ): ?string { if ( '' === trim( $raw ) ) { return '{}'; } return json_decode( $raw ) instanceof stdClass ? $raw : null; } /** * The audit-api path for a route, with the URL's ids filled in. * * Pure, so the unit suite can pin the mapping. The ids are encoded although * the route patterns already exclude anything that would need it. * * @param string $site_id The bound site. * @param string $upstream The template, e.g. `/statements/{id}/generate`. * @param array $params The route's URL parameters. * @return string */ public static function upstream_path( string $site_id, string $upstream, array $params ): string { $filled = preg_replace_callback( '/\{(id|artifact)\}/', static function ( $m ) use ( $params ) { return rawurlencode( (string) ( $params[ $m[1] ] ?? '' ) ); }, $upstream ); return '/sites/' . rawurlencode( $site_id ) . $filled; } /** * What to answer the browser with, from audit-api's answer. * * - No answer: 503 `network_error` — the request never got out (a firewall, * a security plugin) or timed out. * - A 2xx that is not JSON: 503 `unexpected_response`, never a 200 with an * empty body. The bundle would read that as "nothing saved yet" and offer * defaults that, saved, overwrite what is stored. * * 503 and not 502 for both: the bundle reads a 502 as audit-api's "stored, * not published", which neither of these is. * - Any other non-JSON answer keeps its status, a 5xx becoming 503, with a * body in the shape the bundle reads. * * The body is passed on decoded into OBJECTS, which WordPress encodes back * exactly — as arrays, an empty `{}` in the settings came out as `[]`. * `remember` is the statement in a successful answer, as an array, for * `remember_statement()`. * * Pure, for the unit suite. * * @param array{status: int, body: string} $result `Accessibit_Api_Client::forward()`'s result. * @return array{status: int, body: mixed, remember: array|null} */ public static function answer( array $result ): array { $status = (int) $result['status']; $body = json_decode( (string) $result['body'] ); if ( 0 === $status ) { return self::failure( 503, 'network_error', 'Could not reach AccessiBit' ); } if ( ! is_object( $body ) && ! is_array( $body ) ) { return $status >= 200 && $status < 300 ? self::failure( 503, 'unexpected_response', 'AccessiBit answered with something that is not JSON' ) // A gateway's own 502/504 page included: the bundle words 5xx by // status, and only audit-api's JSON says what really happened. : self::failure( $status >= 500 ? 503 : $status, 'request_failed', 'AccessiBit refused the request' ); } $remember = null; if ( $status >= 200 && $status < 300 && isset( $body->statement ) && is_object( $body->statement ) ) { $assoc = json_decode( (string) $result['body'], true ); $remember = $assoc['statement']; } return array( 'status' => $status, 'body' => $body, 'remember' => $remember, ); } /** * A failure in audit-api's error shape. * * @param int $status HTTP status. * @param string $code Machine-readable code. * @param string $message English, for logs; the bundle words it by code. * @return array{status: int, body: array, remember: null} */ private static function failure( int $status, string $code, string $message ): array { return array( 'status' => $status, 'body' => array( 'error' => array( 'code' => $code, 'message' => $message, ), ), 'remember' => null, ); } /** * Keep the statement's id, and whether it is published, for the shortcode * and the block. * * Learned here, from what the Statement screen reads and writes, rather than * asked for on every public page view. * * @param array $statement A statement payload from audit-api. */ public static function remember_statement( array $statement ): void { // The settings as they are now: the answer may have taken a while, and // the site may have been disconnected or rebound meanwhile. $patch = self::statement_patch( $statement, Accessibit_Settings::reload() ); if ( array() !== $patch ) { Accessibit_Settings::update( $patch ); } } /** * The settings to change for a statement payload, or none. * * Published means any language has a `generatedAt`: the files outlive a new * draft, so a statement once published stays embeddable while it is edited. * Written only on a change, since every statement read passes through here. * * Pure, for the unit suite. * * @param array $statement A statement payload from audit-api. * @param array $settings The stored settings. * @return array */ public static function statement_patch( array $statement, array $settings ): array { $raw_id = $statement['id'] ?? null; if ( ! is_string( $raw_id ) || ! preg_match( '/^' . self::ID_PATTERN . '$/', $raw_id ) ) { return array(); } // Another site's statement, or one answered after this install was // disconnected: remembering it would embed a statement that is not // this site's (ACC-411). $bound_site = (string) ( $settings['site_id'] ?? '' ); if ( isset( $statement['siteId'] ) && (string) $statement['siteId'] !== $bound_site ) { return array(); } $published = false; $files = isset( $statement['files'] ) && is_array( $statement['files'] ) ? $statement['files'] : array(); foreach ( $files as $file ) { if ( is_array( $file ) && ! empty( $file['generatedAt'] ) ) { $published = true; break; } } if ( ( $settings['statement_id'] ?? '' ) === $raw_id && (bool) ( $settings['statement_published'] ?? false ) === $published ) { return array(); } return array( 'statement_id' => $raw_id, 'statement_published' => $published, ); } }