diff --git a/server/src/Application/File/UploadService.php b/server/src/Application/File/UploadService.php index b9f263fd..565ec3d3 100644 --- a/server/src/Application/File/UploadService.php +++ b/server/src/Application/File/UploadService.php @@ -23,7 +23,7 @@ /** * POST /files 的上传主流程:限长复制 → 内容嗅探 → 扩展名+MIME 双白名单 → - * 幂等预检 → Flysystem 落盘 → sand_system_file 元数据、用途登记与幂等记录 + * 幂等预检 → SafeFs 原子落盘 → sand_system_file 元数据、用途登记与幂等记录 * 同一事务入库。幂等重放经 IdempotentReplay 抛给 FileHttp 转成功信封。 */ final class UploadService diff --git a/server/src/Infra/File/LocalFileStorage.php b/server/src/Infra/File/LocalFileStorage.php index a57e2cf1..2b1d9e52 100644 --- a/server/src/Infra/File/LocalFileStorage.php +++ b/server/src/Infra/File/LocalFileStorage.php @@ -7,13 +7,11 @@ namespace Sandadmin\Infra\File; -use League\Flysystem\Filesystem; -use League\Flysystem\FilesystemException; -use League\Flysystem\Local\LocalFilesystemAdapter; use Sandadmin\Domain\File\FileException; /** - * 1.0 只接本机磁盘,直接用 Flysystem Local adapter(§3.8.4/§4.3,不再自定义存储接口)。 + * 1.0 只接本机磁盘,一切写/删/判存都经 SafeFs 收口(M-03): + * 根内限定 + lstat 拒软链 + 原子写 + 显式权限位。 * 对象键是随机生成的 storage_key,原始文件名只写 sand_system_file 元数据; * 存储根在 web 根之外(config/file.php 默认 runtime/files)。 */ @@ -22,7 +20,7 @@ final class LocalFileStorage public const KEY_PATTERN = '/\A[a-f0-9]{32}\z/'; private function __construct( - private readonly Filesystem $filesystem, + private readonly SafeFs $safe, private readonly string $root, ) { } @@ -32,25 +30,22 @@ public static function open(string $root): self if ($root === '') { throw FileException::internal('存储配置无效'); } - if (!is_dir($root) && !mkdir($root, 0700, true) && !is_dir($root)) { - throw FileException::internal('无法创建存储目录'); + try { + $safe = SafeFs::open($root); + } catch (SafeFsException $error) { + throw FileException::internal('存储目录不可用', $error); } - $resolved = realpath($root); - if ($resolved === false || !is_dir($resolved) || !is_writable($resolved)) { + $resolved = $safe->root(); + if (!is_writable($resolved)) { throw FileException::internal('存储目录不可用'); } - $adapter = new LocalFilesystemAdapter( - $resolved, - null, - LOCK_EX, - LocalFilesystemAdapter::DISALLOW_LINKS, - ); - - return new self(new Filesystem($adapter), $resolved); + + return new self($safe, $resolved); } /** * 流式写入并返回随机对象键;键冲突时重试。 + * 写盘经 SafeFs 原子写:同目录临时文件 + rename 落位,权限位显式 0640。 * * @param resource $stream */ @@ -64,8 +59,8 @@ public function writeStream(mixed $stream): string } try { $key = $this->allocateKey(); - $this->filesystem->writeStream($key, $stream); - } catch (FilesystemException $error) { + $this->safe->writeStream($key, $stream, 0640); + } catch (SafeFsException $error) { throw FileException::internal('文件写入失败', $error); } @@ -76,8 +71,8 @@ public function exists(string $key): bool { self::assertKey($key); try { - return $this->filesystem->fileExists($key); - } catch (FilesystemException $error) { + return $this->safe->kind($key) === 'file'; + } catch (SafeFsException $error) { throw FileException::internal('无法读取存储', $error); } } @@ -86,16 +81,16 @@ public function delete(string $key): void { self::assertKey($key); try { - if (!$this->filesystem->fileExists($key)) { + if ($this->safe->kind($key) === null) { return; } - $this->filesystem->delete($key); - } catch (FilesystemException $error) { + $this->safe->removeFile($key); + } catch (SafeFsException $error) { throw FileException::internal('文件删除失败', $error); } } - /** 本机适配器下对象键即根目录内相对路径;仅下载响应使用。 */ + /** 本机存储下对象键即根目录内相对路径;仅下载响应使用。 */ public function localPath(string $key): string { self::assertKey($key); @@ -114,7 +109,7 @@ private function allocateKey(): string { for ($attempt = 0; $attempt < 3; $attempt++) { $key = bin2hex(random_bytes(16)); - if (!$this->filesystem->fileExists($key)) { + if ($this->safe->kind($key) === null) { return $key; } } diff --git a/server/src/Infra/File/SafeFs.php b/server/src/Infra/File/SafeFs.php new file mode 100644 index 00000000..b920e66f --- /dev/null +++ b/server/src/Infra/File/SafeFs.php @@ -0,0 +1,484 @@ +root; + } + + /** + * 规范化相对路径并校验落在根内,返回根内绝对路径。 + * 拒绝:NUL 字节、.. 段、绝对路径、驱动器盘符、反斜杠、 + * 百分号/双重编码绕过,以及任一级(含中间级)已存在组件是符号链接。 + * 允许末尾若干段尚不存在(写入目标),但存在级一律过 lstat 检查。 + */ + public function resolve(string $relative): string + { + $segments = self::normalizeSegments($relative); + $path = $this->root; + foreach ($segments as $segment) { + $path .= '/' . $segment; + // is_link 走 lstat 不跟随链接;不存在的段跳过,存在的任一级是链接即拒 + if (is_link($path)) { + throw SafeFsException::of(SafeFsException::SYMLINK, '路径组件是符号链接:' . $path); + } + } + + return $path; + } + + /** 存在性/类型判断:file|dir,不存在为 null;路径任一级是链接时 resolve 已先拒。 */ + public function kind(string $relative): ?string + { + $path = $this->resolve($relative); + if (!file_exists($path)) { + return null; + } + + return is_dir($path) ? 'dir' : 'file'; + } + + /** 显式权限位建目录(含中间级),已存在不报错。 */ + public function makeDir(string $relative, int $perm = 0755): void + { + $segments = self::normalizeSegments($relative); + $path = $this->root; + foreach ($segments as $segment) { + $path .= '/' . $segment; + if (is_dir($path) && !is_link($path)) { + continue; + } + if (file_exists($path) || is_link($path)) { + throw SafeFsException::of(SafeFsException::MKDIR_FAILED, '目录路径被非目录占用:' . $path); + } + if (!mkdir($path, $perm)) { + throw SafeFsException::of(SafeFsException::MKDIR_FAILED, '无法创建目录:' . $path); + } + chmod($path, $perm); + } + } + + /** + * 流式原子写:先写同目录随机唯一名临时文件,chmod 后 rename 落位。 + * 分块复制不整读入内存;任何一步失败回收临时文件,回收失败随异常上报。 + * maxBytes 非空时是实际写出字节的硬切断:再写一块就越限即中止, + * 不越过上限、不落位,按 SIZE_EXCEEDED 拒绝——调用方不能靠 + * 「源自称的尺寸」预估,只信逐块累计的真实字节。 + * + * @param resource $stream + */ + public function writeStream(string $relative, mixed $stream, int $perm = 0644, ?int $maxBytes = null): int + { + if (!is_resource($stream)) { + throw SafeFsException::of(SafeFsException::WRITE_FAILED, '写入源不是可读流'); + } + $target = $this->resolve($relative); + $parent = dirname($target); + if ($parent !== $this->root) { + $this->makeDir(self::relativeTo($this->root, $parent)); + } + $staging = tempnam($parent, '.tmp-'); + if ($staging === false) { + throw SafeFsException::of(SafeFsException::WRITE_FAILED, '无法分配临时文件:' . $parent); + } + chmod($staging, $perm); + $out = fopen($staging, 'wb'); + if ($out === false) { + $note = $this->discardStaging($staging); + throw SafeFsException::of(SafeFsException::WRITE_FAILED, '无法写入临时文件:' . $staging . $note); + } + $bytes = 0; + try { + while (!feof($stream)) { + $chunk = fread($stream, self::CHUNK_BYTES); + if ($chunk === false) { + throw SafeFsException::of(SafeFsException::WRITE_FAILED, '读取写入源失败'); + } + if ($chunk === '') { + break; + } + if ($maxBytes !== null && $bytes + strlen($chunk) > $maxBytes) { + throw SafeFsException::of( + SafeFsException::SIZE_EXCEEDED, + '实际写出字节将超过上限 ' . $maxBytes . ',流式硬切断中止', + ); + } + if (fwrite($out, $chunk) === false) { + throw SafeFsException::of(SafeFsException::WRITE_FAILED, '写入临时文件失败:' . $staging); + } + $bytes += strlen($chunk); + } + } catch (\Throwable $error) { + fclose($out); + $note = $this->discardStaging($staging); + if ($error instanceof SafeFsException) { + throw SafeFsException::of($error->reason, $error->getMessage() . $note, $error); + } + + throw SafeFsException::of(SafeFsException::WRITE_FAILED, '写入临时文件失败' . $note, $error); + } + fclose($out); + // temp 与目标同目录即同设备,rename 不会跨设备;仍显式报错不降级复制 + if (!rename($staging, $target)) { + $note = $this->discardStaging($staging); + + throw SafeFsException::of(SafeFsException::MOVE_FAILED, '临时文件落位失败:' . $target . $note); + } + + return $bytes; + } + + /** + * 小字节串原子写;大内容一律走 writeStream。 + * maxBytes 语义同 writeStream 的实际字节硬切断,返回写入字节数。 + */ + public function writeBytes(string $relative, string $bytes, int $perm = 0644, ?int $maxBytes = null): int + { + $stream = fopen('php://temp', 'w+b'); + if ($stream === false) { + throw SafeFsException::of(SafeFsException::WRITE_FAILED, '无法准备写入缓冲'); + } + fwrite($stream, $bytes); + rewind($stream); + try { + return $this->writeStream($relative, $stream, $perm, $maxBytes); + } finally { + fclose($stream); + } + } + + /** + * 根内改名:源与目标都过 resolve 检查,源必须存在且任一级不是链接。 + * rename 失败显式报错,不降级为复制+删除(跨设备语义不同会留半成品)。 + */ + public function moveWithin(string $fromRelative, string $toRelative): void + { + $from = $this->resolve($fromRelative); + $to = $this->resolve($toRelative); + $this->assertMovable($from); + $parent = dirname($to); + if (!is_dir($parent)) { + throw SafeFsException::of(SafeFsException::MOVE_FAILED, '目标父目录不存在:' . $parent); + } + if (!rename($from, $to)) { + throw SafeFsException::of(SafeFsException::MOVE_FAILED, '改名失败:' . $from . ' → ' . $to); + } + } + + /** + * 跨登记根改名(如暂存根 → 插件根):两侧各自过根内与链接检查再 rename。 + * 跨设备 rename 失败显式报错,不静默降级复制。 + */ + public function moveTo(SafeFs $target, string $fromRelative, string $toRelative): void + { + $from = $this->resolve($fromRelative); + $to = $target->resolve($toRelative); + $this->assertMovable($from); + $parent = dirname($to); + if (!is_dir($parent)) { + throw SafeFsException::of(SafeFsException::MOVE_FAILED, '目标父目录不存在:' . $parent); + } + if (!rename($from, $to)) { + throw SafeFsException::of( + SafeFsException::MOVE_FAILED, + '跨根改名失败(含跨设备拒绝降级复制):' . $from . ' → ' . $to, + ); + } + } + + /** + * 递归删除根内目录树:lstat 判定,符号链接只解链本身绝不跟随, + * 拒绝删除登记根本身。任何一项删除失败汇总抛出,不吞掉。 + */ + public function removeTree(string $relative): void + { + $segments = self::normalizeSegments($relative); + if ($segments === []) { + throw SafeFsException::of(SafeFsException::REMOVE_FAILED, '拒绝删除登记根本身'); + } + $path = $this->root; + foreach ($segments as $index => $segment) { + $isLastSegment = $index === count($segments) - 1; + $path .= '/' . $segment; + if (!$isLastSegment && is_link($path)) { + throw SafeFsException::of(SafeFsException::SYMLINK, '路径中间级是符号链接:' . $path); + } + } + if (!file_exists($path) && !is_link($path)) { + return; + } + $failures = []; + $this->removeNode($path, $failures); + if ($failures !== []) { + throw SafeFsException::of( + SafeFsException::REMOVE_FAILED, + '删除未全部完成:' . implode(';', $failures), + ); + } + } + + /** 删除根内单个文件或空链接;目标是目录时拒绝(防误用,目录走 removeTree)。 */ + public function removeFile(string $relative): void + { + $path = $this->resolve($relative); + if (!file_exists($path) && !is_link($path)) { + return; + } + if (!is_link($path) && is_dir($path)) { + throw SafeFsException::of(SafeFsException::REMOVE_FAILED, '目标是目录,应走 removeTree:' . $path); + } + if (!unlink($path)) { + throw SafeFsException::of(SafeFsException::REMOVE_FAILED, '无法删除文件:' . $path); + } + } + + /** + * 静态守卫入口:按绝对路径删树,路径必须落在某个登记根内。 + * 供 journal/恢复流程等只持绝对路径的调用点使用;根不存在时该根跳过。 + * + * @param list $roots + */ + public static function removeTreeGuarded(string $absolute, array $roots): void + { + [$safe, $relative] = self::bind($absolute, $roots); + $safe->removeTree($relative); + } + + /** + * 静态守卫入口:跨根改名,两端都必须落在各自登记根内。 + * + * @param list $fromRoots + * @param list $toRoots + */ + public static function moveGuarded(string $from, string $to, array $fromRoots, array $toRoots): void + { + [$safeFrom, $fromRelative] = self::bind($from, $fromRoots); + [$safeTo, $toRelative] = self::bind($to, $toRoots); + $safeFrom->moveTo($safeTo, $fromRelative, $toRelative); + } + + /** + * 规范化入口:zip 条目等不可信相对路径的段级校验,大小写归一在 + * 调用方做名单比较时另行 strtolower——本函数只做结构与编码判定。 + * + * @return list + */ + public static function normalizeSegments(string $relative): array + { + self::assertCleanName($relative); + $segments = []; + foreach (explode('/', $relative) as $segment) { + if ($segment === '' || $segment === '.') { + continue; + } + if ($segment === '..') { + throw SafeFsException::of(SafeFsException::TRAVERSAL, '路径含 .. 段:' . $relative); + } + $segments[] = $segment; + } + if ($segments === []) { + throw SafeFsException::of(SafeFsException::TRAVERSAL, '路径为空或只有分隔符:' . $relative); + } + + return $segments; + } + + /** + * 结构与编码校验:NUL、反斜杠变体、绝对路径、驱动器盘符、 + * 百分号编码与双重编码绕过。解码后形态与原形态都要过同一套判定。 + */ + public static function assertCleanName(string $name): void + { + if ($name === '') { + throw SafeFsException::of(SafeFsException::TRAVERSAL, '路径为空'); + } + if (str_contains($name, "\0")) { + throw SafeFsException::of(SafeFsException::ENCODING_BYPASS, '路径含 NUL 字节'); + } + if (str_contains($name, '\\')) { + throw SafeFsException::of(SafeFsException::TRAVERSAL, '路径含反斜杠变体:' . $name); + } + if (str_starts_with($name, '/') || preg_match('/^[A-Za-z]:\//', $name) === 1 || preg_match('/^[A-Za-z]:\z/', $name) === 1) { + throw SafeFsException::of(SafeFsException::TRAVERSAL, '路径是绝对路径或带盘符:' . $name); + } + // 编码绕过:原样不含 .. 但解码后含(含双重编码),与正写同罪 + $decoded = $name; + for ($pass = 0; $pass < self::MAX_DECODE_PASSES; $pass++) { + $next = rawurldecode($decoded); + if ($next === $decoded) { + break; + } + $decoded = $next; + } + if ($decoded !== $name) { + if (str_contains($decoded, "\0")) { + throw SafeFsException::of(SafeFsException::ENCODING_BYPASS, '路径解码后含 NUL 字节:' . $name); + } + $decodedSegments = explode('/', str_replace('\\', '/', $decoded)); + foreach ($decodedSegments as $segment) { + if ($segment === '..' || preg_match('/^[A-Za-z]:\z/', $segment) === 1) { + throw SafeFsException::of( + SafeFsException::ENCODING_BYPASS, + '路径解码后出现穿越段或盘符:' . $name, + ); + } + } + } + } + + /** + * 把绝对路径绑到包含它的登记根上,返回实例与根内相对路径。 + * 根内判定按大小写归一(macOS 开发机与 Linux 生产语义对齐)。 + * + * @param list $roots + * @return array{SafeFs, string} + */ + private static function bind(string $absolute, array $roots): array + { + foreach ($roots as $root) { + if (!is_dir($root)) { + continue; + } + $resolved = realpath($root); + if ($resolved === false) { + continue; + } + // 根是调用方登记的服务端路径:realpath 定型拼写与传入的原始拼写 + // 指向同一目录(/tmp 与 /private/tmp 这类别名),两种拼写都接受; + // 根以下的相对部分仍由 resolve 逐级 lstat 拒软链,别名放松到不了根内组件 + $candidate = mb_strtolower($absolute); + foreach ([$resolved, rtrim($root, '/')] as $spelling) { + $prefix = mb_strtolower(rtrim($spelling, '/')) . '/'; + if (str_starts_with($candidate, $prefix)) { + $safe = new self($resolved); + $relative = substr($absolute, strlen(rtrim($spelling, '/')) + 1); + + return [$safe, $relative]; + } + } + } + + throw SafeFsException::of(SafeFsException::OUTSIDE_ROOT, '路径不在任何登记根内:' . $absolute); + } + + /** 根内绝对路径转相对路径;调用方须保证确在根内。 */ + private static function relativeTo(string $root, string $absolute): string + { + $prefix = rtrim($root, '/') . '/'; + if (str_starts_with($absolute, $prefix)) { + return substr($absolute, strlen($prefix)); + } + + return $absolute; + } + + private function assertMovable(string $from): void + { + if (!file_exists($from) && !is_link($from)) { + throw SafeFsException::of(SafeFsException::MOVE_FAILED, '源路径不存在:' . $from); + } + if (is_link($from)) { + throw SafeFsException::of(SafeFsException::SYMLINK, '拒绝移动符号链接:' . $from); + } + } + + /** + * lstat 逐级删除:链接只解链不进树;失败记入 failures 不中断, + * 由调用方汇总抛出——清理失败要上报不吞掉。 + * + * @param list $failures + */ + private function removeNode(string $path, array &$failures): void + { + if (is_link($path)) { + if (!unlink($path)) { + $failures[] = '无法删除符号链接:' . $path; + } + + return; + } + if (!is_dir($path)) { + if (!unlink($path)) { + $failures[] = '无法删除文件:' . $path; + } + + return; + } + $items = scandir($path); + if ($items === false) { + $failures[] = '无法读取目录:' . $path; + + return; + } + foreach ($items as $item) { + if ($item === '.' || $item === '..') { + continue; + } + $this->removeNode($path . '/' . $item, $failures); + } + if (!rmdir($path)) { + $failures[] = '无法删除目录:' . $path; + } + } + + /** 回收临时文件;返回空串或「回收失败」说明,由调用方并进异常消息上报。 */ + private function discardStaging(string $staging): string + { + if ((file_exists($staging) || is_link($staging)) && !unlink($staging)) { + return ';临时文件回收失败需人工清理:' . $staging; + } + + return ''; + } +} diff --git a/server/src/Infra/File/SafeFsException.php b/server/src/Infra/File/SafeFsException.php new file mode 100644 index 00000000..d4db366a --- /dev/null +++ b/server/src/Infra/File/SafeFsException.php @@ -0,0 +1,39 @@ +, error_code: ?string} * payload 是 zip 内插件目录前缀(plugin// 或 server/) */ - public static function inspect(string $zipFile, ?string $expectedSha256): array + public static function inspect(string $zipFile, ?string $expectedSha256, array $limits = []): array { $empty = ['manifest' => null, 'payload' => null, 'problems' => [], 'error_code' => null]; if (!is_file($zipFile)) { @@ -57,7 +74,7 @@ public static function inspect(string $zipFile, ?string $expectedSha256): array if (!is_string($name) || $name === '') { continue; } - $names[] = str_replace('\\', '/', $name); + $names[] = $name; } $errorCode = null; @@ -70,17 +87,31 @@ public static function inspect(string $zipFile, ?string $expectedSha256): array } } } + $limitArgs = [ + $limits['max_entries'] ?? self::MAX_ENTRIES, + $limits['max_total_bytes'] ?? self::MAX_TOTAL_BYTES, + $limits['max_ratio'] ?? self::MAX_RATIO, + ]; + $zipFileBytes = filesize($zipFile); + if (!is_int($zipFileBytes) || $zipFileBytes <= 0) { + $zip->close(); + + return ['manifest' => null, 'payload' => null, 'problems' => array_merge($problems, ['无法测定安装包实际字节数']), 'error_code' => null]; + } + foreach (self::limitProblems($zip, $limitArgs[0], $limitArgs[1], $limitArgs[2], $zipFileBytes) as $issue) { + $problems[] = $issue; + } if ($problems !== []) { $zip->close(); return ['manifest' => null, 'payload' => null, 'problems' => $problems, 'error_code' => $errorCode]; } - $rawManifest = $zip->getFromName('manifest.json'); - if (!is_string($rawManifest)) { + $rawManifest = self::readEntryBounded($zip, 'manifest.json', self::MANIFEST_MAX_BYTES); + if ($rawManifest === null) { $zip->close(); - return ['manifest' => null, 'payload' => null, 'problems' => ['zip 根缺少 manifest.json'], 'error_code' => null]; + return ['manifest' => null, 'payload' => null, 'problems' => ['zip 根缺少 manifest.json 或清单超过大小上限'], 'error_code' => null]; } $parsed = PluginPackageManifest::parse($rawManifest); if ($parsed['manifest'] === null) { @@ -130,28 +161,43 @@ public static function inspect(string $zipFile, ?string $expectedSha256): array * 把 payload 子树解到 $targetDir(相对路径逐个过白名单), * 并把 zip 根 manifest.json 写进 $targetDir/manifest.json。 * 只在 inspect 通过后调用;IO 失败抛 RuntimeException。 + * 目标目录即本次解包的登记根:一切写入经 SafeFs 限定在根内, + * 流式复制边写边计总字节,超上限即中止并回收整个目标目录, + * 回收失败随异常消息上报。 + * + * @param array{max_entries?: int, max_total_bytes?: int, max_ratio?: float} $limits + * 测试用小上限;生产缺省走类常量 */ public static function unpack( string $zipFile, string $payloadPrefix, string $targetDir, PluginPackageManifest $manifest, + array $limits = [], ): void { + $maxEntries = $limits['max_entries'] ?? self::MAX_ENTRIES; + $maxTotalBytes = $limits['max_total_bytes'] ?? self::MAX_TOTAL_BYTES; + $maxRatio = $limits['max_ratio'] ?? self::MAX_RATIO; + $zipFileBytes = filesize($zipFile); + if (!is_int($zipFileBytes) || $zipFileBytes <= 0) { + throw new \RuntimeException('无法测定安装包实际字节数:' . $zipFile); + } $zip = new \ZipArchive(); if ($zip->open($zipFile, \ZipArchive::RDONLY) !== true) { throw new \RuntimeException('无法打开安装包:' . $zipFile); } - if (!is_dir($targetDir) && !mkdir($targetDir, 0755, true) && !is_dir($targetDir)) { - $zip->close(); - throw new \RuntimeException('无法创建暂存目录:' . $targetDir); - } try { + $limitProblems = self::limitProblems($zip, $maxEntries, $maxTotalBytes, $maxRatio, $zipFileBytes); + if ($limitProblems !== []) { + throw new \RuntimeException('安装包超出解压上限:' . implode(';', $limitProblems)); + } + $safe = SafeFs::open($targetDir, 0755); + $totalBytes = 0; for ($i = 0; $i < $zip->numFiles; $i++) { $name = $zip->getNameIndex($i); if (!is_string($name)) { continue; } - $name = str_replace('\\', '/', $name); if (!str_starts_with($name, $payloadPrefix)) { continue; } @@ -162,68 +208,131 @@ public static function unpack( if ($relative === '') { continue; } - $dest = $targetDir . '/' . $relative; if (str_ends_with($name, '/')) { - if (!is_dir($dest) && !mkdir($dest, 0755, true) && !is_dir($dest)) { - throw new \RuntimeException('无法创建目录:' . $dest); - } + $safe->makeDir($relative, 0755); continue; } - self::writeEntry($zip, $name, $dest); + $totalBytes = self::writeEntryStreamed( + $zip, + $name, + $safe, + $relative, + $totalBytes, + $maxTotalBytes, + $zipFileBytes, + $maxRatio, + ); } - $rawManifest = $zip->getFromName('manifest.json'); - if (!is_string($rawManifest)) { - throw new \RuntimeException('zip 根缺少 manifest.json'); + $rawManifest = self::readEntryBounded($zip, 'manifest.json', self::MANIFEST_MAX_BYTES); + if ($rawManifest === null) { + throw new \RuntimeException('zip 根缺少 manifest.json 或清单超过大小上限'); + } + // 根清单与载荷同吃一锅预算:声明/实际复核、剩余额度硬切断、 + // 压缩比递增复核一项不少,防止 manifest 成预算外通道 + $manifestBytes = strlen($rawManifest); + if ($totalBytes + $manifestBytes > $maxTotalBytes) { + throw new \RuntimeException('解压总大小超过上限 ' . $maxTotalBytes . ' 字节(根清单计入同一预算)'); } // 根清单覆盖 payload 内同名文件,落位后的声明以 zip 根为准 - if (file_put_contents($targetDir . '/manifest.json', $rawManifest) === false) { - throw new \RuntimeException('无法写入 manifest.json 到 ' . $targetDir); + $safe->writeBytes('manifest.json', $rawManifest, 0644, $maxTotalBytes - $totalBytes); + $totalBytes += $manifestBytes; + self::assertAmplificationWithin($totalBytes, $zipFileBytes, $maxRatio); + $manifestStat = $zip->statName('manifest.json'); + if (is_array($manifestStat) && $manifestStat['size'] !== $manifestBytes) { + throw new \RuntimeException( + 'zip 条目声明尺寸 ' . $manifestStat['size'] . ' 与实际解压 ' . $manifestBytes . ' 字节不符:manifest.json', + ); } + } catch (\Throwable $error) { + // 失败回收:目标目录是本次解包独占的暂存根,整体清掉不留半成品 + self::discardTree($targetDir, $error); } finally { $zip->close(); } } - /** 条目路径是否踩红线;返回问题描述或 null。 */ + /** + * zip bomb 三条上限预检(按 zip 目录项声明的尺寸): + * 条目数、解压后总大小、压缩比,任一命中即拒。 + * 压缩比口径是 archive amplification:声明解压总字节 / zip 文件真实字节数。 + * 头部 comp_size 同样是攻击者可控字段(deflate 流自带结束标记,改大不影响解压), + * 一律不作安全分母。声明值只是快速预检,解包时另按实际字节递增复核。 + * + * @return list + */ + private static function limitProblems( + \ZipArchive $zip, + int $maxEntries, + int $maxTotalBytes, + float $maxRatio, + int $zipFileBytes, + ): array { + $problems = []; + if ($zip->numFiles > $maxEntries) { + $problems[] = '条目数 ' . $zip->numFiles . ' 超过上限 ' . $maxEntries; + } + $totalSize = 0; + for ($i = 0; $i < $zip->numFiles; $i++) { + $stat = $zip->statIndex($i); + if (!is_array($stat)) { + continue; + } + $totalSize += $stat['size']; + } + if ($totalSize > $maxTotalBytes) { + $problems[] = '解压后总大小 ' . $totalSize . ' 字节超过上限 ' . $maxTotalBytes; + } + if ($totalSize > 0 && $totalSize / $zipFileBytes > $maxRatio) { + $problems[] = '压缩比 ' . round($totalSize / $zipFileBytes, 1) . ' 超过上限 ' . $maxRatio + . '(archive amplification:声明解压字节 / zip 文件真实字节)'; + } + + return $problems; + } + + /** 条目路径是否踩红线;返回问题描述或 null。名单比较大小写归一。 */ private static function entryProblem(string $name): ?string { - if (str_starts_with($name, '/') || preg_match('/^[A-Za-z]:\//', $name) === 1) { - return 'zip 条目是绝对路径:' . $name; + try { + $segments = SafeFs::normalizeSegments($name); + } catch (SafeFsException $error) { + return 'zip 条目路径非法:' . $name . '(' . $error->getMessage() . ')'; } - $segments = explode('/', $name); - $isDirectory = str_ends_with($name, '/'); - $base = $isDirectory ? ($segments[count($segments) - 2] ?? '') : $segments[count($segments) - 1]; + $base = $segments[count($segments) - 1]; + $baseLower = strtolower($base); foreach ($segments as $segment) { - if ($segment === '..') { - return 'zip 条目含 .. 段:' . $name; - } - if (in_array($segment, self::BANNED_SEGMENTS, true)) { + if (in_array(strtolower($segment), self::BANNED_SEGMENTS, true)) { return 'zip 条目含禁带目录 ' . $segment . '/:' . $name; } // migrations 段单独成条:拒因不是「禁带文件」而是「执行器未实现」, - // inspect 据此回填 error_code,文案要让安装方看懂 - if ($segment === 'migrations') { + // inspect 据此回填 error_code,文案要让安装方看懂;名单比较大小写归一 + if (strtolower($segment) === 'migrations') { return 'zip 条目含 migrations 迁移目录,迁移执行器未实现,暂不支持:' . $name; } } - if (in_array($base, self::BANNED_FILES, true)) { + if (in_array($baseLower, self::BANNED_FILES, true)) { return 'zip 条目含禁带迁移脚本:' . $name; } - if (preg_match('/^\.env(\..*)?$/', $base) === 1) { + if (preg_match('/^\.env(\..*)?$/', $baseLower) === 1) { return 'zip 条目含环境配置:' . $name; } - if (str_ends_with($base, '.phar') || str_ends_with($base, '.so')) { + if (str_ends_with($baseLower, '.phar') || str_ends_with($baseLower, '.so')) { return 'zip 条目含编译产物:' . $name; } return null; } - /** 条目路径是否含 migrations 目录段(目录项自身也算)。 */ + /** 条目路径是否含 migrations 目录段(目录项自身也算;大小写归一)。 */ private static function isMigrationsEntry(string $name): bool { - foreach (explode('/', $name) as $segment) { - if ($segment === 'migrations') { + try { + $segments = SafeFs::normalizeSegments($name); + } catch (SafeFsException) { + return false; + } + foreach ($segments as $segment) { + if (strtolower($segment) === 'migrations') { return true; } } @@ -231,23 +340,121 @@ private static function isMigrationsEntry(string $name): bool return false; } - private static function writeEntry(\ZipArchive $zip, string $name, string $dest): void + /** + * 逐条流式写出:不整读入内存,按实际解压字节执法。 + * zip 中央目录的 uncompressed size 可以被伪造,因此: + * - 总大小上限不靠声明值预估,而把剩余额度传给 SafeFs 作实际字节硬切断; + * - 压缩比按累计实际解压字节对照 zip 文件真实字节数递增复核; + * - 单条写完复核声明尺寸与实际字节,不一致按异常包拒绝。 + * 返回累计后的总字节数。 + */ + private static function writeEntryStreamed( + \ZipArchive $zip, + string $name, + SafeFs $safe, + string $relative, + int $totalBytes, + int $maxTotalBytes, + int $zipFileBytes, + float $maxRatio, + ): int { + $source = $zip->getStream($name); + if ($source === false) { + throw new \RuntimeException('无法读取 zip 条目:' . $name); + } + try { + $stat = $zip->statName($name); + $declared = is_array($stat) ? $stat['size'] : 0; + $remaining = $maxTotalBytes - $totalBytes; + if ($declared > $remaining) { + throw new \RuntimeException('解压总大小超过上限 ' . $maxTotalBytes . ' 字节(流式计数中止)'); + } + try { + $written = $safe->writeStream($relative, $source, 0644, $remaining); + } catch (SafeFsException $error) { + if ($error->reason === SafeFsException::SIZE_EXCEEDED) { + throw new \RuntimeException( + '解压总大小超过上限 ' . $maxTotalBytes . ' 字节(按实际解压字节硬切断)', + 0, + $error, + ); + } + + throw $error; + } + } finally { + fclose($source); + } + $totalBytes += $written; + self::assertAmplificationWithin($totalBytes, $zipFileBytes, $maxRatio); + if ($written !== $declared) { + throw new \RuntimeException( + 'zip 条目声明尺寸 ' . $declared . ' 与实际解压 ' . $written . ' 字节不符:' . $name, + ); + } + + return $totalBytes; + } + + /** + * 压缩比递增复核,口径 archive amplification:实际解出总字节 / zip 文件真实字节数。 + * 分母取自 filesize,不信 zip 头部任何尺寸字段;padding 真实增大输入文件 + * 体积时按同口径稀释,这是明确口径而非漏洞——膨胀的输入本身有传输/存储成本。 + */ + private static function assertAmplificationWithin(int $totalBytes, int $zipFileBytes, float $maxRatio): void { - $parent = dirname($dest); - if (!is_dir($parent) && !mkdir($parent, 0755, true) && !is_dir($parent)) { - throw new \RuntimeException('无法创建目录:' . $parent); + if ($totalBytes > 0 && $totalBytes / $zipFileBytes > $maxRatio) { + throw new \RuntimeException( + '压缩比 ' . round($totalBytes / $zipFileBytes, 1) + . ' 超过上限 ' . $maxRatio . '(archive amplification:实际解出字节 / zip 文件真实字节)', + ); } + } + + /** + * 读取单个 zip 条目为字符串,按上限流式截停:超限或不存在返回 null。 + * 只用于有界小文件(manifest.json),载荷条目一律走 writeEntryStreamed。 + */ + private static function readEntryBounded(\ZipArchive $zip, string $name, int $maxBytes): ?string + { $source = $zip->getStream($name); if ($source === false) { - throw new \RuntimeException('无法读取 zip 条目:' . $name); + return null; } - $target = fopen($dest, 'wb'); - if ($target === false) { + $content = ''; + try { + while (!feof($source)) { + $chunk = fread($source, 8192); + if ($chunk === false) { + return null; + } + if ($chunk === '') { + break; + } + $content .= $chunk; + if (strlen($content) > $maxBytes) { + return null; + } + } + } finally { fclose($source); - throw new \RuntimeException('无法写入文件:' . $dest); } - stream_copy_to_stream($source, $target); - fclose($target); - fclose($source); + + return $content; + } + + /** 解包失败回收目标目录;回收失败并进原异常消息上报,不吞掉。 */ + private static function discardTree(string $targetDir, \Throwable $cause): never + { + $note = ''; + if (is_dir($targetDir)) { + try { + SafeFs::removeTreeGuarded($targetDir, [dirname($targetDir)]); + } catch (\Throwable $cleanup) { + $note = ';已写内容回收失败需人工清理 ' . $targetDir . ':' . $cleanup->getMessage(); + } + } + + throw new \RuntimeException($cause->getMessage() . $note, 0, $cause); } } diff --git a/server/src/Module/Package/PackageExecutor.php b/server/src/Module/Package/PackageExecutor.php index e665a5a3..7982ae6f 100644 --- a/server/src/Module/Package/PackageExecutor.php +++ b/server/src/Module/Package/PackageExecutor.php @@ -10,6 +10,7 @@ use Sandadmin\Contract\Build\ContractBuild; use Sandadmin\Contract\KernelApi\KernelApiVersion; use Sandadmin\Infra\BuildKind; +use Sandadmin\Infra\File\SafeFs; /** * 离线包安装/升级/卸载执行器(CLI 通道)。顺序:构建闸 → Ed25519 验签 @@ -95,9 +96,8 @@ public function uninstall(string $app, string $dataPolicy = 'keep'): array $pending = []; try { $journal->setPaths($id, backup: $backup); - if (!rename($pluginPath, $backup)) { - throw new \RuntimeException('无法挪走插件目录:' . $pluginPath); - } + // 跨根改名经 SafeFs:两端根内限定 + 拒软链,失败显式报错不降级复制 + SafeFs::moveGuarded($pluginPath, $backup, [$this->pluginDir], [$this->workDir]); $journal->mark($id, 'removed'); $this->registry->recordUninstall($app, false); $unregistered = true; @@ -108,7 +108,7 @@ public function uninstall(string $app, string $dataPolicy = 'keep'): array $pending = array_merge($report['problems'], $report['conflicts']); throw new \RuntimeException('插件契约收集未通过'); } - PackageJournal::removeTree($backup); + SafeFs::removeTreeGuarded($backup, [$this->workDir]); $journal->mark($id, 'purged'); $journal->finish($id); @@ -120,7 +120,14 @@ public function uninstall(string $app, string $dataPolicy = 'keep'): array return $this->report('ok', $app, $current, 'done', $problems, false, false, false); } catch (\Throwable $error) { $problems = array_merge($pending, ['操作中断:' . $error->getMessage()]); - $restored = !is_dir($backup) || rename($backup, $pluginPath); + $restored = true; + if (is_dir($backup)) { + try { + SafeFs::moveGuarded($backup, $pluginPath, [$this->workDir], [$this->pluginDir]); + } catch (\Throwable) { + $restored = false; + } + } if (!$restored) { $problems[] = '插件目录未能恢复,需人工核查 ' . $pluginPath; } @@ -145,9 +152,29 @@ public function recover(): array $leftovers = glob($this->workDir . '/staged-*'); if ($leftovers !== false) { foreach ($leftovers as $dir) { - if (is_dir($dir)) { - PackageJournal::removeTree($dir); + if (!is_dir($dir)) { + continue; + } + try { + SafeFs::removeTreeGuarded($dir, [$this->workDir]); $notes[] = '清掉无 journal 的暂存目录 ' . $dir; + } catch (\Throwable $error) { + $notes[] = '暂存目录清理失败需人工核查 ' . $dir . ':' . $error->getMessage(); + } + } + } + // 无 journal 的隔离目录同属残留:验签前中断的唯一遗物 + $isolations = glob($this->workDir . '/iso-*'); + if ($isolations !== false) { + foreach ($isolations as $dir) { + if (!is_dir($dir)) { + continue; + } + try { + SafeFs::removeTreeGuarded($dir, [$this->workDir]); + $notes[] = '清掉中断操作的隔离目录 ' . $dir; + } catch (\Throwable $error) { + $notes[] = '隔离目录清理失败需人工核查 ' . $dir . ':' . $error->getMessage(); } } } @@ -200,17 +227,32 @@ private function recoverOrphanBackups(array &$notes): void } $pluginPath = $this->pluginDir . '/' . $match[1]; if (is_dir($pluginPath)) { - PackageJournal::removeTree($dir); - $notes[] = '清掉已完成操作的遗留备份 ' . $dir; - } elseif (rename($dir, $pluginPath)) { + try { + SafeFs::removeTreeGuarded($dir, [$this->workDir]); + $notes[] = '清掉已完成操作的遗留备份 ' . $dir; + } catch (\Throwable $error) { + $notes[] = '遗留备份清理失败需人工核查 ' . $dir . ':' . $error->getMessage(); + } + continue; + } + try { + SafeFs::moveGuarded($dir, $pluginPath, [$this->workDir], [$this->pluginDir]); $notes[] = '恢复孤儿备份 ' . $dir . ' 到 ' . $pluginPath; - } else { - $notes[] = '孤儿备份恢复失败,需人工核查 ' . $dir; + } catch (\Throwable $error) { + $notes[] = '孤儿备份恢复失败,需人工核查 ' . $dir . ':' . $error->getMessage(); } } } - /** @return array{result: string, app: ?string, version: ?string, stage: string, problems: list, sha256_verified: bool, signature_verified: bool, data_removed: bool, error_code: ?string} */ + /** + * 顺序:编译闸 → 隔离复制 → 副本验签 → 副本 inspect → 安装闸 → journal + * → 副本解包暂存 → 落位 → 记账 → 契约收集 → 清隔离目录。 + * TOCTOU 消解:zip 先流式拷入本操作独占的 iso- 隔离目录,之后 + * 验签/检查/解包只操作隔离副本,原路径不再使用;验签失败零载荷写入, + * 隔离副本随清理回收,清理失败如实进 problems 不吞掉。 + * + * @return array{result: string, app: ?string, version: ?string, stage: string, problems: list, sha256_verified: bool, signature_verified: bool, data_removed: bool, error_code: ?string} + */ private function applyPackage( string $zipFile, ?string $sha256, @@ -222,7 +264,57 @@ private function applyPackage( if ($this->isLocked()) { return $this->fail(null, null, 'gate', ['编译版或生产宿主不执行插件安装与升级'], $shaOk); } - // 先验签再解包:此时 zip 目录项都还没解析、零写入, + try { + $isolation = $this->isolatePackage($zipFile); + } catch (\Throwable $error) { + return $this->fail(null, null, 'isolate', ['操作中断:' . $error->getMessage()], $shaOk); + } + try { + $result = $this->applyIsolated($isolation . '/package.zip', $sha256, $signatureFile, $allowUnsigned, $kind, $shaOk); + } catch (\Throwable $error) { + $result = $this->fail(null, null, 'isolate', ['操作中断:' . $error->getMessage()], $shaOk); + } + try { + SafeFs::removeTreeGuarded($isolation, [$this->workDir]); + } catch (\Throwable $cleanup) { + $result['problems'][] = '隔离目录清理失败需人工核查 ' . $isolation . ':' . $cleanup->getMessage(); + } + + return $result; + } + + /** 包流式拷入本操作独占隔离目录,返回隔离目录绝对路径。 */ + private function isolatePackage(string $zipFile): string + { + if (!is_file($zipFile)) { + throw new \RuntimeException('安装包不存在:' . $zipFile); + } + $safe = SafeFs::open($this->workDir); + $name = 'iso-' . bin2hex(random_bytes(6)); + $safe->makeDir($name, 0700); + $source = fopen($zipFile, 'rb'); + if ($source === false) { + throw new \RuntimeException('无法读取安装包:' . $zipFile); + } + try { + $safe->writeStream($name . '/package.zip', $source, 0600); + } finally { + fclose($source); + } + + return $safe->root() . '/' . $name; + } + + /** @return array{result: string, app: ?string, version: ?string, stage: string, problems: list, sha256_verified: bool, signature_verified: bool, data_removed: bool, error_code: ?string} */ + private function applyIsolated( + string $zipFile, + ?string $sha256, + ?string $signatureFile, + bool $allowUnsigned, + string $kind, + bool $shaOk, + ): array { + // 先验签再解包:此时 zip 目录项都还没解析、零载荷写入, // 编译版闸在前面已整体拒绝,allowUnsigned 的口子进不了生产 $signature = PackageSignature::checkPackage($zipFile, $signatureFile, $this->trustStore->load(), $allowUnsigned); if ($signature['problems'] !== []) { @@ -255,23 +347,18 @@ private function applyPackage( $stage = 'extract'; $pending = []; try { - if (!is_dir($this->pluginDir) && !mkdir($this->pluginDir, 0755, true) && !is_dir($this->pluginDir)) { - throw new \RuntimeException('无法创建插件目录:' . $this->pluginDir); - } + $this->ensurePluginDir(); PackageArchive::unpack($zipFile, $seen['payload'], $staged, $manifest); $journal->setPaths($id, staged: $staged); $journal->mark($id, 'staged'); $stage = 'place'; if ($kind === 'upgrade' && is_dir($pluginPath)) { $journal->setPaths($id, backup: $backup); - if (!rename($pluginPath, $backup)) { - throw new \RuntimeException('无法挪走旧版插件目录:' . $pluginPath); - } + // 跨根改名经 SafeFs:两端根内限定 + 拒软链,失败显式报错不降级复制 + SafeFs::moveGuarded($pluginPath, $backup, [$this->pluginDir], [$this->workDir]); $journal->mark($id, 'backup'); } - if (!rename($staged, $pluginPath)) { - throw new \RuntimeException('无法落位插件目录:' . $pluginPath); - } + SafeFs::moveGuarded($staged, $pluginPath, [$this->workDir], [$this->pluginDir]); $journal->mark($id, 'placed'); $stage = 'register'; $digest = hash_file('sha256', $pluginPath . '/manifest.json'); @@ -285,7 +372,7 @@ private function applyPackage( throw new \RuntimeException('插件契约收集未通过'); } if (is_dir($backup)) { - PackageJournal::removeTree($backup); + SafeFs::removeTreeGuarded($backup, [$this->workDir]); } $journal->finish($id); @@ -298,6 +385,17 @@ private function applyPackage( } } + private function ensurePluginDir(): void + { + if (is_dir($this->pluginDir)) { + return; + } + if (!mkdir($this->pluginDir, 0755, true) && !is_dir($this->pluginDir)) { + throw new \RuntimeException('无法创建插件目录:' . $this->pluginDir); + } + chmod($this->pluginDir, 0755); + } + /** * @return list */ @@ -405,7 +503,7 @@ private function shaMatches(string $zipFile, ?string $sha256): bool private function journal(): PackageJournal { - return new PackageJournal($this->workDir); + return new PackageJournal($this->workDir, $this->pluginDir); } /** diff --git a/server/src/Module/Package/PackageJournal.php b/server/src/Module/Package/PackageJournal.php index 180ec5e4..ae838bba 100644 --- a/server/src/Module/Package/PackageJournal.php +++ b/server/src/Module/Package/PackageJournal.php @@ -7,6 +7,8 @@ namespace Sandadmin\Module\Package; +use Sandadmin\Infra\File\SafeFs; + /** * 插件操作的失败恢复 journal:工作目录下一操作一 JSON, * 记 kind、app、已完成步骤与 staged/backup/plugin 三个路径。 @@ -17,15 +19,16 @@ */ final class PackageJournal { - public function __construct(private readonly string $workDir) - { + public function __construct( + private readonly string $workDir, + private readonly ?string $pluginDir = null, + ) { } public function begin(string $kind, string $app, string $dataPolicy, string $plugin): string { - if (!is_dir($this->workDir) && (file_exists($this->workDir) || !mkdir($this->workDir, 0755, true)) && !is_dir($this->workDir)) { - throw new \RuntimeException('无法创建 journal 目录:' . $this->workDir); - } + // 工作目录即登记根:创建/解析失败(含被同名文件占位)在这里抛出 + SafeFs::open($this->workDir); $id = $kind . '-' . bin2hex(random_bytes(6)); $this->write($id, [ 'kind' => $kind, @@ -71,8 +74,14 @@ public function setPaths(string $id, ?string $staged = null, ?string $backup = n public function finish(string $id): void { $file = $this->fileOf($id); - if (is_file($file)) { - unlink($file); + if (!is_file($file)) { + return; + } + try { + SafeFs::open($this->workDir)->removeFile(basename($file)); + } catch (\Throwable $error) { + // 删不掉会在下次 recover 重放同一 journal,必须上报不能吞掉 + error_log('journal 清理失败 ' . $file . ' ' . $error::class . ': ' . $error->getMessage()); } } @@ -91,8 +100,7 @@ public function rollback(string $id): ?string $backup = $data['backup']; $plugin = $data['plugin']; if (is_string($staged) && is_dir($staged)) { - self::removeTree($staged); - $notes[] = '清掉暂存目录 ' . $staged; + $this->removeGuarded($staged, [$this->workDir], $notes, '清掉暂存目录 ' . $staged); } if ($data['kind'] === 'uninstall') { if (in_array('purged', $data['steps'], true)) { @@ -100,12 +108,12 @@ public function rollback(string $id): ?string } elseif (in_array('unregistered', $data['steps'], true)) { // 账本已记卸载,只能向前把遗留备份删完 if (is_string($backup) && is_dir($backup)) { - self::removeTree($backup); - $notes[] = '清掉已卸载插件的遗留备份 ' . $backup; + $this->removeGuarded($backup, [$this->workDir], $notes, '清掉已卸载插件的遗留备份 ' . $backup); } } elseif (is_string($backup) && is_dir($backup) && is_string($plugin)) { // 账本还没记卸载,目录挪回去 - if (!is_dir($plugin) && self::ensureParent($plugin) && rename($backup, $plugin)) { + $restored = !is_dir($plugin) && self::ensureParent($plugin) && $this->moveGuarded($backup, $plugin, $notes); + if ($restored) { $notes[] = '恢复插件目录 ' . $plugin; } else { $notes[] = '无法恢复插件目录 ' . $plugin; @@ -113,11 +121,10 @@ public function rollback(string $id): ?string } } else { if (in_array('placed', $data['steps'], true) && is_string($plugin) && is_dir($plugin)) { - self::removeTree($plugin); - $notes[] = '删除未完成的插件目录 ' . $plugin; + $this->removeGuarded($plugin, $this->pluginRoots($plugin), $notes, '删除未完成的插件目录 ' . $plugin); } if (is_string($backup) && is_dir($backup) && is_string($plugin) && !is_dir($plugin)) { - if (self::ensureParent($plugin) && rename($backup, $plugin)) { + if (self::ensureParent($plugin) && $this->moveGuarded($backup, $plugin, $notes)) { $notes[] = '恢复旧版插件目录 ' . $plugin; } else { $notes[] = '无法恢复旧版插件目录 ' . $plugin; @@ -156,42 +163,64 @@ public function recoverPending(): array } /** - * 符号链接只删链接本身,绝不递归:is_dir 跟随链接,不先判 is_link - * 会把插件目录里指向外部的软链当成真目录,删到插件目录外面。 + * 删除一律经 SafeFs 收口:lstat 不跟随符号链接,目标必须落在登记根内; + * 清理失败记进恢复笔记上报,不吞掉。 + * + * @param list $notes + * @param list $roots */ - public static function removeTree(string $dir): void + private function removeGuarded(string $path, array $roots, array &$notes, string $doneNote): void { - if (is_link($dir)) { - unlink($dir); - - return; + try { + SafeFs::removeTreeGuarded($path, $roots); + $notes[] = $doneNote; + } catch (\Throwable $error) { + $notes[] = '清理失败需人工核查 ' . $path . ':' . $error->getMessage(); } - if (!is_dir($dir)) { - return; - } - $items = scandir($dir); - if ($items === false) { - return; - } - foreach ($items as $item) { - if ($item === '.' || $item === '..') { - continue; - } - $path = $dir . '/' . $item; - if (is_link($path) || !is_dir($path)) { - unlink($path); - } else { - self::removeTree($path); - } + } + + /** + * 恢复挪回一律经 SafeFs 跨根改名:两端根内限定 + 拒符号链接, + * 失败记笔记返回 false,不静默降级复制。 + * + * @param list $notes + */ + private function moveGuarded(string $from, string $to, array &$notes): bool + { + try { + SafeFs::moveGuarded($from, $to, [$this->workDir], $this->pluginRoots($to)); + + return true; + } catch (\Throwable $error) { + $notes[] = '改名失败 ' . $from . ' → ' . $to . ':' . $error->getMessage(); + + return false; } - rmdir($dir); + } + + /** + * 插件侧登记根:构造时给了 pluginDir 就用它;没给(旧式调用)退化为 + * 目标父目录——根内限定弱化但 lstat 拒软链与失败上报仍然生效。 + * + * @return list + */ + private function pluginRoots(string $plugin): array + { + return [$this->pluginDir ?? dirname($plugin)]; } private static function ensureParent(string $dir): bool { $parent = dirname($dir); + if (is_dir($parent)) { + return true; + } + if (!mkdir($parent, 0755, true) && !is_dir($parent)) { + return false; + } + chmod($parent, 0755); - return is_dir($parent) || (mkdir($parent, 0755, true) && is_dir($parent)); + return true; } private function fileOf(string $id): string @@ -233,8 +262,10 @@ private function read(string $id): ?array private function write(string $id, array $data): void { $json = json_encode($data, JSON_UNESCAPED_SLASHES); - if (!is_string($json) || file_put_contents($this->fileOf($id), $json) === false) { - throw new \RuntimeException('无法写 journal:' . $this->fileOf($id)); + if (!is_string($json)) { + throw new \RuntimeException('无法编码 journal:' . $this->fileOf($id)); } + // 原子写:先落同目录临时文件再 rename,进程中断不留半个 JSON + SafeFs::open($this->workDir)->writeBytes(basename($this->fileOf($id)), $json, 0600); } } diff --git a/server/tests/Support/FailMidwayStream.php b/server/tests/Support/FailMidwayStream.php new file mode 100644 index 00000000..9368e01f --- /dev/null +++ b/server/tests/Support/FailMidwayStream.php @@ -0,0 +1,57 @@ +reads++; + if ($this->reads === 1) { + return str_repeat('x', min($count, 256)); + } + + return false; + } + + public function stream_eof(): bool + { + return false; + } + + public function stream_close(): void + { + } +} diff --git a/server/tests/Support/FileKit.php b/server/tests/Support/FileKit.php index 307ff148..bba1ebf4 100644 --- a/server/tests/Support/FileKit.php +++ b/server/tests/Support/FileKit.php @@ -17,7 +17,7 @@ use Sandadmin\Tests\Support\FakeFileRepository; use Sandadmin\Tests\Support\FakeIdempotencyStore; -/** 单元测试装配:真实 Flysystem 本地存储(临时目录)+ 内存仓储。 */ +/** 单元测试装配:真实本机存储(临时目录,走 SafeFs)+ 内存仓储。 */ final class FileKit { public static function scratchRoot(): string @@ -41,10 +41,11 @@ public static function removeTree(string $root): void continue; } $path = $item->getPathname(); - if ($item->isDir()) { - rmdir($path); - } else { + // 链接只解链:isDir 跟随符号链接,会把指向外部的链当真目录 rmdir + if ($item->isLink() || !$item->isDir()) { unlink($path); + } else { + rmdir($path); } } rmdir($root); diff --git a/server/tests/Support/PackageKit.php b/server/tests/Support/PackageKit.php index 0e8c6a01..bd653666 100644 --- a/server/tests/Support/PackageKit.php +++ b/server/tests/Support/PackageKit.php @@ -35,16 +35,105 @@ public static function fixtureZip(string $file, string $app, ?string $manifest = $zip->close(); } - /** @param array $entries zip 内路径 => 文本内容 */ - public static function makeZip(string $file, array $entries): void + /** + * @param array $entries zip 内路径 => 文本内容 + * @param string $archiveComment zip 归档注释:真实增大文件体积的合法 padding + * (EOCD 注释上限 65535 字节),测试 archive amplification 稀释口径用 + */ + public static function makeZip(string $file, array $entries, string $archiveComment = ''): void { $zip = self::openZip($file); foreach ($entries as $name => $content) { $zip->addFromString($name, $content); } + if ($archiveComment !== '') { + $zip->setArchiveComment($archiveComment); + } $zip->close(); } + /** + * 机械改写 zip 头里指定条目的 uncompressed size 字段(本地头与中央目录都改), + * 模拟中央目录声明说谎的恶意包:条目内容不变,CRC 仍对得上实际数据。 + * 只用于测试,fakeSize 须落在 uint32 内。 + */ + public static function forgeEntrySize(string $file, string $entry, int $fakeSize): void + { + $raw = file_get_contents($file); + if (!is_string($raw)) { + throw new \RuntimeException('无法读取测试 zip:' . $file); + } + $patched = 0; + // 本地文件头 PK\x03\x04:uncompressed size 在头偏移 22,名字在偏移 30 + $patched += self::patchHeaders($raw, "PK\x03\x04", 22, 26, 30, $entry, $fakeSize); + // 中央目录 PK\x01\x02:uncompressed size 在头偏移 24,名字在偏移 46 + $patched += self::patchHeaders($raw, "PK\x01\x02", 24, 28, 46, $entry, $fakeSize); + if ($patched === 0) { + throw new \RuntimeException('测试 zip 中找不到条目头:' . $entry); + } + if (file_put_contents($file, $raw) === false) { + throw new \RuntimeException('无法写回伪造后的测试 zip'); + } + } + + /** + * 机械改写 zip 头里指定条目的 compressed size 字段(本地头与中央目录都改)。 + * deflate 流自带结束标记,comp_size 改大不影响 ZipArchive 解压—— + * 所以它是攻击者可控字段,测试压缩比分母不得依赖它。 + */ + public static function forgeEntryCompSize(string $file, string $entry, int $fakeSize): void + { + $raw = file_get_contents($file); + if (!is_string($raw)) { + throw new \RuntimeException('无法读取测试 zip:' . $file); + } + // 本地文件头 comp_size 在头偏移 18,中央目录在头偏移 20 + $patched = self::patchHeaders($raw, "PK\x03\x04", 18, 26, 30, $entry, $fakeSize) + + self::patchHeaders($raw, "PK\x01\x02", 20, 28, 46, $entry, $fakeSize); + if ($patched === 0) { + throw new \RuntimeException('测试 zip 中找不到条目头:' . $entry); + } + if (file_put_contents($file, $raw) === false) { + throw new \RuntimeException('无法写回伪造后的测试 zip'); + } + } + + /** + * 扫描给定签名的所有头,名字匹配的条目把 uncompressed size 改写为 fakeSize。 + * 返回改写的头数;按引用直接改 $raw。 + */ + private static function patchHeaders( + string &$raw, + string $signature, + int $sizeOffset, + int $nameLengthOffset, + int $nameOffset, + string $entry, + int $fakeSize, + ): int { + $patched = 0; + $position = 0; + $length = strlen($raw); + while (($found = strpos($raw, $signature, $position)) !== false) { + $position = $found + 1; + if ($found + $nameOffset > $length) { + continue; + } + $nameLength = unpack('vlen', substr($raw, $found + $nameLengthOffset, 2)); + if (!is_array($nameLength) || !is_int($nameLength['len'])) { + continue; + } + $name = substr($raw, $found + $nameOffset, $nameLength['len']); + if ($name !== $entry) { + continue; + } + $raw = substr_replace($raw, pack('V', $fakeSize), $found + $sizeOffset, 4); + $patched++; + } + + return $patched; + } + public static function fixtureDir(string $app): string { return self::repoRoot() . '/server/tests/Fixtures/plugin/' . $app; diff --git a/server/tests/Unit/Infra/File/SafeFsTest.php b/server/tests/Unit/Infra/File/SafeFsTest.php new file mode 100644 index 00000000..89e44016 --- /dev/null +++ b/server/tests/Unit/Infra/File/SafeFsTest.php @@ -0,0 +1,475 @@ +dir = FileKit::scratchRoot(); + if (!mkdir($this->dir, 0755, true) && !is_dir($this->dir)) { + self::fail('无法创建临时目录'); + } + } + + protected function tearDown(): void + { + if ($this->dir !== '' && is_dir($this->dir)) { + FileKit::removeTree($this->dir); + $this->dir = ''; + } + } + + public function testWriteAndReadLegitFile(): void + { + $safe = $this->open('root'); + + $safe->writeBytes('sub/dir/hello.txt', '内容-abc', 0644); + + self::assertFileExists($safe->root() . '/sub/dir/hello.txt'); + self::assertSame('内容-abc', file_get_contents($safe->root() . '/sub/dir/hello.txt')); + self::assertSame('file', $safe->kind('sub/dir/hello.txt')); + self::assertNull($safe->kind('sub/dir/missing.txt')); + self::assertSame('dir', $safe->kind('sub/dir')); + } + + public function testExplicitPermissionBits(): void + { + $safe = $this->open('root'); + $safe->writeBytes('a.txt', 'x', 0640); + $safe->makeDir('deep', 0750); + + $filePerm = fileperms($safe->root() . '/a.txt'); + $dirPerm = fileperms($safe->root() . '/deep'); + self::assertIsInt($filePerm); + self::assertIsInt($dirPerm); + // 显式 chmod 生效,不依赖 umask 巧合 + self::assertSame(0640, $filePerm & 0777); + self::assertSame(0750, $dirPerm & 0777); + } + + public function testWriteStreamCopiesChunked(): void + { + $safe = $this->open('root'); + $payload = str_repeat('0123456789', 5000); + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, $payload); + rewind($stream); + + $written = $safe->writeStream('big.bin', $stream, 0644); + fclose($stream); + + self::assertSame(strlen($payload), $written); + self::assertSame(strlen($payload), filesize($safe->root() . '/big.bin')); + } + + public function testMoveWithinSucceeds(): void + { + $safe = $this->open('root'); + $safe->writeBytes('from.txt', 'x'); + + $safe->moveWithin('from.txt', 'to.txt'); + + self::assertFileDoesNotExist($safe->root() . '/from.txt'); + self::assertFileExists($safe->root() . '/to.txt'); + } + + public function testMoveToAcrossRootsSucceeds(): void + { + $from = $this->open('work'); + $to = $this->open('plugin'); + $from->writeBytes('staged/manifest.json', '{}'); + + $from->moveTo($to, 'staged', 'sand-hello'); + // 跨根目录改名 + self::assertFileExists($to->root() . '/sand-hello/manifest.json'); + self::assertDirectoryDoesNotExist($from->root() . '/staged'); + } + + public function testRemoveTreeDeletesRealTree(): void + { + $safe = $this->open('root'); + $safe->writeBytes('tree/sub/file.txt', 'x'); + + $safe->removeTree('tree'); + + self::assertDirectoryDoesNotExist($safe->root() . '/tree'); + } + + public function testDotDotRejected(): void + { + $safe = $this->open('root'); + $this->expectException(SafeFsException::class); + $this->expectExceptionMessageMatches('/\.\./'); + $safe->writeBytes('../escape.txt', 'x'); + } + + public function testNestedDotDotRejected(): void + { + $safe = $this->open('root'); + try { + $safe->writeBytes('sub/../../escape.txt', 'x'); + self::fail('嵌套 .. 段未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::TRAVERSAL, $error->reason); + } + self::assertFileDoesNotExist($this->dir . '/escape.txt'); + } + + public function testAbsolutePathRejected(): void + { + $safe = $this->open('root'); + $this->expectException(SafeFsException::class); + $safe->writeBytes('/etc/passwd-copy', 'x'); + } + + public function testDriveLetterRejected(): void + { + $safe = $this->open('root'); + $this->expectException(SafeFsException::class); + $safe->writeBytes('C:/windows/system32/evil', 'x'); + } + + public function testBackslashVariantRejected(): void + { + $safe = $this->open('root'); + try { + $safe->writeBytes('sub\\..\\..\\evil', 'x'); + self::fail('反斜杠变体未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::TRAVERSAL, $error->reason); + } + } + + public function testNulByteRejected(): void + { + $safe = $this->open('root'); + try { + $safe->writeBytes("evil\0.txt", 'x'); + self::fail('NUL 字节未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::ENCODING_BYPASS, $error->reason); + } + } + + public function testPercentEncodedTraversalRejected(): void + { + $safe = $this->open('root'); + try { + $safe->writeBytes('%2e%2e/escape.txt', 'x'); + self::fail('百分号编码穿越未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::ENCODING_BYPASS, $error->reason); + } + } + + public function testDoubleEncodedTraversalRejected(): void + { + $safe = $this->open('root'); + // %252e 解码一轮得 %2e,再一轮得 .:双重编码绕过与正写同罪 + try { + $safe->writeBytes('%252e%252e/escape.txt', 'x'); + self::fail('双重编码穿越未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::ENCODING_BYPASS, $error->reason); + } + } + + public function testHarmlessPercentNameAccepted(): void + { + $safe = $this->open('root'); + // 100% 不是合法编码三联,解码不变,不得误伤 + $safe->writeBytes('100%-off.txt', 'x'); + self::assertFileExists($safe->root() . '/100%-off.txt'); + } + + public function testWriteThroughSymlinkedDirRejected(): void + { + $outside = $this->dir . '/outside'; + mkdir($outside, 0755, true); + $safe = $this->open('root'); + self::assertTrue(symlink($outside, $safe->root() . '/linked')); + + try { + $safe->writeBytes('linked/evil.txt', 'x'); + self::fail('经软链目录写入未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::SYMLINK, $error->reason); + } + self::assertFileDoesNotExist($outside . '/evil.txt'); + } + + public function testWriteOntoSymlinkFileRejected(): void + { + $outside = $this->dir . '/outside.txt'; + file_put_contents($outside, 'keep'); + $safe = $this->open('root'); + self::assertTrue(symlink($outside, $safe->root() . '/link.txt')); + + try { + $safe->writeBytes('link.txt', 'evil'); + self::fail('写入符号链接未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::SYMLINK, $error->reason); + } + self::assertSame('keep', file_get_contents($outside)); + } + + public function testMiddleSymlinkComponentRejectedEvenInsideRoot(): void + { + // 链接指向根内也算拒绝:任一级是符号链接即拒,不看指向哪里 + $safe = $this->open('root'); + $safe->makeDir('real', 0755); + self::assertTrue(symlink($safe->root() . '/real', $safe->root() . '/alias')); + + try { + $safe->writeBytes('alias/file.txt', 'x'); + self::fail('根内中间级软链未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::SYMLINK, $error->reason); + } + } + + public function testRemoveTreeNeverFollowsSymlinks(): void + { + // 1d M3 事故形态:树里混着指向根外的软链,删除只能解链, + // 根外目标一个字节都不能少 + $outside = $this->dir . '/outside'; + mkdir($outside, 0755, true); + file_put_contents($outside . '/keep.txt', 'stay'); + $safe = $this->open('root'); + $safe->writeBytes('tree/sub/file.txt', 'x'); + self::assertTrue(symlink($outside, $safe->root() . '/tree/dir-link')); + self::assertTrue(symlink($outside . '/keep.txt', $safe->root() . '/tree/file-link')); + self::assertTrue(symlink($this->dir . '/missing', $safe->root() . '/tree/dangling')); + + $safe->removeTree('tree'); + + self::assertDirectoryDoesNotExist($safe->root() . '/tree'); + self::assertDirectoryExists($outside); + self::assertSame('stay', file_get_contents($outside . '/keep.txt')); + } + + public function testRemoveTreeOnSymlinkTargetRejected(): void + { + // 删除目标路径中间级是软链:拒绝,绝不跟随出去删根外内容 + $outside = $this->dir . '/outside'; + mkdir($outside . '/sub', 0755, true); + file_put_contents($outside . '/sub/keep.txt', 'stay'); + $safe = $this->open('root'); + self::assertTrue(symlink($outside, $safe->root() . '/linked')); + + try { + $safe->removeTree('linked/sub'); + self::fail('经软链中间级删除未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::SYMLINK, $error->reason); + } + self::assertSame('stay', file_get_contents($outside . '/sub/keep.txt')); + } + + public function testRemoveTreeOnLinkItselfOnlyUnlinks(): void + { + $target = $this->dir . '/target'; + mkdir($target, 0755, true); + file_put_contents($target . '/keep.txt', 'stay'); + $safe = $this->open('root'); + self::assertTrue(symlink($target, $safe->root() . '/link')); + + $safe->removeTree('link'); + + self::assertFalse(is_link($safe->root() . '/link')); + self::assertSame('stay', file_get_contents($target . '/keep.txt')); + } + + public function testMoveSymlinkRejected(): void + { + $safe = $this->open('root'); + $safe->writeBytes('real.txt', 'x'); + self::assertTrue(symlink($safe->root() . '/real.txt', $safe->root() . '/link.txt')); + + try { + $safe->moveWithin('link.txt', 'moved.txt'); + self::fail('移动符号链接未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::SYMLINK, $error->reason); + } + } + + public function testRemoveTreeGuardedRejectsOutsideRoot(): void + { + $safe = $this->open('root'); + $outside = $this->dir . '/outside'; + mkdir($outside, 0755, true); + + try { + SafeFs::removeTreeGuarded($outside, [$safe->root()]); + self::fail('根外删除未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::OUTSIDE_ROOT, $error->reason); + } + self::assertDirectoryExists($outside); + } + + public function testMoveGuardedCrossRootRejectsSymlinkSource(): void + { + $work = $this->open('work'); + $plugin = $this->open('plugin'); + $outside = $this->dir . '/outside'; + mkdir($outside, 0755, true); + self::assertTrue(symlink($outside, $work->root() . '/staged-x')); + + try { + SafeFs::moveGuarded($work->root() . '/staged-x', $plugin->root() . '/app', [$work->root()], [$plugin->root()]); + self::fail('软链源跨根改名未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::SYMLINK, $error->reason); + } + } + + public function testCaseInsensitiveRootBinding(): void + { + // 大小写归一判定:候选路径与登记根仅大小写不同仍按根内处理 + // (语义对齐 macOS 开发机与 Linux 生产),实际落点按 realpath 定型根 + $safe = $this->open('root'); + $safe->writeBytes('a.txt', 'x'); + $upper = strtoupper($safe->root()); + + try { + SafeFs::removeTreeGuarded($upper . '/missing.txt', [$safe->root()]); + } catch (SafeFsException $error) { + self::assertNotSame( + SafeFsException::OUTSIDE_ROOT, + $error->reason, + '仅大小写不同的拼写不应判根外', + ); + } + // 合法文件未被误伤 + self::assertFileExists($safe->root() . '/a.txt'); + } + + public function testAtomicWriteLeavesNoTempResidue(): void + { + $safe = $this->open('root'); + $safe->writeBytes('done.txt', str_repeat('x', 100000)); + + $leftovers = glob($safe->root() . '/.tmp-*'); + self::assertSame([], $leftovers === false ? [] : $leftovers); + self::assertSame(100000, filesize($safe->root() . '/done.txt')); + } + + public function testOverwrittenFileNeverTruncatedMidway(): void + { + // 唯一名临时文件 + rename 落位:并发写同一目标不互相截断, + // 任一时刻读到的要么是完整旧版要么是完整新版 + $safe = $this->open('root'); + $safe->writeBytes('shared.txt', str_repeat('a', 5000)); + $safe->writeBytes('shared.txt', str_repeat('b', 5000)); + + $content = file_get_contents($safe->root() . '/shared.txt'); + self::assertIsString($content); + self::assertTrue( + $content === str_repeat('a', 5000) || $content === str_repeat('b', 5000), + '读到截断的半成品', + ); + self::assertSame(str_repeat('b', 5000), $content); + } + + public function testWriteFailureCleansTemp(): void + { + // 可读但中途失败的流:第一块真实写入临时文件后第二次读取返回 false, + // 覆盖「临时文件已创建、已写部分内容之后失败」的回收路径 + FailMidwayStream::register(); + $stream = fopen(FailMidwayStream::SCHEME . '://x', 'rb'); + self::assertIsResource($stream); + $safe = $this->open('root'); + + try { + $safe->writeStream('fail.bin', $stream); + self::fail('中途失败的流写入未被拒绝'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::WRITE_FAILED, $error->reason); + } finally { + fclose($stream); + } + + $leftovers = glob($safe->root() . '/.tmp-*'); + self::assertSame([], $leftovers === false ? [] : $leftovers, '中途失败后临时文件必须回收'); + self::assertFileDoesNotExist($safe->root() . '/fail.bin'); + } + + public function testWriteStreamMaxBytesHardCutoff(): void + { + // 实际字节硬切断:源长度超过上限即中止,不越过上限、不落位、不留临时文件 + $safe = $this->open('root'); + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, str_repeat('z', 10000)); + rewind($stream); + + try { + $safe->writeStream('capped.bin', $stream, 0644, 9000); + self::fail('超过字节上限的写入未被硬切断'); + } catch (SafeFsException $error) { + self::assertSame(SafeFsException::SIZE_EXCEEDED, $error->reason); + } finally { + fclose($stream); + } + + self::assertFileDoesNotExist($safe->root() . '/capped.bin'); + $leftovers = glob($safe->root() . '/.tmp-*'); + self::assertSame([], $leftovers === false ? [] : $leftovers, '硬切断后临时文件必须回收'); + } + + public function testWriteStreamWithinMaxBytesPasses(): void + { + // 上限内合法写入不得误伤;正好踩线的长度也允许(超一块才切断) + $safe = $this->open('root'); + foreach ([4000, 5000] as $index => $length) { + $stream = fopen('php://temp', 'w+b'); + self::assertIsResource($stream); + fwrite($stream, str_repeat('z', $length)); + rewind($stream); + $written = $safe->writeStream('ok' . $index . '.bin', $stream, 0644, 5000); + fclose($stream); + self::assertSame($length, $written); + self::assertSame($length, filesize($safe->root() . '/ok' . $index . '.bin')); + } + } + + public function testRemoveTreeFailureReportedNotSwallowed(): void + { + $safe = $this->open('root'); + // 删除登记根本身必须显式拒绝,而不是静默成功 + try { + $safe->removeTree('.'); + self::fail('删除登记根未被拒绝'); + } catch (SafeFsException $error) { + self::assertNotSame('', $error->getMessage()); + } + } + + private function open(string $sub): SafeFs + { + return SafeFs::open($this->dir . '/' . $sub); + } +} diff --git a/server/tests/Unit/Module/Package/PackageArchiveTest.php b/server/tests/Unit/Module/Package/PackageArchiveTest.php index 0a2c2636..579a4b1d 100644 --- a/server/tests/Unit/Module/Package/PackageArchiveTest.php +++ b/server/tests/Unit/Module/Package/PackageArchiveTest.php @@ -206,6 +206,396 @@ public function testExtractWritesSubtreeAndRootManifest(): void self::assertSame('sand-hello', $parsed['manifest']?->app); } + public function testCaseVariantVendorRejected(): void + { + $this->assertRejected(['plugin/sand-hello/Vendor/pkg/a.php' => 'x'], 'Vendor'); + } + + public function testCaseVariantNodeModulesRejected(): void + { + $this->assertRejected(['web/NODE_MODULES/pkg/index.js' => 'x'], 'NODE_MODULES'); + } + + public function testCaseVariantInstallSqlRejected(): void + { + $this->assertRejected(['plugin/sand-hello/Install.SQL' => 'select 1'], 'Install.SQL'); + } + + public function testCaseVariantEnvRejected(): void + { + $this->assertRejected(['plugin/sand-hello/.ENV' => 'SECRET=1'], '.ENV'); + } + + public function testCaseVariantPharRejected(): void + { + $this->assertRejected(['plugin/sand-hello/APP.PHAR' => 'x'], '.PHAR'); + } + + public function testCaseVariantSoRejected(): void + { + $this->assertRejected(['plugin/sand-hello/LIB.SO' => 'x'], '.SO'); + } + + public function testPercentEncodedTraversalEntryRejected(): void + { + $this->assertRejected(['plugin/sand-hello/%2e%2e/evil.php' => 'x'], '解码后'); + } + + public function testDoubleEncodedTraversalEntryRejected(): void + { + $this->assertRejected(['plugin/sand-hello/%252e%252e/evil.php' => 'x'], '解码后'); + } + + public function testBackslashEntryRejected(): void + { + $this->assertRejected(['plugin\\sand-hello\\evil.php' => 'x'], '反斜杠'); + } + + public function testEntryCountLimitRejected(): void + { + $entries = ['manifest.json' => PackageKit::fixtureManifest('sand-hello')]; + for ($i = 0; $i < 8; $i++) { + $entries['plugin/sand-hello/f' . $i . '.php'] = 'zip('manyentries'); + PackageKit::makeZip($file, $entries); + + $seen = PackageArchive::inspect($file, null, ['max_entries' => 4]); + + self::assertNull($seen['manifest']); + self::assertStringContainsString('条目数', implode("\n", $seen['problems'])); + } + + public function testTotalSizeLimitRejected(): void + { + $file = $this->zip('bigtotal'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + // 随机内容压缩率低,声明尺寸即实际尺寸 + 'plugin/sand-hello/big.bin' => bin2hex(random_bytes(4096)), + ]); + + $seen = PackageArchive::inspect($file, null, ['max_total_bytes' => 4096]); + + self::assertNull($seen['manifest']); + self::assertStringContainsString('总大小', implode("\n", $seen['problems'])); + } + + public function testCompressionRatioLimitRejected(): void + { + $file = $this->zip('ratiobomb'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + // 全零内容压缩比数百倍,典型 zip bomb 形态 + 'plugin/sand-hello/bomb.bin' => str_repeat('0', 200000), + ]); + + $seen = PackageArchive::inspect($file, null, ['max_ratio' => 10.0]); + + self::assertNull($seen['manifest']); + self::assertStringContainsString('压缩比', implode("\n", $seen['problems'])); + } + + public function testRatioBombRejectedAtDefaultLimits(): void + { + $file = $this->zip('ratiobomb-default'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/bomb.bin' => str_repeat('0', 200000), + ]); + + // 缺省上限 100:200k 全零压缩比远超,正写包则远低于此 + $seen = PackageArchive::inspect($file, null); + + self::assertNull($seen['manifest']); + self::assertStringContainsString('压缩比', implode("\n", $seen['problems'])); + } + + public function testUnpackEnforcesLimitsAndCleansUp(): void + { + $file = $this->zip('limitunpack'); + PackageKit::fixtureZip($file, 'sand-hello'); + $seen = PackageArchive::inspect($file, null); + $manifest = $seen['manifest']; + $payload = $seen['payload']; + self::assertNotNull($manifest); + self::assertNotNull($payload); + $target = $this->dir . '/staged-limited'; + + try { + // 合法包 + 测试小上限:unpack 自己的上限闸必须挡住,与 inspect 无关 + PackageArchive::unpack($file, $payload, $target, $manifest, ['max_entries' => 1]); + self::fail('unpack 上限闸未拦住超限包'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('上限', $error->getMessage()); + } + } + + public function testUnpackFailureCleansPartialTree(): void + { + // 载荷条目合法但 zip 根缺 manifest.json:条目已写出才发现, + // 失败必须回收整个暂存目录,不留半成品 + $file = $this->zip('nomanifest-unpack'); + PackageKit::makeZip($file, [ + 'plugin/sand-hello/app/x.php' => ' 'openapi: 3.1.0', + ]); + $raw = file_get_contents(PackageKit::fixtureDir('sand-hello') . '/manifest.json'); + self::assertIsString($raw); + $parsed = PluginPackageManifest::parse($raw); + $manifest = $parsed['manifest']; + self::assertNotNull($manifest); + $target = $this->dir . '/staged-partial'; + + try { + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest); + self::fail('缺清单的 unpack 未被拒绝'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('manifest.json', $error->getMessage()); + } + + self::assertDirectoryDoesNotExist($target, '失败回收后暂存目录不应残留'); + } + + public function testLegitMixedCaseNamesAccepted(): void + { + // 合法大写文件名不得误伤:只有名单变体与正写同罪 + $file = $this->zip('legitcase'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/App/Controller/NoteController.php' => ' 'openapi: 3.1.0', + ]); + + $seen = PackageArchive::inspect($file, null); + + self::assertSame([], $seen['problems']); + self::assertSame('plugin/sand-hello/', $seen['payload']); + } + + public function testForgedDeclaredSizeCaughtByTotalCap(): void + { + // 中央目录 uncompressed size 伪造为 100,实际解压约 3MiB: + // 总大小上限必须按实际字节硬切断,且暂存目录整体回收 + $file = $this->zip('forged-cap'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/big.bin' => str_repeat("\0", 3 * 1024 * 1024), + ]); + PackageKit::forgeEntrySize($file, 'plugin/sand-hello/big.bin', 100); + $manifest = $this->helloManifest(); + $target = $this->dir . '/staged-forged-cap'; + + try { + // 比例上限放宽到不触发,单独验证总大小硬切断 + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest, [ + 'max_total_bytes' => 1024 * 1024, + 'max_ratio' => 100000.0, + ]); + self::fail('伪造声明尺寸的 unpack 未被总大小上限拦住'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('解压总大小超过上限', $error->getMessage()); + } + + self::assertDirectoryDoesNotExist($target, '失败回收后暂存目录不应残留'); + } + + public function testForgedDeclaredSizeCaughtByRatio(): void + { + // 同类伪造:声明极小让 inspect 预检放行,压缩比必须按实际解压字节递增复核命中 + $file = $this->zip('forged-ratio'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/big.bin' => str_repeat("\0", 3 * 1024 * 1024), + ]); + PackageKit::forgeEntrySize($file, 'plugin/sand-hello/big.bin', 100); + $manifest = $this->helloManifest(); + $target = $this->dir . '/staged-forged-ratio'; + + try { + // 总大小放宽到不触发,压缩比测试小上限 10:3MiB 全零实际比约千倍 + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest, [ + 'max_total_bytes' => 64 * 1024 * 1024, + 'max_ratio' => 10.0, + ]); + self::fail('伪造声明尺寸的 unpack 未被压缩比复核拦住'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('压缩比', $error->getMessage()); + } + + self::assertDirectoryDoesNotExist($target, '失败回收后暂存目录不应残留'); + } + + public function testForgedDeclaredSizeMismatchRejected(): void + { + // 不可压缩内容 + 伪造声明:比例与总大小都在限内时, + // 单条写完的声明/实际复核仍必须拒 + $file = $this->zip('forged-mismatch'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/blob.bin' => random_bytes(300 * 1024), + ]); + PackageKit::forgeEntrySize($file, 'plugin/sand-hello/blob.bin', 100); + $manifest = $this->helloManifest(); + $target = $this->dir . '/staged-forged-mismatch'; + + try { + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest, [ + 'max_total_bytes' => 64 * 1024 * 1024, + 'max_ratio' => 100000.0, + ]); + self::fail('声明与实际不符的 unpack 未被拒绝'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('不符', $error->getMessage()); + } + + self::assertDirectoryDoesNotExist($target, '失败回收后暂存目录不应残留'); + } + + public function testForgedDeclaredSizeRejectedAtDefaultRatio(): void + { + // 缺省上限下同类伪造也必须被拒:3MiB 全零实际压缩比远超 100 + $file = $this->zip('forged-default'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/big.bin' => str_repeat("\0", 3 * 1024 * 1024), + ]); + PackageKit::forgeEntrySize($file, 'plugin/sand-hello/big.bin', 100); + $manifest = $this->helloManifest(); + $target = $this->dir . '/staged-forged-default'; + + try { + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest); + self::fail('缺省上限下伪造声明尺寸的 unpack 未被拒绝'); + } catch (\RuntimeException $error) { + self::assertNotSame('', $error->getMessage()); + } + + self::assertDirectoryDoesNotExist($target, '失败回收后暂存目录不应残留'); + } + + public function testForgedCompSizeRejectedByAmplification(): void + { + // 只伪造 comp_size(985->30000)、不改 zip 实际字节、uncomp 声明诚实: + // comp_size 是攻击者可控字段,archive amplification 口径下伪造它毫无意义, + // 生产默认上限(不注入测试参数)即拒 + $file = $this->zip('forged-comp'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/big.bin' => str_repeat("\0", 1024 * 1024), + ]); + PackageKit::forgeEntryCompSize($file, 'plugin/sand-hello/big.bin', 30000); + $manifest = $this->helloManifest(); + $target = $this->dir . '/staged-forged-comp'; + + try { + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest); + self::fail('伪造 comp_size 的 unpack 未被拒绝'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('压缩比', $error->getMessage()); + } + + self::assertDirectoryDoesNotExist($target, '失败回收后暂存目录不应残留'); + } + + public function testPaddingDilutesAmplificationRatio(): void + { + // padding 口径对照:归档注释真实增大 zip 文件体积(不是头部字段), + // archive amplification 被真实稀释时按口径允许通过。 + // 该用例同时是辨别性证据:若分母误用 comp_size 合计(约几百字节), + // 压缩比约数百倍必被拒;只有分母是真实文件字节才能通过 + $file = $this->zip('padded'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/data.bin' => str_repeat("\0", 300 * 1024), + ], str_repeat('p', 60000)); + $zipFileBytes = filesize($file); + self::assertIsInt($zipFileBytes); + self::assertGreaterThan(60000, $zipFileBytes, 'padding 必须真实落进文件字节'); + $manifest = $this->helloManifest(); + $target = $this->dir . '/staged-padded'; + + // 300KB 实际解出 / 61KB+ 真实文件 ≈ 5 倍,测试上限 10 下按口径允许 + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest, [ + 'max_total_bytes' => 64 * 1024 * 1024, + 'max_ratio' => 10.0, + ]); + + self::assertFileExists($target . '/data.bin'); + self::assertSame(300 * 1024, filesize($target . '/data.bin')); + } + + public function testForgedManifestSizeCountsIntoBudget(): void + { + // 根清单伪造声明尺寸(10)+ 实际约 10KB:必须计入同一总预算, + // cap 4096 下拒绝且清理——验收者曾实测此形态落盘 14037 字节且成功 + $file = $this->zip('forged-manifest-cap'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello') . str_repeat(' ', 10000), + 'plugin/sand-hello/x.php' => str_repeat('a', 100), + ]); + PackageKit::forgeEntrySize($file, 'manifest.json', 10); + $manifest = $this->helloManifest(); + $target = $this->dir . '/staged-forged-manifest'; + + try { + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest, [ + 'max_total_bytes' => 4096, + 'max_ratio' => 100000.0, + ]); + self::fail('根清单超预算的 unpack 未被拒绝'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('解压总大小超过上限', $error->getMessage()); + } + + self::assertDirectoryDoesNotExist($target, '失败回收后暂存目录不应残留'); + } + + public function testForgedManifestSizeMismatchRejected(): void + { + // 预算放宽时,根清单声明/实际复核仍必须拒 + $file = $this->zip('forged-manifest-mismatch'); + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello') . str_repeat(' ', 10000), + 'plugin/sand-hello/x.php' => str_repeat('a', 100), + ]); + PackageKit::forgeEntrySize($file, 'manifest.json', 10); + $manifest = $this->helloManifest(); + $target = $this->dir . '/staged-manifest-mismatch'; + + try { + PackageArchive::unpack($file, 'plugin/sand-hello/', $target, $manifest, [ + 'max_total_bytes' => 64 * 1024 * 1024, + 'max_ratio' => 100000.0, + ]); + self::fail('根清单声明与实际不符的 unpack 未被拒绝'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('不符', $error->getMessage()); + } + + self::assertDirectoryDoesNotExist($target, '失败回收后暂存目录不应残留'); + } + + public function testLegitManifestWithinBudgetAccepted(): void + { + // 合法包不误伤:预算内容纳载荷+清单时正常落盘 + $file = $this->zip('legit-budget'); + PackageKit::fixtureZip($file, 'sand-hello'); + $seen = PackageArchive::inspect($file, null); + $manifest = $seen['manifest']; + $payload = $seen['payload']; + self::assertNotNull($manifest); + self::assertNotNull($payload); + $target = $this->dir . '/staged-legit-budget'; + + PackageArchive::unpack($file, $payload, $target, $manifest, [ + 'max_total_bytes' => 1024 * 1024, + 'max_ratio' => 100.0, + ]); + + self::assertFileExists($target . '/manifest.json'); + } + public function testMigrationsEntryRejected(): void { // 迁移执行器未实现:payload 子树里的 migrations 目录段必须拒收, @@ -291,6 +681,15 @@ public function testOtherProblemsKeepNullErrorCode(): void self::assertNull($seen['error_code']); } + private function helloManifest(): PluginPackageManifest + { + $parsed = PluginPackageManifest::parse(PackageKit::fixtureManifest('sand-hello')); + $manifest = $parsed['manifest']; + self::assertNotNull($manifest); + + return $manifest; + } + private function zip(string $name): string { return $this->dir . '/' . $name . '.zip'; diff --git a/server/tests/Unit/Module/Package/PackageExecutorTest.php b/server/tests/Unit/Module/Package/PackageExecutorTest.php index 85f6b284..107cff7c 100644 --- a/server/tests/Unit/Module/Package/PackageExecutorTest.php +++ b/server/tests/Unit/Module/Package/PackageExecutorTest.php @@ -581,7 +581,103 @@ public function testInstallReportsFailureWhenWorkdirIsFile(): void $result = $executor->install($this->zip('hello'), null, allowUnsigned: true); self::assertSame('failed', $result['result']); - self::assertSame('journal', $result['stage']); + // work-dir 被同名文件占位时隔离复制就建不起来:按失败报告返回而非崩溃 + self::assertSame('isolate', $result['stage']); + } + + public function testInstallLeavesNoIsolationResidue(): void + { + // TOCTOU 隔离目录(iso-*)在成功安装后必须清掉; + // 验签/inspect/unpack 只操作隔离副本,原 zip 路径不再使用 + $zip = $this->zip('hello'); + + $result = $this->executor()->install($zip, null, allowUnsigned: true); + + self::assertSame('ok', $result['result'], implode("\n", $result['problems'])); + $leftovers = glob($this->dir . '/work/iso-*'); + self::assertSame([], $leftovers === false ? [] : $leftovers, '隔离目录不应残留'); + } + + public function testFailedInstallLeavesNoIsolationResidue(): void + { + // 验签失败不解包零写入:隔离副本也随清理回收 + $signed = $this->signedZip('hello-iso-cleanup'); + PackageSigningKit::writeSidecar( + $signed['signature'], + PackageSigningKit::TEST_KID, + str_repeat("\x07", SODIUM_CRYPTO_SIGN_BYTES), + ); + + $result = $this->executor()->install($signed['zip'], null, $signed['signature']); + + self::assertSame('failed', $result['result']); + $leftovers = glob($this->dir . '/work/iso-*'); + self::assertSame([], $leftovers === false ? [] : $leftovers, '失败回收后隔离目录不应残留'); + } + + public function testInstallRejectsZipBomb(): void + { + // zip bomb 端到端:压缩比超限的包在 inspect 阶段拒绝,插件目录零写入 + $file = $this->dir . '/bomb.zip'; + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/bomb.bin' => str_repeat('0', 200000), + ]); + + $result = $this->executor()->install($file, null, allowUnsigned: true); + + self::assertSame('failed', $result['result']); + self::assertSame('inspect', $result['stage']); + self::assertStringContainsString('压缩比', implode("\n", $result['problems'])); + self::assertDirectoryDoesNotExist($this->pluginPath('sand-hello')); + } + + public function testInstallRejectsForgedCompSizeBomb(): void + { + // 验收者第二轮手法端到端:只伪造 comp_size(985->30000)不改 zip 实际字节。 + // archive amplification 口径下压缩比分母是隔离副本的真实文件字节, + // 伪造头部 comp_size 不再能稀释,端到端拒装、插件目录零写入 + $file = $this->dir . '/forged-comp-bomb.zip'; + PackageKit::makeZip($file, [ + 'manifest.json' => PackageKit::fixtureManifest('sand-hello'), + 'plugin/sand-hello/big.bin' => str_repeat("\0", 1024 * 1024), + ]); + PackageKit::forgeEntryCompSize($file, 'plugin/sand-hello/big.bin', 30000); + + $result = $this->executor()->install($file, null, allowUnsigned: true); + + self::assertSame('failed', $result['result']); + self::assertStringContainsString('压缩比', implode("\n", $result['problems'])); + self::assertDirectoryDoesNotExist($this->pluginPath('sand-hello')); + } + + public function testInstallRejectsCaseVariantVendor(): void + { + // 名单大小写归一:Vendor 变体与正写同罪,端到端拒装 + $file = $this->dir . '/casevendor.zip'; + PackageKit::fixtureZip($file, 'sand-hello', null, ['plugin/sand-hello/Vendor/x/a.php' => 'executor()->install($file, null, allowUnsigned: true); + + self::assertSame('failed', $result['result']); + self::assertSame('inspect', $result['stage']); + self::assertDirectoryDoesNotExist($this->pluginPath('sand-hello')); + } + + public function testInstallRejectsWhenPluginDirIsSymlink(): void + { + // 软链陷阱端到端:work/plugin 根侧任一环节是链接,落位必须失败 + // 而不是跟着链接写到根外。这里把已装插件目录换成软链再升级。 + $first = $this->executor()->install($this->zip('hello'), null, allowUnsigned: true); + self::assertSame('ok', $first['result'], implode("\n", $first['problems'])); + $pluginPath = $this->pluginPath('sand-hello'); + $movedPluginDir = $this->dir . '/real-plugin'; + self::assertTrue(rename($pluginPath, $movedPluginDir)); + self::assertTrue(symlink($movedPluginDir, $pluginPath)); + + $result = $this->executor()->upgrade($this->zip('hello-2', ['version' => '0.2.0']), null, allowUnsigned: true); + + self::assertSame('failed', $result['result'], '软链插件目录上的升级必须失败'); } public function testMemoryRegistryKeepsStateAcrossInstances(): void diff --git a/server/tests/Unit/Module/Package/PackageJournalTest.php b/server/tests/Unit/Module/Package/PackageJournalTest.php index 2dd676b7..ba3f5578 100644 --- a/server/tests/Unit/Module/Package/PackageJournalTest.php +++ b/server/tests/Unit/Module/Package/PackageJournalTest.php @@ -8,6 +8,7 @@ namespace Sandadmin\Tests\Unit\Module\Package; use PHPUnit\Framework\TestCase; +use Sandadmin\Infra\File\SafeFs; use Sandadmin\Module\Package\PackageJournal; use Sandadmin\Tests\Support\FileKit; @@ -245,7 +246,7 @@ public function testRemoveTreeUnlinksSymlinksWithoutFollowing(): void self::assertTrue(symlink($outside . '/keep.txt', $tree . '/file-link')); self::assertTrue(symlink($this->dir . '/missing', $tree . '/dangling')); - PackageJournal::removeTree($tree); + SafeFs::removeTreeGuarded($tree, [$this->dir]); self::assertDirectoryDoesNotExist($tree); self::assertDirectoryExists($outside); @@ -260,7 +261,7 @@ public function testRemoveTreeOnSymlinkOnlyRemovesLink(): void $link = $this->dir . '/link'; self::assertTrue(symlink($target, $link)); - PackageJournal::removeTree($link); + SafeFs::removeTreeGuarded($link, [$this->dir]); self::assertFalse(is_link($link)); self::assertDirectoryExists($target);