diff --git a/app/Console/Commands/DownloadSubmission.php b/app/Console/Commands/DownloadSubmission.php new file mode 100644 index 0000000000..335755ce6c --- /dev/null +++ b/app/Console/Commands/DownloadSubmission.php @@ -0,0 +1,272 @@ +argument('id'); + if (!Str::isUuid($id)) { + return $this->failWith("{$id} is not a valid submission ID"); + } + + $output = $this->option('output'); + $writes_to_file = is_string($output) && $output !== ''; + if (!$writes_to_file && $this->input->hasParameterOption('--output')) { + return $this->failWith('--output needs a path'); + } + + $submission = Submission::find($id); + if ($submission === null) { + return $this->failWith("Submission {$id} does not exist"); + } + + // The target is checked before reading the file, which on S3 downloads it. + $target = null; + if ($writes_to_file) { + $target = $this->checkedTarget($submission, (string) $output); + if ($target === null) { + return self::FAILURE; + } + } + + try { + if (!Storage::fileExists($submission->path)) { + return $this->failWith("The file of submission {$id} was not found at {$submission->path}"); + } + $source = Storage::readStream($submission->path); + if ($source === null) { + throw new RuntimeException("Unable to read {$submission->path}"); + } + } catch (Throwable $e) { + return $this->failWith("The file of submission {$id} could not be read: " . ConsoleUtils::errorCause($e)); + } + + try { + return $target === null ? $this->writeToStdout($source) : $this->writeToFile($source, $target); + } finally { + fclose($source); + } + } + + /** + * Copy the file to stdout. The file is the command's output rather than a message, so it's written even with + * --quiet, and a failure to write it, such as to a closed pipe or a full disk, fails the command. On a terminal, a + * binary file isn't written, and any other file is shown with its control characters escaped. + * + * @param resource $source + */ + private function writeToStdout($source): int + { + try { + $chunk = stream_get_contents($source, self::CHUNK_LENGTH); + if ($chunk === false) { + throw new RuntimeException('Unable to read the file'); + } + $terminal = $this->writesToTerminal(); + if ($terminal && str_contains($chunk, "\0")) { + return $this->failWith('This file is binary, so it isn\'t written to the terminal. Redirect the output or use --output.'); + } + + $output = $this->output->getOutput(); + $held = ''; + while (true) { + $at_end = feof($source); + if ($terminal) { + // Unless the file ends there, a "\r" or "\xC2" at the end of a part is held back for the next, which + // could finish it as a line break or a C1 control. + $chunk = $held . $chunk; + $held = !$at_end && (str_ends_with($chunk, "\r") || str_ends_with($chunk, "\xC2")) ? $chunk[-1] : ''; + $chunk = ConsoleUtils::printable(substr($chunk, 0, strlen($chunk) - strlen($held))); + } + self::writeRaw($output, $chunk); + if ($at_end) { + break; + } + $chunk = fread($source, self::CHUNK_LENGTH); + if ($chunk === false) { + throw new RuntimeException('Unable to read the file'); + } + } + if ($output instanceof StreamOutput && !fflush($output->getStream())) { + throw new RuntimeException('Unable to write to stdout'); + } + } catch (Throwable $e) { + // A reader that stops early, such as head, closes the pipe. Like cat, the command says nothing about it. + if (str_contains($e->getMessage(), 'Broken pipe')) { + return self::FAILURE; + } + return $this->failWith('The file could not be copied: ' . ConsoleUtils::errorCause($e)); + } + + return self::SUCCESS; + } + + /** + * Write to stdout as is. Output that isn't a stream, such as when the command is called from code, reports no + * write errors. + */ + private static function writeRaw(OutputInterface $output, string $data): void + { + if (!$output instanceof StreamOutput) { + $output->write($data, false, OutputInterface::OUTPUT_RAW | OutputInterface::VERBOSITY_QUIET); + } elseif (fwrite($output->getStream(), $data) !== strlen($data)) { + throw new RuntimeException('Unable to write to stdout'); + } + } + + /** + * The file to write to: the given path, or the default name inside it if it's a directory. Null after reporting + * a target that mustn't or can't be written. + */ + private function checkedTarget(Submission $submission, string $output): ?string + { + $target = is_dir($output) ? rtrim($output, '/') . '/' . self::defaultName($submission) : $output; + if (str_ends_with($target, '/')) { + $this->failWith("{$output} isn't a directory"); + return null; + } + if (file_exists($target) && !is_file($target)) { + $this->failWith("{$target} exists and isn't a regular file"); + return null; + } + if ((is_link($target) || file_exists($target)) && $this->option('force') !== true) { + $this->failWith("{$target} already exists. Use --force to overwrite it."); + return null; + } + $directory = dirname($target); + if (!is_dir($directory) || !is_writable($directory)) { + $this->failWith("Can't write to the directory {$directory}"); + return null; + } + return $target; + } + + /** + * Copy the file to the given path. The copy goes to a temporary file beside the target, which only replaces the + * target once it's complete. + * + * @param resource $source + */ + private function writeToFile($source, string $target): int + { + $directory = dirname($target); + $temporary = false; + try { + // tempnam() creates the file readable by its owner only. If it can't create it here, it creates it in + // the system's temporary directory instead, with a notice. + $temporary = @tempnam($directory, '.' . basename($target) . '.'); + if ($temporary === false || dirname($temporary) !== realpath($directory)) { + throw new RuntimeException("Unable to create a temporary file in {$directory}"); + } + $destination = fopen($temporary, 'wb'); + if ($destination === false) { + throw new RuntimeException("Unable to write {$target}"); + } + try { + $bytes = stream_copy_to_stream($source, $destination); + if ($bytes === false || !fflush($destination)) { + throw new RuntimeException("Unable to write {$target}"); + } + } finally { + fclose($destination); + } + if (!rename($temporary, $target)) { + throw new RuntimeException("Unable to move {$temporary} to {$target}"); + } + } catch (Throwable $e) { + if ($temporary !== false) { + @unlink($temporary); + } + return $this->failWith('The file could not be copied: ' . ConsoleUtils::errorCause($e)); + } + + $this->output->getErrorStyle()->writeln( + OutputFormatter::escape("Wrote {$target} (" . number_format((int) ceil($bytes / 1024)) . ' KB)') + ); + return self::SUCCESS; + } + + /** + * The name the file is written under in a directory: the submission's ID, followed by ".xml" for an XML file, or + * the name the client gave a data file. That name comes from the uploader, so only the end of its base name is + * kept, in safe characters. + */ + private static function defaultName(Submission $submission): string + { + if ($submission->filename === null) { + return "{$submission->id}.xml"; + } + + $filename = basename(str_replace('\\', '/', $submission->filename)); + $filename = substr((string) preg_replace('/[^A-Za-z0-9._-]/', '_', $filename), -self::MAX_CLIENT_NAME_LENGTH); + return $filename === '' ? $submission->id : "{$submission->id}-{$filename}"; + } + + /** + * Whether stdout is a terminal, which control characters in the file could act on. + */ + protected function writesToTerminal(): bool + { + $output = $this->output->getOutput(); + return $output instanceof StreamOutput && stream_isatty($output->getStream()); + } + + /** + * Report an error on stderr, so that it never mixes with a file written to stdout, even with --quiet. A message can + * include text from elsewhere, such as a storage error, so its control characters are escaped. + */ + private function failWith(string $message): int + { + $this->output->getErrorStyle()->writeln( + '' . OutputFormatter::escape(ConsoleUtils::printable($message)) . '', + OutputInterface::VERBOSITY_QUIET, + ); + return self::FAILURE; + } +} diff --git a/app/Console/Commands/ShowSubmission.php b/app/Console/Commands/ShowSubmission.php index 9d6c9a8c3f..a866c00691 100644 --- a/app/Console/Commands/ShowSubmission.php +++ b/app/Console/Commands/ShowSubmission.php @@ -6,6 +6,7 @@ use App\Enums\SubmissionStatus; use App\Models\Submission; +use App\Utils\ConsoleUtils; use Carbon\CarbonInterface; use Illuminate\Console\Command; use Illuminate\Support\Carbon; @@ -84,21 +85,13 @@ private function field(string $label, string ...$values): void } /** - * Split text into lines that print as written: console markup is escaped, and control characters other than tabs, - * including the C1 controls U+0080 to U+009F, are shown as \xNN so that they can't act on the terminal. + * Split text into lines that print as written, with their control characters escaped and console markup escaped. * * @return array */ private static function printableLines(string $text): array { - return array_map( - fn (string $line): string => OutputFormatter::escape((string) preg_replace_callback( - '/[\x00-\x08\x0B-\x1F\x7F]|\xC2[\x80-\x9F]/', - fn (array $match): string => sprintf('\x%02X', ord($match[0][-1])), - $line, - )), - explode("\n", str_replace(["\r\n", "\r"], "\n", $text)), - ); + return array_map(OutputFormatter::escape(...), explode("\n", ConsoleUtils::printable($text))); } private function showBuild(Submission $submission): void @@ -188,13 +181,7 @@ private static function describeFile(string $path): string } return "{$path} (" . number_format((int) ceil(Storage::size($path) / 1024)) . ' KB)'; } catch (Throwable $e) { - // Storage errors, such as the AWS SDK's, can spread their cause over several lines. - $message = trim($e->getPrevious()?->getMessage() ?? ''); - if ($message === '') { - $message = trim($e->getMessage()); - } - $cause = rtrim((string) preg_replace('/\s+/', ' ', $message), '. '); - return "{$path} (could not be checked: {$cause})"; + return "{$path} (could not be checked: " . ConsoleUtils::errorCause($e) . ')'; } } diff --git a/app/Utils/ConsoleUtils.php b/app/Utils/ConsoleUtils.php new file mode 100644 index 0000000000..4f87701b11 --- /dev/null +++ b/app/Utils/ConsoleUtils.php @@ -0,0 +1,35 @@ + sprintf('\x%02X', ord($match[0][-1])), + str_replace(["\r\n", "\r"], "\n", $text), + ); + } + + /** + * The cause of an error on one line. Storage errors such as the AWS SDK's spread it over several lines. + */ + public static function errorCause(Throwable $e): string + { + $message = trim($e->getPrevious()?->getMessage() ?? ''); + if ($message === '') { + $message = trim($e->getMessage()); + } + return rtrim((string) preg_replace('/\s+/', ' ', $message), '. '); + } +} diff --git a/app/cdash/tests/CMakeLists.txt b/app/cdash/tests/CMakeLists.txt index b8412cf361..64e89dc34d 100644 --- a/app/cdash/tests/CMakeLists.txt +++ b/app/cdash/tests/CMakeLists.txt @@ -392,6 +392,8 @@ add_feature_test_in_transaction(/Feature/Console/ListSubmissionsCommandTest) add_feature_test_in_transaction(/Feature/Console/ShowSubmissionCommandTest) +add_feature_test_in_transaction(/Feature/Console/DownloadSubmissionCommandTest) + add_feature_test_in_transaction(/Feature/Submission/XmlSubmissionTest) add_feature_test_in_transaction(/Feature/Submission/UnparsedSubmissionTest) diff --git a/tests/Feature/Console/DownloadSubmissionCommandTest.php b/tests/Feature/Console/DownloadSubmissionCommandTest.php new file mode 100644 index 0000000000..4f9f64efe1 --- /dev/null +++ b/tests/Feature/Console/DownloadSubmissionCommandTest.php @@ -0,0 +1,721 @@ +\n\n"; + + private Project $project; + private string $directory; + private string $working_directory; + + protected function setUp(): void + { + parent::setUp(); + + Storage::fake(); + $this->project = $this->makePublicProject(); + $this->directory = sys_get_temp_dir() . '/' . Str::uuid()->toString(); + mkdir($this->directory); + $this->working_directory = (string) getcwd(); + } + + protected function tearDown(): void + { + chdir($this->working_directory); + chmod($this->directory, 0o700); + File::deleteDirectory($this->directory); + + parent::tearDown(); + } + + /** + * @param array $attributes + */ + private function makeSubmission(array $attributes = [], ?string $contents = self::XML): Submission + { + $submission = Submission::factory()->create($attributes + [ + 'projectid' => $this->project->id, + 'path' => 'parsed/linux-release_Build.xml', + ]); + if ($contents !== null) { + Storage::put($submission->path, $contents); + } + return $submission; + } + + /** + * Run the command, and return its exit code and everything it printed. + * + * @param array $options + * + * @return array{int, string} + */ + private function download(string $id, array $options = []): array + { + $code = Artisan::call('submission:download', ['id' => $id] + $options); + return [$code, Artisan::output()]; + } + + /** + * Run the command as it runs in a shell, with stdout going to the given stream and messages to stderr, and return + * its exit code and what it wrote to stderr. + * + * @param resource $stdout + * @param array $options + * + * @return array{int, string} + */ + private function downloadInShell(string $id, $stdout, array $options = []): array + { + $stderr = new BufferedOutput(); + try { + $output = self::consoleOutput($stdout, $stderr); + } catch (InvalidArgumentException $e) { + self::fail($e->getMessage()); + } + $code = Artisan::call('submission:download', ['id' => $id] + $options, $output); + return [$code, $stderr->fetch()]; + } + + /** + * @param resource $stdout + * + * @throws InvalidArgumentException + */ + private static function consoleOutput($stdout, BufferedOutput $stderr): StreamOutput&ConsoleOutputInterface + { + return new class($stdout, $stderr) extends StreamOutput implements ConsoleOutputInterface { + /** + * @param resource $stream + * + * @throws InvalidArgumentException + */ + public function __construct($stream, private readonly BufferedOutput $stderr) + { + parent::__construct($stream); + } + + public function getErrorOutput(): OutputInterface + { + return $this->stderr; + } + + /** + * Apply the verbosity to stderr too, as ConsoleOutput does. + */ + public function setVerbosity(int $level): void + { + parent::setVerbosity($level); + $this->stderr->setVerbosity($level); + } + + public function setErrorOutput(OutputInterface $error): void + { + throw new LogicException('Not used'); + } + + public function section(): ConsoleSectionOutput + { + throw new LogicException('Not used'); + } + }; + } + + /** + * @param resource $stream + */ + private static function contentsOf($stream): string + { + rewind($stream); + return (string) stream_get_contents($stream); + } + + /** + * Have the command treat its output as a terminal. + */ + private function writeToTerminal(): void + { + $command = Mockery::mock(DownloadSubmission::class . '[writesToTerminal]', []) + ->shouldAllowMockingProtectedMethods(); + $command->shouldReceive('writesToTerminal')->andReturn(true); + $this->app->instance(DownloadSubmission::class, $command); + } + + /** + * Make reading the stored file fail part-way through. + */ + private function failReadingPartWayThrough(): void + { + $failing_stream = new class { + /** @var resource|null */ + public $context; + + private bool $read = false; + + public function stream_open(string $path, string $mode, int $options, ?string &$opened_path): bool + { + return true; + } + + public function stream_read(int $count): string + { + if ($this->read) { + throw new RuntimeException('Input/output error'); + } + $this->read = true; + return 'partial contents'; + } + + public function stream_eof(): bool + { + return false; + } + + /** + * @return array + */ + public function stream_stat(): array + { + return []; + } + }; + stream_wrapper_register('failing', $failing_stream::class); + $this->beforeApplicationDestroyed(fn () => stream_wrapper_unregister('failing')); + $disk = Mockery::mock(Storage::disk())->makePartial(); + $disk->shouldReceive('readStream')->andReturn(fopen('failing://file', 'rb')); + Storage::set(Config::string('filesystems.default'), $disk); + } + + /** + * @return array + */ + private function filesInDirectory(): array + { + $files = scandir($this->directory); + self::assertIsArray($files); + return array_values(array_diff($files, ['.', '..'])); + } + + public function testWritesFileToStdout(): void + { + $submission = $this->makeSubmission(); + $stdout = fopen('php://memory', 'w+'); + self::assertIsResource($stdout); + + self::assertSame([Command::SUCCESS, ''], $this->downloadInShell($submission->id, $stdout)); + self::assertSame(self::XML, self::contentsOf($stdout)); + } + + public function testWritesLargeBinaryFileToStdoutWhenItIsNotATerminal(): void + { + $contents = str_repeat("\x1F\x8B\x08\0binary contents\n", 10000); + $submission = $this->makeSubmission(['type' => 'GcovTar', 'filename' => 'gcov.tar'], $contents); + $stdout = fopen('php://memory', 'w+'); + self::assertIsResource($stdout); + + self::assertSame([Command::SUCCESS, ''], $this->downloadInShell($submission->id, $stdout)); + self::assertSame($contents, self::contentsOf($stdout)); + } + + /** + * The file is the command's output rather than a message, so --quiet doesn't hold it back. + */ + public function testWritesFileToStdoutEvenWhenQuiet(): void + { + $submission = $this->makeSubmission(); + $stdout = fopen('php://memory', 'w+'); + self::assertIsResource($stdout); + + self::assertSame([Command::SUCCESS, ''], $this->downloadInShell($submission->id, $stdout, ['--quiet' => true])); + self::assertSame(self::XML, self::contentsOf($stdout)); + } + + /** + * Called from code, the command writes to the output it's given. + */ + public function testWritesFileToOutputThatIsNotAStream(): void + { + $submission = $this->makeSubmission(); + + self::assertSame([Command::SUCCESS, self::XML], $this->download($submission->id)); + self::assertSame([Command::SUCCESS, self::XML], $this->download($submission->id, ['--quiet' => true])); + } + + /** + * Like cat, the command fails when its output can't be written, such as to a full disk or a closed pipe. + */ + public function testFailsWhenStdoutCannotBeWritten(): void + { + $submission = $this->makeSubmission(); + $stdout = fopen('/dev/full', 'w'); + self::assertIsResource($stdout); + + [$code, $stderr] = $this->downloadInShell($submission->id, $stdout); + + self::assertSame(Command::FAILURE, $code); + self::assertStringStartsWith('The file could not be copied: ', $stderr); + self::assertStringEndsWith("No space left on device\n", $stderr); + self::assertSame(1, substr_count($stderr, "\n")); + } + + /** + * A reader that stops early, such as head, closes the pipe, which cat doesn't report either. + */ + public function testSaysNothingWhenTheReaderStopsEarly(): void + { + $submission = $this->makeSubmission([], str_repeat("0123456789\n", 100000)); + $stdout = popen('true', 'w'); + self::assertIsResource($stdout); + + try { + self::assertSame([Command::FAILURE, ''], $this->downloadInShell($submission->id, $stdout)); + } finally { + pclose($stdout); + } + } + + public function testShowsErrorsEvenWhenQuiet(): void + { + $submission = $this->makeSubmission([], null); + $stdout = fopen('php://memory', 'w+'); + self::assertIsResource($stdout); + + self::assertSame( + [Command::FAILURE, "The file of submission {$submission->id} was not found at parsed/linux-release_Build.xml\n"], + $this->downloadInShell($submission->id, $stdout, ['--quiet' => true]), + ); + self::assertSame('', self::contentsOf($stdout)); + } + + public function testWritesMessagesToStderr(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/build.xml"; + $stdout = fopen('php://memory', 'w+'); + self::assertIsResource($stdout); + + self::assertSame( + [Command::SUCCESS, "Wrote {$target} (1 KB)\n"], + $this->downloadInShell($submission->id, $stdout, ['--output' => $target]), + ); + self::assertSame( + [Command::FAILURE, "{$target} already exists. Use --force to overwrite it.\n"], + $this->downloadInShell($submission->id, $stdout, ['--output' => $target]), + ); + self::assertSame('', self::contentsOf($stdout)); + } + + public function testWritesTextFileToTerminal(): void + { + $this->writeToTerminal(); + $submission = $this->makeSubmission(); + + self::assertSame([Command::SUCCESS, self::XML], $this->download($submission->id)); + } + + /** + * @return array + */ + public static function textWithControlCharacters(): array + { + $chunk = str_repeat('x', 8191); + return [ + 'escape sequence' => ["\e[2Jq7x\n", "\\x1B[2Jq7x\n"], + 'C1 control' => ["\u{9B}2Jq7x\n", "\\x9B2Jq7x\n"], + 'other controls' => ["q7x\x01\x0B\x0C\x7F\n", "q7x\\x01\\x0B\\x0C\\x7F\n"], + 'tabs and other characters' => ["\tq7x é日\u{A0}\n", "\tq7x é日\u{A0}\n"], + 'line breaks' => ["q7x\r\nx7q\rq7\n", "q7x\nx7q\nq7\n"], + 'NUL after the first 8 KB' => ["{$chunk}x\0", "{$chunk}x\\x00"], + 'line break split between parts' => ["{$chunk}\r\nq7x", "{$chunk}\nq7x"], + 'C1 control split between parts' => ["{$chunk}\u{9B}q7x", "{$chunk}\\x9Bq7x"], + 'line break at the end of a part' => ["{$chunk}\r", "{$chunk}\n"], + ]; + } + + /** + * Control characters could act on a terminal, so there they're shown as \xNN, except for tabs and line breaks. + */ + #[DataProvider('textWithControlCharacters')] + public function testEscapesControlCharactersOnTerminal(string $contents, string $shown): void + { + $this->writeToTerminal(); + $submission = $this->makeSubmission([], $contents); + + self::assertSame([Command::SUCCESS, $shown], $this->download($submission->id)); + } + + /** + * A binary file would be unreadable on a terminal. A NUL byte anywhere in the first 8 KB marks a file as binary. + */ + public function testRefusesToWriteBinaryFileToTerminal(): void + { + $this->writeToTerminal(); + $submission = $this->makeSubmission(['type' => 'GcovTar', 'filename' => 'gcov.tar'], str_repeat('x', 8191) . "\0binary"); + + self::assertSame( + [Command::FAILURE, "This file is binary, so it isn't written to the terminal. Redirect the output or use --output.\n"], + $this->download($submission->id), + ); + } + + public function testWritesFileToOutputPath(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/build.xml"; + + self::assertSame([Command::SUCCESS, "Wrote {$target} (1 KB)\n"], $this->download($submission->id, ['--output' => $target])); + self::assertSame(self::XML, file_get_contents($target)); + self::assertSame(0o600, fileperms($target) & 0o777); + self::assertSame(['build.xml'], $this->filesInDirectory()); + } + + public function testRejectsEmptyOutputPath(): void + { + $submission = $this->makeSubmission(); + + self::assertSame([Command::FAILURE, "--output needs a path\n"], $this->download($submission->id, ['--output' => ''])); + } + + public function testWritesXmlFileIntoDirectoryUnderItsId(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/{$submission->id}.xml"; + + self::assertSame([Command::SUCCESS, "Wrote {$target} (1 KB)\n"], $this->download($submission->id, ['--output' => $this->directory])); + self::assertSame(self::XML, file_get_contents($target)); + } + + public function testWritesIntoDirectoryGivenWithTrailingSeparator(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/{$submission->id}.xml"; + + self::assertSame([Command::SUCCESS, "Wrote {$target} (1 KB)\n"], $this->download($submission->id, ['--output' => "{$this->directory}/"])); + self::assertSame(self::XML, file_get_contents($target)); + } + + public function testWritesIntoRelativeDirectory(): void + { + $submission = $this->makeSubmission(); + chdir($this->directory); + + self::assertSame( + [Command::SUCCESS, "Wrote ./{$submission->id}.xml (1 KB)\n"], + $this->download($submission->id, ['--output' => '.']), + ); + self::assertSame([$submission->id . '.xml'], $this->filesInDirectory()); + } + + /** + * @return array + */ + public static function clientFilenames(): array + { + return [ + 'plain' => ['gcov.tar', '-gcov.tar'], + 'path' => ['../../q7x/gcov data.tar', '-gcov_data.tar'], + 'Windows path' => ['C:\\q7x\\gcov.tar', '-gcov.tar'], + 'unsafe characters' => ['x7é日;$(q).tar', '-x7________q_.tar'], + 'trailing separator' => ['q7x/', '-q7x'], + 'only a separator' => ['/', ''], + 'long' => [str_repeat('q', 300) . '.tar', '-' . str_repeat('q', 196) . '.tar'], + ]; + } + + /** + * The name the client gave a data file comes from the uploader, so only the end of its base name is used, in safe + * characters. + */ + #[DataProvider('clientFilenames')] + public function testWritesDataFileIntoDirectoryUnderItsIdAndSafeName(string $filename, string $suffix): void + { + $submission = $this->makeSubmission(['type' => 'GcovTar', 'filename' => $filename], 'contents'); + + self::assertSame(Command::SUCCESS, $this->download($submission->id, ['--output' => $this->directory])[0]); + + self::assertSame([$submission->id . $suffix], $this->filesInDirectory()); + } + + public function testRefusesToOverwriteExistingFile(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/build.xml"; + file_put_contents($target, 'earlier download'); + + self::assertSame( + [Command::FAILURE, "{$target} already exists. Use --force to overwrite it.\n"], + $this->download($submission->id, ['--output' => $target]), + ); + self::assertSame('earlier download', file_get_contents($target)); + } + + public function testRefusesToOverwriteFileInDirectoryUnderDefaultName(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/{$submission->id}.xml"; + file_put_contents($target, 'earlier download'); + + self::assertSame( + [Command::FAILURE, "{$target} already exists. Use --force to overwrite it.\n"], + $this->download($submission->id, ['--output' => $this->directory]), + ); + self::assertSame('earlier download', file_get_contents($target)); + } + + public function testOverwritesExistingFileWithForce(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/build.xml"; + file_put_contents($target, 'earlier download'); + + self::assertSame( + [Command::SUCCESS, "Wrote {$target} (1 KB)\n"], + $this->download($submission->id, ['--output' => $target, '--force' => true]), + ); + self::assertSame(self::XML, file_get_contents($target)); + self::assertSame(['build.xml'], $this->filesInDirectory()); + } + + /** + * A symbolic link counts as an existing file even if what it points to doesn't exist, and --force replaces the + * link itself rather than writing through it. + */ + public function testReplacesSymbolicLinkOnlyWithForce(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/build.xml"; + symlink("{$this->directory}/elsewhere.xml", $target); + + self::assertSame( + [Command::FAILURE, "{$target} already exists. Use --force to overwrite it.\n"], + $this->download($submission->id, ['--output' => $target]), + ); + + $this->download($submission->id, ['--output' => $target, '--force' => true]); + + self::assertFalse(is_link($target)); + self::assertSame(self::XML, file_get_contents($target)); + self::assertSame(['build.xml'], $this->filesInDirectory()); + } + + /** + * Replacing a device or a named pipe with a regular file is never what's wanted, including through a symbolic link + * such as /dev/stdout. + */ + public function testRefusesToReplaceFileThatIsNotRegularEvenWithForce(): void + { + $submission = $this->makeSubmission(); + $link = "{$this->directory}/null"; + symlink('/dev/null', $link); + + self::assertSame( + [Command::FAILURE, "/dev/null exists and isn't a regular file\n"], + $this->download($submission->id, ['--output' => '/dev/null', '--force' => true]), + ); + self::assertSame( + [Command::FAILURE, "{$link} exists and isn't a regular file\n"], + $this->download($submission->id, ['--output' => $link, '--force' => true]), + ); + self::assertTrue(is_link($link)); + } + + /** + * A path that ends in a separator names a directory, so if there's none, nothing is read or written. + */ + public function testRefusesPathEndingInSeparatorThatIsNotADirectory(): void + { + $submission = $this->makeSubmission(); + file_put_contents("{$this->directory}/build.xml", 'earlier download'); + $disk = Mockery::mock(Storage::disk())->makePartial(); + $disk->shouldNotReceive('readStream'); + Storage::set(Config::string('filesystems.default'), $disk); + + self::assertSame( + [Command::FAILURE, "{$this->directory}/missing/ isn't a directory\n"], + $this->download($submission->id, ['--output' => "{$this->directory}/missing/"]), + ); + self::assertSame( + [Command::FAILURE, "{$this->directory}/build.xml/ isn't a directory\n"], + $this->download($submission->id, ['--output' => "{$this->directory}/build.xml/", '--force' => true]), + ); + self::assertSame(['build.xml'], $this->filesInDirectory()); + } + + public function testRefusesToWriteIntoMissingDirectory(): void + { + $submission = $this->makeSubmission(); + + self::assertSame( + [Command::FAILURE, "Can't write to the directory {$this->directory}/missing\n"], + $this->download($submission->id, ['--output' => "{$this->directory}/missing/build.xml"]), + ); + } + + /** + * A directory that can be written but not searched lets tempnam() fall back to the system's temporary directory, + * where the file must not be left. + */ + public function testLeavesNoTemporaryFileWhenItCannotBeCreatedBesideTheTarget(): void + { + if (posix_geteuid() === 0) { + self::markTestSkipped('Directory permissions don\'t apply to root.'); + } + $submission = $this->makeSubmission(); + $temporary_files = glob(sys_get_temp_dir() . '/.build.xml.*'); + chmod($this->directory, 0o600); + + self::assertSame( + [Command::FAILURE, "The file could not be copied: Unable to create a temporary file in {$this->directory}\n"], + $this->download($submission->id, ['--output' => "{$this->directory}/build.xml"]), + ); + self::assertSame($temporary_files, glob(sys_get_temp_dir() . '/.build.xml.*')); + } + + /** + * A file that can't be read to the end, such as one on a failing disk, leaves nothing behind. + */ + public function testLeavesNoFileWhenReadingFails(): void + { + $submission = $this->makeSubmission(); + $this->failReadingPartWayThrough(); + + self::assertSame( + [Command::FAILURE, "The file could not be copied: Input/output error\n"], + $this->download($submission->id, ['--output' => $this->directory]), + ); + self::assertSame([], $this->filesInDirectory()); + } + + public function testKeepsExistingFileWhenOverwritingItFails(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/build.xml"; + file_put_contents($target, 'earlier download'); + $this->failReadingPartWayThrough(); + + self::assertSame( + [Command::FAILURE, "The file could not be copied: Input/output error\n"], + $this->download($submission->id, ['--output' => $target, '--force' => true]), + ); + self::assertSame('earlier download', file_get_contents($target)); + self::assertSame(['build.xml'], $this->filesInDirectory()); + } + + /** + * On S3, reading the file downloads all of it, so a target that can't be written is reported first. + */ + public function testChecksTargetBeforeReadingTheFile(): void + { + $submission = $this->makeSubmission(); + $target = "{$this->directory}/build.xml"; + file_put_contents($target, 'earlier download'); + $disk = Mockery::mock(Storage::disk())->makePartial(); + $disk->shouldNotReceive('readStream'); + Storage::set(Config::string('filesystems.default'), $disk); + + self::assertSame( + [Command::FAILURE, "{$target} already exists. Use --force to overwrite it.\n"], + $this->download($submission->id, ['--output' => $target]), + ); + } + + public function testSaysWhenFileIsNotFound(): void + { + $submission = $this->makeSubmission([], null); + + self::assertSame( + [Command::FAILURE, "The file of submission {$submission->id} was not found at parsed/linux-release_Build.xml\n"], + $this->download($submission->id), + ); + } + + /** + * Messages can include text from elsewhere, such as this storage error, which repeats the path it refused. + */ + public function testEscapesControlCharactersInMessages(): void + { + $submission = $this->makeSubmission(['path' => "inbox/q7x\e[2J.tar"], null); + + self::assertSame( + [Command::FAILURE, "The file of submission {$submission->id} could not be read: Corrupted path detected: inbox/q7x\\x1B[2J.tar\n"], + $this->download($submission->id), + ); + } + + public function testSaysWhenFileCannotBeOpened(): void + { + $submission = $this->makeSubmission(); + $disk = Mockery::mock(Storage::disk())->makePartial(); + $disk->shouldReceive('readStream')->andThrow(UnableToReadFile::fromLocation($submission->path, 'Permission denied')); + Storage::set(Config::string('filesystems.default'), $disk); + + self::assertSame( + [Command::FAILURE, "The file of submission {$submission->id} could not be read: Unable to read file from location: parsed/linux-release_Build.xml. Permission denied\n"], + $this->download($submission->id), + ); + } + + public function testSaysWhenS3CannotBeReached(): void + { + $submission = $this->makeSubmission([], null); + Config::set('filesystems.disks.s3', [ + 'driver' => 's3', + 'key' => 'key', + 'secret' => 'secret', + 'region' => 'us-east-1', + 'bucket' => 'cdash', + 'endpoint' => 'http://127.0.0.1:1', + 'use_path_style_endpoint' => true, + 'throw' => true, + ]); + Config::set('filesystems.default', 's3'); + Storage::forgetDisk('s3'); + + [$code, $output] = $this->download($submission->id); + + self::assertSame(Command::FAILURE, $code); + self::assertStringStartsWith("The file of submission {$submission->id} could not be read: ", $output); + self::assertStringContainsString('127.0.0.1:1', $output); + } + + public function testRejectsMalformedId(): void + { + self::assertSame([Command::FAILURE, "019ab4c2 is not a valid submission ID\n"], $this->download('019ab4c2')); + } + + public function testRejectsUnknownId(): void + { + $id = Str::uuid7()->toString(); + + self::assertSame([Command::FAILURE, "Submission {$id} does not exist\n"], $this->download($id)); + } +}