Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions inc/Modules/Rest/Abstract_REST_Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ abstract class Abstract_REST_Controller extends WP_REST_Controller implements Re
*/
public function register_hooks(): void {
add_action( 'rest_api_init', [ $this, 'register_routes' ] );
add_filter( 'rest_post_dispatch', [ $this, 'handle_vip_reached_origin' ], 10, 3 );
}

/**
Expand All @@ -54,6 +55,30 @@ public function register_routes(): void {
throw new \Exception( __FUNCTION__ . ' Method not implemented.' );
}

/**
* Marks the 502 and 503 errors of OneSearch's routes as coming from the site, on VIP.
*
* VIP's edge swaps a 502 or 503 body for its error page unless the response says it came from the site.
*
* @see https://docs.wpvip.com/infrastructure/edge-servers/custom-error-pages/.
*
* @param \WP_HTTP_Response $response The response.
* @param \WP_REST_Server $server The REST server.
* @param \WP_REST_Request $request The request.
* @phpstan-param \WP_REST_Request<array<string,mixed>> $request
*/
public function handle_vip_reached_origin( \WP_HTTP_Response $response, \WP_REST_Server $server, \WP_REST_Request $request ): \WP_HTTP_Response { // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter
if (
in_array( $response->get_status(), [ 502, 503 ], true ) &&
str_starts_with( $request->get_route(), '/' . self::NAMESPACE . '/' ) &&
defined( 'VIP_GO_APP_ENVIRONMENT' )
) {
$response->header( 'x-vip-reached-origin', 'true' );
}

return $response;
}

/**
* Whether the request is from a brand site of this governing site, signed with that brand's API key.
*
Expand Down
2 changes: 1 addition & 1 deletion inc/Modules/Rest/Indexer_Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ static function ( array $reported ): array {

if ( is_wp_error( $report ) || ! is_array( $site ) || ! array_key_exists( 'index', $site ) || ( null !== $site['index'] && null === $index ) ) {
$sites[ $site_url ] = [
'error' => is_wp_error( $report ) ? $report->get_error_message() : __( 'The site returned an invalid response.', 'onesearch' ),
'error' => is_wp_error( $report ) ? $report->get_error_message() : __( 'The brand site returned an invalid response.', 'onesearch' ),
];
continue;
}
Expand Down
57 changes: 25 additions & 32 deletions inc/Modules/Rest/Remote_Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ public static function get_all_brand_post_types(): array|\WP_Error {
$all_sites = [];
$errors = [];
foreach ( Settings::get_shared_sites() as $site_data ) {
$response = self::request_brand_site( 'all-post-types', $site_data );
$response = self::request_brand_site( $site_data, 'all-post-types' );

if ( is_wp_error( $response ) ) {
$errors[] = [
Expand All @@ -315,16 +315,7 @@ public static function get_all_brand_post_types(): array|\WP_Error {
continue;
}

$response_data = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $response_data ) ) {
$errors[] = [
'site_url' => $site_data['url'],
'message' => __( 'The site returned an invalid response.', 'onesearch' ),
];
continue;
}

foreach ( $response_data['sites'] as $site_url => $site_data ) {
foreach ( $response['sites'] as $site_url => $site_data ) {
if ( ! is_array( $site_data ) ) {
continue;
}
Expand Down Expand Up @@ -356,7 +347,7 @@ public static function get_all_brand_post_types(): array|\WP_Error {
* @return true|\WP_Error True if the brand site started it.
*/
public static function reindex_brand_site( array $site_data ): true|\WP_Error {
$response = self::request_brand_site( 'indexer', $site_data, [ 'method' => \WP_REST_Server::CREATABLE ] );
$response = self::request_brand_site( $site_data, 'indexer', \WP_REST_Server::CREATABLE );

return is_wp_error( $response ) ? $response : true;
}
Expand All @@ -369,15 +360,7 @@ public static function reindex_brand_site( array $site_data ): true|\WP_Error {
* @return array<mixed>|\WP_Error The report as the brand site sent it.
*/
public static function get_brand_status( array $site_data ): array|\WP_Error {
$response = self::request_brand_site( 'indexer', $site_data );

if ( is_wp_error( $response ) ) {
return $response;
}

$report = json_decode( wp_remote_retrieve_body( $response ), true );

return is_array( $report ) ? $report : new \WP_Error( 'onesearch_rest_invalid_response', __( 'The site returned an invalid response.', 'onesearch' ) );
return self::request_brand_site( $site_data, 'indexer' );
}

/**
Expand Down Expand Up @@ -424,45 +407,55 @@ public static function clear_brand_sites_config_cache( ?string $site_url = null
}

/**
* Sends a request to a OneSearch route on a brand site, and fails unless the brand site answers with a 200.
* Sends a JSON request to a OneSearch route on a brand site, and decodes its answer. Anything but a 200 is an error with the brand site's own message.
*
* @param string $route The route, relative to the OneSearch namespace.
* @param array{url: string, api_key: string} $site_data The brand site, with its stored key.
* @param array<string,mixed> $args Extra request arguments, like the method.
* @param string $route The route, relative to the OneSearch namespace.
* @param string $method The request method.
* @param ?array<string,mixed> $body The request body, if any.
*
* @return array<string,mixed>|\WP_Error The response, or the brand site's error.
* @return array<int|string,mixed>|\WP_Error The decoded response, or the brand site's error.
*/
private static function request_brand_site( string $route, array $site_data, array $args = [] ): array|\WP_Error {
public static function request_brand_site( array $site_data, string $route, string $method = \WP_REST_Server::READABLE, ?array $body = null ): array|\WP_Error {
if ( empty( $site_data['url'] ) || empty( $site_data['api_key'] ) ) {
return new \WP_Error( 'onesearch_missing_site_data', __( "This site's URL or API key is missing. Remove the site and add it again.", 'onesearch' ) );
}

$args = [ 'method' => $method ];
if ( null !== $body ) {
$args['body'] = (string) wp_json_encode( $body );
}

$response = self::request( $site_data['url'], $route, $site_data['api_key'], $args );

if ( is_wp_error( $response ) ) {
$response->add_data( [ 'status' => 502 ] );
return $response;
}

$code = (int) wp_remote_retrieve_response_code( $response );
$data = json_decode( wp_remote_retrieve_body( $response ), true );

if ( 401 === $code || 403 === $code ) {
return new \WP_Error( 'onesearch_bad_key', __( 'The brand site rejected the API key. This usually happens when the brand site regenerates its key. Copy the key from the brand site\'s OneSearch settings, then edit the site under Brand Sites and paste it in.', 'onesearch' ) );
return new \WP_Error( 'onesearch_bad_key', __( 'The brand site rejected the API key. This is usually caused when the brand site regenerates its API key. Copy the key from the brand site\'s OneSearch settings, then edit the site under Brand Sites and paste it in.', 'onesearch' ), [ 'status' => 400 ] );
}

if ( 200 !== $code ) {
$site_error = json_decode( wp_remote_retrieve_body( $response ), true );

return new \WP_Error(
'onesearch_rest_failed_to_connect',
is_string( $site_error['message'] ?? null )
? $site_error['message']
is_string( $data['message'] ?? null )
? $data['message']
/* translators: %d: HTTP status code. */
: sprintf( __( 'The brand site answered with error %d.', 'onesearch' ), $code ),
[ 'status' => $code ]
);
}

return $response;
if ( ! is_array( $data ) ) {
return new \WP_Error( 'onesearch_rest_invalid_response', __( 'The brand site returned an invalid response.', 'onesearch' ), [ 'status' => 500 ] );
}

return $data;
}

/**
Expand Down
12 changes: 1 addition & 11 deletions inc/Modules/Rest/Shared_Sites_Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,17 +108,7 @@ public function set_shared_sites( WP_REST_Request $request ): WP_REST_Response|\
$checked = Remote_Client::check_brand_site( $site['url'], $site['api_key'] );

if ( is_wp_error( $checked ) ) {
$response = rest_convert_error_to_response( $checked );
/**
* VIP's edge swaps a 502 body for its error page unless the response says it came from the site.
*
* @see https://docs.wpvip.com/infrastructure/edge-servers/custom-error-pages/.
*/
if ( 502 === $response->get_status() && defined( 'VIP_GO_APP_ENVIRONMENT' ) ) {
$response->header( 'x-vip-reached-origin', 'true' );
}

return $response;
return $checked;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php
/**
* Tests for Abstract_REST_Controller.
*
* @package OneSearch\Tests\Integration\Modules\Rest
*/

declare( strict_types = 1 );

namespace OneSearch\Tests\Integration\Modules\Rest;

use OneSearch\Main;
use OneSearch\Modules\Rest\Abstract_REST_Controller;
use OneSearch\Tests\TestCase;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;

/**
* The errors OneSearch's routes send through VIP's edge.
*/
#[CoversClass( Abstract_REST_Controller::class )]
#[CoversClass( Main::class )]
class Abstract_REST_ControllerTest extends TestCase {
/**
* {@inheritDoc}
*/
public function setUp(): void {
parent::setUp();

$this->set_up_governing_site();
wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) );

update_option( 'permalink_structure', '/%postname%/' );
( new \ReflectionProperty( Main::class, 'instance' ) )->setValue( null, null );
Main::instance();
}

/**
* {@inheritDoc}
*/
public function tearDown(): void {
global $wp_rest_server;
$wp_rest_server = null;

( new \ReflectionProperty( Main::class, 'instance' ) )->setValue( null, null );
unset( $_SERVER['REQUEST_METHOD'], $_SERVER['CONTENT_TYPE'], $GLOBALS['HTTP_RAW_POST_DATA'] );
$_GET = [];

parent::tearDown();
}

/**
* On VIP, the 502 of an unreachable brand site and a 503 from a OneSearch route carry x-vip-reached-origin.
*/
#[RunInSeparateProcess]
#[PreserveGlobalState( false )]
public function test_marks_502_and_503_errors_as_reached_origin_on_vip(): void {
define( 'VIP_GO_APP_ENVIRONMENT', 'production' );

add_filter( 'pre_http_request', static fn (): \WP_Error => new \WP_Error( 'http_request_failed', 'cURL error 6: Could not resolve host' ) );
$server = $this->serve( 'POST', '/shared-sites', [ 'sites_data' => [ $this->new_brand_site() ] ] );

$this->assertSame( 502, $server->status );
$this->assertSame( 'true', $server->sent_headers['x-vip-reached-origin'] ?? null );
$this->assertSame( 'onesearch_health_check_failed', json_decode( $server->sent_body, true )['code'] ?? null );

add_filter( 'rest_pre_dispatch', static fn (): \WP_Error => new \WP_Error( 'onesearch_down', 'Down for maintenance.', [ 'status' => 503 ] ) );
$server = $this->serve( 'GET', '/shared-sites', [] );

$this->assertSame( 503, $server->status );
$this->assertSame( 'true', $server->sent_headers['x-vip-reached-origin'] ?? null );
$this->assertSame( 'Down for maintenance.', json_decode( $server->sent_body, true )['message'] ?? null );
}

/**
* Off VIP, a 502 doesn't get the header.
*/
public function test_leaves_502_errors_unmarked_off_vip(): void {
$filter = static fn (): \WP_Error => new \WP_Error( 'http_request_failed', 'cURL error 6: Could not resolve host' );
add_filter( 'pre_http_request', $filter );

$server = $this->serve( 'POST', '/shared-sites', [ 'sites_data' => [ $this->new_brand_site() ] ] );

remove_filter( 'pre_http_request', $filter );

$this->assertSame( 502, $server->status );
$this->assertArrayNotHasKey( 'x-vip-reached-origin', $server->sent_headers );
}

/**
* Serves a request to a OneSearch route as WordPress serves it over HTTP.
*
* @param string $method The method.
* @param string $route The route, relative to the OneSearch namespace.
* @param array<string,mixed> $body The JSON body, or the query of a GET request.
*/
private function serve( string $method, string $route, array $body ): \Spy_REST_Server {
global $wp_rest_server;
$wp_rest_server = null;
$server = rest_get_server();
$this->assertInstanceOf( \Spy_REST_Server::class, $server );

$_SERVER['REQUEST_METHOD'] = $method;
if ( 'GET' === $method ) {
$_GET = $body;
} else {
$_SERVER['CONTENT_TYPE'] = 'application/json';
$GLOBALS['HTTP_RAW_POST_DATA'] = (string) wp_json_encode( $body ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
}

$server->serve_request( '/' . Abstract_REST_Controller::NAMESPACE . $route );

return $server;
}

/**
* A brand site that isn't stored yet, so saving it runs its health check.
*
* @return array<string,string>
*/
private function new_brand_site(): array {
return [
'name' => 'Brand Two',
'url' => 'https://two.example.org',
'api_key' => 'key-two',
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ static function ( $preempt, array $args, string $url ) use ( $reports ) { // php
],
$status['sites']['https://brand-a.example.com/']['index']
);
$this->assertSame( [ 'error' => 'The site returned an invalid response.' ], $status['sites']['https://brand-b.example.com/'] );
$this->assertSame( [ 'error' => 'The brand site returned an invalid response.' ], $status['sites']['https://brand-b.example.com/'] );
$this->assertSame( [ 'error' => 'cURL error 7' ], $status['sites']['https://brand-c.example.com/'] );
$this->assertSame(
[
Expand Down
Loading
Loading