Skip to content

Commit 96ddd15

Browse files
fix: SVG sanitization for file uploaded with 'sideload' action
1 parent 17379f8 commit 96ddd15

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

inc/class-main.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ public function init() {
4242
if ( ! function_exists( 'is_wpcom_vip' ) ) {
4343
add_filter( 'upload_mimes', array( $this, 'allow_meme_types' ), PHP_INT_MAX ); // phpcs:ignore WordPressVIPMinimum.Hooks.RestrictedHooks.upload_mimes
4444
add_filter( 'wp_handle_upload_prefilter', array( $this, 'check_svg_and_sanitize' ) );
45+
add_filter( 'wp_handle_sideload_prefilter', array( $this, 'check_svg_and_sanitize' ) );
4546
add_filter( 'wp_check_filetype_and_ext', array( $this, 'fix_mime_type_json_svg' ), 75, 3 );
4647
add_filter( 'wp_generate_attachment_metadata', array( $this, 'generate_svg_attachment_metadata' ), PHP_INT_MAX, 2 );
4748
}
@@ -398,6 +399,10 @@ public function check_svg_and_sanitize( $file ) {
398399
'otter-blocks'
399400
);
400401
}
402+
403+
$path_info = pathinfo( $file['name'] );
404+
$unique_suffix = '-' . substr( md5( uniqid() ), 0, 6 );
405+
$file['name'] = $path_info['filename'] . $unique_suffix . '.' . $path_info['extension'];
401406
}
402407

403408
return $file;

tests/assets/test-img.png

67 Bytes
Loading

tests/test-svg-upload.php

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ private function handle_upload( $file ) {
2121

2222
if ( file_exists( $tmp_path ) ) {
2323
return [
24-
'name' => $file,
24+
'name' => $filename,
2525
'type' => 'image/svg+xml',
2626
'tmp_name' => $tmp_path,
2727
'error' => 0,
@@ -44,9 +44,29 @@ public function test_svg_upload() {
4444
// We check that no error was attached.
4545
$this->assertTrue( empty( $response['error'] ) );
4646

47+
// Check if the filename has been changed.
48+
$this->assertNotEquals( $file['name'], $response['name'] );
49+
4750
$contents = file_get_contents( $response['tmp_name'] );
4851

4952
// We check that the SVG was sanitized.
5053
$this->assertTrue( strpos( $contents, '<script>' ) === false );
5154
}
55+
56+
public function test_non_svg_upload() {
57+
// Set the user as the current user.
58+
wp_set_current_user( 1 );
59+
60+
$main = new ThemeIsle\GutenbergBlocks\Main();
61+
$main->init();
62+
63+
$file = $this->handle_upload( __DIR__ . '/assets/test-img.png' );
64+
$response = $main->check_svg_and_sanitize( $file );
65+
66+
// We check that no error was attached.
67+
$this->assertTrue( empty( $response['error'] ) );
68+
69+
// The filter should not change non-svg file names.
70+
$this->assertEquals( $file['name'], $response['name'] );
71+
}
5272
}

0 commit comments

Comments
 (0)