From bdd2ef18a18eb9e061b3d62a420528ee0e75fa55 Mon Sep 17 00:00:00 2001 From: Peter Downey Date: Tue, 1 Dec 2026 19:10:45 -0500 Subject: [PATCH 1/2] Test the download streaming that ends a request esse_output_file_content() no longer ends the request: esse_serve_file_download() calls exit after it. The steps before streaming move into esse_start_file_download(). A download does the same things in the same order, and the unit suite can now run each step. New tests cover a started download (buffers cleared, rate limit started, download recorded), the streamed bytes, a stream that stops early, and a download refused before the rate limit starts. Unit coverage rises from 62.98% to 63.81%; the workflow's floor goes from 58 to 61. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/wp-compatibility-test.yml | 2 +- includes/download.php | 29 +++++--- tests/unit/DownloadTest.php | 74 ++++++++++++++++++++- 3 files changed, 93 insertions(+), 12 deletions(-) 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/unit/DownloadTest.php b/tests/unit/DownloadTest.php index 6703c6c..a31e004 100644 --- a/tests/unit/DownloadTest.php +++ b/tests/unit/DownloadTest.php @@ -1,15 +1,16 @@ $file Validated file data. + * @return array Opened download. + */ + private function start_download( array $file ): array { + $level = ob_get_level(); + ob_start(); + echo 'output from another plugin'; + try { + $opened = esse_start_file_download( $file ); + $this->assertSame( 0, ob_get_level(), 'Nothing buffered can reach the download.' ); + } finally { + while ( ob_get_level() < $level ) { + ob_start(); + } + } + + return $opened; + } + + public function test_a_started_download_clears_buffers_and_is_recorded_before_it_is_streamed(): void { + $file = esse_validate_export_file_for_download( self::ARCHIVE, $this->directory_name ); + + $opened = $this->start_download( $file ); + + $this->assertFalse( esse_check_download_rate_limit(), 'The rate limit has started.' ); + $this->assertStringContainsString( 'Export downloaded: ' . self::ARCHIVE, $this->stored_log() ); + + $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_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, From 952d5175d4171dc606e989dc16aa98e3be202527 Mon Sep 17 00:00:00 2001 From: Peter Downey Date: Tue, 1 Dec 2026 19:25:26 -0500 Subject: [PATCH 2/2] Run the whole download in its own PHP process PHPUnit 13 marks a test risky when the code under test closes PHPUnit's own output buffer, which esse_serve_file_download() must do before it streams a file. The whole download now runs in a separate PHP process (tests/download-request.php): the test checks that only the file reaches the output, that no buffer is left, and, from a report written at shutdown after the exit, that the rate limit started and the download was recorded. Streaming an opened handle stays an in-process test. Co-Authored-By: Claude Opus 5.5 --- tests/download-request.php | 45 ++++++++++++++++++++++++++++ tests/unit/DownloadTest.php | 60 ++++++++++++++++++------------------- 2 files changed, 74 insertions(+), 31 deletions(-) create mode 100644 tests/download-request.php 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 a31e004..d2c8577 100644 --- a/tests/unit/DownloadTest.php +++ b/tests/unit/DownloadTest.php @@ -3,8 +3,8 @@ * Tests for downloading and deleting an export: the request checks, the rate limit, path and * identity validation, opening and streaming the exact file, and deletion. * - * esse_serve_file_download() ends the PHP process after its two steps, so the steps run here - * on their own. + * esse_serve_file_download() clears every output buffer, PHPUnit's too, and ends the PHP process, + * so a whole download runs in its own process (tests/download-request.php). * * @package EngineScript_Site_Exporter */ @@ -173,46 +173,44 @@ public function test_download_headers_can_be_set_for_any_name(): void { esse_set_download_headers( 'notes.txt', -5 ); } - /** - * Start a download as a request would, then give PHPUnit back the output buffers it closed. - * - * @param array $file Validated file data. - * @return array Opened download. - */ - private function start_download( array $file ): array { - $level = ob_get_level(); - ob_start(); - echo 'output from another plugin'; - try { - $opened = esse_start_file_download( $file ); - $this->assertSame( 0, ob_get_level(), 'Nothing buffered can reach the download.' ); - } finally { - while ( ob_get_level() < $level ) { - ob_start(); - } - } - - return $opened; - } - - public function test_a_started_download_clears_buffers_and_is_recorded_before_it_is_streamed(): void { - $file = esse_validate_export_file_for_download( self::ARCHIVE, $this->directory_name ); - - $opened = $this->start_download( $file ); - - $this->assertFalse( esse_check_download_rate_limit(), 'The rate limit has started.' ); - $this->assertStringContainsString( 'Export downloaded: ' . self::ARCHIVE, $this->stored_log() ); + public function test_an_opened_download_is_streamed_whole_and_its_handle_closed(): void { + $opened = esse_open_validated_export_download( esse_validate_export_file_for_download( self::ARCHIVE, $this->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.