diff --git a/.github/actions-lock.txt b/.github/actions-lock.txt index 53719fe5..0b574cc1 100644 --- a/.github/actions-lock.txt +++ b/.github/actions-lock.txt @@ -3,4 +3,9 @@ # workflow-lock-schema: 3 -{"workflow":"npm-audit-fix.yml","sha256":"08d5cec37b75b607ae7bf21b9692a5aa50c503e5fc028c044f88864e20662e01","catalog_commit":"75212d6bed0005c0eb33abe07c28584cc68baf4f"} +{"workflow":"appstore-build-publish.yml","sha256":"3b28bdc6f1a0ac04438a6d498f1425c48c79795515a35c166186f8ad54169834","catalog_commit":"01ded35f8a5c207868efc5802eeace3e72b54a86"} +{"workflow":"block-unconventional-commits.yml","sha256":"682899d221aa96cd1ad93c3cf46970205a083e49e45d9405b86f4b732a350cea","catalog_commit":"01ded35f8a5c207868efc5802eeace3e72b54a86"} +{"workflow":"lint-info-xml.yml","sha256":"3a2ed92f25ae9a233d6d64d44bd122b39dee0f153e7a1a9dc81bfb19adcec09b","catalog_commit":"01ded35f8a5c207868efc5802eeace3e72b54a86"} +{"workflow":"npm-audit-fix.yml","sha256":"e122e78371daf2cbc302c18eeeec4846066b0e6a4e2636ea12732ba3ef211973","catalog_commit":"01ded35f8a5c207868efc5802eeace3e72b54a86"} +{"workflow":"prepare-release.yml","sha256":"cf0be036dcb62669e489bcefea915564bebd737c513c6c9aa843bf46f06c4cd8","catalog_commit":"01ded35f8a5c207868efc5802eeace3e72b54a86"} +{"workflow":"reuse.yml","sha256":"f563735e1a573cca3acb2975321ee760e5d52cb6ca64bfcc11a5da4ae0f9bf73","catalog_commit":"01ded35f8a5c207868efc5802eeace3e72b54a86"} diff --git a/.github/workflows/npm-audit-fix.yml b/.github/workflows/npm-audit-fix.yml index 0952637b..9af57bb7 100644 --- a/.github/workflows/npm-audit-fix.yml +++ b/.github/workflows/npm-audit-fix.yml @@ -83,7 +83,7 @@ jobs: - name: Create Pull Request if: steps.checkout.outcome == 'success' - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3 with: token: ${{ steps.app-token.outputs.token }} commit-message: 'fix(deps): resolve npm audit vulnerabilities' diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml index d40d841b..b4fe6d35 100644 --- a/.github/workflows/phpunit.yml +++ b/.github/workflows/phpunit.yml @@ -50,7 +50,7 @@ jobs: - name: Install archive backends needed by tests run: | sudo apt-get update -qq - sudo apt-get install -y -qq p7zip-full + sudo apt-get install -y -qq p7zip-full zstd - name: Run unit tests run: composer run test:unit -- --no-progress diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml index a165ef65..2ac29361 100644 --- a/.github/workflows/playwright.yml +++ b/.github/workflows/playwright.yml @@ -96,6 +96,16 @@ jobs: maintenance:install --database sqlite --database-name nextcloud \ --admin-user e2e --admin-pass "$NEXTCLOUD_ADMIN_PASSWORD" docker exec -u www-data extract-playwright-nextcloud php /var/www/html/occ app:enable extract + docker exec -u www-data extract-playwright-nextcloud php /var/www/html/occ app:enable files_sharing + # Exercise the non-ZIP extractors in the disposable Nextcloud itself. + # These binaries are not installed by the stock Nextcloud image. + docker exec -u root extract-playwright-nextcloud sh -ec ' + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq p7zip-full unrar-free zstd >/dev/null + command -v 7za + command -v zstd + command -v unrar + ' # The first-run wizard overlays the Files action menu on fresh NC # installations; disable it only within this disposable test instance. docker exec -u www-data extract-playwright-nextcloud php /var/www/html/occ app:disable firstrunwizard diff --git a/.nextcloud-release.yml b/.nextcloud-release.yml index 039f527c..93384ec5 100644 --- a/.nextcloud-release.yml +++ b/.nextcloud-release.yml @@ -20,6 +20,7 @@ version: history: previous_release: reachable-tag + initial_ref: b1252308a867580bdef509b4418b66de17352e25 changelog: strategy: per-major diff --git a/README.md b/README.md index 51d67a9c..fa181311 100644 --- a/README.md +++ b/README.md @@ -39,32 +39,65 @@ the archive directory. | Tool | Purpose | Install | |------|---------|---------| | PHP `zip` extension | Zip archives | bundled with most PHP builds | -| PHP `rar` extension **or** `unrar` | Rar archives | `pecl install rar` **or** `apt-get install unrar` | +| PHP `rar`, `unrar` **or** full `7z` | Rar archives | `pecl install rar` **or** `apt-get install unrar` **or** `apt-get install 7zip` | | `p7zip` / `p7zip-full` | Tar, Gzip, Bzip2, 7z, Deb | `apt-get install p7zip p7zip-full` | Extraction needs enough free space in the server's temporary directory for the uncompressed archive. Symbolic links in archives are not supported. -The `zip` PHP extension is required for Zip files. Rar needs either the PHP -`rar` extension or the `unrar` binary; every other format is handled by the -`7za` binary shipped with p7zip. +External decoders require PHP `proc_open` to be enabled; if it is disabled, +extraction fails closed rather than falling back to unsupervised `exec()`. +ZIP extraction enforces the destination's available Nextcloud quota, staging +disk free space, and two configurable safety limits (defaults: **2 GiB** total +uncompressed bytes and **10,000** entries). The limits apply before extraction +using ZIP metadata and during streaming using the actual bytes written. +Administrators may adjust them for trusted large archives, for example: + +```bash +occ config:app:set extract max_extracted_bytes --value=4294967296 +occ config:app:set extract max_archive_entries --value=20000 +``` + +The same configured limits and destination-space estimates are now checked +against the *declared* contents of archives handled by `7za` (7z, tar, +Gzip, Bzip2 and Deb) **before** launching their extraction. Unlike the ZIP +streaming path, an external decoder may expand beyond dishonest archive +metadata before the app can stop it. Command-line decoders now run under a +best-effort supervisor that periodically measures the staging directory, +interrupts processes that exceed the configured size or entry budget, and +enforces a default **300-second** timeout. Administrators can change it with +`occ config:app:set extract max_extraction_seconds --value=600`. +Checks are periodic and can be exceeded briefly; this is **not** a strict +filesystem quota. High-risk deployments should isolate temporary storage +with an operating-system-enforced limit. When available, the supervisor +runs command-line decoders in their own POSIX session and terminates remaining +child processes on completion or failure. The PHP `rar` extension follows a +separate bounded streaming path with CRC checks rather than spawning a decoder, +but it still cannot provide an operating-system-enforced CPU or disk quota. + +The `zip` PHP extension is required for ZIP files. RAR uses the PHP `rar` +extension, `unrar`, or full `7z`. TAR, XZ, 7z, gzip, bzip2, and DEB use `7za`. +Zstandard (`.zst` and `.tar.zst`) uses the optional `zstd` executable, or full +`7z` **24.01 or newer**. Zstandard archives do not reliably expose an expanded +size in archive listings, so the staging supervisor is the protection for these +formats; its limits are best-effort, not strict disk quotas. #### Ubuntu / Debian ```bash -sudo apt-get install p7zip p7zip-full unrar +sudo apt-get install p7zip p7zip-full unrar zstd ``` #### Fedora / RHEL / CentOS ```bash -sudo dnf install p7zip p7zip-plugins unrar +sudo dnf install p7zip p7zip-plugins unrar zstd ``` #### macOS ```bash -brew install p7zip +brew install p7zip zstd ``` ## 📦 Installation @@ -132,19 +165,37 @@ brew install p7zip The action is offered for readable archives when you can create files in their parent folder. Extraction never modifies the archive itself. +If an archive contains a filename the Nextcloud storage cannot represent +(including some legacy character encodings), extraction fails explicitly rather +than discarding those entries and reporting a misleading success. Valid UTF-8 +names are preserved. A newly created target folder is removed if the import +fails partway through. Legacy clients merging into an existing folder may still +leave partial changes, since deleting that folder could destroy pre-existing +user data. + ### Supported formats | Format | Extensions | Extraction backend | |--------|------------|--------------------| | Zip | `.zip` | PHP `zip` extension | -| Rar | `.rar` | PHP `rar` extension or `unrar` | +| Rar | `.rar` | PHP `rar` extension, `unrar`, or full `7z` fallback | | Tar | `.tar` | `7za` | | Tar + Gzip | `.tar.gz`, `.tgz` | `7za` | | Tar + Bzip2 | `.tar.bz2`, `.tbz2` | `7za` | +| Tar + XZ | `.tar.xz`, `.txz` | `7za` (two-pass) | +| Zstandard | `.zst`, `.zstd` | `zstd` or full `7z` 24.01+ | +| Tar + Zstandard | `.tar.zst`, `.tar.zstd`, `.tzst` | `zstd` or full `7z` 24.01+, then `7za` | | Gzip | `.gz` | `7za` | | 7z | `.7z` | `7za` | | Deb | `.deb` | `7za` | +On systems without the PHP `rar` extension or `unrar`, the full `7z` +executable can extract supported RAR archives as an additional fallback. +The smaller `7za` executable does not necessarily support RAR or Zstandard; +on Debian 13, install the `7zip` package to obtain the full decoder. For +Zstandard, installing the `zstd` command is sufficient and works even when +older full 7z versions cannot decode `.zst`. + > **Note:** Archives protected by a password are not supported. Extraction works > on a normal Nextcloud data directory, on object storage and with server-side > encryption enabled. On non-local storage the archive is unpacked into a @@ -153,9 +204,10 @@ parent folder. Extraction never modifies the archive itself. ### External storage -Archives on an external storage are unpacked through a temporary folder in the -app's own data directory, then moved into place. If a previous run was -interrupted, that temporary folder is removed before the new extraction starts. +Archives on external and local storage are unpacked into a request-owned +temporary directory and imported through the Nextcloud files API. This avoids +cross-device renames and updates the file cache for the destination. Temporary +staging content is removed after the request, including on failure. ## 🛠️ Development @@ -250,17 +302,19 @@ not introduce automatic release publishing. The archive tool could not unpack the file. Common causes: -- **Tool missing**: for Rar archives install the PHP `rar` extension or the - `unrar` binary; for every other format install `p7zip` and `p7zip-full` and - check that `7za` is on the `PATH` of the web server user. +- **Tool missing**: for RAR install the PHP `rar` extension, `unrar`, or full + `7z`; for TAR, XZ, 7z, gzip, bzip2 and DEB install `p7zip-full` and check + that `7za` is on the web server user's `PATH`. For Zstandard install `zstd` + or full `7z` version 24.01 or newer. - **Damaged or unreadable archive**: the file is truncated, corrupt, or not actually an archive of that format. - **Permissions**: the web server user cannot read the archive or write into the target folder. - **Insufficient space** on the volume holding the archive. -For a failed `7za` or `unrar` run the Nextcloud log records the exit code and the -tool output. Zip extraction and a missing tool are not logged with that detail. +For a failed external decoder, the Nextcloud log records the rejection reason +(for example a timeout, output limit or nonzero exit). To avoid unbounded +memory consumption, raw decoder output is not retained in extraction logs. ### "Unsupported archive type" @@ -279,18 +333,17 @@ app like any other folder. - **Server-side encryption enabled.** The encryption storage wrapper does the same, because it has to decrypt to a temporary file first. -The app detects both through `Storage::isLocal()`. On local storage it keeps -unpacking the archive next to the original file, which avoids copying the -payload a second time. +Both local and non-local archives are staged separately and published through +Nextcloud's files API. The backend never unpacks into an untracked path next +to the original file. If extraction used to report "Extraction is only supported on local storage" on these setups, update to a version that includes the import step. ### A password-protected archive -Password-protected archives are not supported. Zip and the 7-Zip formats report -"Oops something went wrong."; Rar with the PHP `rar` extension is the exception, -because that path does not surface a failure. +Password-protected archives are not supported, including ZIP, 7z, and RAR. +An encrypted archive must not be reported as successfully extracted. ### Large archives diff --git a/appinfo/info.xml b/appinfo/info.xml index 3c1e2d4c..fca07be0 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -15,15 +15,14 @@ * 7z * Deb * Bzip2 + * Xz / tar.xz + * Zstandard / tar.zst * **Requirements :** - * Rar PHP extension (pecl -v install rar) - - * **OR** - * unrar (sudo apt-get install unrar) - - * **AND** - * p7zip (sudo apt-get install p7zip p7zip-full) + * PHP zip extension for ZIP + * p7zip / p7zip-full (7za) for 7z, TAR, XZ, GZIP, BZIP2 and DEB + * PHP rar, unrar or full 7z for RAR + * zstd or full 7z (24.01+) for Zstandard * **Note :** Password-protected archives are not supported yet. Object storage and server-side encryption are supported: the archive is unpacked into a diff --git a/lib/Capabilities.php b/lib/Capabilities.php index ee5c9d95..95b12c32 100644 --- a/lib/Capabilities.php +++ b/lib/Capabilities.php @@ -23,6 +23,8 @@ final class Capabilities implements IPublicCapability { 'extract-tar-gz', 'extract-tar-bz2', 'extract-tar-xz', + 'extract-zstd', + 'extract-tar-zstd', 'extract-7z', ]; diff --git a/lib/Controller/ExtractionController.php b/lib/Controller/ExtractionController.php index 7d0c5702..ac3365b9 100644 --- a/lib/Controller/ExtractionController.php +++ b/lib/Controller/ExtractionController.php @@ -54,6 +54,11 @@ final class ExtractionController extends AEnvironmentAwareController { 'application/x-bzip2' => 'other', 'application/x-deb' => 'other', 'application/x-compressed' => 'other', + 'application/x-xz' => 'other', + 'application/x-xz-compressed-tar' => 'other', + 'application/zstd' => 'zstd', + 'application/x-zstd' => 'zstd', + 'application/x-zstd-compressed-tar' => 'zstd', ]; /** @@ -64,7 +69,7 @@ final class ExtractionController extends AEnvironmentAwareController { * expands it in a single pass, so treating it as wrapped would make the * controller look for a second archive inside the extracted payload. */ - private const WRAPPED_TARBALL_EXTENSIONS = ['tar.gz', 'tgz', 'tar.bz2', 'tbz', 'tbz2', 'tar.xz', 'txz']; + private const WRAPPED_TARBALL_EXTENSIONS = ['tar.gz', 'tgz', 'tar.bz2', 'tbz', 'tbz2', 'tar.xz', 'txz', 'tar.zst', 'tar.zstd', 'tzst']; /** @var Folder */ private $userFolder; @@ -176,12 +181,14 @@ private static function isUsableRelativeDestinationPath(string $path): bool { * @param string $extractTo The local file-system path of the destination. * @return array{code: 0|1, desc?: string} */ - private function extractWrappedTarball(string $file, string $extractTo): array { + private function extractWrappedTarball(string $file, string $extractTo, ?int $availableBytes = null, bool $zstd = false, ?string $archiveName = null): array { // A unique scratch directory: a predictable sibling name could collide // with, and then delete, an unrelated folder in the same directory. $scratch = $extractTo . '.unwrapped.' . bin2hex(random_bytes(8)); - $response = $this->extractionService->extractOther($file, $scratch); + $response = $zstd + ? $this->extractionService->extractZstd($file, $scratch, $availableBytes, $archiveName) + : $this->extractionService->extractOther($file, $scratch, $availableBytes); if (($response['code'] ?? 0) === 0) { $this->removeDirectory($scratch); return $response; @@ -194,7 +201,7 @@ private function extractWrappedTarball(string $file, string $extractTo): array { return ['code' => 0, 'desc' => $this->l->t('Oops something went wrong.')]; } - $response = $this->extractionService->extractOther($innerTar, $extractTo); + $response = $this->extractionService->extractOther($innerTar, $extractTo, $availableBytes); $this->removeDirectory($scratch); return $response; @@ -260,8 +267,29 @@ private function removeDirectory(string $directory): void { */ private function postExtract(string $fileName, string $directory, string $extractTo, bool $rejectExisting = false): void { $this->assertNoSymbolicLinks($extractTo); - $this->removeForbiddenFiles($extractTo); - $this->importDirectory($extractTo, $this->destinationFolder($directory, $fileName, $rejectExisting)); + $this->assertValidExtractedNames($extractTo); + + // Only a newly created destination belongs entirely to this operation. + // Never delete an existing folder, which legacy clients may merge into. + $parent = $this->userFolder->get($directory); + if (!($parent instanceof Folder)) { + throw new NotPermittedException('Destination is not a folder'); + } + $destinationExisted = $parent->nodeExists($fileName); + $target = $this->destinationFolder($directory, $fileName, $rejectExisting); + try { + $this->importDirectory($extractTo, $target); + } catch (\Throwable $e) { + if (!$destinationExisted) { + try { + $target->delete(); + } catch (\Throwable $cleanupError) { + $this->logger->error('Could not remove a partially imported extraction: ' . $cleanupError->getMessage()); + } + } + $this->logger->error('Extraction import failed: ' . $e->getMessage()); + throw new NotPermittedException('Could not complete extraction'); + } } /** @@ -284,22 +312,22 @@ private function assertNoSymbolicLinks(string $directory): void { } /** - * Delete every extracted file whose name Nextcloud forbids. + * Check every file and directory component before any data is published. + * Silently removing an invalid name can report success for a partial archive, + * which users may mistake for a complete backup extraction. * * @param string $directory The local file-system path of the extracted tree. */ - private function removeForbiddenFiles(string $directory): void { - // SKIP_DOTS matters: without it the iterator yields `.` and `..` for every - // directory in the tree, which isFilenameValid() rejects and unlink() then - // fails on. + private function assertValidExtractedNames(string $directory): void { $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::SELF_FIRST, ); - foreach ($iterator as $file) { - /** @var \SplFileInfo $file */ - if (!$this->filenameValidator->isFilenameValid($file->getBasename())) { - $this->logger->warning(__METHOD__ . ': removing blacklisted file: ' . $file->getPathname()); - unlink($file->getPathname()); + foreach ($iterator as $entry) { + /** @var \SplFileInfo $entry */ + $name = $entry->getBasename(); + if (preg_match('//u', $name) !== 1 || !$this->filenameValidator->isFilenameValid($name)) { + throw new NotPermittedException('Archive contains filenames that Nextcloud cannot store'); } } } @@ -510,17 +538,24 @@ public function execute( switch ($type) { case 'zip': - $response = $this->extractionService->extractZip($file, $extractTo); + $response = $this->extractionService->extractZip($file, $extractTo, $destinationParent->getFreeSpace()); break; case 'rar': - $response = $this->extractionService->extractRar($file, $extractTo); + $response = $this->extractionService->extractRar($file, $extractTo, $destinationParent->getFreeSpace()); + break; + case 'zstd': + if (self::isWrappedTarball($nameOfFile)) { + $response = $this->extractWrappedTarball($file, $extractTo, $destinationParent->getFreeSpace(), true, $nameOfFile); + } else { + $response = $this->extractionService->extractZstd($file, $extractTo, $destinationParent->getFreeSpace(), $nameOfFile); + } break; default: if (self::isWrappedTarball($nameOfFile) === true) { - $response = $this->extractWrappedTarball($file, $extractTo); + $response = $this->extractWrappedTarball($file, $extractTo, $destinationParent->getFreeSpace()); } else { // A plain .tar and every non-tar format is a single 7za pass. - $response = $this->extractionService->extractOther($file, $extractTo); + $response = $this->extractionService->extractOther($file, $extractTo, $destinationParent->getFreeSpace()); } break; } @@ -538,7 +573,10 @@ public function execute( $this->postExtract($fileName, $directory, $extractTo, $targetDirName !== null); } catch (NotFoundException|NotPermittedException|InvalidPathException $e) { $this->logger->error(__METHOD__ . ': could not publish the extracted folder: ' . $e->getMessage()); - return new DataResponse(['code' => 0, 'desc' => $this->l->t('Oops something went wrong.')]); + $description = $e->getMessage() === 'Archive contains filenames that Nextcloud cannot store' + ? $this->l->t('Archive contains filenames that Nextcloud cannot store') + : $this->l->t('Oops something went wrong.'); + return new DataResponse(['code' => 0, 'desc' => $description]); } finally { if ($scratch !== null) { $this->removeDirectory($scratch); diff --git a/lib/Service/ArchiveSafetyValidator.php b/lib/Service/ArchiveSafetyValidator.php new file mode 100644 index 00000000..a2aa76d7 --- /dev/null +++ b/lib/Service/ArchiveSafetyValidator.php @@ -0,0 +1,51 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +use OCP\IL10N; +use Psr\Log\LoggerInterface; + +/** Validate entry names and archive metadata independently from decoders. */ +final class ArchiveSafetyValidator { + public function __construct( + private IL10N $l, + private LoggerInterface $logger, + ) { + } + + private function isUnsafePath(string $entry): bool { + $path = str_replace('\\', '/', $entry); + if (preg_match('/[\x00-\x1f\x7f]/', $entry) === 1) { + return true; + } + if (str_starts_with($path, '/') || preg_match('/^[a-zA-Z]:/', $path) === 1) { + return true; + } + return preg_match('#(^|/)\.\.($|/)#', $path) === 1; + } + + public function rejectUnsafe(string $entry): ?array { + if (!$this->isUnsafePath($entry)) { + return null; + } + $this->logger->warning('Refusing archive with unsafe entry'); + return ['code' => 0, 'desc' => $this->l->t('Archive contains an unsafe path and was not extracted')]; + } + + public function rejectUnsafeMetadata(string $line): ?array { + if (preg_match('/^(?:Symbolic Link|Hard Link|Junction|Reparse Point)\s*=\s*\S/i', $line) !== 1 + && !(str_starts_with($line, 'Attributes = ') + && preg_match('/(?:^|\s)[lbpcs][-rwxstST]{9}(?:\s|$)/', $line) === 1)) { + return null; + } + $this->logger->warning('Refusing archive with links or special files'); + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } +} diff --git a/lib/Service/BoundedStreamCopier.php b/lib/Service/BoundedStreamCopier.php new file mode 100644 index 00000000..d9dfb496 --- /dev/null +++ b/lib/Service/BoundedStreamCopier.php @@ -0,0 +1,77 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +/** + * Copy decoded bytes with one cumulative budget and optional size, deadline + * and CRC requirements. Input ownership remains with the calling extractor. + */ +final class BoundedStreamCopier { + /** + * @param resource $input + */ + public function copy( + $input, + string $target, + int &$written, + int $budget, + ?int $expectedBytes = null, + ?string $expectedCrc = null, + ?int $deadline = null, + ): bool { + if ($budget < 0 || $written < 0 || $written > $budget || ($expectedBytes !== null && $expectedBytes < 0)) { + return false; + } + // Preserve ZIP overwrite semantics; RAR entries must never overwrite. + $output = @fopen($target, $expectedBytes === null ? 'wb' : 'xb'); + if ($output === false) { + return false; + } + $entryBytes = 0; + $hash = $expectedCrc !== null ? hash_init('crc32b') : null; + try { + while (!feof($input)) { + if ($deadline !== null && hrtime(true) >= $deadline) { + return false; + } + $chunk = fread($input, 65536); + if ($chunk === false || ($chunk === '' && !feof($input))) { + return false; + } + $length = strlen($chunk); + if ($length > $budget - $written || ($expectedBytes !== null && $length > $expectedBytes - $entryBytes)) { + return false; + } + $offset = 0; + while ($offset < $length) { + if ($deadline !== null && hrtime(true) >= $deadline) { + return false; + } + $count = fwrite($output, substr($chunk, $offset)); + if ($count === false || $count === 0) { + return false; + } + $offset += $count; + } + if ($hash !== null) { + hash_update($hash, $chunk); + } + $entryBytes += $length; + $written += $length; + } + } finally { + fclose($output); + } + if ($expectedBytes !== null && $entryBytes !== $expectedBytes) { + return false; + } + return $hash === null || hash_equals(strtolower($expectedCrc), hash_final($hash)); + } +} diff --git a/lib/Service/CliArchiveExtractor.php b/lib/Service/CliArchiveExtractor.php new file mode 100644 index 00000000..f2ce74c1 --- /dev/null +++ b/lib/Service/CliArchiveExtractor.php @@ -0,0 +1,253 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +namespace OCA\Extract\Service; + +use OCP\IL10N; +use Psr\Log\LoggerInterface; + +/** Preflight and supervise external archive formats through 7za, 7z and unrar. */ +final class CliArchiveExtractor { + private const DEFAULT_MAX_EXTRACTED_BYTES = 2147483648; + private const DEFAULT_MAX_ARCHIVE_ENTRIES = 10000; + private const MAX_ARCHIVE_LISTING_BYTES = 16777216; + private const ARCHIVE_LIST_TIMEOUT_SECONDS = 20; + public function __construct( + private IL10N $l, + private LoggerInterface $logger, + private ArchiveSafetyValidator $safety, + private ExtractionLimits $limits, + ) { + } + + private function listWithLimits(array $command): ?array { + $result = ResourceLimitedProcess::capture( + $command, + self::MAX_ARCHIVE_LISTING_BYTES, + self::ARCHIVE_LIST_TIMEOUT_SECONDS, + ); + if (!$result['success']) { + $this->logger->warning('Archive listing rejected: ' . $result['reason']); + return null; + } + return explode("\n", $result['output']); + } + + private function assertSafeRarShell(string $file): ?array { + $output = $this->listWithLimits(['unrar', 'lb', $file]); + if ($output === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + foreach ($output as $entry) { + $entry = rtrim($entry, "\r"); + if ($entry !== '' && ($error = $this->safety->rejectUnsafe($entry))) { + return $error; + } + } + // The plain filename list does not reveal links. Inspect entry types + // before extraction, using 7z technical metadata when available. + if ($this->isCommandAvailable('7z')) { + return $this->assertSafeRarSevenZip($file); + } + $details = $this->listWithLimits(['unrar', 'lt', $file]); + if ($details === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + $types = 0; + foreach ($details as $line) { + if (preg_match('/^\s*Type\s*:\s*(.+)$/i', $line, $match) === 1) { + $types++; + if (preg_match('/^(?:File|Directory)$/i', trim($match[1])) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } + } + } + if ($types === 0) { + return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry types')]; + } + return null; + } + + private function assertSafe7z(string $file, ?int $availableBytes, ?int $temporarySpace): ?array { + $output = $this->listWithLimits(['7za', 'l', '-ba', '-slt', $file]); + if ($output === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; + } + $budget = $this->limits->configuredLimit('max_extracted_bytes', self::DEFAULT_MAX_EXTRACTED_BYTES); + if ($availableBytes !== null && $availableBytes >= 0) { + $budget = min($budget, $availableBytes); + } + if ($temporarySpace !== null && $temporarySpace >= 0) { + $budget = min($budget, $temporarySpace); + } + $entryLimit = $this->limits->entryLimit(); + $entries = 0; + $size = 0; + foreach ($output as $line) { + $line = rtrim($line, "\r"); + if ($error = $this->safety->rejectUnsafeMetadata($line)) { + return $error; + } + if (str_starts_with($line, 'Path = ')) { + if ($error = $this->safety->rejectUnsafe(substr($line, 7))) { + return $error; + } + $entries++; + if ($entries > $entryLimit) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } + } elseif (str_starts_with($line, 'Size = ')) { + $declaredSize = filter_var(trim(substr($line, 7)), FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]); + if ($declaredSize === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; + } + if ($declaredSize > $budget - $size) { + return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; + } + $size += $declaredSize; + } + } + return null; + } + + private function runExternalDecoder(array $command, string $extractTo, ?int $availableBytes = null): array { + $limit = $this->limits->byteBudget($extractTo, $availableBytes); + $result = ResourceLimitedProcess::run( + $command, + $extractTo, + $limit, + $this->limits->entryLimit(), + $this->limits->timeout(), + ); + if (!$result['success']) { + $this->logger->warning('Archive decoder stopped: ' . $result['reason']); + $message = match ($result['reason']) { + 'size' => 'Archive exceeds the allowed extraction size', + 'entries' => 'Archive contains too many files', + 'timeout' => 'Archive extraction timed out', + 'symlink' => 'Symbolic links are not supported in extracted archives', + default => 'Could not extract archive', + }; + return ['code' => 0, 'desc' => $this->l->t($message)]; + } + return ['code' => 1]; + } + + public function extractRar(string $file, string $extractTo, ?int $availableBytes = null): array { + if (!$this->isCommandAvailable('unrar')) { + return $this->extractRarWithSevenZip($file, $extractTo, $availableBytes); + } + if ($error = $this->assertSafeRarShell($file)) { + return $error; + } + return $this->runExternalDecoder(['unrar', 'x', $file, '-R', $extractTo . '/', '-o+'], $extractTo, $availableBytes); + } + + public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array { + + $temporarySpace = disk_free_space(dirname($extractTo)); + if ($error = $this->assertSafe7z( + $file, + $availableBytes, + $temporarySpace === false ? null : (int)$temporarySpace, + )) { + return $error; + } + return $this->runExternalDecoder(['7za', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); + } + + /** + * Zstandard is a single-file stream, not a multi-entry archive. The format + * does not require an uncompressed length in its header, so a declared-size + * preflight cannot reliably protect its output. Use the staging supervisor + * for both optional decoders and never let a temporary source basename + * decide the user-visible output filename. + */ + public function extractZstd(string $file, string $extractTo, ?int $availableBytes = null, ?string $archiveName = null): array { + $name = $archiveName ?? basename($file); + $targetName = preg_replace('/\.(?:zst|zstd)$/i', '', $name); + if (!is_string($targetName) || $targetName === '' || $targetName === '.' || $targetName === '..' + || str_contains($targetName, '/') || str_contains($targetName, '\\') + || preg_match('/[\x00-\x1f\x7f]/', $targetName) === 1 || preg_match('//u', $targetName) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; + } + + if ($this->isCommandAvailable('zstd')) { + if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; + } + return $this->runExternalDecoder( + ['zstd', '-d', '-q', '-f', '-o', $extractTo . '/' . $targetName, '--', $file], + $extractTo, + $availableBytes, + ); + } + + if (!$this->isCommandAvailable('7z')) { + return ['code' => 0, 'desc' => $this->l->t('Zstandard extraction requires zstd or full 7z version 24.01 or newer')]; + } + $listing = $this->listWithLimits(['7z', 'l', '-slt', $file]); + if ($listing === null || !in_array('Type = zstd', array_map('trim', $listing), true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not inspect Zstandard archive with full 7z')]; + } + $response = $this->runExternalDecoder(['7z', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); + if ($response['code'] === 0) { + return $response; + } + + // Full 7z names the output after the local archive copy. Rename the + // single decoded stream to the original Nextcloud filename when needed. + if (!is_dir($extractTo)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract archive')]; + } + $entries = iterator_to_array(new \FilesystemIterator($extractTo, \FilesystemIterator::SKIP_DOTS), false); + if (count($entries) !== 1 || !$entries[0]->isFile() || $entries[0]->isLink()) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract archive')]; + } + if ($entries[0]->getFilename() !== $targetName && !rename($entries[0]->getPathname(), $extractTo . '/' . $targetName)) { + return ['code' => 0, 'desc' => $this->l->t('Could not prepare extracted filename')]; + } + return $response; + } + + private function assertSafeRarSevenZip(string $file): ?array { + $output = $this->listWithLimits(['7z', 'l', '-ba', '-slt', $file]); + if ($output === null) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + foreach ($output as $line) { + $line = rtrim($line, "\r"); + if ($error = $this->safety->rejectUnsafeMetadata($line)) { + return $error; + } + if (str_starts_with($line, 'Path = ')) { + if ($error = $this->safety->rejectUnsafe(substr($line, 7))) { + return $error; + } + } + } + return null; + } + + private function extractRarWithSevenZip(string $file, string $extractTo, ?int $availableBytes = null): array { + if (!$this->isCommandAvailable('7z')) { + return ['code' => 0, 'desc' => $this->l->t('RAR extraction requires unrar, the PHP rar extension, or the full 7z binary')]; + } + if ($error = $this->assertSafeRarSevenZip($file)) { + return $error; + } + return $this->runExternalDecoder(['7z', '-y', 'x', $file, '-o' . $extractTo], $extractTo, $availableBytes); + } + + private function isCommandAvailable(string $binary): bool { + $return = 0; + $output = []; + exec('command -v ' . escapeshellarg($binary) . ' >/dev/null 2>&1', $output, $return); + return $return === 0; + } +} diff --git a/lib/Service/DecoderProcess.php b/lib/Service/DecoderProcess.php new file mode 100644 index 00000000..4a979014 --- /dev/null +++ b/lib/Service/DecoderProcess.php @@ -0,0 +1,187 @@ + */ + private array $pipes; + private ?int $exitCode = null; + private ?int $groupId = null; + private int $outputBytes = 0; + private bool $drainedSinceLastPoll = false; + private string $output = ''; + + /** + * @param resource $process + * @param array $pipes + */ + private function __construct( + $process, + array $pipes, + private readonly bool $isolated, + ) { + $this->process = $process; + $this->pipes = $pipes; + } + + /** + * @param non-empty-list $command A fixed argument vector, not a shell command + */ + public static function start(array $command): ?self { + if (!function_exists('proc_open')) { + return null; + } + $isolated = false; + $command = self::isolatedCommand($command, $isolated); + try { + $process = proc_open($command, [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ], $pipes, null, null, ['bypass_shell' => true]); + } catch (\Throwable) { + return null; + } + if (!is_resource($process)) { + return null; + } + fclose($pipes[0]); + stream_set_blocking($pipes[1], false); + stream_set_blocking($pipes[2], false); + return new self($process, $pipes, $isolated); + } + + /** + * Drain stdout and stderr without buffering extraction output. For archive + * listings, limit the combined bytes while only retaining stdout. + */ + public function drain(?int $outputLimit): ?string { + $this->drainedSinceLastPoll = false; + $remaining = self::MAX_DRAIN_PER_POLL; + foreach ([1, 2] as $index) { + while ($remaining > 0) { + $chunk = fread($this->pipes[$index], min(65536, $remaining)); + if ($chunk === false) { + return 'io'; + } + if ($chunk === '') { + break; + } + $length = strlen($chunk); + $this->drainedSinceLastPoll = true; + $remaining -= $length; + if ($outputLimit !== null) { + if ($length > $outputLimit - $this->outputBytes) { + return 'output'; + } + $this->outputBytes += $length; + if ($index === 1) { + $this->output .= $chunk; + } + } + } + } + return null; + } + + /** Whether the last drain pass consumed bytes from either process pipe. */ + public function hadOutput(): bool { + return $this->drainedSinceLastPoll; + } + + public function hasExited(): bool { + $status = proc_get_status($this->process); + if ($this->isolated && $this->groupId === null) { + $this->groupId = self::processGroupId($status); + } + if (!$status['running'] && ($this->exitCode === null || $this->exitCode < 0)) { + $this->exitCode = $status['exitcode']; + } + return !$status['running']; + } + + public function outputComplete(): bool { + return feof($this->pipes[1]) && feof($this->pipes[2]); + } + + public function output(): string { + return $this->output; + } + + /** Always tear down the process group and release every pipe. */ + public function close(): int { + $this->stopProcess(); + fclose($this->pipes[1]); + fclose($this->pipes[2]); + $closedCode = proc_close($this->process); + if (($this->exitCode === null || $this->exitCode < 0) && $closedCode >= 0) { + $this->exitCode = $closedCode; + } + return $this->exitCode ?? -1; + } + + /** + * @param non-empty-list $command + * @return non-empty-list + */ + private static function isolatedCommand(array $command, bool &$isolated): array { + $isolated = false; + if (DIRECTORY_SEPARATOR !== '/' || !function_exists('posix_kill') || !function_exists('posix_getpgid') || !function_exists('posix_getpgrp')) { + return $command; + } + foreach (['/usr/bin/setsid', '/bin/setsid'] as $binary) { + if (is_executable($binary)) { + $isolated = true; + return [$binary, ...$command]; + } + } + return $command; + } + + /** + * @param array{pid: int, running: bool, command: string, exitcode: int, signaled: bool, stopped: bool, stopsig: int, termsig: int} $status + */ + private static function processGroupId(array $status): ?int { + $pid = $status['pid']; + if ($pid <= 1 || $pid === posix_getpgrp()) { + return null; + } + return @posix_getpgid($pid) === $pid ? $pid : null; + } + + private function stopProcess(): void { + if ($this->isolated && $this->groupId === null) { + $this->groupId = self::processGroupId(proc_get_status($this->process)); + } + if ($this->groupId !== null) { + @posix_kill(-$this->groupId, 15); + usleep(self::TERMINATION_WAIT_US); + if (@posix_kill(-$this->groupId, 0)) { + @posix_kill(-$this->groupId, 9); + } + } + if (proc_get_status($this->process)['running']) { + proc_terminate($this->process); + usleep(self::TERMINATION_WAIT_US); + if (proc_get_status($this->process)['running']) { + proc_terminate($this->process, 9); + } + } + } +} diff --git a/lib/Service/ExtractionLimits.php b/lib/Service/ExtractionLimits.php new file mode 100644 index 00000000..11b291ae --- /dev/null +++ b/lib/Service/ExtractionLimits.php @@ -0,0 +1,49 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +use OCP\IConfig; + +/** Resolve positive application limits without exposing configuration parsing. */ +final class ExtractionLimits { + public function __construct( + private IConfig $config, + ) { + } + + public function configuredLimit(string $key, int $default): int { + $value = $this->config->getAppValue('extract', $key, (string)$default); + if (!is_string($value) || filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false) { + return $default; + } + return (int)$value; + } + + /** Calculate the staging budget consistently across ZIP, RAR and CLI. */ + public function byteBudget(string $extractTo, ?int $availableBytes): int { + $limit = $this->configuredLimit('max_extracted_bytes', 2147483648); + if ($availableBytes !== null && $availableBytes >= 0) { + $limit = min($limit, $availableBytes); + } + $space = disk_free_space(dirname($extractTo)); + if ($space !== false) { + $limit = min($limit, (int)$space); + } + return $limit; + } + + public function entryLimit(): int { + return $this->configuredLimit('max_archive_entries', 10000); + } + + public function timeout(): int { + return $this->configuredLimit('max_extraction_seconds', 300); + } +} diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index cd3252f4..2b9c5a00 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -3,209 +3,50 @@ /** * SPDX-FileCopyrightText: 2012-2022 Paul Lereverend * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ - namespace OCA\Extract\Service; +use OCP\IConfig; use OCP\IL10N; use Psr\Log\LoggerInterface; -use ZipArchive; +/** Stable entry point for the Nextcloud extraction controller. */ final class ExtractionService { + private ZipExtractor $zip; + private PhpRarExtractor $phpRar; + private CliArchiveExtractor $cli; - public function __construct( - private IL10N $l, - private LoggerInterface $logger, - ) { - } - - /** - * Reject archive names that may escape the extraction staging directory, - * including absolute, Windows drive and traversal paths. - */ - private function isUnsafePath(string $entry): bool { - $path = str_replace('\\', '/', $entry); - if (preg_match('/[\x00-\x1f\x7f]/', $entry) === 1) { - return true; - } - if (str_starts_with($path, '/') || preg_match('/^[a-zA-Z]:/', $path) === 1) { - return true; - } - return preg_match('#(^|/)\.\.($|/)#', $path) === 1; - } - - /** @return null|array{code: 0, desc: string} */ - private function rejectUnsafe(string $entry): ?array { - if (!$this->isUnsafePath($entry)) { - return null; - } - $this->logger->warning('Refusing archive with unsafe entry'); - return ['code' => 0, 'desc' => $this->l->t('Archive contains an unsafe path and was not extracted')]; + public function __construct(IL10N $l, LoggerInterface $logger, IConfig $config) { + $safety = new ArchiveSafetyValidator($l, $logger); + $limits = new ExtractionLimits($config); + $copier = new BoundedStreamCopier(); + $this->zip = new ZipExtractor($l, $safety, $limits, $copier); + $this->phpRar = new PhpRarExtractor($l, $logger, $safety, $limits, $copier); + $this->cli = new CliArchiveExtractor($l, $logger, $safety, $limits); } - /** @return null|array{code: 0, desc: string} */ - private function assertSafeZip(ZipArchive $zip): ?array { - for ($i = 0; $i < $zip->numFiles; $i++) { - $name = $zip->getNameIndex($i); - if ($name === false) { - return ['code' => 0, 'desc' => $this->l->t('Failed to read archive index')]; - } - if ($error = $this->rejectUnsafe($name)) { - return $error; - } - } - return null; + /** @return array{code: 0|1, desc?: string} */ + public function extractZip(string $file, string $extractTo, ?int $availableBytes = null): array { + return $this->zip->extract($file, $extractTo, $availableBytes); } - /** @return null|array{code: 0, desc: string} */ - private function assertSafeRarShell(string $file): ?array { - $output = []; - $return = 0; - exec('unrar lb ' . escapeshellarg($file) . ' 2>&1', $output, $return); - if ($return !== 0) { - $this->logger->error('unrar list failed (rc=' . $return . '): ' . implode("\n", $output)); - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - foreach ($output as $entry) { - if ($entry !== '' && ($error = $this->rejectUnsafe($entry))) { - return $error; - } + /** @return array{code: 0|1, desc?: string} */ + public function extractRar(string $file, string $extractTo, ?int $availableBytes = null): array { + if (extension_loaded('rar')) { + return $this->phpRar->extract($file, $extractTo, $availableBytes); } - return null; + return $this->cli->extractRar($file, $extractTo, $availableBytes); } - /** @return null|array{code: 0, desc: string} */ - private function assertSafe7z(string $file): ?array { - $output = []; - $return = 0; - exec('7za l -ba -slt ' . escapeshellarg($file) . ' 2>&1', $output, $return); - if ($return !== 0) { - $this->logger->error('7za list failed (rc=' . $return . '): ' . implode("\n", $output)); - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect archive contents')]; - } - foreach ($output as $line) { - if (str_starts_with($line, 'Path = ')) { - if ($error = $this->rejectUnsafe(substr($line, 7))) { - return $error; - } - } - } - return null; + /** @return array{code: 0|1, desc?: string} */ + public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array { + return $this->cli->extractOther($file, $extractTo, $availableBytes); } - /** - * @return (bool|int|mixed)[] - * - * @psalm-return array{code: 0|1, desc?: string} - */ - public function extractZip(string $file, string $extractTo): array { - $response = []; - - if (!extension_loaded('zip')) { - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Zip extension is not available')]); - return $response; - } - - $zip = new ZipArchive(); - - if ($zip->open($file) !== true) { - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Cannot open Zip file')]); - return $response; - } - - if ($error = $this->assertSafeZip($zip)) { - $zip->close(); - return $error; - } - - $success = $zip->extractTo($extractTo); - $zip->close(); - $response = array_merge($response, ['code' => $success ? 1 : 0]); - return $response; - } - - /** - * @return (int|mixed)[] - * - * @psalm-return array{code: 0|1, desc?: string} - */ - public function extractRar(string $file, string $extractTo): array { - $response = []; - - if (!extension_loaded('rar')) { - if ($error = $this->assertSafeRarShell($file)) { - return $error; - } - $output = []; - $return = 0; - exec('unrar x ' . escapeshellarg($file) . ' -R ' . escapeshellarg($extractTo) . '/ -o+', $output, $return); - if ($return !== 0) { - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Oops something went wrong. Check that you have rar extension or unrar installed')]); - $this->logger->error('unrar failed with exit code ' . $return . '. Output: ' . print_r($output, true)); - return $response; - } - } else { - $rar_file = rar_open($file); - if ($rar_file === false) { - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Cannot open Rar file')]); - return $response; - } - $list = rar_list($rar_file); - if ($list === false) { - rar_close($rar_file); - return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; - } - foreach ($list as $archive_file) { - if ($error = $this->rejectUnsafe($archive_file->getName())) { - rar_close($rar_file); - return $error; - } - } - foreach ($list as $archive_file) { - $entry = rar_entry_get($rar_file, $archive_file->getName()); - if ($entry->extract($extractTo) === false) { - // A password-protected or damaged entry fails here; without this - // check the method reported success and the caller published a - // partial result. - rar_close($rar_file); - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Oops something went wrong.')]); - $this->logger->error('rar_entry::extract failed for ' . $archive_file->getName()); - return $response; - } - } - rar_close($rar_file); - } - - $response = array_merge($response, ['code' => 1]); - return $response; - } - - /** - * @return (int|mixed)[] - * - * @psalm-return array{code: 0|1, desc?: string} - */ - public function extractOther(string $file, string $extractTo): array { - $response = []; - - if ($error = $this->assertSafe7z($file)) { - return $error; - } - $output = []; - $return = 0; - exec('7za -y x ' . escapeshellarg($file) . ' -o' . escapeshellarg($extractTo), $output, $return); - - // 7za reports failure through its exit code: 0 on success, 2 on a fatal - // error such as a corrupt archive or a missing file, 127 when the - // binary itself is absent. The output line count is not a usable signal - // because failures print more lines than successes. - if ($return !== 0) { - $response = array_merge($response, ['code' => 0, 'desc' => $this->l->t('Oops something went wrong.')]); - $this->logger->error('7za failed with exit code ' . $return . '. Is 7-Zip installed? Output: ' . print_r($output, true)); - return $response; - } - $response = array_merge($response, ['code' => 1]); - return $response; + /** @return array{code: 0|1, desc?: string} */ + public function extractZstd(string $file, string $extractTo, ?int $availableBytes = null, ?string $archiveName = null): array { + return $this->cli->extractZstd($file, $extractTo, $availableBytes, $archiveName); } } diff --git a/lib/Service/PhpRarExtractor.php b/lib/Service/PhpRarExtractor.php new file mode 100644 index 00000000..a83b53b4 --- /dev/null +++ b/lib/Service/PhpRarExtractor.php @@ -0,0 +1,113 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +use OCP\IL10N; +use Psr\Log\LoggerInterface; + +/** Extract via the optional PHP rar extension, with bounded streaming. */ +final class PhpRarExtractor { + public function __construct( + private IL10N $l, + private LoggerInterface $logger, + private ArchiveSafetyValidator $safety, + private ExtractionLimits $limits, + private BoundedStreamCopier $copier, + ) { + } + + public function extract(string $file, string $extractTo, ?int $availableBytes): array { + $archive = rar_open($file); + if ($archive === false) { + return ['code' => 0, 'desc' => $this->l->t('Cannot open Rar file')]; + } + try { + $entries = rar_list($archive); + if ($entries === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect RAR contents')]; + } + $entryLimit = $this->limits->entryLimit(); + $entryCount = 0; + $budget = $this->limits->byteBudget($extractTo, $availableBytes); + $declared = 0; + $paths = []; + foreach ($entries as $entry) { + if (++$entryCount > $entryLimit) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } + $name = str_replace('\\', '/', $entry->getName()); + $relative = rtrim($name, '/'); + if ($relative === '' || preg_match('//u', $relative) !== 1 || isset($paths[$relative])) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; + } + if ($error = $this->safety->rejectUnsafe($name)) { + return $error; + } + $paths[$relative] = true; + if ($entry->isEncrypted()) { + return ['code' => 0, 'desc' => $this->l->t('Encrypted RAR archives are not supported')]; + } + // Unix RAR4 entries can encode links and devices as native + // filesystem types. RAR5 redirects are never materialized: + // getStream() writes regular file bytes under PHP control. + if (defined('RAR_HOST_UNIX') && $entry->getHostOs() === constant('RAR_HOST_UNIX')) { + $type = $entry->getAttr() & 0xf000; + if ($type !== 0x8000 && $type !== 0x4000) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains links or unsupported special files')]; + } + } + $size = $entry->getUnpackedSize(); + if ($size === false || $size < 0 || $size > $budget - $declared) { + return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; + } + $declared += $size; + } + if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; + } + $written = 0; + $deadline = hrtime(true) + min($this->limits->timeout(), 3600) * 1000000000; + foreach ($entries as $entry) { + $name = rtrim(str_replace('\\', '/', $entry->getName()), '/'); + $target = $extractTo . '/' . $name; + if ($entry->isDirectory()) { + if (!is_dir($target) && !mkdir($target, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } + continue; + } + if (!is_dir(dirname($target)) && !mkdir(dirname($target), 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } + $crc = $entry->getCrc(); + if (!is_string($crc) || preg_match('/^[0-9a-fA-F]{8}$/', $crc) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Could not verify RAR entry integrity')]; + } + $input = $entry->getStream(); + if ($input === false) { + return ['code' => 0, 'desc' => $this->l->t('Could not read RAR entry')]; + } + try { + if (!$this->copier->copy($input, $target, $written, $budget, $entry->getUnpackedSize(), $crc, $deadline)) { + return ['code' => 0, 'desc' => $this->l->t('RAR extraction exceeded limits or failed integrity verification')]; + } + } finally { + fclose($input); + } + } + return ['code' => 1]; + } catch (\Throwable $e) { + $this->logger->warning('RAR stream extraction failed: ' . $e->getMessage()); + return ['code' => 0, 'desc' => $this->l->t('Could not extract RAR archive')]; + } finally { + rar_close($archive); + } + } +} diff --git a/lib/Service/ResourceLimitedProcess.php b/lib/Service/ResourceLimitedProcess.php new file mode 100644 index 00000000..c46bd18b --- /dev/null +++ b/lib/Service/ResourceLimitedProcess.php @@ -0,0 +1,102 @@ + $command Fixed executable and argument vector + * @return array{success: bool, reason: string} + */ + public static function run(array $command, string $directory, int $maxBytes, int $maxEntries, int $timeoutSeconds): array { + if ($maxBytes < 0 || $maxEntries < 1) { + return ['success' => false, 'reason' => 'unavailable']; + } + $result = self::execute($command, $timeoutSeconds, new StagingBudgetInspector($directory, $maxBytes, $maxEntries), null); + return ['success' => $result['success'], 'reason' => $result['reason']]; + } + + /** + * @param non-empty-list $command Fixed executable and argument vector + * @return array{success: bool, reason: string, output: string} + */ + public static function capture(array $command, int $maxOutputBytes, int $timeoutSeconds): array { + if ($maxOutputBytes < 1) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; + } + return self::execute($command, $timeoutSeconds, null, $maxOutputBytes); + } + + /** + * Share one supervision loop for archive extraction and metadata listing. + * Only extraction needs filesystem scans; only listing retains stdout. + * + * @param non-empty-list $command + * @return array{success: bool, reason: string, output: string} + */ + private static function execute(array $command, int $timeoutSeconds, ?StagingBudgetInspector $inspector, ?int $maxOutputBytes): array { + if ($timeoutSeconds < 1) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; + } + $process = DecoderProcess::start($command); + if ($process === null) { + return ['success' => false, 'reason' => 'unavailable', 'output' => '']; + } + + $reason = null; + // Preserve the configured extraction timeout; limit listing to one hour. + $deadline = microtime(true) + ($maxOutputBytes === null ? $timeoutSeconds : min($timeoutSeconds, 3600)); + try { + while (true) { + $reason = $process->drain($maxOutputBytes); + if ($reason !== null) { + break; + } + $reason = $inspector?->inspect(); + if ($reason !== null) { + break; + } + if (microtime(true) >= $deadline) { + $reason = 'timeout'; + break; + } + if ($process->hasExited() && ($maxOutputBytes === null || $process->outputComplete())) { + break; + } + // A verbose decoder can fill the pipe much faster than a 50 ms + // polling cadence allows it to be drained. Keep reading promptly + // while data flows; retain the slower cadence when idle. + usleep($process->hadOutput() ? 1000 : self::POLL_INTERVAL_US); + } + } catch (\Throwable) { + $reason = 'inspection'; + } finally { + $exitCode = $process->close(); + } + + if ($reason === null) { + try { + $reason = $inspector?->inspect(); + } catch (\Throwable) { + $reason = 'inspection'; + } + } + if ($reason === null && $exitCode !== 0) { + $reason = 'exit'; + } + return ['success' => $reason === null, 'reason' => $reason ?? '', 'output' => $process->output()]; + } +} diff --git a/lib/Service/StagingBudgetInspector.php b/lib/Service/StagingBudgetInspector.php new file mode 100644 index 00000000..679a9e69 --- /dev/null +++ b/lib/Service/StagingBudgetInspector.php @@ -0,0 +1,60 @@ +directory)) { + return 'symlink'; + } + if (!is_dir($this->directory)) { + return file_exists($this->directory) ? 'inspection' : null; + } + $bytes = 0; + $entries = 0; + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::SELF_FIRST, + ); + foreach ($iterator as $entry) { + if ($entry->isLink()) { + return 'symlink'; + } + if (++$entries > $this->maxEntries) { + return 'entries'; + } + if (!$entry->isDir()) { + // Fail closed for device nodes, pipes and sockets in staging. + if (!$entry->isFile()) { + return 'inspection'; + } + $size = $entry->getSize(); + if ($size < 0 || $size > $this->maxBytes - $bytes) { + return 'size'; + } + $bytes += $size; + } + } + return null; + } +} diff --git a/lib/Service/ZipExtractor.php b/lib/Service/ZipExtractor.php new file mode 100644 index 00000000..c3c1a79b --- /dev/null +++ b/lib/Service/ZipExtractor.php @@ -0,0 +1,115 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Service; + +use OCP\IL10N; +use ZipArchive; + +/** ZIP-specific archive inspection and bounded extraction. */ +final class ZipExtractor { + public function __construct( + private IL10N $l, + private ArchiveSafetyValidator $safety, + private ExtractionLimits $limits, + private BoundedStreamCopier $copier, + ) { + } + + private function assertSafeZip(ZipArchive $zip): ?array { + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = $zip->getNameIndex($i); + if ($name === false) { + return ['code' => 0, 'desc' => $this->l->t('Failed to read archive index')]; + } + if ($error = $this->safety->rejectUnsafe($name)) { + return $error; + } + } + return null; + } + + public function extract(string $file, string $extractTo, ?int $availableBytes = null): array { + if (!extension_loaded('zip')) { + return ['code' => 0, 'desc' => $this->l->t('Zip extension is not available')]; + } + + $zip = new ZipArchive(); + if ($zip->open($file) !== true) { + return ['code' => 0, 'desc' => $this->l->t('Cannot open Zip file')]; + } + + try { + if ($error = $this->assertSafeZip($zip)) { + return $error; + } + + $limit = $this->limits->byteBudget($extractTo, $availableBytes); + if ($zip->numFiles > $this->limits->entryLimit()) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains too many files')]; + } + + // Check declared sizes before creating any staging content. Streaming + // below also enforces the actual size if metadata is dishonest. + $declared = 0; + for ($i = 0; $i < $zip->numFiles; $i++) { + $stat = $zip->statIndex($i); + if ($stat === false || !isset($stat['size']) || !is_int($stat['size']) || $stat['size'] < 0) { + return ['code' => 0, 'desc' => $this->l->t('Failed to inspect Zip contents')]; + } + if ($stat['size'] > $limit - $declared) { + return ['code' => 0, 'desc' => $this->l->t('Archive exceeds the allowed extraction size')]; + } + $declared += $stat['size']; + } + + if (!is_dir($extractTo) && !mkdir($extractTo, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not prepare extraction directory')]; + } + + $written = 0; + $seen = []; + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = $zip->getNameIndex($i); + if ($name === false || $name === '' || preg_match('//u', $name) !== 1) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains an invalid filename')]; + } + $relative = rtrim($name, '/'); + if (isset($seen[$relative])) { + return ['code' => 0, 'desc' => $this->l->t('Archive contains duplicate filenames')]; + } + $seen[$relative] = true; + $path = $extractTo . '/' . $relative; + if (str_ends_with($name, '/')) { + if (!is_dir($path) && !mkdir($path, 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; + } + continue; + } + if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0700, true)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; + } + $input = $zip->getStreamIndex($i); + if ($input === false) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; + } + try { + if (!$this->copier->copy($input, $path, $written, $limit)) { + return ['code' => 0, 'desc' => $this->l->t('Could not extract Zip archive')]; + } + } finally { + fclose($input); + } + } + return ['code' => 1]; + } finally { + $zip->close(); + } + } +} diff --git a/package-lock.json b/package-lock.json index 85dd062d..1a314668 100644 --- a/package-lock.json +++ b/package-lock.json @@ -130,35 +130,6 @@ "keyv": "^5.6.0" } }, - "node_modules/@cacheable/memory/node_modules/@keyv/bigmap": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", - "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "hashery": "^1.4.0", - "hookified": "^1.15.0" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "keyv": "^5.6.0" - } - }, - "node_modules/@cacheable/memory/node_modules/keyv": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", - "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@keyv/serialize": "^1.1.1" - } - }, "node_modules/@cacheable/utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", @@ -171,17 +142,6 @@ "keyv": "^5.6.0" } }, - "node_modules/@cacheable/utils/node_modules/keyv": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", - "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@keyv/serialize": "^1.1.1" - } - }, "node_modules/@ckpack/vue-color": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/@ckpack/vue-color/-/vue-color-1.6.0.tgz", @@ -914,25 +874,25 @@ } }, "node_modules/@eslint/config-array": { - "version": "0.23.5", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", - "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", + "version": "0.23.6", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz", + "integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==", "dev": true, "license": "Apache-2.0", "peer": true, "dependencies": { "@eslint/object-schema": "^3.0.5", "debug": "^4.3.1", - "minimatch": "^10.2.4" + "minimatch": "^11.0.5" }, "engines": { "node": "^20.19.0 || ^22.13.0 || >=24" } }, "node_modules/@eslint/config-helpers": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.6.0.tgz", - "integrity": "sha512-ii6Bw9jJ2zi2cWA2Z+9/QZ/+3DX6kwaV5Q986D/CdP3Lap3w/pgQZ373FV7byY/i7L4IRH/G43I5dz1ClsCbpA==", + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", + "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==", "dev": true, "license": "Apache-2.0", "peer": true, @@ -1005,9 +965,9 @@ } }, "node_modules/@eslint/plugin-kit": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.2.tgz", - "integrity": "sha512-+CNAzxglkrpNf/kKywqQfk74QjtceuOE7Qm+AF8miRvPF/wmmK5+OJOgVh3AVTT3RP2mH3+FOaxlE5v72owk0A==", + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", + "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -1134,6 +1094,13 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -1191,6 +1158,24 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@keyv/bigmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", + "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "hashery": "^1.4.0", + "hookified": "^1.15.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "keyv": "^5.6.0" + } + }, "node_modules/@keyv/serialize": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", @@ -3008,17 +2993,17 @@ "license": "MIT" }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.63.0.tgz", - "integrity": "sha512-rvwSgqT+DHpWdzfSzPatRLm02a0GlESt++9iy3hLCDY4BgkaLcl8LBi9Yh7XGFBpwcBE/K3024QuXWTpbz4FfQ==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.73.0.tgz", + "integrity": "sha512-UkygMFer53Yzn29MCYFTHf34hGXf5KJhiDWfIm1tXtXRrym1CS6l5H9Y3yCtPWChpC0/f93H88gdj8tN0dd4kw==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.63.0", - "@typescript-eslint/type-utils": "8.63.0", - "@typescript-eslint/utils": "8.63.0", - "@typescript-eslint/visitor-keys": "8.63.0", + "@typescript-eslint/scope-manager": "8.73.0", + "@typescript-eslint/type-utils": "8.73.0", + "@typescript-eslint/utils": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" @@ -3031,15 +3016,15 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.63.0", + "@typescript-eslint/parser": "^8.73.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.6.tgz", - "integrity": "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw==", + "version": "7.0.16", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.16.tgz", + "integrity": "sha512-52N+Y4HRMOJmbLmr+DqO4iSRyyB7N52gm7PWCT6h0p978+oKbqHCB7gIJIwZvBUsjlSdWbrBFqUSmIFNZMpn0A==", "dev": true, "license": "MIT", "engines": { @@ -3047,16 +3032,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.63.0.tgz", - "integrity": "sha512-gwh4gvvlaVDKKxyfxMG+Gnu1u9X0OQBwyGLkbwB65dIzBKnxeRiJlNFqlI3zwVhNXJIs6qV7mlFCn/BIajlVig==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.73.0.tgz", + "integrity": "sha512-AuL45bVcmssHfZ3Di3cs9Q0l4gBm4ZFVrJOQEE7VpqW+PVgQaEwSwazz4TVIiFabXkk6U51EprYDwqw+HR8ePw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.63.0", - "@typescript-eslint/types": "8.63.0", - "@typescript-eslint/typescript-estree": "8.63.0", - "@typescript-eslint/visitor-keys": "8.63.0", + "@typescript-eslint/scope-manager": "8.73.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0", "debug": "^4.4.3" }, "engines": { @@ -3072,14 +3057,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.63.0.tgz", - "integrity": "sha512-e5dh0/UI0ok53AlZ5wRkXCB32z/f2jUZqPR/ygAw5WYaSw8j9EoJWlS7wQjr/dmOaqWjnPIn2m+HhVPCMWGZVQ==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.73.0.tgz", + "integrity": "sha512-/pEf8Rc4Mjk+qJnY0uO1+Gadeal8uv50xpuic+srG2vIVatA0XxvWMUeMtFvs6OCHqftiQ7/+qH4aehG5stzIA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.63.0", - "@typescript-eslint/types": "^8.63.0", + "@typescript-eslint/tsconfig-utils": "^8.73.0", + "@typescript-eslint/types": "^8.73.0", "debug": "^4.4.3" }, "engines": { @@ -3094,14 +3079,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.63.0.tgz", - "integrity": "sha512-uUyfMWCnDSN8bCpcrY8nGP2BLkQ9Xn0GsipcONcpIDWhwhO4ZSyHvyS14U3X75mzxWxL3I2UZIrenTzdzcJO8A==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.73.0.tgz", + "integrity": "sha512-/TjD738Iq2rzj5z0ixVOi+TsvgjAzZPLPaH1yWdDBytR/HTR5gMpyYWZeCe5WTQZLwk3ho8AV7U3muoQCRtXBQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.63.0", - "@typescript-eslint/visitor-keys": "8.63.0" + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -3112,9 +3097,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.63.0.tgz", - "integrity": "sha512-sUAbkulqBAsncKnbRP3+7CtQFRKicexnj7ZwNC6ddCR7EmrXvjvdCYMJbUIqMd6lwoEriZjwLo08aS5tSjVMHg==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.73.0.tgz", + "integrity": "sha512-lmtCFOfYaJfpqZywGuXi4FpNtE+NQ+YLe3T0K9rtEDcW8ZuGWvfI++pj8r05sYMI8vWT2CYK4rWyedmD6Rp4og==", "dev": true, "license": "MIT", "engines": { @@ -3129,15 +3114,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.63.0.tgz", - "integrity": "sha512-Nzzh/OGxVCOjObjaj1CQF2RUasyYy2Jfuh+zZ3PjLzG2fYRriAiZLib9UKtO+CpQAS3YHiAS+ckZDclwqI1TPA==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.73.0.tgz", + "integrity": "sha512-MOC9i4xy1F7KcDde7Ip8jf1SrRiALb2Km4UWxGNjUE2YlhjIEo1ayE27GHIwIQyfWuHTmEonQT14uyurlyC6aA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.63.0", - "@typescript-eslint/typescript-estree": "8.63.0", - "@typescript-eslint/utils": "8.63.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0", + "@typescript-eslint/utils": "8.73.0", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, @@ -3154,9 +3139,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.63.0.tgz", - "integrity": "sha512-xyLtl9DUBBFrcJS4x2pIqGLH68/tC2uOa4Z7pUteW09D3bXnnXUom4dyPikzWgB7llmIc1zoeI3aoUdC4rPK/Q==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.73.0.tgz", + "integrity": "sha512-O/1ytYzflF16QDKXx4/qOXg1IuZp+n7hr9t+S0nv7N/2Tl8rJiNCshztV1gcSUvHbPtoX3+zmNbtSAyVbzxVfw==", "dev": true, "license": "MIT", "engines": { @@ -3168,18 +3153,18 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.63.0.tgz", - "integrity": "sha512-ygBkU+B7ex5UI/gKhaqexWev79uISfIv7XQCRNYO/jmD8rGLPyWLAb3KMRT6nd8Gt9bmUBi9+iX6tBdYfOY81Q==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.73.0.tgz", + "integrity": "sha512-InjlBkSdWceIwIBWSwS3ENUp+i0O02PGX3Zv2wnihWJC1WDVGvG7mTHuf8b57uAaITj94d6tRPDH+sUEtXdRQQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.63.0", - "@typescript-eslint/tsconfig-utils": "8.63.0", - "@typescript-eslint/types": "8.63.0", - "@typescript-eslint/visitor-keys": "8.63.0", + "@typescript-eslint/project-service": "8.73.0", + "@typescript-eslint/tsconfig-utils": "8.73.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0", "debug": "^4.4.3", - "minimatch": "^10.2.2", + "minimatch": "^11.0.1", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" @@ -3192,20 +3177,26 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { + "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev", "typescript": ">=4.8.4 <6.1.0" + }, + "peerDependenciesMeta": { + "@typescript/native": { + "optional": true + } } }, "node_modules/@typescript-eslint/utils": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.63.0.tgz", - "integrity": "sha512-fUKaeAvrTuQg/Tgt3nliAUSZHJM6DlCcfyEmxCvlX8kieWSStBX+5O5Fnidtc3i2JrH+9c/GL4RY2iasd/GPTA==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.73.0.tgz", + "integrity": "sha512-j2SVJJvVkXdUL0WcEzo4vEH1mO1vIi8KlVukcYA2MgMZvYN2LlZR4PmsW+GTSxSW24j6Q/EP7+MOifLtg5hmsA==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.63.0", - "@typescript-eslint/types": "8.63.0", - "@typescript-eslint/typescript-estree": "8.63.0" + "@typescript-eslint/scope-manager": "8.73.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -3220,13 +3211,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.63.0.tgz", - "integrity": "sha512-UexrHGnGTpbuQHct2ExOc2ZcFbGUS9FOesCxxqdBGcpI1BxYu/LZ6U8Aq6/72XtF/qRBk9nhuGHFJIXXMhPMdw==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.73.0.tgz", + "integrity": "sha512-k4lsFVpRZICbltkIEEH4hZRkwXkqDF1GHBpClKQOHQY+RkoZAAuyc1ci3I6p+CB6v3U4jaHIUshc4RzzQXZWLg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.63.0", + "@typescript-eslint/types": "8.73.0", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -4688,17 +4679,6 @@ "qified": "^0.10.1" } }, - "node_modules/cacheable/node_modules/keyv": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", - "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@keyv/serialize": "^1.1.1" - } - }, "node_modules/call-bind": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", @@ -4959,9 +4939,9 @@ "license": "MIT" }, "node_modules/colord": { - "version": "2.9.3", - "resolved": "https://registry.npmjs.org/colord/-/colord-2.9.3.tgz", - "integrity": "sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw==", + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/colord/-/colord-2.14.0.tgz", + "integrity": "sha512-eSdMel9EBvdFxnchObp7gljRoqYQLr+zXhaxjkym7syVphw1FIhfQwgsA5Bv3jArflZPJEa1rmQtGpa7NRc7Rw==", "dev": true, "license": "MIT", "peer": true @@ -5116,14 +5096,20 @@ } }, "node_modules/create-ecdh": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.4.tgz", - "integrity": "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.5.tgz", + "integrity": "sha512-pZhCMTQKw9Stf8FZAFPYJIyUVmM+YIwxNmdrynOaD3h19YbH8GsFMkedPTfpHv6McKXFScfs0pdsfcgPVzO50A==", "dev": true, "license": "MIT", "dependencies": { - "bn.js": "^4.1.0", - "elliptic": "^6.5.3" + "bn.js": "^4.12.5", + "elliptic": "^6.6.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/create-ecdh/node_modules/bn.js": { @@ -5844,9 +5830,9 @@ } }, "node_modules/eslint": { - "version": "10.7.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.7.0.tgz", - "integrity": "sha512-GVTD7s1vdIl6UYvAfriOPeY1Df8LIZjfofLvHwde+erDHGGuHyuM6xoxRxmHiebhYuD2p1vN4wWh0XzPARSGDQ==", + "version": "10.15.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz", + "integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==", "dev": true, "license": "MIT", "peer": true, @@ -5856,11 +5842,11 @@ "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", - "@eslint/config-array": "^0.23.5", - "@eslint/config-helpers": "^0.6.0", + "@eslint/config-array": "^0.23.6", + "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", - "@eslint/plugin-kit": "^0.7.2", - "@humanfs/node": "^0.16.6", + "@eslint/plugin-kit": "^0.7.3", + "@humanfs/node": "^0.16.8", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", @@ -5874,14 +5860,14 @@ "esquery": "^1.7.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^8.0.0", + "file-entry-cache": "11.1.5 || >11.1.6 <12", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "minimatch": "^10.2.4", + "minimatch": "^11.0.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, @@ -6414,17 +6400,14 @@ } }, "node_modules/file-entry-cache": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", - "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "version": "11.1.5", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", + "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "flat-cache": "^4.0.0" - }, - "engines": { - "node": ">=16.0.0" + "flat-cache": "^6.1.23" } }, "node_modules/fill-range": { @@ -6459,24 +6442,22 @@ } }, "node_modules/flat-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", - "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "version": "6.1.23", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", + "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.4" - }, - "engines": { - "node": ">=16" + "cacheable": "^2.5.0", + "flatted": "^3.4.2", + "hookified": "^1.15.0" } }, "node_modules/flatted": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", - "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", "dev": true, "license": "ISC", "peer": true @@ -7640,14 +7621,6 @@ "node": ">=20.0.0" } }, - "node_modules/json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", @@ -7686,14 +7659,14 @@ } }, "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "json-buffer": "3.0.1" + "@keyv/serialize": "^1.1.1" } }, "node_modules/kind-of": { @@ -8969,16 +8942,17 @@ "license": "MIT" }, "node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^5.0.5" + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -9618,9 +9592,9 @@ "license": "MIT" }, "node_modules/pbkdf2": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.6.tgz", - "integrity": "sha512-BT6eelPB1EyGHo8pC0o9Bl6k6SYVhKO1jEbd3lcTrtr7XHdjP8BW1YpfCV3G9Kwkxgattk+S5q2/RvuttCsS1g==", + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.7.tgz", + "integrity": "sha512-nS4mvFgVwUrecPTRdpdseM2fwpdfnX0/HibA8DgBRQtihUAzHQYJFU2l+OlEtiXtpqkrMvCPDwyXMUnASDt6Qw==", "dev": true, "license": "MIT", "dependencies": { @@ -11360,30 +11334,6 @@ "stylelint": ">= 11 < 18" } }, - "node_modules/stylelint/node_modules/file-entry-cache": { - "version": "11.1.5", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", - "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "flat-cache": "^6.1.23" - } - }, - "node_modules/stylelint/node_modules/flat-cache": { - "version": "6.1.23", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", - "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "cacheable": "^2.5.0", - "flatted": "^3.4.2", - "hookified": "^1.15.0" - } - }, "node_modules/stylelint/node_modules/ignore": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.6.tgz", @@ -11832,16 +11782,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.63.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.63.0.tgz", - "integrity": "sha512-xgwXyzG4sK9ALkBxbyGkTMMOS+imnW65iPhxCQMK83KhxyoDNW7l+IDqEf9vMdoUidHpOoS967RCq4eMiTexwQ==", + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.73.0.tgz", + "integrity": "sha512-+EnKy9rkYPun4l+kG2bDuYWQ6y1tGVgdR/tY1U9AC6h21CjEwOoc7gsjwe0FXB8uWFzk4QiCFbuRWgX758PiAg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.63.0", - "@typescript-eslint/parser": "8.63.0", - "@typescript-eslint/typescript-estree": "8.63.0", - "@typescript-eslint/utils": "8.63.0" + "@typescript-eslint/eslint-plugin": "8.73.0", + "@typescript-eslint/parser": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0", + "@typescript-eslint/utils": "8.73.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" diff --git a/src/actions/extract-action.ts b/src/actions/extract-action.ts index f2c05651..3de08eb9 100644 --- a/src/actions/extract-action.ts +++ b/src/actions/extract-action.ts @@ -8,7 +8,7 @@ import type { ActionContext, ActionContextSingle, IFileAction, IFolder, INode } import ArchiveArrowUpSvg from '@mdi/svg/svg/archive-arrow-up.svg?raw' import axios from '@nextcloud/axios' import { emit } from '@nextcloud/event-bus' -import { Folder, Permission, registerFileAction } from '@nextcloud/files' +import { FileType, Folder, Permission, registerFileAction } from '@nextcloud/files' import { translate as t } from '@nextcloud/l10n' import { generateOcsUrl } from '@nextcloud/router' import { createApp } from 'vue' @@ -32,6 +32,11 @@ export const SUPPORTED_ARCHIVE_MIME_TYPES = [ 'application/x-bzip2', 'application/x-deb', 'application/x-compressed', + 'application/x-xz', + 'application/x-xz-compressed-tar', + 'application/zstd', + 'application/x-zstd', + 'application/x-zstd-compressed-tar', ] interface ExtractedFolder { @@ -75,7 +80,22 @@ function archiveMimeOf(node: INode): string | undefined { if (mime !== '' && mime !== 'application/octet-stream') { return mime } - return node.attributes?.getcontenttype as string | undefined + const davMime = node.attributes?.getcontenttype as string | undefined + if (davMime && davMime !== 'application/octet-stream') { + return davMime + } + + // Nextcloud 33–35 may classify XZ archives as octet-stream, leaving the + // Files action hidden despite a working server decoder. Infer only these + // known extensions when both reported MIME values are unspecified. + const fileName = node.basename.toLowerCase() + if (fileName.endsWith('.tar.xz') || fileName.endsWith('.txz') || fileName.endsWith('.xz')) { + return 'application/x-xz' + } + if (fileName.endsWith('.zst') || fileName.endsWith('.zstd') || fileName.endsWith('.tzst')) { + return 'application/zstd' + } + return undefined } /** @@ -200,6 +220,7 @@ function isEnabled(context: ActionContext): boolean { const [node] = context.nodes return node !== undefined + && node.type === FileType.File && isSupportedArchive(node) && (node.permissions & Permission.READ) !== 0 && (context.folder.permissions & Permission.CREATE) !== 0 diff --git a/tests/Fixtures/valid.tar.xz b/tests/Fixtures/valid.tar.xz new file mode 100644 index 00000000..774f5091 Binary files /dev/null and b/tests/Fixtures/valid.tar.xz differ diff --git a/tests/Fixtures/valid.tar.zst b/tests/Fixtures/valid.tar.zst new file mode 100644 index 00000000..9717bf59 Binary files /dev/null and b/tests/Fixtures/valid.tar.zst differ diff --git a/tests/Fixtures/valid.zst b/tests/Fixtures/valid.zst new file mode 100644 index 00000000..5b65ebc9 Binary files /dev/null and b/tests/Fixtures/valid.zst differ diff --git a/tests/playwright/e2e/extract.spec.ts b/tests/playwright/e2e/extract.spec.ts index 24accbec..902ed126 100644 --- a/tests/playwright/e2e/extract.spec.ts +++ b/tests/playwright/e2e/extract.spec.ts @@ -5,9 +5,10 @@ import type { APIRequestContext } from '@playwright/test' -import { expect, test } from '@playwright/test' +import { request as apiRequest, expect, test } from '@playwright/test' import { Buffer } from 'node:buffer' -import { randomUUID } from 'node:crypto' +import { createHash, randomUUID } from 'node:crypto' +import { readFile } from 'node:fs/promises' const user = process.env.NC_ADMIN_USER ?? 'e2e' const password = process.env.NEXTCLOUD_ADMIN_PASSWORD @@ -16,6 +17,49 @@ if (!password) { } const authorization = 'Basic ' + Buffer.from(user + ':' + password).toString('base64') const fixture = Buffer.from('UEsDBBQAAAAIAK1mdV2a8R5qHQAAABsAAAAJAAAAaGVsbG8udHh0c60oKUpMLlFIKsovL04tUnA1clUoSCwuTk3hAgBQSwECFAMUAAAACACtZnVdmvEeah0AAAAbAAAACQAAAAAAAAAAAAAAgAEAAAAAaGVsbG8udHh0UEsFBgAAAAABAAEANwAAAEQAAAAAAA==', 'base64') +/** + * Construct a valid single-file, STORE-method ZIP using only Node built-ins. + * This provides a deterministic, moderately large integration fixture without + * adding a dependency, an external archive builder or a committed large file. + */ +function storedZip(name: string, contents: Buffer): Buffer { + const bytes = Buffer.from(name, 'utf8') + let crc = 0xFFFFFFFF + for (const byte of contents) { + crc ^= byte + for (let bit = 0; bit < 8; bit++) { + crc = (crc >>> 1) ^ (crc & 1 ? 0xEDB88320 : 0) + } + } + crc = (crc ^ 0xFFFFFFFF) >>> 0 + + const local = Buffer.alloc(30) + local.writeUInt32LE(0x04034B50, 0) + local.writeUInt16LE(20, 4) + local.writeUInt32LE(crc, 14) + local.writeUInt32LE(contents.length, 18) + local.writeUInt32LE(contents.length, 22) + local.writeUInt16LE(bytes.length, 26) + + const central = Buffer.alloc(46) + central.writeUInt32LE(0x02014B50, 0) + central.writeUInt16LE(20, 4) + central.writeUInt16LE(20, 6) + central.writeUInt32LE(crc, 16) + central.writeUInt32LE(contents.length, 20) + central.writeUInt32LE(contents.length, 24) + central.writeUInt16LE(bytes.length, 28) + + const end = Buffer.alloc(22) + end.writeUInt32LE(0x06054B50, 0) + end.writeUInt16LE(1, 8) + end.writeUInt16LE(1, 10) + end.writeUInt32LE(central.length + bytes.length, 12) + end.writeUInt32LE(local.length + bytes.length + contents.length, 16) + + return Buffer.concat([local, bytes, contents, central, bytes, end]) +} + const apiHeaders = { Authorization: authorization, 'OCS-APIRequest': 'true', @@ -24,8 +68,12 @@ const apiHeaders = { const extractEndpoint = '/ocs/v2.php/apps/extract/api/v1/extraction/execute?format=json' /** DAV operations run only against the disposable user configured for CI. */ +function davFor(username: string, path: string): string { + return '/remote.php/dav/files/' + encodeURIComponent(username) + '/' + path.split('/').map(encodeURIComponent).join('/') +} + function dav(path: string): string { - return '/remote.php/dav/files/' + encodeURIComponent(user) + '/' + path.split('/').map(encodeURIComponent).join('/') + return davFor(user, path) } /** Upload a small synthetic ZIP into the disposable Nextcloud installation. */ @@ -71,6 +119,48 @@ test('OCS extracts a ZIP to the chosen destination on Nextcloud Files', async ({ } }) +/** + * Regression coverage for large-file extraction, avoiding a tiny fixture as + * the sole evidence that streamed Nextcloud imports preserve full contents. + */ +test('OCS preserves a 16 MiB file extracted from a ZIP', async ({ request }) => { + const name = 'extract-sized-' + randomUUID().slice(0, 8) + '.zip' + const destination = 'extract-sized-' + randomUUID().slice(0, 8) + const expected = Buffer.alloc(16 * 1024 * 1024, 0x42) + try { + const uploaded = await request.put(dav(name), { + headers: { Authorization: authorization, 'Content-Type': 'application/zip' }, + data: storedZip('medium.bin', expected), + }) + expect(uploaded.status()).toBe(201) + const response = await request.post(extractEndpoint, { + headers: apiHeaders, + data: { + nameOfFile: name, + directory: '/', + external: false, + mime: 'application/zip', + targetDirName: destination, + }, + }) + expect(response.ok()).toBeTruthy() + const result = await response.json() + expect(result.ocs.data.code).toBe(1) + const extracted = await request.get(dav(destination + '/medium.bin'), { + headers: { Authorization: authorization }, + }) + expect(extracted.status()).toBe(200) + const actual = await extracted.body() + expect(actual.length).toBe(expected.length) + const actualHash = createHash('sha256').update(actual).digest('hex') + const expectedHash = createHash('sha256').update(expected).digest('hex') + expect(actualHash).toBe(expectedHash) + } finally { + await deleteFile(request, name) + await deleteFile(request, destination) + } +}) + test('OCS rejects destination traversal before writing any files', async ({ request }) => { const file = await uploadArchive(request) try { @@ -164,3 +254,230 @@ test('Files action validates, cancels and confirms extraction destinations', asy await deleteFile(request, dir) } }) + +/** + * Integration coverage for the 7za path, which the default Nextcloud image + * cannot exercise unless the binary is installed in its disposable container. + */ +test('OCS extracts a real 7z archive on Nextcloud', async ({ request }) => { + const name = 'extract-e2e-' + randomUUID().slice(0, 8) + '.7z' + const destination = 'extract-7z-' + randomUUID().slice(0, 8) + const archive = await readFile(new URL('../../Fixtures/valid.7z', import.meta.url)) + try { + const uploaded = await request.put(dav(name), { + headers: { Authorization: authorization, 'Content-Type': 'application/x-7z-compressed' }, + data: archive, + }) + expect(uploaded.status()).toBe(201) + const response = await request.post(extractEndpoint, { + headers: apiHeaders, + data: { + nameOfFile: name, + directory: '/', + external: false, + mime: 'application/x-7z-compressed', + targetDirName: destination, + }, + }) + expect(response.ok()).toBeTruthy() + const result = await response.json() + expect(result.ocs.data.code).toBe(1) + const extracted = await request.get(dav(destination + '/hello.txt'), { + headers: { Authorization: authorization }, + }) + expect(extracted.status()).toBe(200) + expect(await extracted.text()).toBe('hello world\n') + } finally { + await deleteFile(request, name) + await deleteFile(request, destination) + } +}) + +/** + * Exercise the MIME-to-decoder contract with real XZ/Zstandard archives. + * The original archive and destination are always disposable CI fixtures. + */ +for (const entry of [ + { fixtureName: 'valid.tar.xz', extension: '.tar.xz', mime: 'application/x-xz', resultName: 'hello.txt' }, + { fixtureName: 'valid.zst', extension: '.zst', mime: 'application/zstd', resultName: '' }, + { fixtureName: 'valid.tar.zst', extension: '.tar.zst', mime: 'application/zstd', resultName: 'hello.txt' }, +]) { + test(`OCS extracts ${entry.extension} with supervised decoder`, async ({ request }) => { + const stem = 'extract-format-' + randomUUID().slice(0, 8) + const file = stem + entry.extension + const destination = stem + '-out' + const archive = await readFile(new URL('../../Fixtures/' + entry.fixtureName, import.meta.url)) + try { + const uploaded = await request.put(dav(file), { + headers: { Authorization: authorization, 'Content-Type': entry.mime }, + data: archive, + }) + expect(uploaded.status()).toBe(201) + const response = await request.post(extractEndpoint, { + headers: apiHeaders, + data: { + nameOfFile: file, + directory: '/', + external: false, + mime: entry.mime, + targetDirName: destination, + }, + }) + expect(response.ok()).toBeTruthy() + const result = await response.json() + expect(result.ocs.data.code).toBe(1) + const extracted = await request.get(dav(destination + '/' + (entry.resultName || stem)), { + headers: { Authorization: authorization }, + }) + expect(extracted.status()).toBe(200) + expect(await extracted.text()).toBe('hello world\n') + } finally { + await deleteFile(request, file) + await deleteFile(request, destination) + } + }) +} + +/** + * Regression for XZ/Zstandard action visibility. A passing OCS request alone + * does not prove the Files menu recognises the MIME returned by Nextcloud. + */ +test('Files displays the Extract action for XZ and Zstandard archives', async ({ request, page }) => { + const dir = 'extract-formats-menu-' + randomUUID().slice(0, 8) + const created = await request.fetch(dav(dir), { method: 'MKCOL', headers: { Authorization: authorization } }) + expect(created.status()).toBe(201) + const formats = [ + { file: 'archive.tar.xz', mime: 'application/x-xz', fixtureName: 'valid.tar.xz' }, + { file: 'archive.zst', mime: 'application/zstd', fixtureName: 'valid.zst' }, + ] + try { + for (const format of formats) { + const archive = await readFile(new URL('../../Fixtures/' + format.fixtureName, import.meta.url)) + const uploaded = await request.put(dav(dir + '/' + format.file), { + headers: { Authorization: authorization, 'Content-Type': format.mime }, + data: archive, + }) + expect(uploaded.status()).toBe(201) + } + await page.goto('/login') + await page.locator('#user').fill(user) + await page.locator('#password').fill(password) + await page.locator('button[type=submit]').click() + await expect(page.getByRole('button', { name: 'Settings menu' })).toBeVisible({ timeout: 30_000 }) + await page.goto('/apps/files/files?dir=' + encodeURIComponent('/' + dir)) + const onboarding = page.getByRole('dialog').filter({ has: page.getByRole('button', { name: "What's new?" }) }) + if (await onboarding.isVisible()) { + await onboarding.getByRole('button', { name: 'Close' }).click() + } + for (const format of formats) { + const row = page.locator('[data-cy-files-list-row-name="' + format.file + '"]') + await expect(row).toBeVisible({ timeout: 30_000 }) + await row.getByRole('button', { name: 'Actions' }).click() + await page.getByRole('menuitem', { name: /Extract/i }).click() + const dialog = page.getByRole('dialog', { name: 'Extract archive' }) + await expect(dialog).toBeVisible() + await dialog.getByRole('button', { name: 'Cancel' }).click() + await expect(dialog).toBeHidden() + } + } finally { + await deleteFile(request, dir) + } +}) + +/** + * A recipient writing to a shared directory must extract into that recipient's + * own Files view, not into an invisible or owner-only folder. Create everything + * inside disposable CI Nextcloud; never touch real accounts or data. + */ +test('A share recipient can extract a ZIP to a writable shared folder', async ({ request }) => { + const recipient = 'extractci' + randomUUID().replaceAll('-', '').slice(0, 12) + const recipientPassword = 'ExtractCI!' + randomUUID().replaceAll('-', '') + const recipientAuthorization = 'Basic ' + Buffer.from(recipient + ':' + recipientPassword).toString('base64') + // Each user needs an independent cookie jar: Nextcloud creates sessions even + // when Basic authorization is sent on the original OCS request context. + const recipientRequest = await apiRequest.newContext({ + baseURL: process.env.PLAYWRIGHT_BASE_URL ?? 'http://127.0.0.1:18135', + extraHTTPHeaders: { Authorization: recipientAuthorization, 'OCS-APIRequest': 'true' }, + }) + const dir = 'extract-shared-' + randomUUID().slice(0, 8) + const archiveName = 'uploaded-by-recipient.zip' + let userCreated = false + let folderCreated = false + + try { + const newUser = await request.post('/ocs/v2.php/cloud/users?format=json', { + headers: apiHeaders, + form: { userid: recipient, password: recipientPassword }, + }) + userCreated = newUser.ok() + expect(newUser.ok()).toBeTruthy() + const newUserData = await newUser.json() + expect([100, 200]).toContain(newUserData.ocs.meta.statuscode) + + const created = await request.fetch(dav(dir), { + method: 'MKCOL', + headers: { Authorization: authorization }, + }) + folderCreated = created.status() === 201 + expect(folderCreated).toBeTruthy() + + const share = await request.post('/ocs/v2.php/apps/files_sharing/api/v1/shares?format=json', { + headers: apiHeaders, + form: { path: '/' + dir, shareType: '0', shareWith: recipient, permissions: '31' }, + }) + expect(share.ok()).toBeTruthy() + const shareData = await share.json() + expect([100, 200]).toContain(shareData.ocs.meta.statuscode) + + const uploaded = await recipientRequest.put(davFor(recipient, dir + '/' + archiveName), { + headers: { Authorization: recipientAuthorization, 'Content-Type': 'application/zip' }, + data: fixture, + }) + expect(uploaded.status()).toBe(201) + + // Positive control: the owner must see files uploaded through this share + // before testing whether the Extract import updates the owner's view. + const ownerArchive = await request.get(dav(dir + '/' + archiveName), { + headers: { Authorization: authorization }, + }) + expect(ownerArchive.status(), 'Owner should see an ordinary upload in the shared folder').toBe(200) + + const response = await recipientRequest.post(extractEndpoint, { + headers: { Accept: 'application/json' }, + data: { + nameOfFile: archiveName, + directory: '/' + dir, + external: false, + mime: 'application/zip', + targetDirName: 'recipient-extracted', + }, + }) + expect(response.ok()).toBeTruthy() + const result = await response.json() + expect(result.ocs.data.code).toBe(1) + + const contexts: Array<[string, APIRequestContext, string]> = [ + [recipient, recipientRequest, recipientAuthorization], + [user, request, authorization], + ] + for (const [account, context, auth] of contexts) { + const path = davFor(account, dir + '/recipient-extracted/hello.txt') + await expect.poll(async () => { + const file = await context.get(path, { headers: { Authorization: auth } }) + return file.status() + }, { timeout: 12_000, message: `Extracted file must be visible to ${account}` }).toBe(200) + const extracted = await context.get(path, { headers: { Authorization: auth } }) + expect(await extracted.text()).toBe('Extract browser E2E passed\n') + } + } finally { + await recipientRequest.dispose() + if (folderCreated) { + await deleteFile(request, dir) + } + if (userCreated) { + await request.delete('/ocs/v2.php/cloud/users/' + encodeURIComponent(recipient) + '?format=json', { + headers: apiHeaders, + }) + } + } +}) diff --git a/tests/unit/ArchiveSafetyValidatorTest.php b/tests/unit/ArchiveSafetyValidatorTest.php new file mode 100644 index 00000000..4c604589 --- /dev/null +++ b/tests/unit/ArchiveSafetyValidatorTest.php @@ -0,0 +1,46 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Tests\unit; + +use OCA\Extract\Service\ArchiveSafetyValidator; +use OCP\IL10N; +use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; + +final class ArchiveSafetyValidatorTest extends TestCase { + private ArchiveSafetyValidator $validator; + + protected function setUp(): void { + $l10n = $this->createStub(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $s): string => $s); + $this->validator = new ArchiveSafetyValidator($l10n, $this->createStub(LoggerInterface::class)); + } + + public function testRejectsTraversalAndAbsoluteNames(): void { + foreach (['../outside', 'a/../../outside', '/etc/passwd', 'C:\\\\Windows\\\\secret', 'some/..\\\\outside', "bad\0name"] as $name) { + self::assertSame(0, $this->validator->rejectUnsafe($name)['code'], $name); + } + } + + public function testAcceptsValidUnicodeAndNestedNames(): void { + foreach (['Café.txt', '한국어/전자책.txt', 'dir/sub/file.txt'] as $name) { + self::assertNull($this->validator->rejectUnsafe($name), $name); + } + } + + public function testRejectsActualLinksButNotEmptyLinkFields(): void { + foreach (['Symbolic Link = ../out', 'Hard Link = file', 'Attributes = A lrwxrwxrwx'] as $line) { + self::assertSame(0, $this->validator->rejectUnsafeMetadata($line)['code']); + } + foreach (['Symbolic Link = ', 'Hard Link = ', 'Attributes = RA', 'Attributes = A -rw-r--r--'] as $line) { + self::assertNull($this->validator->rejectUnsafeMetadata($line)); + } + } +} diff --git a/tests/unit/BoundedStreamCopierTest.php b/tests/unit/BoundedStreamCopierTest.php new file mode 100644 index 00000000..7d9d6aa8 --- /dev/null +++ b/tests/unit/BoundedStreamCopierTest.php @@ -0,0 +1,87 @@ +directory = sys_get_temp_dir() . '/extract-copy-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($this->directory, 0700)); + } + + protected function tearDown(): void { + foreach (glob($this->directory . '/*') ?: [] as $path) { + unlink($path); + } + rmdir($this->directory); + } + + private function stream(string $contents) { + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, $contents); + rewind($stream); + return $stream; + } + + public function testCopiesWithinBudgetAndVerifiesCrc(): void { + $stream = $this->stream('hello world'); + $written = 0; + try { + self::assertTrue((new BoundedStreamCopier())->copy($stream, $this->directory . '/good.txt', $written, 11, 11, hash('crc32b', 'hello world'))); + self::assertSame(11, $written); + self::assertSame('hello world', file_get_contents($this->directory . '/good.txt')); + } finally { + fclose($stream); + } + } + + public function testRejectsSizeOverflowAndWrongCrc(): void { + $stream = $this->stream('1234567890'); + $written = 0; + try { + self::assertFalse((new BoundedStreamCopier())->copy($stream, $this->directory . '/over.txt', $written, 9, 10, hash('crc32b', '1234567890'))); + self::assertSame(0, $written); + } finally { + fclose($stream); + } + $stream = $this->stream('hello'); + try { + self::assertFalse((new BoundedStreamCopier())->copy($stream, $this->directory . '/crc.txt', $written, 10, 5, 'deadbeef')); + } finally { + fclose($stream); + } + } + + public function testDoesNotOverwriteRarDestination(): void { + file_put_contents($this->directory . '/exists.txt', 'original'); + $stream = $this->stream('new'); + $written = 0; + try { + self::assertFalse((new BoundedStreamCopier())->copy($stream, $this->directory . '/exists.txt', $written, 100, 3, hash('crc32b', 'new'))); + self::assertSame('original', file_get_contents($this->directory . '/exists.txt')); + } finally { + fclose($stream); + } + } + + public function testCopyWithoutDeclaredSizeUsesZipSemantics(): void { + $stream = $this->stream('payload'); + $written = 0; + try { + self::assertTrue((new BoundedStreamCopier())->copy($stream, $this->directory . '/zip.txt', $written, 7)); + self::assertSame('payload', file_get_contents($this->directory . '/zip.txt')); + } finally { + fclose($stream); + } + } +} diff --git a/tests/unit/CapabilitiesTest.php b/tests/unit/CapabilitiesTest.php index 39ca09a2..596574e7 100644 --- a/tests/unit/CapabilitiesTest.php +++ b/tests/unit/CapabilitiesTest.php @@ -56,6 +56,8 @@ public function testGetCapabilitiesListsEverySupportedArchiveFeature(): void { self::assertContains('extract-zip', $capabilities['extract']['features']); self::assertContains('extract-rar', $capabilities['extract']['features']); self::assertContains('extract-7z', $capabilities['extract']['features']); + self::assertContains('extract-zstd', $capabilities['extract']['features']); + self::assertContains('extract-tar-zstd', $capabilities['extract']['features']); } /** diff --git a/tests/unit/ExtractionControllerTest.php b/tests/unit/ExtractionControllerTest.php index c1abe022..d9d29157 100644 --- a/tests/unit/ExtractionControllerTest.php +++ b/tests/unit/ExtractionControllerTest.php @@ -43,6 +43,9 @@ public function testEverySupportedExtensionHasAMimeType(): void { 'application/x-bzip2', // .bz2 and .tbz2 'application/x-7z-compressed', // .7z 'application/x-deb', // .deb + 'application/x-xz', // .xz and .tar.xz on some servers + 'application/x-xz-compressed-tar', // .tar.xz + 'application/zstd', // .zst and .tar.zst ]; foreach ($nextcloudArchiveMimeTypes as $mime) { @@ -69,6 +72,8 @@ public function testGzipUsesTheGenericStrategy(): void { public function testZipAndRarUseTheirDedicatedStrategies(): void { self::assertSame('zip', ExtractionController::SUPPORTED_MIME_TYPES['application/zip']); self::assertSame('rar', ExtractionController::SUPPORTED_MIME_TYPES['application/x-rar-compressed']); + self::assertSame('other', ExtractionController::SUPPORTED_MIME_TYPES['application/x-xz-compressed-tar']); + self::assertSame('zstd', ExtractionController::SUPPORTED_MIME_TYPES['application/zstd']); } /** @@ -76,7 +81,7 @@ public function testZipAndRarUseTheirDedicatedStrategies(): void { */ public function testEveryStrategyIsKnown(): void { foreach (ExtractionController::SUPPORTED_MIME_TYPES as $mime => $strategy) { - self::assertContains($strategy, ['zip', 'rar', 'other'], "$mime maps to unknown strategy $strategy"); + self::assertContains($strategy, ['zip', 'rar', 'other', 'zstd'], "$mime maps to unknown strategy $strategy"); } } @@ -94,6 +99,9 @@ public function testWrappedTarballsAreRecognised(): void { 'archive.tar.gz', 'archive.tar.bz2', 'archive.tar.xz', + 'archive.tar.zst', + 'archive.tar.zstd', + 'archive.tzst', 'archive.tgz', 'archive.tbz', 'archive.tbz2', @@ -111,7 +119,7 @@ public function testWrappedTarballsAreRecognised(): void { public function testPlainArchivesAreNotWrappedTarballs(): void { $method = new \ReflectionMethod(ExtractionController::class, 'isWrappedTarball'); - $plain = ['archive.tar', 'archive.zip', 'archive.7z', 'archive.rar', 'archive.deb', 'archive.gz']; + $plain = ['archive.tar', 'archive.zip', 'archive.7z', 'archive.rar', 'archive.deb', 'archive.gz', 'archive.zst']; foreach ($plain as $name) { self::assertFalse($method->invoke(null, $name), "$name should take the single-pass path"); } @@ -128,6 +136,11 @@ public function testResultFolderNameDropsBothSuffixes(): void { 'archive.tar.gz' => 'archive', 'archive.tgz' => 'archive', 'archive.tar.bz2' => 'archive', + 'archive.tar.xz' => 'archive', + 'archive.tar.zst' => 'archive', + 'archive.tar.zstd' => 'archive', + 'archive.tzst' => 'archive', + 'archive.zst' => 'archive', 'archive.tbz2' => 'archive', 'archive.tar' => 'archive', 'my.data.tar.gz' => 'my.data', @@ -148,7 +161,7 @@ public function testDegenerateArchiveNamesAreRejected(): void { $name = new \ReflectionMethod(ExtractionController::class, 'resultFolderName'); $usable = new \ReflectionMethod(ExtractionController::class, 'isUsableFolderName'); - foreach (['.tar.gz', '.tar', '.tbz2', '.gz', '..tar.gz', '...tar.gz', '..', '.'] as $fileName) { + foreach (['.tar.gz', '.tar.zst', '.tar', '.tbz2', '.gz', '..tar.gz', '...tar.gz', '..', '.'] as $fileName) { self::assertFalse( $usable->invoke(null, $name->invoke(null, $fileName)), "$fileName must not be accepted as a result folder", @@ -205,7 +218,7 @@ function () use ($scratch): string { // A real service instance. The archive path does not exist, so extractZip() // reports "Cannot open Zip file" — reaching it proves the non-local storage // no longer refuses the request. - $service = new ExtractionService($l10n, $this->createStub(LoggerInterface::class)); + $service = new ExtractionService($l10n, $this->createStub(LoggerInterface::class), $this->createStub(\OCP\IConfig::class)); $controller = new ExtractionController( 'extract', @@ -271,7 +284,7 @@ static function () use ($scratch): string { // A real service instance. The archive path does not exist, so // extractZip() reports "Cannot open Zip file" — reaching it proves the // local-storage path let the request through. - $service = new ExtractionService($l10n, $this->createStub(LoggerInterface::class)); + $service = new ExtractionService($l10n, $this->createStub(LoggerInterface::class), $this->createStub(\OCP\IConfig::class)); $controller = new ExtractionController( 'extract', @@ -317,7 +330,7 @@ public function testExecuteRejectsReadOnlyDestination(): void { $controller = new ExtractionController( 'extract', $this->createStub(IRequest::class), - new ExtractionService($l10n, $this->createStub(LoggerInterface::class)), + new ExtractionService($l10n, $this->createStub(LoggerInterface::class), $this->createStub(\OCP\IConfig::class)), $rootFolder, $l10n, $this->createStub(LoggerInterface::class), @@ -464,12 +477,10 @@ function (string $path, $content) use (&$created) { } /** - * Forbidden file names are removed before the tree is published. - * - * The walk must skip the `.` and `..` entries: the filename validator rejects - * them, and the removal then fails because unlink() cannot remove a directory. + * Invalid names cause a failure before publication; valid extracted data + * must not be discarded to make an incomplete extraction appear successful. */ - public function testRemoveForbiddenFilesSkipsDotEntries(): void { + public function testInvalidNamesAreRejectedWithoutSilentlyDroppingFiles(): void { $source = sys_get_temp_dir() . '/extract-forbidden-' . bin2hex(random_bytes(6)); mkdir($source . '/sub', 0700, true); file_put_contents($source . '/keep.txt', 'keep'); @@ -478,25 +489,48 @@ public function testRemoveForbiddenFilesSkipsDotEntries(): void { $validator = $this->createStub(IFilenameValidator::class); $validator->method('isFilenameValid')->willReturnCallback( - // The real validator rejects `.` and `..` as dot directories, so the - // stub must too, otherwise it would hide a walk that visits them. static fn (string $name): bool => $name !== '.htaccess' && $name !== '.' && $name !== '..', ); - $reflection = new \ReflectionClass(ExtractionController::class); - $controller = $reflection->newInstanceWithoutConstructor(); + $controller = (new \ReflectionClass(ExtractionController::class))->newInstanceWithoutConstructor(); $this->setProperty($controller, 'filenameValidator', $validator); - $this->setProperty($controller, 'logger', $this->createStub(LoggerInterface::class)); - - $method = new \ReflectionMethod(ExtractionController::class, 'removeForbiddenFiles'); + $check = new \ReflectionMethod(ExtractionController::class, 'assertValidExtractedNames'); try { - $method->invoke($controller, $source); - + try { + $check->invoke($controller, $source); + self::fail('Invalid extracted names must abort the operation'); + } catch (NotPermittedException $e) { + self::assertSame('Archive contains filenames that Nextcloud cannot store', $e->getMessage()); + } self::assertFileExists($source . '/keep.txt'); - self::assertFileDoesNotExist($source . '/.htaccess'); - self::assertFileDoesNotExist($source . '/sub/.htaccess'); - self::assertDirectoryExists($source . '/sub'); + self::assertFileExists($source . '/.htaccess'); + self::assertFileExists($source . '/sub/.htaccess'); + } finally { + $this->removeDirectory($source); + } + } + + /** + * Valid names in accented, Korean and Chinese scripts must not be rejected. + */ + public function testValidUnicodeNamesArePreserved(): void { + $source = sys_get_temp_dir() . '/extract-unicode-' . bin2hex(random_bytes(6)); + mkdir($source . '/한국어', 0700, true); + file_put_contents($source . '/Café.txt', 'cafe'); + file_put_contents($source . '/한국어/전자책.txt', 'book'); + file_put_contents($source . '/中文.txt', 'chinese'); + + $validator = $this->createStub(IFilenameValidator::class); + $validator->method('isFilenameValid')->willReturn(true); + $controller = (new \ReflectionClass(ExtractionController::class))->newInstanceWithoutConstructor(); + $this->setProperty($controller, 'filenameValidator', $validator); + + try { + (new \ReflectionMethod(ExtractionController::class, 'assertValidExtractedNames'))->invoke($controller, $source); + self::assertFileExists($source . '/Café.txt'); + self::assertFileExists($source . '/한국어/전자책.txt'); + self::assertFileExists($source . '/中文.txt'); } finally { $this->removeDirectory($source); } diff --git a/tests/unit/ExtractionDestinationTest.php b/tests/unit/ExtractionDestinationTest.php index f51fc29d..d74e1e9c 100644 --- a/tests/unit/ExtractionDestinationTest.php +++ b/tests/unit/ExtractionDestinationTest.php @@ -183,6 +183,7 @@ function (string $name, $stream) use (&$written) { $year->expects(self::once())->method('newFolder')->with('Q4 #2026')->willReturn($destination); $folder = $this->createMock(Folder::class); $folder->method('isCreatable')->willReturn(true); + $folder->method('getFreeSpace')->willReturn(-2); $folder->method('nodeExists')->willReturn(false); $folder->expects(self::once())->method('newFolder')->with('reports')->willReturn($year); $folder->method('get')->willReturnCallback( @@ -217,7 +218,7 @@ static function () use ($scratch): string { $controller = new ExtractionController( 'extract', $this->createStub(IRequest::class), - new ExtractionService($l10n, $logger), + new ExtractionService($l10n, $logger, $this->createStub(\OCP\IConfig::class)), $root, $l10n, $logger, @@ -279,7 +280,7 @@ private function controller(Folder $folder, ITempManager $temp, ?IFilenameValida return new ExtractionController( 'extract', $this->createStub(IRequest::class), - new ExtractionService($l10n, $logger), + new ExtractionService($l10n, $logger, $this->createStub(\OCP\IConfig::class)), $root, $l10n, $logger, diff --git a/tests/unit/ExtractionLimitsTest.php b/tests/unit/ExtractionLimitsTest.php new file mode 100644 index 00000000..fb8d7a53 --- /dev/null +++ b/tests/unit/ExtractionLimitsTest.php @@ -0,0 +1,31 @@ + + * SPDX-FileCopyrightText: 2022 Claus-Justus Heine + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Extract\Tests\unit; + +use OCA\Extract\Service\ExtractionLimits; +use OCP\IConfig; +use PHPUnit\Framework\TestCase; + +final class ExtractionLimitsTest extends TestCase { + public function testInvalidLimitsFallBackToSafeDefaults(): void { + $config = $this->createStub(IConfig::class); + $config->method('getAppValue')->willReturnCallback(static fn (string $app, string $key, string $default): string => 'not-an-int'); + $limits = new ExtractionLimits($config); + self::assertSame(10000, $limits->entryLimit()); + self::assertSame(300, $limits->timeout()); + } + + public function testQuotaCanOnlyReduceTheBudget(): void { + $config = $this->createStub(IConfig::class); + $config->method('getAppValue')->willReturnCallback(static fn (string $app, string $key, string $default): string => $default); + $limits = new ExtractionLimits($config); + self::assertSame(15, $limits->byteBudget(sys_get_temp_dir() . '/extract-limits-destination', 15)); + } +} diff --git a/tests/unit/ExtractionPathSafetyTest.php b/tests/unit/ExtractionPathSafetyTest.php index 94e10538..ffe96a87 100644 --- a/tests/unit/ExtractionPathSafetyTest.php +++ b/tests/unit/ExtractionPathSafetyTest.php @@ -9,6 +9,7 @@ namespace OCA\Extract\Tests\unit; +use OCA\Extract\Service\ArchiveSafetyValidator; use OCA\Extract\Service\ExtractionService; use OCP\IL10N; use PHPUnit\Framework\TestCase; @@ -19,18 +20,19 @@ final class ExtractionPathSafetyTest extends TestCase { private function service(): ExtractionService { $l10n = $this->createStub(IL10N::class); $l10n->method('t')->willReturnCallback(static fn (string $s): string => $s); - return new ExtractionService($l10n, $this->createStub(LoggerInterface::class)); + return new ExtractionService($l10n, $this->createStub(LoggerInterface::class), $this->createStub(\OCP\IConfig::class)); } public function testUnsafeArchiveEntryNamesAreRejected(): void { - $method = new \ReflectionMethod(ExtractionService::class, 'isUnsafePath'); - $service = $this->service(); + $l10n = $this->createStub(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $s): string => $s); + $validator = new ArchiveSafetyValidator($l10n, $this->createStub(LoggerInterface::class)); foreach (['../escape.txt', 'a/../../escape.txt', '..\\escape.txt', '/etc/passwd', '\\\\server\\share', 'C:\\outside.txt', 'C:relative.txt', "a\x00b"] as $entry) { - self::assertTrue($method->invoke($service, $entry), 'Unsafe path accepted: ' . bin2hex($entry)); + self::assertSame(0, $validator->rejectUnsafe($entry)['code'], 'Unsafe path accepted: ' . bin2hex($entry)); } foreach (['safe.txt', 'nested/file.txt', 'nested\\file.txt', 'a/..name.txt', './inside.txt'] as $entry) { - self::assertFalse($method->invoke($service, $entry), 'Safe path rejected: ' . $entry); + self::assertNull($validator->rejectUnsafe($entry), 'Safe path rejected: ' . $entry); } } diff --git a/tests/unit/ExtractionRollbackTest.php b/tests/unit/ExtractionRollbackTest.php new file mode 100644 index 00000000..10279878 --- /dev/null +++ b/tests/unit/ExtractionRollbackTest.php @@ -0,0 +1,93 @@ + [false], + 'existing legacy folder is never deleted' => [true], + ]; + } + + /** + * An interrupted import must not leave a partly created new destination, + * nor remove an existing folder that a legacy client was merging into. + */ + #[DataProvider('destinationCases')] + public function testImportFailureHandlesDestinationSafely(bool $alreadyExists): void { + $source = sys_get_temp_dir() . '/extract-rollback-' . bin2hex(random_bytes(6)); + self::assertTrue(mkdir($source, 0700)); + file_put_contents($source . '/one.txt', 'one'); + file_put_contents($source . '/two.txt', 'two'); + + $target = $this->createMock(Folder::class); + $target->method('isCreatable')->willReturn(true); + $target->expects($alreadyExists ? self::never() : self::once())->method('delete'); + $calls = 0; + $target->expects(self::exactly(2))->method('newFile')->willReturnCallback( + function (string $relative, $stream) use (&$calls): File { + self::assertIsResource($stream); + $calls++; + if ($calls === 2) { + throw new NotPermittedException('simulated quota or storage failure'); + } + return $this->createStub(File::class); + }, + ); + + $parent = $this->createMock(Folder::class); + $parent->method('isCreatable')->willReturn(true); + $parent->expects(self::exactly(2))->method('nodeExists')->with('result')->willReturn($alreadyExists); + if ($alreadyExists) { + $parent->expects(self::once())->method('get')->with('result')->willReturn($target); + } else { + $parent->expects(self::once())->method('newFolder')->with('result')->willReturn($target); + } + + $userFolder = $this->createMock(Folder::class); + $userFolder->method('get')->with('/')->willReturn($parent); + $validator = $this->createStub(IFilenameValidator::class); + $validator->method('isFilenameValid')->willReturn(true); + $controller = (new \ReflectionClass(ExtractionController::class))->newInstanceWithoutConstructor(); + (new \ReflectionProperty(ExtractionController::class, 'filenameValidator'))->setValue($controller, $validator); + (new \ReflectionProperty(ExtractionController::class, 'userFolder'))->setValue($controller, $userFolder); + (new \ReflectionProperty(ExtractionController::class, 'logger'))->setValue($controller, $this->createStub(LoggerInterface::class)); + + try { + try { + (new \ReflectionMethod(ExtractionController::class, 'postExtract'))->invoke( + $controller, + 'result', + '/', + $source, + !$alreadyExists, + ); + self::fail('A partial import must not report success'); + } catch (NotPermittedException $e) { + self::assertSame('Could not complete extraction', $e->getMessage()); + } + self::assertSame(2, $calls); + } finally { + unlink($source . '/one.txt'); + unlink($source . '/two.txt'); + rmdir($source); + } + } +} diff --git a/tests/unit/ExtractionServiceTest.php b/tests/unit/ExtractionServiceTest.php index ab6d6b37..15316b10 100644 --- a/tests/unit/ExtractionServiceTest.php +++ b/tests/unit/ExtractionServiceTest.php @@ -41,7 +41,7 @@ protected function setUp(): void { ); $this->logger = $this->createStub(LoggerInterface::class); - $this->service = new ExtractionService($this->l10n, $this->logger); + $this->service = new ExtractionService($this->l10n, $this->logger, $this->createStub(\OCP\IConfig::class)); $this->tmpDir = sys_get_temp_dir() . '/extract-test-' . bin2hex(random_bytes(6)); if (mkdir($this->tmpDir, 0777, true) === false && is_dir($this->tmpDir) === false) { @@ -175,6 +175,195 @@ public function testExtractOtherExtractsAValidArchive(): void { self::assertSame("hello world\n", file_get_contents($destination . '/hello.txt')); } + /** + * The 7za listing must preflight the declared uncompressed size against + * the same Nextcloud destination quota used for ZIP. + */ + public function testRejects7zThatExceedsDestinationQuota(): void { + if (trim((string)shell_exec('command -v 7za 2>/dev/null')) === '') { + self::markTestSkipped('7za is not installed'); + } + $archive = __DIR__ . '/../Fixtures/valid.7z'; + $out = $this->tmpDir . '/out'; + + $response = $this->service->extractOther($archive, $out, 5); + + self::assertSame(0, $response['code']); + self::assertSame('Archive exceeds the allowed extraction size', $response['desc']); + self::assertDirectoryDoesNotExist($out); + } + + /** + * The regular-sized fixture must still extract when the available quota + * covers its declared uncompressed bytes. + */ + public function testExtracts7zWithinDestinationQuota(): void { + if (trim((string)shell_exec('command -v 7za 2>/dev/null')) === '') { + self::markTestSkipped('7za is not installed'); + } + $archive = __DIR__ . '/../Fixtures/valid.7z'; + $out = $this->tmpDir . '/out'; + + $response = $this->service->extractOther($archive, $out, 100); + + self::assertSame(['code' => 1], $response); + self::assertSame("hello world\n", file_get_contents($out . '/hello.txt')); + } + + /** + * TAR is handled by the external 7za decoder too: its declared size must + * be checked before any output is staged. A permitted quota is the + * positive control using the exact same synthetic archive. + */ + public function testTarArchiveRespectsDestinationQuota(): void { + if (trim((string)shell_exec('command -v 7za 2>/dev/null')) === '') { + self::markTestSkipped('7za is not installed'); + } + $archive = $this->tmpDir . '/quota.tar'; + $tar = new \PharData($archive); + $tar->addFromString('payload.txt', str_repeat('x', 256)); + unset($tar); + + $denied = $this->tmpDir . '/denied'; + $failure = $this->service->extractOther($archive, $denied, 64); + self::assertSame(0, $failure['code']); + self::assertSame('Archive exceeds the allowed extraction size', $failure['desc']); + self::assertDirectoryDoesNotExist($denied); + + $allowed = $this->tmpDir . '/allowed'; + self::assertSame(['code' => 1], $this->service->extractOther($archive, $allowed, 512)); + self::assertSame(str_repeat('x', 256), file_get_contents($allowed . '/payload.txt')); + } + + + + + + + + + /** + * A decompression bomb must be refused before staging any files when the + * total uncompressed content cannot fit the user's Nextcloud quota. + */ + public function testRejectsZipExceedingDestinationQuotaBeforeWriting(): void { + $archive = $this->tmpDir . '/too-large.zip'; + $this->createZip($archive, ['large.txt' => str_repeat('x', 100)]); + $out = $this->tmpDir . '/out'; + + $response = $this->service->extractZip($archive, $out, 50); + + self::assertSame(0, $response['code']); + self::assertSame('Archive exceeds the allowed extraction size', $response['desc']); + self::assertDirectoryDoesNotExist($out); + } + + /** + * A configurable entry count rejects an archive with excessive file-count + * amplification, without creating the output directory. + */ + public function testRejectsZipWithTooManyEntries(): void { + $archive = $this->tmpDir . '/too-many.zip'; + $this->createZip($archive, ['first.txt' => 'a', 'second.txt' => 'b']); + $config = $this->createStub(\OCP\IConfig::class); + $config->method('getAppValue')->willReturnCallback( + static fn (string $app, string $key, string $default): string => $key === 'max_archive_entries' ? '1' : $default, + ); + $service = new ExtractionService($this->l10n, $this->logger, $config); + $out = $this->tmpDir . '/out'; + + $response = $service->extractZip($archive, $out); + + self::assertSame(0, $response['code']); + self::assertSame('Archive contains too many files', $response['desc']); + self::assertDirectoryDoesNotExist($out); + } + + /** + * Bounded streaming still preserves UTF-8 paths, nested directories and + * archive contents for legitimate files. + */ + public function testStreamedZipPreservesUnicodeNames(): void { + $archive = $this->tmpDir . '/unicode.zip'; + $this->createZip($archive, [ + 'Café.txt' => 'cafe', + '한국어/전자책.txt' => 'korean', + '中文.txt' => 'chinese', + ]); + $out = $this->tmpDir . '/out'; + + $response = $this->service->extractZip($archive, $out); + + self::assertSame(['code' => 1], $response); + self::assertSame('cafe', file_get_contents($out . '/Café.txt')); + self::assertSame('korean', file_get_contents($out . '/한국어/전자책.txt')); + self::assertSame('chinese', file_get_contents($out . '/中文.txt')); + } + + /** + * Zstandard is decoded with the modern full 7z executable. The binary + * fixture avoids depending on zstd being installed for test generation. + */ + public function testExtractZstdDecodesAValidArchive(): void { + if (trim((string)shell_exec('command -v zstd 2>/dev/null || command -v 7z 2>/dev/null')) === '') { + self::markTestSkipped('Neither zstd nor full 7z is installed'); + } + $archive = __DIR__ . '/../Fixtures/valid.zst'; + $destination = $this->tmpDir . '/out'; + $response = $this->service->extractZstd($archive, $destination); + + self::assertSame(['code' => 1], $response); + self::assertSame("hello world\n", file_get_contents($destination . '/valid')); + } + + /** + * An external storage may hand the controller a temporary local file with + * no archive extension. The client-supplied original filename is the only + * source for the destination name, regardless of the temporary basename. + */ + public function testExtractZstdWithExtensionlessTemporaryArchive(): void { + if (trim((string)shell_exec('command -v zstd 2>/dev/null || command -v 7z 2>/dev/null')) === '') { + self::markTestSkipped('Neither zstd nor full 7z is installed'); + } + $temporarySource = $this->tmpDir . '/archive-copy-without-extension'; + self::assertTrue(copy(__DIR__ . '/../Fixtures/valid.zst', $temporarySource)); + $destination = $this->tmpDir . '/out'; + $response = $this->service->extractZstd($temporarySource, $destination, null, 'original-filename.zst'); + + self::assertSame(['code' => 1], $response); + self::assertSame("hello world\n", file_get_contents($destination . '/original-filename')); + } + + /** + * Zstandard does not expose a reliable expanded size in 7z listings. + * The staging supervisor must still reject bytes exceeding a tight quota. + */ + public function testExtractZstdRejectsExceededDestinationQuota(): void { + if (trim((string)shell_exec('command -v zstd 2>/dev/null || command -v 7z 2>/dev/null')) === '') { + self::markTestSkipped('Neither zstd nor full 7z is installed'); + } + $archive = __DIR__ . '/../Fixtures/valid.zst'; + $response = $this->service->extractZstd($archive, $this->tmpDir . '/out', 5); + + self::assertSame(0, $response['code']); + self::assertSame('Archive exceeds the allowed extraction size', $response['desc']); + } + + /** + * Do not report success for an arbitrary file masquerading as Zstandard. + */ + public function testExtractZstdRejectsCorruptInput(): void { + if (trim((string)shell_exec('command -v zstd 2>/dev/null || command -v 7z 2>/dev/null')) === '') { + self::markTestSkipped('Neither zstd nor full 7z is installed'); + } + $archive = $this->tmpDir . '/corrupt.zst'; + file_put_contents($archive, 'not zstandard'); + $response = $this->service->extractZstd($archive, $this->tmpDir . '/out'); + + self::assertSame(0, $response['code']); + self::assertArrayHasKey('desc', $response); + } + /** * A rar archive without rar support reports failure. */ diff --git a/tests/unit/RarFallbackTest.php b/tests/unit/RarFallbackTest.php new file mode 100644 index 00000000..a1210231 --- /dev/null +++ b/tests/unit/RarFallbackTest.php @@ -0,0 +1,64 @@ +/dev/null')) !== '') { + self::markTestSkipped('RAR support already provided by unrar or PHP extension'); + } + if (trim((string)shell_exec('command -v 7z 2>/dev/null')) === '') { + self::markTestSkipped('The full 7z executable is required for this fallback test'); + } + + $directory = sys_get_temp_dir() . '/extract-rar-fallback-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($directory, 0700)); + $archive = $directory . '/fixture.rar'; + file_put_contents($archive, base64_decode(self::RAR_FIXTURE, true)); + $destination = $directory . '/out'; + $l10n = $this->createStub(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $text): string => $text); + $service = new ExtractionService($l10n, $this->createStub(LoggerInterface::class), $this->createStub(\OCP\IConfig::class)); + + try { + $result = $service->extractRar($archive, $destination); + self::assertSame(['code' => 1], $result); + self::assertSame("hello libarchive test suite!\n", file_get_contents($destination . '/helloworld.txt')); + } finally { + if (is_dir($destination)) { + $files = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($destination, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST, + ); + foreach ($files as $entry) { + if ($entry->isLink() || !$entry->isDir()) { + unlink($entry->getPathname()); + } else { + rmdir($entry->getPathname()); + } + } + rmdir($destination); + } + unlink($archive); + rmdir($directory); + } + } +} diff --git a/tests/unit/ResourceLimitedProcessTest.php b/tests/unit/ResourceLimitedProcessTest.php new file mode 100644 index 00000000..f474e419 --- /dev/null +++ b/tests/unit/ResourceLimitedProcessTest.php @@ -0,0 +1,193 @@ +directory = sys_get_temp_dir() . '/extract-bounded-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($this->directory, 0700)); + } + + protected function tearDown(): void { + if (isset($this->directory) && is_dir($this->directory)) { + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST, + ); + foreach ($iterator as $entry) { + $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); + } + rmdir($this->directory); + } + parent::tearDown(); + } + + public function testAcceptsExtractionBelowLimits(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'file_put_contents($argv[1] . "/ok.txt", "safe");', $this->directory, + ], $this->directory, 16, 2, 3); + self::assertSame(['success' => true, 'reason' => ''], $result); + self::assertSame('safe', file_get_contents($this->directory . '/ok.txt')); + } + + public function testRejectsTooManyBytesEvenWhenProcessExitsSuccessfully(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'file_put_contents($argv[1] . "/large.txt", str_repeat("x", 256));', $this->directory, + ], $this->directory, 64, 3, 3); + self::assertSame(['success' => false, 'reason' => 'size'], $result); + } + + public function testRejectsTooManyEntries(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'foreach(range(1, 4) as $i){ file_put_contents($argv[1] . "/" . $i, "a"); }', $this->directory, + ], $this->directory, 50, 2, 3); + self::assertSame(['success' => false, 'reason' => 'entries'], $result); + } + + public function testStopsDecoderThatRunsBeyondDeadline(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'while (true) { usleep(200000); }', + ], $this->directory, 50, 2, 1); + self::assertSame(['success' => false, 'reason' => 'timeout'], $result); + } + + + public function testRejectsStagedSymbolicLinks(): void { + if (!function_exists('symlink')) { + self::markTestSkipped('Symbolic links are unavailable on this platform'); + } + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'symlink("somewhere-outside", $argv[1] . "/link");', $this->directory, + ], $this->directory, 50, 2, 3); + self::assertSame(['success' => false, 'reason' => 'symlink'], $result); + } + + + public function testLargeStdoutDoesNotBlockAValidDecoder(): void { + $result = ResourceLimitedProcess::run( + [PHP_BINARY, '-r', 'echo str_repeat("x", 1000000);'], + $this->directory, + 100, + 10, + 3, + ); + self::assertSame(['success' => true, 'reason' => ''], $result); + } + + public function testLargeStderrDoesNotBlockAValidDecoder(): void { + $result = ResourceLimitedProcess::run( + [PHP_BINARY, '-r', 'fwrite(STDERR, str_repeat("x", 1000000));'], + $this->directory, + 100, + 10, + 3, + ); + self::assertSame(['success' => true, 'reason' => ''], $result); + } + + public function testListingRejectsExcessOutput(): void { + $result = ResourceLimitedProcess::capture( + [PHP_BINARY, '-r', 'echo str_repeat("x", 1000000);'], + 1024, + 3, + ); + self::assertFalse($result['success']); + self::assertSame('output', $result['reason']); + self::assertLessThanOrEqual(1024, strlen($result['output'])); + } + + public function testListingHasDeadline(): void { + $result = ResourceLimitedProcess::capture( + [PHP_BINARY, '-r', 'sleep(10);'], + 1024, + 1, + ); + self::assertFalse($result['success']); + self::assertSame('timeout', $result['reason']); + } + + public function testListingAcceptsNormalOutput(): void { + $result = ResourceLimitedProcess::capture( + [PHP_BINARY, '-r', 'echo "Path = normal.txt\nSize = 5\n";'], + 1024, + 3, + ); + self::assertSame(['success' => true, 'reason' => '', 'output' => "Path = normal.txt\nSize = 5\n"], $result); + } + + + public function testTimeoutStopsChildProcessInIsolatedSession(): void { + if (!function_exists('posix_kill') || !is_executable('/usr/bin/setsid')) { + $result = ResourceLimitedProcess::run( + [PHP_BINARY, '-r', 'sleep(5);'], + $this->directory, + 128, + 5, + 1, + ); + self::assertSame('timeout', $result['reason']); + return; + } + + $marker = $this->directory . '/child-survived.txt'; + $pidFile = $this->directory . '/child.pid'; + $script = <<<'PHP' +$child = proc_open( + [PHP_BINARY, '-r', 'usleep(1800000); file_put_contents($argv[1], "survived");', $argv[1]], + [ + 0 => ['file', '/dev/null', 'r'], + 1 => ['file', '/dev/null', 'w'], + 2 => ['file', '/dev/null', 'w'], + ], + $pipes, +); +if (is_resource($child)) { + file_put_contents($argv[2], (string)proc_get_status($child)['pid']); +} +sleep(5); +PHP; + try { + $result = ResourceLimitedProcess::run( + [PHP_BINARY, '-r', $script, $marker, $pidFile], + $this->directory, + 128, + 5, + 1, + ); + self::assertSame('timeout', $result['reason']); + self::assertFileExists($pidFile); + usleep(1100000); + self::assertFileDoesNotExist($marker, 'Timed-out decoder descendants must not continue writing'); + } finally { + if (is_file($pidFile)) { + $pid = (int)file_get_contents($pidFile); + if ($pid > 1) { + @posix_kill($pid, 9); + } + } + } + } + + public function testDoesNotAcceptNonZeroExit(): void { + $result = ResourceLimitedProcess::run([ + PHP_BINARY, '-r', 'exit(9);', + ], $this->directory, 50, 2, 3); + self::assertSame(['success' => false, 'reason' => 'exit'], $result); + } +} diff --git a/tests/unit/StagingBudgetInspectorTest.php b/tests/unit/StagingBudgetInspectorTest.php new file mode 100644 index 00000000..62ef3330 --- /dev/null +++ b/tests/unit/StagingBudgetInspectorTest.php @@ -0,0 +1,79 @@ +directory = sys_get_temp_dir() . '/extract-inspector-' . bin2hex(random_bytes(8)); + self::assertTrue(mkdir($this->directory, 0700)); + } + + protected function tearDown(): void { + if (isset($this->directory) && is_dir($this->directory)) { + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST, + ); + foreach ($iterator as $entry) { + if ($entry->isDir() && !$entry->isLink()) { + rmdir($entry->getPathname()); + } else { + unlink($entry->getPathname()); + } + } + rmdir($this->directory); + } + parent::tearDown(); + } + + public function testAcceptsNestedContentWithinLimits(): void { + self::assertTrue(mkdir($this->directory . '/nested', 0700)); + self::assertSame(5, file_put_contents($this->directory . '/nested/file', 'hello')); + self::assertNull((new StagingBudgetInspector($this->directory, 5, 2))->inspect()); + } + + public function testRejectsExcessBytes(): void { + self::assertSame(6, file_put_contents($this->directory . '/file', '123456')); + self::assertSame('size', (new StagingBudgetInspector($this->directory, 5, 1))->inspect()); + } + + public function testRejectsExcessEntriesIncludingDirectories(): void { + self::assertTrue(mkdir($this->directory . '/nested', 0700)); + self::assertSame(1, file_put_contents($this->directory . '/nested/file', 'x')); + self::assertSame('entries', (new StagingBudgetInspector($this->directory, 100, 1))->inspect()); + } + + public function testRejectsSymlinkWithoutFollowingIt(): void { + if (!function_exists('symlink')) { + self::markTestSkipped('Symlinks are not available'); + } + self::assertTrue(symlink('/etc/passwd', $this->directory . '/link')); + self::assertSame('symlink', (new StagingBudgetInspector($this->directory, 100, 10))->inspect()); + } + + public function testAbsentOutputDirectoryHasNoContent(): void { + self::assertNull((new StagingBudgetInspector($this->directory . '/not-yet-created', 100, 5))->inspect()); + } + + public function testRejectsSymlinkUsedAsOutputDirectory(): void { + if (!function_exists('symlink')) { + self::markTestSkipped('Symlinks are not available'); + } + $alias = $this->directory . '/alias'; + self::assertTrue(symlink('/tmp', $alias)); + self::assertSame('symlink', (new StagingBudgetInspector($alias, 100, 10))->inspect()); + } +} diff --git a/tests/unit/WrappedTarballExtractionTest.php b/tests/unit/WrappedTarballExtractionTest.php index 3bd7f339..1287e0d0 100644 --- a/tests/unit/WrappedTarballExtractionTest.php +++ b/tests/unit/WrappedTarballExtractionTest.php @@ -54,7 +54,7 @@ protected function setUp(): void { $reflection = new \ReflectionClass(ExtractionController::class); $this->controller = $reflection->newInstanceWithoutConstructor(); - $this->setProperty('extractionService', new ExtractionService($l10n, $this->createStub(LoggerInterface::class))); + $this->setProperty('extractionService', new ExtractionService($l10n, $this->createStub(LoggerInterface::class), $this->createStub(\OCP\IConfig::class))); $this->setProperty('logger', $this->createStub(LoggerInterface::class)); $this->setProperty('l', $l10n); } @@ -174,6 +174,37 @@ public function testACorruptWrappedTarballReportsFailure(): void { self::assertDirectoryDoesNotExist($destination); } + /** + * XZ-compressed tarballs use the established supervised two-pass decoder. + */ + public function testTarXzIsUnpackedFromFixture(): void { + $archive = __DIR__ . '/../Fixtures/valid.tar.xz'; + $destination = $this->tmpDir . '/xz-result'; + $method = new \ReflectionMethod(ExtractionController::class, 'extractWrappedTarball'); + $response = $method->invoke($this->controller, $archive, $destination); + + self::assertSame(['code' => 1], $response); + self::assertSame("hello world\n", file_get_contents($destination . '/hello.txt')); + self::assertSame([], glob($destination . '.unwrapped*') ?: []); + } + + /** + * TAR+Zstandard first uses modern full 7z, then expands the inner tar. + */ + public function testTarZstdIsUnpackedFromFixture(): void { + if (trim((string)shell_exec('command -v zstd 2>/dev/null || command -v 7z 2>/dev/null')) === '') { + self::markTestSkipped('Neither zstd nor full 7z is installed'); + } + $archive = __DIR__ . '/../Fixtures/valid.tar.zst'; + $destination = $this->tmpDir . '/zstd-result'; + $method = new \ReflectionMethod(ExtractionController::class, 'extractWrappedTarball'); + $response = $method->invoke($this->controller, $archive, $destination, null, true); + + self::assertSame(['code' => 1], $response); + self::assertSame("hello world\n", file_get_contents($destination . '/hello.txt')); + self::assertSame([], glob($destination . '.unwrapped*') ?: []); + } + /** * A plain `.tar` is expanded by a single 7za pass, so it must never be sent * down the two-pass path. diff --git a/tests/unit/ZipExtractorTest.php b/tests/unit/ZipExtractorTest.php new file mode 100644 index 00000000..46ccec32 --- /dev/null +++ b/tests/unit/ZipExtractorTest.php @@ -0,0 +1,45 @@ +open($archive, ZipArchive::CREATE | ZipArchive::OVERWRITE)); + self::assertTrue($zip->addFromString('../outside.txt', 'unsafe')); + $zip->close(); + + $l10n = $this->createStub(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $s): string => $s); + $validator = new ArchiveSafetyValidator($l10n, $this->createStub(LoggerInterface::class)); + $extractor = new ZipExtractor($l10n, $validator, new ExtractionLimits($this->createStub(IConfig::class)), new BoundedStreamCopier()); + $out = $directory . '/result'; + try { + $response = $extractor->extract($archive, $out); + self::assertSame(0, $response['code']); + self::assertDirectoryDoesNotExist($out); + self::assertFileDoesNotExist($directory . '/outside.txt'); + } finally { + unlink($archive); + rmdir($directory); + } + } +}