Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/wp-compatibility-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 21 additions & 8 deletions includes/download.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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() );
Expand All @@ -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;
}
45 changes: 45 additions & 0 deletions tests/download-request.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
/**
* One download request in its own PHP process, for DownloadTest.
*
* esse_serve_file_download() clears every output buffer and ends the process, which a test in
* PHPUnit's own process cannot allow. The download goes to standard output; what the request
* recorded is written as JSON to the report file at shutdown, after the exit.
*
* Usage: php download-request.php <empty temporary directory> <report file>
*
* @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 <empty temporary directory> <report file>\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 ) );
72 changes: 69 additions & 3 deletions tests/unit/DownloadTest.php
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
<?php
/**
* Tests for downloading and deleting an export: the request checks, the rate limit, path and
* identity validation, opening the exact file, and deletion.
* identity validation, opening and streaming the exact file, and deletion.
*
* Streaming the file ends the PHP process, so it is not run here.
* 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
*/

/**
* Covers includes/download.php up to the point where the file is streamed.
* Covers includes/download.php up to the exit that ends a download.
*/
final class DownloadTest extends SseTestCase {

Expand Down Expand Up @@ -172,6 +173,71 @@ public function test_download_headers_can_be_set_for_any_name(): void {
esse_set_download_headers( 'notes.txt', -5 );
}

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.

$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,
Expand Down
Loading