Skip to content
Open
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
5 changes: 4 additions & 1 deletion assets/src/components/SiteModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ const SiteModal = ( {

// A blank API key means the user hasn't typed one yet.
const typedApiKey = ( formData.api_key ?? '' ).trim();
const needsApiKey = ! editing || formData.url !== originalData?.url;
const needsApiKey =
! editing ||
withTrailingSlash( formData.url.trim() ) !==
withTrailingSlash( originalData?.url ?? '' );

// Check if form data has changed from original data (only for editing mode)
const hasChanges = useMemo( () => {
Expand Down
6 changes: 2 additions & 4 deletions inc/Modules/Rest/Algolia_Credentials_Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,8 @@ public function register_routes(): void {
* @param \WP_REST_Request<array<string,mixed>> $request Request.
*/
public function update_algolia_credentials( $request ): \WP_REST_Response|\WP_Error {
$parameters = $request->get_json_params();

$app_id = isset( $parameters['app_id'] ) ? sanitize_text_field( $parameters['app_id'] ) : '';
$write_key = isset( $parameters['write_key'] ) ? sanitize_text_field( $parameters['write_key'] ) : '';
$app_id = sanitize_text_field( $request['app_id'] );
$write_key = sanitize_text_field( $request['write_key'] );

if ( empty( $app_id ) || empty( $write_key ) ) {
return new \WP_Error(
Expand Down
24 changes: 13 additions & 11 deletions inc/Modules/Rest/Shared_Sites_Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Shared_Sites_Controller extends Abstract_REST_Controller {
*/
public function register_routes(): void {
/**
* Register a route which will store array of sites data like site name, site url, its GitHub repo and api key.
* Register a route which will store the brand sites' name, URL, logo and API key.
*/
register_rest_route(
self::NAMESPACE,
Expand Down Expand Up @@ -63,32 +63,34 @@ public function register_routes(): void {
* Set shared sites data.
*
* @param \WP_REST_Request $request The request object.
* @phpstan-param \WP_REST_Request<array<string,mixed>> $request
*
* @return \WP_REST_Response|\WP_Error
*/
public function set_shared_sites( WP_REST_Request $request ): WP_REST_Response|\WP_Error {

$body = $request->get_body();
$decoded_body = json_decode( $body, true );
$sites_data = $decoded_body['sites_data'] ?? [];

$sites_data = (array) $request['sites_data'];
$stored_sites = array_column( Settings::get_shared_sites(), null, 'id' );

// check if same url exists more than once or not.
$urls = [];
$to_check = [];
foreach ( $sites_data as &$site ) {
if ( isset( $site['url'] ) && in_array( $site['url'], $urls, true ) ) {
$url = Utils::normalize_url( (string) ( $site['url'] ?? '' ) );
if ( isset( $site['url'] ) && in_array( $url, $urls, true ) ) {
return new \WP_Error( 'duplicate_site_url', __( 'Brand Site already exists.', 'onesearch' ), [ 'status' => 400 ] );
}

// Use the normalized URL for consistency.
$site['url'] = $url;

// Add a unique ID if it doesn't exist.
$site['id'] = $site['id'] ?? wp_generate_uuid4();

// The browser never gets the keys, so a site saved without one keeps its stored key. Not once its URL changes, since the key belongs to the old site.
// The browser never gets the keys, so a site saved without one keeps its stored key.
$site['api_key'] = trim( (string) ( $site['api_key'] ?? '' ) );
$stored = '' !== $site['id'] ? ( $stored_sites[ $site['id'] ] ?? null ) : null;
$same_url = null !== $stored && Utils::normalize_url( (string) ( $site['url'] ?? '' ) ) === Utils::normalize_url( $stored['url'] );
$same_url = null !== $stored && Utils::normalize_url( $stored['url'] ) === $url;

if ( $same_url && '' === $site['api_key'] ) {
$site['api_key'] = $stored['api_key'];
}
Expand All @@ -98,12 +100,12 @@ public function set_shared_sites( WP_REST_Request $request ): WP_REST_Response|\
$to_check[] = $site;
}

$urls[] = $site['url'] ?? '';
$urls[] = $url;
}
unset( $site );

foreach ( $to_check as $site ) {
$checked = Remote_Client::check_brand_site( (string) ( $site['url'] ?? '' ), $site['api_key'] );
$checked = Remote_Client::check_brand_site( $site['url'], $site['api_key'] );

if ( is_wp_error( $checked ) ) {
$response = rest_convert_error_to_response( $checked );
Expand Down
13 changes: 2 additions & 11 deletions inc/Modules/Settings/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,7 @@ public static function get_shared_sites(): array {

$decrypted_api_key = ! empty( $brand['api_key'] ) ? Encryptor::decrypt( $brand['api_key'] ) : '';

// Always use a trailing-slash URL.
$url = trailingslashit( $brand['url'] );
$url = Utils::normalize_url( $brand['url'] );

$brands_to_return[ $url ] = [
'api_key' => $decrypted_api_key ?: '',
Expand Down Expand Up @@ -291,11 +290,7 @@ public static function get_shared_sites_without_keys(): array {
* }
*/
public static function get_shared_site_by_url( string $site_url ): ?array {
$brand_sites = self::get_shared_sites();

$normalized_url = trailingslashit( $site_url );

return $brand_sites[ $normalized_url ] ?? null;
return self::get_shared_sites()[ Utils::normalize_url( $site_url ) ] ?? null;
}

/**
Expand All @@ -318,13 +313,9 @@ public static function set_shared_sites( array $sites ): bool {
if ( empty( $site['api_key'] ) || empty( $site['url'] ) ) {
continue;
}
// Ensure URLs are trailing-slashed.
$site['url'] = trailingslashit( $site['url'] );

// Encrypt API keys before saving.
$encrypted_key = Encryptor::encrypt( $site['api_key'] );

// Bail if encryption fails.
if ( false === $encrypted_key ) {
return false;
}
Expand Down
26 changes: 26 additions & 0 deletions tests/js/SiteModal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,32 @@ describe( 'SiteModal', () => {
expect( screen.getByText( 'API Key*' ) ).toBeInTheDocument();
} );

it( "doesn't need the key again when an edit only adds or drops the trailing slash", () => {
const stored = {
...baseFormData,
id: 'one',
url: 'https://brand.example.com/',
api_key: '',
};

render(
<SiteModalHarness
editing
initialData={ {
...stored,
url: 'https://brand.example.com',
} }
originalData={ stored }
sites={ [ stored ] }
/>
);

expect(
screen.getByRole( 'button', { name: 'Update Site' } )
).toBeEnabled();
expect( screen.queryByText( 'API Key*' ) ).not.toBeInTheDocument();
} );

it( 'shows the server message when saving fails', async () => {
const onSubmit = vi.fn().mockResolvedValue( 'Invalid site data.' );

Expand Down
123 changes: 123 additions & 0 deletions tests/phpunit/Integration/Modules/Rest/Shared_Sites_ControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,40 @@ public function test_set_shared_sites_rejects_duplicate_urls(): void {
$this->assertSame( [], $requested_urls );
}

/**
* URLs that differ only by a trailing slash are the same site, so they're rejected and nothing is saved or checked.
*/
public function test_set_shared_sites_rejects_urls_that_differ_by_a_trailing_slash(): void {
$requested_urls = [];
$filter = static function ( $preempt, $args, $url ) use ( &$requested_urls ) { // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter
$requested_urls[] = $url;
return new \WP_Error( 'blocked', 'Intercepted' );
};
add_filter( 'pre_http_request', $filter, 10, 3 );

$response = $this->set_shared_sites(
[
[
'url' => 'https://dup.example.com',
'name' => 'Dup 1',
'api_key' => 'k1',
],
[
'url' => 'https://dup.example.com/',
'name' => 'Dup 2',
'api_key' => 'k2',
],
]
);

remove_filter( 'pre_http_request', $filter );

$this->assertSame( 400, $response->get_status() );
$this->assertSame( 'duplicate_site_url', $response->get_data()['code'] );
$this->assertSame( [], $requested_urls );
$this->assertSame( [], Settings::get_shared_sites() );
}

/**
* Saves valid sites data successfully.
*/
Expand Down Expand Up @@ -210,6 +244,41 @@ public function test_set_shared_sites_keeps_stored_keys(): void {
$this->assertArrayNotHasKey( 'api_key', $response->get_data()['shared_sites'][0] );
}

/**
* Brand sites sent as a form are saved like the JSON ones, instead of replacing the stored sites with none.
*/
public function test_set_shared_sites_saves_form_encoded_sites(): void {
Settings::set_shared_sites(
[
[
'id' => 'abc-1',
'name' => 'A',
'url' => 'https://a.example.com',
'api_key' => 'ka',
],
]
);

$sites_data = [
[
'id' => 'abc-1',
'name' => 'A renamed',
'url' => 'https://a.example.com',
],
];

$request = new WP_REST_Request( 'POST', '/onesearch/v1/shared-sites' );
$request->set_header( 'Content-Type', 'application/x-www-form-urlencoded' );
$request->set_body_params( [ 'sites_data' => $sites_data ] );
$request->set_body( http_build_query( [ 'sites_data' => $sites_data ] ) );

$response = $this->server->dispatch( $request );

$this->assertSame( 200, $response->get_status() );
$this->assertSame( 'A renamed', Settings::get_shared_sites()['https://a.example.com/']['name'] );
$this->assertSame( 'ka', Settings::get_shared_sites()['https://a.example.com/']['api_key'] );
}

/**
* A blank key, even with stray whitespace, keeps the stored key, but a site that moved to another URL doesn't keep it and is checked again.
*/
Expand Down Expand Up @@ -273,6 +342,60 @@ public function test_set_shared_sites_only_keeps_the_key_of_an_unchanged_url():
$this->assertSame( '', $sites['https://elsewhere.example.com/']['api_key'] );
}

/**
* Ensures that URLs pasted with spaces around them are trimmed and checked correctly.
*/
public function test_set_shared_sites_trim_url_whitespace(): void {
Settings::set_shared_sites(
[
[
'id' => 'abc-1',
'name' => 'A',
'url' => 'https://a.example.com',
'api_key' => 'key-a',
],
]
);

$checked_urls = [];
$filter = static function ( $preempt, $args, $url ) use ( &$checked_urls ): array { // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter
$checked_urls[] = $url;

return [
'response' => [
'code' => 200,
'message' => 'OK',
],
'body' => '',
'headers' => [],
'cookies' => [],
];
};
add_filter( 'pre_http_request', $filter, 10, 3 );

$response = $this->set_shared_sites(
[
[
'id' => 'abc-1',
'name' => 'A',
'url' => 'https://a.example.com/ ',
],
[
'name' => 'B',
'url' => ' https://b.example.com ',
'api_key' => 'key-b',
],
]
);

remove_filter( 'pre_http_request', $filter );

$this->assertSame( 200, $response->get_status() );
$this->assertSame( [ 'https://b.example.com/wp-json/onesearch/v1/governing-site' ], $checked_urls );
$this->assertSame( [ 'https://a.example.com/', 'https://b.example.com/' ], array_keys( Settings::get_shared_sites() ) );
$this->assertSame( 'key-a', Settings::get_shared_sites()['https://a.example.com/']['api_key'] );
}

/**
* Saving health-checks a new site from this server with its key, and leaves the unchanged ones alone.
*/
Expand Down
Loading