diff --git a/assets/src/video-player/web-components/__tests__/player.test.js b/assets/src/video-player/web-components/__tests__/player.test.js
new file mode 100644
index 000000000..4f3a9ab39
--- /dev/null
+++ b/assets/src/video-player/web-components/__tests__/player.test.js
@@ -0,0 +1,50 @@
+/**
+ * Tests for the video player web component.
+ */
+
+describe( 'optimole-video-player', () => {
+ beforeAll( () => {
+ global.OMVideoPlayerBlock = {
+ play: 'Play',
+ pause: 'Pause',
+ mute: 'Mute',
+ unmute: 'Unmute',
+ fullscreen: 'Fullscreen',
+ exitFullscreen: 'Exit fullscreen'
+ };
+
+ require( '../player' );
+ });
+
+ afterEach( () => {
+ document.body.innerHTML = '';
+ });
+
+ const mount = ( src ) => {
+ const player = document.createElement( 'optimole-video-player' );
+ if ( src ) {
+ player.setAttribute( 'video-src', src );
+ }
+ document.body.appendChild( player );
+
+ return player.querySelector( 'video' );
+ };
+
+ test( 'uses the whole video-src attribute as the video source', () => {
+ const sources = [
+ 'https://example.org/clip.mp4',
+ 'https://example.org/clip.mp4?" data-extra="1'
+ ];
+
+ sources.forEach( ( src ) => {
+ const video = mount( src );
+
+ expect( video.getAttribute( 'src' ) ).toBe( src );
+ expect( video.getAttributeNames().sort() ).toEqual([ 'class', 'src' ]);
+ });
+ });
+
+ test( 'leaves the video without a source when video-src is not set', () => {
+ expect( mount( null ).hasAttribute( 'src' ) ).toBe( false );
+ });
+});
diff --git a/assets/src/video-player/web-components/player.js b/assets/src/video-player/web-components/player.js
index ed75ab9e3..a18dbf4ff 100644
--- a/assets/src/video-player/web-components/player.js
+++ b/assets/src/video-player/web-components/player.js
@@ -71,7 +71,7 @@ class OptimoleVideoPlayer extends HTMLElement {
render() {
this.innerHTML = `
-
+
${this.getIcon( this.icons.spinner )}
${this.getIcon( this.icons.play )}
@@ -90,6 +90,11 @@ class OptimoleVideoPlayer extends HTMLElement {
`;
+
+ // The source is set on the element, so the URL is never read as markup.
+ if ( this.videoSrc ) {
+ this.querySelector( '.optml-video' ).setAttribute( 'src', this.videoSrc );
+ }
}
setupEventListeners() {
diff --git a/inc/api.php b/inc/api.php
index da8e38758..abe79bd07 100644
--- a/inc/api.php
+++ b/inc/api.php
@@ -246,7 +246,6 @@ private function build_args( $method, $url, $headers, $params ) {
'method' => $method,
'timeout' => 45,
'user-agent' => 'Optimle WP (v' . OPTML_VERSION . ') ',
- 'sslverify' => false,
'headers' => $headers,
];
if ( $method !== 'GET' ) {
@@ -297,7 +296,6 @@ public function call_onboard_api( $images = [] ) {
],
'timeout' => 60,
'blocking' => true,
- 'sslverify' => false,
'data_format' => 'body',
];
return wp_remote_post( $this->onboard_api_root, $options );
@@ -405,7 +403,6 @@ public function log_offload_error( $error_response ) {
'headers' => [ 'Content-Type' => 'application/json' ],
'timeout' => 15,
'blocking' => true,
- 'sslverify' => false,
'data_format' => 'body',
'body' => [
'error_body' => wp_json_encode( $body ),
diff --git a/inc/lazyload_replacer.php b/inc/lazyload_replacer.php
index 86db4b793..67664aa65 100644
--- a/inc/lazyload_replacer.php
+++ b/inc/lazyload_replacer.php
@@ -41,6 +41,10 @@ final class Optml_Lazyload_Replacer extends Optml_App_Replacer {
* attribute value starts with a backslash is not matched, so JSON-escaped iframe markup is left as written.
*/
private const TAG_ATTRIBUTE = self::TAG_ATTRIBUTE_SEPARATOR . '[^\s"\'>\/=]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s"\'>\\\\][^\s>]*))?';
+ /**
+ * One image tag attribute with its separator, whose value may be JSON-escaped, with quotes written as \" or \'.
+ */
+ private const IMAGE_TAG_ATTRIBUTE = self::TAG_ATTRIBUTE_SEPARATOR . '[^\s"\'>\/=\\\\]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\\\\"[^"]*?\\\\"|\\\\\'[^\']*?\\\\\'|(?:[^\s"\'>\\\\]|\\\\(?!["\']))[^\s>]*))?';
/**
* If frame lazyload is present on page.
*
@@ -282,22 +286,26 @@ public function lazyload_tag_replace( $new_tag, $original_url, $new_url, $optml_
);
}
+ $loading = [];
+ // Most tags do not hold the word at all, and need no pattern.
+ $has_loading = stripos( $new_tag, 'loading' ) !== false && preg_match( $this->image_attribute_pattern( 'loading' ), $new_tag, $loading ) === 1;
+ // Only a quoted value that is not JSON-escaped is changed; any other loading attribute is kept as written.
+ $after_loading = isset( $loading[3] ) ? substr( $new_tag, strlen( $loading[0] ) ) : null;
+
if ( self::instance()->settings->get( 'native_lazyload' ) === 'enabled' ) {
- // First check if loading attribute already exists
- if ( strpos( $new_tag, 'loading=' ) !== false ) {
- // Replace existing loading attribute with lazy
- $loading_attr = $is_slashed ? 'loading=\"lazy\"' : 'loading="lazy"';
- $new_tag = preg_replace( '/loading=(["\'])[^"\']*\1/i', $loading_attr, $new_tag );
- } else {
+ $lazy_attr = $is_slashed ? 'loading=\"lazy\"' : 'loading="lazy"';
+ if ( ! $has_loading ) {
// No loading attribute exists, add it after is_valid_mimetype_from_url( $original_url, [ 'gif' => true, 'svg' => true ] );
@@ -362,8 +370,11 @@ public function lazyload_tag_replace( $new_tag, $original_url, $new_url, $optml_
);
// We remove srcset and sizes attributes since our lazyload does not need them.
- $pattern = '/\s+(?:srcset|sizes)=("[^"]*"|\'[^\']*\'|\\\\"[^\\\\"]*\\\\")/i';
- $new_tag = preg_replace( $pattern, '', $new_tag );
+ foreach ( [ 'srcset', 'sizes' ] as $attribute ) {
+ if ( stripos( $new_tag, $attribute ) !== false ) {
+ $new_tag = preg_replace( $this->image_attribute_pattern( $attribute ), '$1', $new_tag, 1 ) ?? $new_tag;
+ }
+ }
// We keep this for srcset lazyload compatibility that might break our mechanism.
$new_tag = str_replace( 'srcset=', 'old-srcset=', $new_tag );
@@ -374,6 +385,27 @@ public function lazyload_tag_replace( $new_tag, $original_url, $new_url, $optml_
return $new_tag . '' . $no_script_tag . ' ';
}
+ /**
+ * Build the pattern that finds an attribute of an image tag.
+ *
+ * Every attribute before it is matched whole, so the same text inside another attribute's value is not taken
+ * for the attribute. Group 1 is the tag up to the attribute's separator and group 2 the separator. Group 3 is
+ * the value, set only when it is quoted and not JSON-escaped; a JSON-escaped value is matched when it is
+ * double-quoted and holds no backslash.
+ *
+ * @param string $name Attribute name.
+ *
+ * @return string The pattern.
+ */
+ private function image_attribute_pattern( string $name ): string {
+ static $patterns = [];
+
+ if ( ! isset( $patterns[ $name ] ) ) {
+ $patterns[ $name ] = '#^((?:\s*)? (?:(?!\s*' . $name . '\s*=)' . self::IMAGE_TAG_ATTRIBUTE . ')*))(' . self::TAG_ATTRIBUTE_SEPARATOR . ')' . $name . '\s*=\s*(?:("[^"]*"|\'[^\']*\')|\\\\"[^\\\\"]*\\\\"|[^\s"\'>\\\\][^\s>]*)#i';
+ }
+
+ return $patterns[ $name ];
+ }
/**
* Replaces video embeds with lazyload embeds.
*
diff --git a/inc/logger.php b/inc/logger.php
index a020e64aa..73a62c15d 100644
--- a/inc/logger.php
+++ b/inc/logger.php
@@ -10,6 +10,11 @@ class Optml_Logger {
const LOG_SEPARATOR = '==========';
+ /**
+ * The option that holds the random part of this site's log file names.
+ */
+ const FILE_TOKEN_OPTION = 'optml_log_file_token';
+
/**
* Upload directory.
*
@@ -18,9 +23,9 @@ class Optml_Logger {
private $upload_dir;
/**
- * Log filenames.
+ * The log types, with the fixed file name each was stored under before file names carried a hash.
*
- * @var array
+ * @var array
*/
private $log_filenames = [
self::LOG_TYPE_OFFLOAD => 'offload.log',
@@ -64,8 +69,62 @@ private function __construct() {
}
add_action( 'wp_ajax_optml_fetch_logs', [ $this, 'fetch_logs_ajax_handler' ] );
+ add_action( 'admin_init', [ $this, 'protect_log_files' ] );
+ }
+
+ /**
+ * Get the path of a log file.
+ *
+ * The file name carries a random token stored for this site, so the log cannot be requested by guessing its
+ * URL. A log written under the earlier fixed name is moved to the new one.
+ *
+ * @param string $type Type of log (offload/rollback).
+ *
+ * @return string Absolute path of the log file.
+ */
+ private function get_file_path( $type ) {
+ $token = get_option( self::FILE_TOKEN_OPTION );
+ if ( ! is_string( $token ) || '' === $token ) {
+ $token = wp_generate_password( 32, false );
+ update_option( self::FILE_TOKEN_OPTION, $token );
+ }
+
+ $legacy_path = $this->upload_dir . $this->log_filenames[ $type ];
+ $file_path = $this->upload_dir . $type . '-' . $token . '.log';
+
+ // A log that cannot be moved is deleted, so nothing stays under the old name.
+ if ( file_exists( $legacy_path ) && ( file_exists( $file_path ) || ! @rename( $legacy_path, $file_path ) ) ) {
+ wp_delete_file( $legacy_path );
+ }
+
+ return $file_path;
}
+ /**
+ * Move the logs written under the earlier fixed names, and add the files that keep a web server from listing
+ * or serving the log directory. A file that already exists is kept as it is.
+ *
+ * @return void
+ */
+ public function protect_log_files() {
+ if ( ! $this->has_permission() ) {
+ return;
+ }
+
+ foreach ( array_keys( $this->log_filenames ) as $type ) {
+ $this->get_file_path( $type );
+ }
+
+ $files = [
+ 'index.html' => '',
+ '.htaccess' => "\n\tRequire all denied\n \n\n\tDeny from all\n \n",
+ ];
+ foreach ( $files as $name => $content ) {
+ if ( ! file_exists( $this->upload_dir . $name ) ) {
+ file_put_contents( $this->upload_dir . $name, $content );
+ }
+ }
+ }
/**
* Adds a log entry.
*
@@ -84,7 +143,7 @@ public function add_log( $type, $message ) {
return false;
}
- $file_path = $this->upload_dir . $this->log_filenames[ $type ];
+ $file_path = $this->get_file_path( $type );
$handle = @fopen( $file_path, 'a' );
if ( $handle === false ) {
@@ -110,9 +169,9 @@ public function get_log( $type, $lines = 500, $separator = '' ) {
return false;
}
- $file_path = $this->upload_dir . $this->log_filenames[ $type ];
+ $file_path = $this->get_file_path( $type );
- if ( $this->has_logs( $type ) ) {
+ if ( file_exists( $file_path ) ) {
$data = $this->tailCustom( $file_path, $lines, true, $separator );
return nl2br( esc_textarea( $data ) );
}
@@ -131,7 +190,7 @@ public function has_logs( $type ) {
return false;
}
- $file_path = $this->upload_dir . $this->log_filenames[ $type ];
+ $file_path = $this->get_file_path( $type );
return file_exists( $file_path );
}
@@ -215,8 +274,8 @@ private function tailCustom( $filepath, $lines = 1, $adaptive = true, $separator
*/
public function fetch_logs_ajax_handler() {
// Check for nonce security
- $nonce = $_REQUEST['nonce'];
- if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
+ $nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';
+ if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) || ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'Security check failed', 'optimole-wp' ) );
}
diff --git a/inc/manager.php b/inc/manager.php
index b55c2de33..5fbba585c 100644
--- a/inc/manager.php
+++ b/inc/manager.php
@@ -524,7 +524,7 @@ public function replace_content( $html, $partial = false ) {
$missing = $this->page_profiler->missing_devices( $profile_id );
$time = time();
$url = esc_url( esc_js( $this->get_current_url() ) );
- $hmac = wp_hash( $profile_id . $time . $url, 'nonce' );
+ $hmac = Profile::sign( $profile_id, $time, $url );
$js_optimizer = str_replace(
[ Profile::PLACEHOLDER, Profile::PLACEHOLDER_MISSING, Profile::PLACEHOLDER_TIME, Profile::PLACEHOLDER_HMAC, Profile::PLACEHOLDER_URL ],
[ $profile_id, implode( ',', $missing ), strval( $time ), $hmac, $url ],
diff --git a/inc/media_offload.php b/inc/media_offload.php
index 785c2a2b1..42c242f38 100644
--- a/inc/media_offload.php
+++ b/inc/media_offload.php
@@ -109,6 +109,14 @@ class Optml_Media_Offload extends Optml_App_Replacer {
* @var bool|string Used to check if the current processed image was deduplicated.
*/
private static $last_deduplicated = false;
+ /**
+ * The uploads whose attachment was given a deduplicated file name, until their metadata is generated.
+ *
+ * Keyed by blog ID and attachment ID, as attachment IDs repeat across the sites of a network.
+ *
+ * @var array
+ */
+ private static $uploaded_files = [];
/**
* Checks if the plugin was installed before adding POST_OFFLOADED_FLAG.
*
@@ -185,6 +193,7 @@ public static function instance() {
add_filter( 'image_downsize', [ self::$instance, 'generate_filter_downsize_urls' ], 10, 3 );
if ( $offload_new_uploads ) {
add_filter( 'wp_generate_attachment_metadata', [ self::$instance, 'generate_image_meta' ], 10, 2 );
+ add_filter( 'wp_generate_attachment_metadata', [ self::$instance, 'keep_uploaded_file_name' ], 11, 2 );
}
add_filter( 'wp_get_attachment_url', [ self::$instance, 'get_image_attachment_url' ], - 999, 2 );
add_filter( 'wp_insert_post_data', [ self::$instance, 'filter_uploaded_images' ] );
@@ -275,7 +284,12 @@ public function wp_update_attached_file_filter( $file, $attachment_id ) {
// if we have current deduplication set and it contains the filename that is updated
// we replace the updated filename with the deduplicated filename
if ( ! empty( self::$current_file_deduplication ) && stripos( self::$current_file_deduplication, $no_ext_file_name ) !== false ) {
- $file = str_replace( $file_name, self::$current_file_deduplication, $file );
+ $alias = str_replace( $file_name, self::$current_file_deduplication, $file );
+ self::$uploaded_files[ get_current_blog_id() . ':' . $attachment_id ] = [
+ 'file' => $file,
+ 'alias' => $alias,
+ ];
+ $file = $alias;
// we need to store the filename we replaced to check when uploading the image if it was deduplicated
self::$last_deduplicated = $file_name;
@@ -289,6 +303,42 @@ public function wp_update_attached_file_filter( $file, $attachment_id ) {
return $file;
}
+ /**
+ * Point an attachment that stayed local back at the file it was uploaded as.
+ *
+ * The deduplicated name belongs to the copy stored in the cloud. When the upload is not offloaded, no local
+ * file was saved under that name, so the attachment keeps the name of its own file.
+ *
+ * @param array|false $meta Attachment metadata, false when WordPress could not read any.
+ * @param int $attachment_id Attachment ID.
+ *
+ * @return array|false The metadata, unchanged.
+ * @uses filter:wp_generate_attachment_metadata
+ */
+ public function keep_uploaded_file_name( $meta, $attachment_id ) {
+ $key = get_current_blog_id() . ':' . $attachment_id;
+ if ( ! isset( self::$uploaded_files[ $key ] ) ) {
+ return $meta;
+ }
+
+ $upload = self::$uploaded_files[ $key ];
+ unset( self::$uploaded_files[ $key ] );
+
+ if ( isset( $meta['file'] ) && self::is_uploaded_image( $meta['file'] ) ) {
+ return $meta;
+ }
+
+ // The name kept for this upload's offload is dropped, so a later upload is not read from this one's file.
+ if ( self::$last_deduplicated === basename( $upload['file'] ) ) {
+ self::$last_deduplicated = false;
+ }
+ // WordPress points the attachment at a scaled or rotated copy while it builds the metadata; that path is kept.
+ if ( get_post_meta( $attachment_id, '_wp_attached_file', true ) === _wp_relative_upload_path( $upload['alias'] ) ) {
+ update_attached_file( $attachment_id, $upload['file'] );
+ }
+
+ return $meta;
+ }
/**
* Function for `wp_insert_attachment_data` filter-hook.
* Because we remove the images when new images are added the wp deduplication using the files will not work
diff --git a/inc/rest.php b/inc/rest.php
index 50e086529..996e309a6 100644
--- a/inc/rest.php
+++ b/inc/rest.php
@@ -155,6 +155,16 @@ class Optml_Rest {
'type' => 'string',
'required' => true,
],
+ 't' => [
+ 'type' => 'integer',
+ ],
+ 'h' => [
+ 'type' => 'string',
+ ],
+ 'pu' => [
+ 'type' => 'string',
+ 'default' => '',
+ ],
'b' => [
'type' => 'object',
'default' => [],
@@ -997,9 +1007,14 @@ public function optimizations( WP_REST_Request $request ) {
if ( $time < time() - 300 ) {
return $this->response( 'Invalid Signature.', 'error' );
}
- if ( wp_hash( $url . $time . $current_url, 'nonce' ) !== $hmac ) {
+ if ( ! hash_equals( Profile::sign( $url, $time, $current_url ), $hmac ) ) {
return $this->response( 'Invalid Signature.', 'error' );
}
+ // A stored profile is kept until it expires.
+ $profile = new Profile();
+ if ( $profile->exists( $url, $device_type ) ) {
+ return $this->response( 'Profile already stored', 'error' );
+ }
$bg_selectors = $request->get_param( 'b' );
$lcp_data = $request->get_param( 'l' );
$crop_status = $request->get_param( 'c' );
@@ -1040,7 +1055,7 @@ public function optimizations( WP_REST_Request $request ) {
array_map( 'sanitize_url', array_values( $bg_urls ) ),
function ( $url ) {
// we ignore urls that are not from our service
- return strpos( $url, Optml_Config::$service_url ) === 0;
+ return self::is_service_url( $url );
}
);
}
@@ -1081,7 +1096,7 @@ function ( $url ) {
array_map( 'sanitize_url', array_values( $lcp_data['u'] ?? [] ) ),
function ( $url ) {
// we ignore urls that are not from our service
- return strpos( $url, Optml_Config::$service_url ) === 0;
+ return self::is_service_url( $url );
}
);
$sanitized_lcp_data['type'] = empty( $sanitized_lcp_data['imageId'] ) ? 'bg' : 'img';
@@ -1090,7 +1105,6 @@ function ( $url ) {
if ( OPTML_DEBUG ) {
do_action( 'optml_log', 'Storing profile data: ' . $url . ' - ' . $device_type . ' - ' . print_r( $above_fold_images, true ) . print_r( $sanitized_selectors, true ) . print_r( $sanitized_lcp_data, true ) . print_r( $sanitized_missing_dimensions, true ) . print_r( $sanitized_missing_srcsets, true ) . print_r( $sanitized_crop_status, true ) );
}
- $profile = new Profile();
$profile->store( $url, $device_type, $above_fold_images, $sanitized_selectors, $sanitized_lcp_data, $sanitized_missing_dimensions, $sanitized_missing_srcsets, $sanitized_crop_status );
if ( $profile->exists_all( $url ) ) {
@@ -1104,6 +1118,20 @@ function ( $url ) {
return $this->response( 'Optimization data stored successfully' );
}
+ /**
+ * Check that a URL points at this site's Optimole host.
+ *
+ * The trailing slash ends the host, so a longer host that only starts with ours is not accepted. No URL is
+ * accepted while the service URL is not set.
+ *
+ * @param string $url The URL to check.
+ *
+ * @return bool
+ */
+ private static function is_service_url( string $url ): bool {
+ return '' !== Optml_Config::$service_url && strpos( $url, trailingslashit( Optml_Config::$service_url ) ) === 0;
+ }
+
/**
* Method to register above fold data routes.
*
diff --git a/inc/v2/PageProfiler/Profile.php b/inc/v2/PageProfiler/Profile.php
index 7ac84831b..e1a5043a5 100644
--- a/inc/v2/PageProfiler/Profile.php
+++ b/inc/v2/PageProfiler/Profile.php
@@ -105,6 +105,22 @@ public function __construct() {
$this->storage = new $storage_class();
}
+ /**
+ * Sign the values a profile submission is bound to.
+ *
+ * The values are JSON-encoded as a list, so the same characters cannot be split differently between
+ * the fields and still produce the same signature.
+ *
+ * @param string $id The profile ID.
+ * @param int $time When the token was issued, as a Unix timestamp.
+ * @param string $url The URL of the profiled page.
+ *
+ * @return string The signature.
+ */
+ public static function sign( string $id, int $time, string $url ): string {
+ return wp_hash( (string) wp_json_encode( [ $id, $time, $url ] ), 'nonce' );
+ }
+
/**
* Generate a unique ID for the page profile
*
diff --git a/inc/video_player.php b/inc/video_player.php
index e12e968ce..0a20be6f5 100644
--- a/inc/video_player.php
+++ b/inc/video_player.php
@@ -143,6 +143,7 @@ private function enqueue_video_player_component_script() {
'optimole-video-player-component',
OPTML_URL . 'assets/build/video-player/frontend/frontend.js',
$asset_file['dependencies'],
+ $asset_file['version']
);
wp_localize_script( 'optimole-video-player-component', self::LOCALIZATION_VAR, $this->get_localization() );
diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon
index a0f7ec18c..96a623298 100644
--- a/phpstan-baseline.neon
+++ b/phpstan-baseline.neon
@@ -1806,12 +1806,6 @@ parameters:
count: 1
path: inc/lazyload_replacer.php
- -
- message: '#^Property Optml_Logger\:\:\$log_filenames type has no value type specified in iterable type array\.$#'
- identifier: missingType.iterableValue
- count: 1
- path: inc/logger.php
-
-
message: '#^Method Optml_Main\:\:activate\(\) has no return type specified\.$#'
identifier: missingType.return
diff --git a/tests/test-api-requests.php b/tests/test-api-requests.php
new file mode 100644
index 000000000..46500603f
--- /dev/null
+++ b/tests/test-api-requests.php
@@ -0,0 +1,67 @@
+>
+ */
+ private $requests = [];
+
+ /**
+ * Set up the test environment before each test.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->requests = [];
+ add_filter( 'pre_http_request', [ $this, 'capture_request' ], 10, 2 );
+ }
+
+ /**
+ * Record the request and answer it without sending anything.
+ *
+ * @param false|array|WP_Error $response The short-circuit value.
+ * @param array $args The request arguments.
+ *
+ * @return array
+ */
+ public function capture_request( $response, $args ) {
+ $this->requests[] = $args;
+
+ return [
+ 'headers' => [],
+ 'body' => '{}',
+ 'response' => [
+ 'code' => 200,
+ 'message' => 'OK',
+ ],
+ 'cookies' => [],
+ 'filename' => null,
+ ];
+ }
+
+ /**
+ * Every request to the Optimole API checks the server certificate.
+ */
+ public function test_requests_verify_the_server_certificate(): void {
+ $api = new Optml_Api();
+
+ $api->get_user_data( 'test-key' );
+ $api->call_onboard_api( [ 'https://example.org/a.jpg' ] );
+ $api->log_offload_error( [ 'response' => [ 'code' => 500 ] ] );
+
+ $this->assertCount( 3, $this->requests );
+ foreach ( $this->requests as $args ) {
+ $this->assertTrue( $args['sslverify'] );
+ }
+ }
+}
diff --git a/tests/test-lazyload-viewport.php b/tests/test-lazyload-viewport.php
index 6008af84d..34ed65324 100644
--- a/tests/test-lazyload-viewport.php
+++ b/tests/test-lazyload-viewport.php
@@ -165,7 +165,7 @@ private function buildOptimizationsRequest(int $device, int $image_id): WP_REST_
'b' => [],
'u' => $url,
't' => $time,
- 'h' => wp_hash($url . $time . $page, 'nonce'),
+ 'h' => Profile::sign($url, $time, $page),
'pu' => $page,
'l' => ['i' => $image_id, 's' => '', 'u' => []],
]
diff --git a/tests/test-lazyload.php b/tests/test-lazyload.php
index df06e0b05..8ff33e651 100644
--- a/tests/test-lazyload.php
+++ b/tests/test-lazyload.php
@@ -427,6 +427,71 @@ public function test_json_should_add_loading () {
$this->assertEquals(3, substr_count( $replaced_content, 'loading=\"lazy\"' ));
}
+ public function test_native_lazyload_reads_loading_as_an_attribute_only() {
+ // As when the images that are never lazy-loaded were already found on the page.
+ Optml_Tag_Replacer::$lazyload_skipped_images = Optml_Lazyload_Replacer::get_skip_lazyload_limit();
+ $settings = new Optml_Settings();
+ $settings->update( 'native_lazyload', 'enabled' );
+ Optml_Manager::instance()->init();
+
+ $content = ' ';
+ $replaced_content = Optml_Manager::instance()->replace_content( $content );
+
+ $this->assertStringContainsString( ' loading="lazy" src=', $replaced_content );
+ $this->assertStringContainsString( 'title="x loading=" alt="y data-note=z">', $replaced_content );
+ }
+
+ public function test_lazyload_removes_loading_as_an_attribute_only() {
+ // As when the images that are never lazy-loaded were already found on the page.
+ Optml_Tag_Replacer::$lazyload_skipped_images = Optml_Lazyload_Replacer::get_skip_lazyload_limit();
+ $content = ' ';
+ $replaced_content = Optml_Manager::instance()->replace_content( $content );
+ // The noscript copy keeps these attributes.
+ $lazy_tag = strstr( $replaced_content, '', true );
+
+ $this->assertStringContainsString( 'data-opt-src', $lazy_tag );
+ $this->assertStringNotContainsString( 'loading="eager"', $lazy_tag );
+ $this->assertStringContainsString( 'title="x loading=" alt="y data-note=z"', $lazy_tag );
+ }
+
+ public function test_lazyload_removes_srcset_and_sizes_as_attributes_only() {
+ // As when the images that are never lazy-loaded were already found on the page.
+ Optml_Tag_Replacer::$lazyload_skipped_images = Optml_Lazyload_Replacer::get_skip_lazyload_limit();
+ $content = ' ';
+ $replaced_content = Optml_Manager::instance()->replace_content( $content );
+
+ // The noscript copy keeps these attributes.
+ $lazy_tag = strstr( $replaced_content, '', true );
+
+ $this->assertStringContainsString( 'data-opt-src', $lazy_tag );
+ $this->assertStringNotContainsString( 'sizes="100vw"', $lazy_tag );
+ $this->assertStringContainsString( 'title=\' sizes="\' alt="\' data-note=z data-x=\'y\'"', $lazy_tag );
+ }
+ public function test_json_native_lazyload_keeps_the_markup_escaped() {
+ // As when the images that are never lazy-loaded were already found on the page.
+ Optml_Tag_Replacer::$lazyload_skipped_images = Optml_Lazyload_Replacer::get_skip_lazyload_limit();
+ $settings = new Optml_Settings();
+ $settings->update( 'native_lazyload', 'enabled' );
+ Optml_Manager::instance()->init();
+
+ $content = [ " " ];
+ $replaced_content = Optml_Manager::instance()->replace_content( json_encode( $content ) );
+
+ $this->assertStringContainsString( 'loading=\"lazy\"', $replaced_content );
+ $this->assertIsArray( json_decode( $replaced_content, true ) );
+ }
+
+ public function test_lazyload_reads_an_unquoted_value_that_starts_with_a_backslash() {
+ // As when the images that are never lazy-loaded were already found on the page.
+ Optml_Tag_Replacer::$lazyload_skipped_images = Optml_Lazyload_Replacer::get_skip_lazyload_limit();
+ $content = ' ';
+ $replaced_content = Optml_Manager::instance()->replace_content( $content );
+ // The noscript copy keeps these attributes.
+ $lazy_tag = strstr( $replaced_content, '', true );
+
+ $this->assertStringContainsString( 'data-path=\local', $lazy_tag );
+ $this->assertStringNotContainsString( 'sizes="100vw"', $lazy_tag );
+ }
public function test_lazyload_iframe() {
$content = '
diff --git a/tests/test-logger.php b/tests/test-logger.php
index 4736c652a..e73dc0d6d 100644
--- a/tests/test-logger.php
+++ b/tests/test-logger.php
@@ -19,6 +19,8 @@ public function setUp():void {
parent::setUp();
$this->logger = Optml_Logger::instance();
+ // The option is rolled back after each test, while the log files written by earlier tests stay.
+ update_option( Optml_Logger::FILE_TOKEN_OPTION, 'tests' );
}
/**
@@ -51,4 +53,101 @@ public function test_get_log() {
$this->assertStringContainsString( 'Test offload message', $this->logger->get_log( 'offload' ) );
$this->assertStringContainsString( 'Test rollback message', $this->logger->get_log( 'rollback' ) );
}
-}
\ No newline at end of file
+
+ /**
+ * A log file is stored under a name that holds a random token kept for the site.
+ */
+ public function test_log_file_name_holds_a_stored_token() {
+ delete_option( Optml_Logger::FILE_TOKEN_OPTION );
+ $this->logger->add_log( Optml_Logger::LOG_TYPE_OFFLOAD, 'Named log message' );
+
+ $token = get_option( Optml_Logger::FILE_TOKEN_OPTION );
+ $this->assertSame( 32, strlen( (string) $token ) );
+ $this->assertTrue( file_exists( $this->log_dir() . 'offload-' . $token . '.log' ) );
+ $this->assertFalse( file_exists( $this->log_dir() . 'offload.log' ) );
+ unlink( $this->log_dir() . 'offload-' . $token . '.log' );
+ }
+ /**
+ * A log written under the earlier fixed name is read from its new name.
+ */
+ public function test_log_written_under_the_earlier_name_is_moved() {
+ array_map( 'unlink', glob( $this->log_dir() . 'rollback*.log' ) );
+ file_put_contents( $this->log_dir() . 'rollback.log', "[Jan 01 00:00:00] Earlier rollback message\n" );
+
+ $this->assertStringContainsString( 'Earlier rollback message', $this->logger->get_log( Optml_Logger::LOG_TYPE_ROLLBACK ) );
+ $this->assertFalse( file_exists( $this->log_dir() . 'rollback.log' ) );
+ }
+
+ /**
+ * A log keeps its file name when the site's salts change.
+ */
+ public function test_log_file_name_does_not_depend_on_the_salts() {
+ $this->logger->add_log( Optml_Logger::LOG_TYPE_OFFLOAD, 'Message before the salt change' );
+
+ add_filter( 'salt', '__return_empty_string' );
+ $log = $this->logger->get_log( Optml_Logger::LOG_TYPE_OFFLOAD );
+ remove_filter( 'salt', '__return_empty_string' );
+
+ $this->assertStringContainsString( 'Message before the salt change', (string) $log );
+ }
+
+ /**
+ * On admin requests the log directory gets the files that keep a web server from listing or serving it.
+ */
+ public function test_log_directory_is_protected() {
+ $this->assertSame( 10, has_action( 'admin_init', [ $this->logger, 'protect_log_files' ] ) );
+
+ // Each file is added on its own, and one that exists is kept as it is.
+ file_put_contents( $this->log_dir() . '.htaccess', '# kept' );
+ array_map( 'unlink', array_filter( [ $this->log_dir() . 'index.html' ], 'file_exists' ) );
+ $this->logger->protect_log_files();
+
+ $this->assertSame( '# kept', file_get_contents( $this->log_dir() . '.htaccess' ) );
+ $this->assertTrue( file_exists( $this->log_dir() . 'index.html' ) );
+
+ unlink( $this->log_dir() . '.htaccess' );
+ $this->logger->protect_log_files();
+
+ $this->assertStringContainsString( 'Require all denied', file_get_contents( $this->log_dir() . '.htaccess' ) );
+ }
+ /**
+ * The log reader answers administrators only.
+ */
+ public function test_log_reader_answers_administrators_only() {
+ $this->logger->add_log( Optml_Logger::LOG_TYPE_OFFLOAD, 'Reader log message' );
+ $_REQUEST['type'] = Optml_Logger::LOG_TYPE_OFFLOAD;
+
+ wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) );
+ $this->assertStringContainsString( 'Reader log message', $this->read_logs() );
+
+ wp_set_current_user( self::factory()->user->create( [ 'role' => 'subscriber' ] ) );
+ $this->assertStringNotContainsString( 'Reader log message', $this->read_logs() );
+
+ unset( $_REQUEST['type'], $_REQUEST['nonce'] );
+ }
+
+ /**
+ * Call the log reader as the current user, with a valid nonce.
+ *
+ * @return string What the reader printed.
+ */
+ private function read_logs(): string {
+ $_REQUEST['nonce'] = wp_create_nonce( 'wp_rest' );
+
+ ob_start();
+ try {
+ $this->logger->fetch_logs_ajax_handler();
+ } catch ( WPDieException $e ) {
+ // The reader always ends the request.
+ }
+
+ return (string) ob_get_clean();
+ }
+
+ /**
+ * The directory the logs are stored in.
+ */
+ private function log_dir(): string {
+ return trailingslashit( wp_upload_dir()['basedir'] ) . 'optimole-logs/';
+ }
+}
diff --git a/tests/test-media.php b/tests/test-media.php
index 737b68417..9b29a195a 100644
--- a/tests/test-media.php
+++ b/tests/test-media.php
@@ -349,6 +349,98 @@ public function test_retryable_error_and_error() {
$this->assertNotEmpty( get_post_meta( self::$sample_attachement, Optml_Media_Offload::META_KEYS['offload_error'], true ) );
self::$error_mark = false;
}
+ public function test_upload_that_stays_local_keeps_its_own_file(): void {
+ // Not an image, so no metadata is generated and the upload is not offloaded.
+ $local = wp_upload_bits( 'optml-keep.jpg', null, 'not an image' );
+ $local_id = $this->insert_uploaded_image( $local, [ 'post_name' => 'optml-keep-renamed' ] );
+
+ $this->assertSame( $local['file'], get_attached_file( $local_id ) );
+
+ // A later upload whose name holds the first one's is offloaded from its own file.
+ $second_id = $this->insert_uploaded_image( wp_upload_bits( 'optml-keep-second.jpg', null, file_get_contents( OPTML_PATH . 'tests/assets/sample-test.jpg' ) ) );
+
+ $this->assertFileExists( $local['file'] );
+ $this->assertTrue( Optml_Media_Offload::is_uploaded_image( wp_get_attachment_metadata( $second_id )['file'] ) );
+ unlink( $local['file'] );
+ }
+
+ public function test_upload_that_stays_local_keeps_the_copy_wordpress_attached(): void {
+ $upload = wp_upload_bits( 'optml-large.jpg', null, 'not an image' );
+ $attachment_id = wp_insert_attachment( $this->image_postdata( $upload, [ 'post_name' => 'optml-large-renamed' ] ), $upload['file'] );
+ // WordPress points the attachment at the scaled copy of a large image before the metadata filters run.
+ $scaled = str_replace( '.jpg', '-scaled.jpg', $upload['file'] );
+ copy( $upload['file'], $scaled );
+ update_attached_file( $attachment_id, $scaled );
+
+ apply_filters( 'wp_generate_attachment_metadata', [], $attachment_id, 'create' );
+
+ $this->assertSame( $scaled, get_attached_file( $attachment_id ) );
+ array_map( 'unlink', [ $upload['file'], $scaled ] );
+ }
+
+ public function test_upload_that_stays_local_leaves_another_pending_upload_to_be_offloaded(): void {
+ $local = wp_upload_bits( 'optml-first.jpg', null, 'not an image' );
+ $local_id = wp_insert_attachment( $this->image_postdata( $local, [ 'post_name' => 'optml-first-renamed' ] ), $local['file'] );
+ $other = wp_upload_bits( 'optml-other.jpg', null, file_get_contents( OPTML_PATH . 'tests/assets/sample-test.jpg' ) );
+ $other_id = wp_insert_attachment( $this->image_postdata( $other, [ 'post_name' => 'optml-other-renamed' ] ), $other['file'] );
+
+ wp_update_attachment_metadata( $local_id, wp_generate_attachment_metadata( $local_id, $local['file'] ) );
+ wp_update_attachment_metadata( $other_id, wp_generate_attachment_metadata( $other_id, $other['file'] ) );
+
+ $this->assertTrue( Optml_Media_Offload::is_uploaded_image( wp_get_attachment_metadata( $other_id )['file'] ) );
+ unlink( $local['file'] );
+ }
+
+ public function test_upload_that_stays_local_is_matched_by_site_and_attachment(): void {
+ $upload = wp_upload_bits( 'optml-site.jpg', null, 'not an image' );
+ $attachment_id = wp_insert_attachment( $this->image_postdata( $upload, [ 'post_name' => 'optml-site-renamed' ] ), $upload['file'] );
+ $attached = get_attached_file( $attachment_id );
+
+ // The same attachment ID on another site of the network is another attachment.
+ $site_id = $GLOBALS['blog_id'];
+ $GLOBALS['blog_id'] = $site_id + 1;
+ Optml_Media_Offload::instance()->keep_uploaded_file_name( [], $attachment_id );
+ $GLOBALS['blog_id'] = $site_id;
+
+ $this->assertSame( $attached, get_attached_file( $attachment_id ) );
+
+ Optml_Media_Offload::instance()->keep_uploaded_file_name( [], $attachment_id );
+
+ $this->assertSame( $upload['file'], get_attached_file( $attachment_id ) );
+ unlink( $upload['file'] );
+ }
+
+ /**
+ * Build the post fields of an uploaded image's attachment.
+ *
+ * @param array{file: string, url: string} $upload The upload, as wp_upload_bits() returns it.
+ * @param array $postdata Post fields added to the attachment.
+ *
+ * @return array
+ */
+ private function image_postdata( array $upload, array $postdata = [] ): array {
+ return array_merge(
+ [
+ 'post_title' => pathinfo( $upload['file'], PATHINFO_FILENAME ),
+ 'post_mime_type' => 'image/jpeg',
+ 'guid' => $upload['url'],
+ ],
+ $postdata
+ );
+ }
+
+ /**
+ * Create the attachment of an uploaded image the way the media endpoints do.
+ *
+ * @param array{file: string, url: string} $upload The upload, as wp_upload_bits() returns it.
+ * @param array $postdata Post fields added to the attachment.
+ */
+ private function insert_uploaded_image( array $upload, array $postdata = [] ): int {
+ $attachment_id = wp_insert_attachment( $this->image_postdata( $upload, $postdata ), $upload['file'] );
+ wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ) );
+
+ return $attachment_id;
+ }
public function test_duplicated_image() {
$content = wp_get_attachment_image( self::$sample_attachement_upper_case );
diff --git a/tests/test-rest-optimizations.php b/tests/test-rest-optimizations.php
index 2d4c12240..bc0c4a4c1 100644
--- a/tests/test-rest-optimizations.php
+++ b/tests/test-rest-optimizations.php
@@ -109,6 +109,9 @@ public function malformed_payloads(): array {
'background URL nested array' => [ [ 'b' => [ self::WATCHER => [ '#hero' => [ [ 'https://example.com/a.jpg' ] ] ] ] ] ],
'LCP background URL nested array' => [ [ 'b' => [], 'l' => [ 'u' => [ [ 'https://example.com/a.jpg' ] ] ] ] ],
'missing dimensions entry string' => [ [ 'b' => [], 'm' => [ 12 => 'size' ] ] ],
+ 'token time with trailing text' => [ [ 't' => time() . 'h' ] ],
+ 'signature list' => [ [ 'h' => [ 'signature' ] ] ],
+ 'page URL list' => [ [ 'pu' => [ 'page' ] ] ],
];
}
@@ -140,6 +143,95 @@ public function test_only_width_srcset_descriptors_are_stored(): void {
$this->assertSame( [ 400 => [ 'h' => 300, 'w' => 400, 'd' => 1, 's' => '400w', 'b' => 768 ] ], $profile->get_missing_srcsets( 12 ) );
}
+ /**
+ * A signature is only valid for the profile ID, time and page URL it was issued for.
+ */
+ public function test_signature_is_bound_to_each_signed_field(): void {
+ $time = time();
+ $page = home_url( '/' );
+
+ // The same characters, with the last one of the profile ID moved to the front of the time.
+ $response = rest_get_server()->dispatch(
+ $this->build_request(
+ [
+ 'u' => 'split-profile-',
+ 't' => (int) ( '9' . $time ),
+ 'h' => Profile::sign( 'split-profile-9', $time, $page ),
+ ]
+ )
+ );
+
+ $this->assertSame( 'error', $response->get_data()['code'] );
+ $this->assertFalse( ( new Profile() )->get_profile_data( 'split-profile-' )[ Profile::DEVICE_TYPE_DESKTOP ] );
+ }
+
+ /**
+ * A profile that is already stored is not replaced by a later submission.
+ */
+ public function test_stored_profile_is_not_replaced(): void {
+ rest_get_server()->dispatch( $this->build_request( [ 'a' => [ 11 ] ] ) );
+ $response = rest_get_server()->dispatch( $this->build_request( [ 'a' => [ 22 ] ] ) );
+
+ $this->assertSame( 'error', $response->get_data()['code'] );
+ $this->assertSame( [ 11 => true ], ( new Profile() )->get_profile_data( self::PROFILE_ID )[ Profile::DEVICE_TYPE_DESKTOP ]['af'] );
+ }
+
+ /**
+ * Only background URLs on the service host are stored; a longer host that starts with it is another host.
+ */
+ public function test_background_urls_are_kept_for_the_service_host_only(): void {
+ $service_url = Optml_Config::$service_url;
+ $this->assertNotSame( '', $service_url );
+ $urls = [ $service_url . '.example.net/a.jpg', $service_url . '/b.jpg' ];
+
+ rest_get_server()->dispatch(
+ $this->build_request(
+ [
+ 'b' => [ self::WATCHER => [ '#hero' => $urls ] ],
+ 'l' => [ 'u' => $urls ],
+ ]
+ )
+ );
+
+ $stored = ( new Profile() )->get_profile_data( self::PROFILE_ID )[ Profile::DEVICE_TYPE_DESKTOP ];
+ $this->assertSame( [ $service_url . '/b.jpg' ], array_values( $stored['bg'][ self::WATCHER ]['#hero'] ) );
+ $this->assertSame( [ $service_url . '/b.jpg' ], array_values( $stored['lcp']['bgUrls'] ) );
+ }
+
+ /**
+ * No background URL is stored while the service URL is not set.
+ */
+ public function test_background_urls_are_dropped_without_a_service_url(): void {
+ $service_url = Optml_Config::$service_url;
+ Optml_Config::$service_url = '';
+
+ rest_get_server()->dispatch( $this->build_request( [ 'l' => [ 'u' => [ '//example.net/a.jpg' ] ] ] ) );
+ Optml_Config::$service_url = $service_url;
+
+ $this->assertSame( [], ( new Profile() )->get_profile_data( self::PROFILE_ID )[ Profile::DEVICE_TYPE_DESKTOP ]['lcp']['bgUrls'] );
+ }
+
+ /**
+ * The token printed with a page is the one the endpoint accepts for it.
+ */
+ public function test_token_printed_with_a_page_is_accepted(): void {
+ $html = Optml_Manager::instance()->replace_content( 'Page
' . Optml_Admin::get_optimizer_script( true ) . '' );
+ $this->assertSame( 1, preg_match( '/var optimoleDataOptimizer = (\{.*?\});/s', $html, $matches ) );
+ $config = json_decode( $matches[1], true );
+
+ $response = rest_get_server()->dispatch(
+ $this->build_request(
+ [
+ 'u' => $config['pageProfileId'],
+ 't' => $config['_t'],
+ 'h' => $config['hmac'],
+ 'pu' => $config['pageProfileUrl'],
+ ]
+ )
+ );
+
+ $this->assertSame( 'success', $response->get_data()['code'] );
+ }
/**
* Build a signed optimizations request as the frontend profiler sends it.
*
@@ -159,7 +251,7 @@ private function build_request( array $fields ): WP_REST_Request {
'a' => [],
'u' => self::PROFILE_ID,
't' => $time,
- 'h' => wp_hash( self::PROFILE_ID . $time . $page, 'nonce' ),
+ 'h' => Profile::sign( self::PROFILE_ID, $time, $page ),
'pu' => $page,
],
$fields