diff --git a/.github/workflows/wp-compatibility-test.yml b/.github/workflows/wp-compatibility-test.yml index 3fe3db2..e173216 100644 --- a/.github/workflows/wp-compatibility-test.yml +++ b/.github/workflows/wp-compatibility-test.yml @@ -1469,7 +1469,7 @@ jobs: env: # The unit suite must cover at least this percentage of the production lines. It is set a few # points below the measured value, so it stops a real drop without failing on small changes. - MINIMUM_LINE_COVERAGE: '58' + MINIMUM_LINE_COVERAGE: '61' steps: - name: Checkout code diff --git a/includes/download.php b/includes/download.php index 0f5f574..2898b31 100644 --- a/includes/download.php +++ b/includes/download.php @@ -279,16 +279,15 @@ function esse_prepare_download_output(): true|WP_Error { } /** - * Streams the exact opened file content and terminates the request. + * Streams the exact opened file content, and logs whether all of it was sent. * * @since 2.0.0 * @param resource $handle Validated open file handle. * @param string $filename Filename for logging. * @param int $expected_size Expected streamed byte count. * @SuppressWarnings("PHPMD.ErrorControlOperator") - * @SuppressWarnings("PHPMD.ExitExpression") The request ends when the file has been sent. */ -function esse_output_file_content( $handle, string $filename, int $expected_size ): never { +function esse_output_file_content( $handle, string $filename, int $expected_size ): void { $streamed_bytes = @fpassthru( $handle ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Stream failure must not inject warning text into an attachment response. fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Closing the exact local download handle. @@ -297,17 +296,16 @@ function esse_output_file_content( $handle, string $filename, int $expected_size } else { esse_log( 'Secure file download served from an identity-checked handle: ' . $filename, 'info' ); } - - exit; } /** - * Serves a file download with exact opened-object validation. + * Opens a download, starts its rate limit, records it, and sends its headers. * - * @since 2.0.0 + * @since 2.1.4 * @param array{filename:string,filepath:string,filesize:int,device:int,inode:int} $file_data Validated file information. + * @return array{handle:resource,filename:string,filesize:int} Opened download. */ -function esse_serve_file_download( array $file_data ): never { +function esse_start_file_download( array $file_data ): array { $opened_file = esse_open_validated_export_download( $file_data ); if ( is_wp_error( $opened_file ) ) { esse_record_activity( 'Export download refused: ' . $opened_file->get_error_message() ); @@ -324,5 +322,20 @@ function esse_serve_file_download( array $file_data ): never { esse_start_download_rate_limit(); esse_record_activity( 'Export downloaded: ' . $opened_file['filename'] ); esse_set_download_headers( $opened_file['filename'], $opened_file['filesize'] ); + + return $opened_file; +} + +/** + * Serves a file download with exact opened-object validation, and ends the request. + * + * @since 2.0.0 + * @param array{filename:string,filepath:string,filesize:int,device:int,inode:int} $file_data Validated file information. + * @SuppressWarnings("PHPMD.ExitExpression") The request ends when the file has been sent. + */ +function esse_serve_file_download( array $file_data ): never { + $opened_file = esse_start_file_download( $file_data ); esse_output_file_content( $opened_file['handle'], $opened_file['filename'], $opened_file['filesize'] ); + + exit; } diff --git a/tests/download-request.php b/tests/download-request.php new file mode 100644 index 0000000..aee1ecf --- /dev/null +++ b/tests/download-request.php @@ -0,0 +1,45 @@ + + * + * @package EngineScript_Site_Exporter + */ + +require __DIR__ . '/bootstrap.php'; + +$sse_work = rtrim( (string) ( $argv[1] ?? '' ), '/\\' ); +$sse_report = (string) ( $argv[2] ?? '' ); +if ( '' === $sse_work || '' === $sse_report || ! is_dir( $sse_work ) ) { + fwrite( STDERR, "Usage: php download-request.php \n" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite -- Test script. + exit( 2 ); +} + +sse_test_reset(); +$GLOBALS['sse_test']['temp_dir'] = $sse_work . '/'; +$GLOBALS['wp_filesystem'] = new WP_Filesystem_Direct(); +$sse_name = 'example.com_enginescript_site_export_20260101_120000.zip'; +$sse_directory = esse_generate_private_export_directory_name(); +mkdir( esse_get_export_directory_path() . '/' . $sse_directory, 0700, true ); +file_put_contents( esse_get_export_directory_path() . '/' . $sse_directory . '/' . $sse_name, str_repeat( 'z', 64 ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture. + +register_shutdown_function( + static function () use ( $sse_report ): void { + $result = array( + 'buffers' => ob_get_level(), + 'rate_limited' => ! esse_check_download_rate_limit(), + 'log' => serialize( $GLOBALS['sse_test']['options'] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Searching the stored log. + ); + file_put_contents( $sse_report, (string) json_encode( $result ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test report. + } +); + +// Output another plugin buffered before the download starts. +ob_start(); +echo 'output from another plugin'; +esse_serve_file_download( esse_validate_export_file_for_download( $sse_name, $sse_directory ) ); diff --git a/tests/unit/DownloadTest.php b/tests/unit/DownloadTest.php index 6703c6c..d2c8577 100644 --- a/tests/unit/DownloadTest.php +++ b/tests/unit/DownloadTest.php @@ -1,15 +1,16 @@ directory_name ) ); + + $streamed = $this->capture( + static function () use ( $opened ): void { + esse_output_file_content( $opened['handle'], $opened['filename'], $opened['filesize'] ); + } + ); + + $this->assertSame( str_repeat( 'z', 64 ), $streamed ); + $this->assertFalse( is_resource( $opened['handle'] ), 'The handle is closed.' ); + $this->assertStringNotContainsString( 'ended before the expected byte count', $this->stored_log() ); + } + + public function test_a_download_request_clears_other_output_records_the_download_and_ends(): void { + $work = $this->make_temporary_directory(); + $report = $work . '/report.json'; + $pipes = array(); + + // The command is this PHP and a script of the suite; nothing in it comes from outside the test. + // nosemgrep: php.lang.security.exec-use.exec-use, php_exec_rule-exec-use + $process = proc_open( array( PHP_BINARY, dirname( __DIR__ ) . '/download-request.php', $work, $report ), array( 1 => array( 'pipe', 'w' ), 2 => array( 'pipe', 'w' ) ), $pipes ); + $this->assertIsResource( $process ); + $output = (string) stream_get_contents( $pipes[1] ); + $errors = (string) stream_get_contents( $pipes[2] ); + fclose( $pipes[1] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Process pipe. + fclose( $pipes[2] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Process pipe. + $status = proc_close( $process ); + + $this->assertSame( 0, $status, $errors ); + $this->assertSame( str_repeat( 'z', 64 ), $output, 'Only the file reaches the response; buffered output from before is dropped.' ); + $result = json_decode( (string) file_get_contents( $report ), true ); + $this->assertSame( 0, $result['buffers'], 'No output buffer is left.' ); + $this->assertTrue( $result['rate_limited'], 'The rate limit started.' ); + $this->assertStringContainsString( 'Export downloaded: ' . self::ARCHIVE, $result['log'] ); + $this->assertStringNotContainsString( 'ended before the expected byte count', $result['log'] ); + } + + public function test_a_download_that_stops_early_is_logged_as_an_error(): void { + $handle = fopen( $this->archive_path(), 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Test fixture. + + $streamed = $this->capture( + static function () use ( $handle ): void { + esse_output_file_content( $handle, self::ARCHIVE, 65 ); + } + ); + + $this->assertSame( 64, strlen( $streamed ) ); + $this->assertStringContainsString( 'Secure file download stream ended before the expected byte count: ' . self::ARCHIVE, $this->stored_log() ); + } + + public function test_a_download_that_cannot_be_opened_is_refused_without_starting_the_rate_limit(): void { + $file = esse_validate_export_file_for_download( self::ARCHIVE, $this->directory_name ); + + $refusal = $this->expect_die( + static function () use ( $file ): void { + esse_serve_file_download( array_merge( $file, array( 'filesize' => 1 ) ) ); + } + ); + + $this->assertSame( 403, $refusal->status ); + $this->assertStringContainsString( 'Export download refused:', $this->stored_log() ); + $this->assertTrue( esse_check_download_rate_limit() ); + } + public function test_deletion_removes_the_archive_and_redirects_with_a_success_notice(): void { $_POST = array( 'file' => self::ARCHIVE,