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 593e62ac..2ac29361 100644 --- a/.github/workflows/playwright.yml +++ b/.github/workflows/playwright.yml @@ -101,8 +101,9 @@ jobs: # 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 >/dev/null + 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 diff --git a/README.md b/README.md index 963a916c..fa181311 100644 --- a/README.md +++ b/README.md @@ -75,26 +75,29 @@ 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 needs either the PHP -`rar` extension or the `unrar` binary; every other format is handled by the -`7za` binary shipped with p7zip. +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 @@ -179,14 +182,19 @@ user data. | 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; on Debian 13, -install the `7zip` package to obtain the full decoder. +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 @@ -196,9 +204,10 @@ install the `7zip` package to obtain the full decoder. ### 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 @@ -293,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" @@ -322,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 1b919bea..8c9bb32f 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 210f95a6..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, ?int $availableBytes = null): 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, $availableBytes); + $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; @@ -536,6 +543,13 @@ public function execute( case 'rar': $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, $destinationParent->getFreeSpace()); diff --git a/lib/Service/CliArchiveExtractor.php b/lib/Service/CliArchiveExtractor.php index 9a87670f..f2ce74c1 100644 --- a/lib/Service/CliArchiveExtractor.php +++ b/lib/Service/CliArchiveExtractor.php @@ -161,6 +161,60 @@ public function extractOther(string $file, string $extractTo, ?int $availableByt 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) { diff --git a/lib/Service/ExtractionService.php b/lib/Service/ExtractionService.php index 9cd1a234..2b9c5a00 100644 --- a/lib/Service/ExtractionService.php +++ b/lib/Service/ExtractionService.php @@ -44,4 +44,9 @@ public function extractRar(string $file, string $extractTo, ?int $availableBytes public function extractOther(string $file, string $extractTo, ?int $availableBytes = null): array { return $this->cli->extractOther($file, $extractTo, $availableBytes); } + + /** @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/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 08ca88ee..902ed126 100644 --- a/tests/playwright/e2e/extract.spec.ts +++ b/tests/playwright/e2e/extract.spec.ts @@ -293,6 +293,97 @@ test('OCS extracts a real 7z archive on Nextcloud', async ({ request }) => { } }) +/** + * 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 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 339d47d1..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", diff --git a/tests/unit/ExtractionServiceTest.php b/tests/unit/ExtractionServiceTest.php index d905be67..15316b10 100644 --- a/tests/unit/ExtractionServiceTest.php +++ b/tests/unit/ExtractionServiceTest.php @@ -300,6 +300,70 @@ public function testStreamedZipPreservesUnicodeNames(): void { 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/WrappedTarballExtractionTest.php b/tests/unit/WrappedTarballExtractionTest.php index cd0703d3..1287e0d0 100644 --- a/tests/unit/WrappedTarballExtractionTest.php +++ b/tests/unit/WrappedTarballExtractionTest.php @@ -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.