From eab418359bbc5095713dfa899c5b2c18b961132d Mon Sep 17 00:00:00 2001 From: supdger Date: Sat, 28 Nov 2026 05:56:44 -0800 Subject: [PATCH] =?UTF-8?q?feat(package):=20=E5=AE=9A=E7=A8=BF=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E4=BF=A1=E4=BB=BB=E6=A0=B9=E5=B9=B6=E6=94=B6=E5=8F=A3?= =?UTF-8?q?=E6=9E=84=E5=BB=BA=E6=9C=9F=E5=88=A4=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 统一 PackageOps 生产/编译判定到构建清单,防止环境变量放宽安装面;信任根文档定稿但 HR1-c 内嵌公钥/kid/吊销仍未实现。 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- server/build-manifest.json | 3 + server/docs/plugin-signing-keys.md | 85 +++++---- server/src/Infra/BuildKind.php | 39 +++++ server/src/Module/Package/PackageExecutor.php | 24 ++- server/src/Module/Package/PackageGate.php | 28 ++- server/src/Module/Package/PackageOps.php | 2 +- .../src/Module/Package/PackageSignature.php | 7 +- .../Integration/Module/Org/OrgFlowTest.php | 27 ++- .../Package/PackageContractLifecycleTest.php | 27 ++- .../Module/Package/PackageOpsTest.php | 4 +- server/tests/Unit/Infra/BuildKindTest.php | 165 ++++++++++++++++++ .../Module/Package/PackageExecutorTest.php | 99 ++++++++--- .../Unit/Module/Package/PackageGateTest.php | 103 +++++++---- .../Unit/Module/Package/PackageOpsTest.php | 6 +- tools/build-release.sh | 24 ++- tools/package-ops | 10 +- 16 files changed, 471 insertions(+), 182 deletions(-) create mode 100644 server/build-manifest.json create mode 100644 server/src/Infra/BuildKind.php create mode 100644 server/tests/Unit/Infra/BuildKindTest.php diff --git a/server/build-manifest.json b/server/build-manifest.json new file mode 100644 index 00000000..54ad5f6a --- /dev/null +++ b/server/build-manifest.json @@ -0,0 +1,3 @@ +{ + "build_kind": "development" +} diff --git a/server/docs/plugin-signing-keys.md b/server/docs/plugin-signing-keys.md index 795dd58b..cb8b470c 100644 --- a/server/docs/plugin-signing-keys.md +++ b/server/docs/plugin-signing-keys.md @@ -1,47 +1,55 @@ -# 插件包签名密钥管理规范(PLG-02) +# 插件包签名密钥管理规范(PLG-02,定稿) 本文是 SandAdmin 1.x 离线插件包签名的密钥管理规范:信任模型、信任根、 -私钥保管、轮换、吊销与验签语义。验签实现见 -`server/src/Module/Package/PackageSignature.php` 与 `tools/package-ops`, -本文是其中「信任根细则放行稿待定」对应的放行稿。 +私钥保管、轮换、吊销、构建门禁与验签语义。验签实现见 +`server/src/Module/Package/PackageSignature.php` 与 `tools/package-ops`。 ## 信任模型 -- 1.x 插件是完全受信代码,权限等同内核;签名是「包来自受信来源且未被 - 篡改」的准入证明,不构成沙箱,不对外暗示有隔离。 +- 插件等于完全信任:插件是权限等同内核的完全受信代码;宿主不提供 + 插件沙箱,文档与对外口径不得暗示存在隔离。签名只是「包来自受信 + 来源且未被篡改」的准入证明。 - 验签失败一律拒绝:未提供签名、签名文件不可读、公钥缺失或不可读、 签名与包字节不符,全部按验签失败处理——不解包、零写入。 ## 信任根与公钥管理 -- 官方发行公钥内嵌进内核发行包,随内核制品一起受签名保护;后台界面 - 不提供修改入口。 -- 部署方自有签名公钥只能经 CLI 加入本地信任白名单,加入动作记审计 - (操作人、时间、key id、公钥指纹);不经网页通道加公钥。 -- 每把公钥有 key id(kid);签名侧车文件携带 kid,验签按 kid 选钥, - 多密钥并存。 +- 官方验签公钥随内核发行版本内嵌分发,每把公钥带 key id(kid)与 + 指纹,并随内核制品一起受签名保护;后台界面不提供新增、修改或删除 + 入口。 +- 部署方自有签名公钥只能经 CLI 加入本地信任白名单;加入动作必须记 + 审计(操作人、时间、kid、公钥指纹),不得经网页通道加公钥。 +- 验签按签名侧车文件携带的 kid 选钥;未知 kid、无 kid 或 kid 不在 + 信任根/白名单内都按验签失败处理。 ## 签名格式 -- 算法:Ed25519,对插件包 zip 字节整体做分离签名;先验签后解包。 +- 算法固定为 Ed25519,对插件包 zip 字节整体做分离签名;所有安装、 + 升级与检查通道都必须先验签后解包。 - 目标格式:签名侧车文件为 JSON 信封—— `{ "kid": "", "alg": "Ed25519", "sig": "" }`。 -- 过渡格式(当前实现):签名与公钥各自成文件、内容为原样字节或 - base64,不带 kid;验签公钥由调用方逐次显式提供。 +- 当前裸签名/base64、公钥由 CLI 逐次显式传入只是开发过渡格式,不带 + kid、不构成信任根。编译版生产宿主禁止安装,因此该过渡格式进不了 + 生产安装路径。 ## 私钥保管 -- 发布私钥离线保管或放 HSM/云 KMS,保管人由技术总监指定并登记在案。 -- CI/构建环境只拿得到签名接口,拿不到私钥本体;每次签名动作双人复核。 +- 生产发布私钥由技术总监书面指定的一名密钥保管人持有,保管人登记在 + 受控密钥台账中;公开仓库文档不登记个人姓名,姓名与交接登记只写入 + 受控台账。私钥离线保管或放入 HSM/云 KMS。 +- 仓库、CI、应用服务器和后台账号都不是生产发布私钥的持有者;CI/构建 + 环境只拿得到签名接口,拿不到私钥本体;每次签名动作双人复核。 - 私钥永不进代码仓库、数据库、日志、Issue 或会话记录;任何环节不出 私钥明文。 +- 本仓不含生产签名私钥,也不含正式官方公钥;仓库内测试密钥只用于 + 开发/测试,不得充当正式信任根。 ## 轮换 -- 新公钥随内核版本下发,新旧公钥并存一段窗口期,窗口内任一受信公钥 - 验签通过的包都可安装。 -- 旧私钥停用即吊销(进吊销列表),不再产生新签名。 -- 轮换的计划、执行人、完成确认全部写审计。 +- 新公钥随内核版本下发,新旧公钥并存一段窗口期;窗口内任一未吊销 + 受信公钥验签通过的包都可安装。 +- 旧私钥停用即吊销,不再产生新签名。 +- 轮换计划、执行人、窗口起止、完成确认全部写审计。 ## 吊销 @@ -49,22 +57,31 @@ - 私钥疑似泄露:立即吊销该 kid、发安全公告、用新密钥重签受影响包; 疑似泄露的密钥一律作废,不得沿用。 -## 验签与安装门禁 - -- check / install / upgrade 三个动作统一先验签后解包。 -- 编译版(生产)宿主整体不执行插件安装与升级;未编译版只有在显式 - `--allow-unsigned` 参数下才放行无签名包——该口子只存在开发/构建 - 环境,不进生产。 -- 验签结果 `signature_verified` 如实落 journal 与输出:真实验签通过 - 才为 true,allow-unsigned 放行记 false。 +## 构建门禁与验签结果 + +- 编译版禁止插件安装、升级、卸载;生产只保留查看、启用、停用。 +- 生产/编译判定只认 `server/build-manifest.json` 的构建期标记, + `Sandadmin\Infra\BuildKind` 是 PackageOps 插件生命周期的唯一判定点: + 只有文件存在、JSON 合法且 `build_kind` 严格等于 `development` 时才是 + 未编译开发构建;文件缺失、不可读、JSON 非法、`build_kind` 缺失或任何 + 其他值都按编译制品处理。 +- 环境变量不能放宽构建门禁。`SAND_PACKAGE_OPS=1` 只是未编译开发构建里 + 的网页申请通道开关,不是生产判定;`APP_ENV`、`SAND_COMPILED` 不参与 + 构建形态判定。 +- 验签结果 `signature_verified` 如实出现在执行结果与 CLI 输出: + 真实验签通过才为 true;`--allow-unsigned` 放行必须为 false。`--allow-unsigned` + 只在未编译开发构建的显式 CLI 演练中可用,不能进入编译版。 ## 实现现状对照 | 规范条目 | 当前实现 | 差距 | | --- | --- | --- | +| 构建期标记与 fail-closed 判定 | 已实现:`server/build-manifest.json` 源码检出为 `development`,发布构建改写为 `compiled`;`BuildKind` 是 PackageOps 插件生命周期的唯一判定点 | 一致 | +| 编译版禁安装/升级/卸载,环境变量不能放宽 | 已实现:CLI 生命周期闸只看构建清单;网页闸经 `PackageGate` 委托 `BuildKind` | 一致 | | 先验签后解包、验签失败一律拒绝 | 已实现:Ed25519 分离签名,验签先于 zip 解析,问题清单即拒绝 | 一致 | -| 编译版/生产禁安装、unsigned 口子只留开发 | 已实现:编译闸在验签前整体拒绝;`allowUnsigned` 仅未编译版显式参数 | 一致 | -| 官方公钥内嵌内核发行包 | 未实现:公钥由调用方 `--pubkey` 逐次传入 | 待实现:信任根内嵌 + 本地白名单 | -| 部署方公钥白名单 + 审计 | 未实现 | 待实现 | -| 签名带 kid、多密钥并存 | 未实现:过渡格式无 kid | 待实现:侧车信封格式 | -| 吊销列表随内核更新下发 | 未实现 | 待实现 | +| `signature_verified` 真值 | 已实现:真验签通过才为 true,`allow-unsigned` 为 false | 一致 | +| 官方公钥内嵌内核发行包 | 未实现:公钥由调用方 `--pubkey` 逐次传入 | 后续 HR1-c:信任根内嵌 | +| 部署方公钥 CLI 白名单 + 审计 | 未实现 | 后续 HR1-c | +| 签名带 kid、多密钥并存 | 未实现:开发过渡格式无 kid | 后续 HR1-c:侧车信封格式 | +| 吊销列表随内核更新下发 | 未实现 | 后续 HR1-c | +| 隔离目录安装闭环 | 未实现 | 后续 HR1-c | diff --git a/server/src/Infra/BuildKind.php b/server/src/Infra/BuildKind.php new file mode 100644 index 00000000..55b0fdda --- /dev/null +++ b/server/src/Infra/BuildKind.php @@ -0,0 +1,39 @@ +devBuildMarker); + return BuildKind::compiledForFile($this->buildManifest); } private function shaMatches(string $zipFile, ?string $sha256): bool diff --git a/server/src/Module/Package/PackageGate.php b/server/src/Module/Package/PackageGate.php index 3bd227bc..719b5a1c 100644 --- a/server/src/Module/Package/PackageGate.php +++ b/server/src/Module/Package/PackageGate.php @@ -7,9 +7,11 @@ namespace Sandadmin\Module\Package; +use Sandadmin\Infra\BuildKind; + /** - * 网页安装开关。生产环境一律视为编译版,不允许在线安装或升级。 - * 未设置 SAND_COMPILED 时也按编译版处理,避免漏配就放开安装。 + * 网页安装开关。生产等于编译制品,构建形态只委托 BuildKind 判定; + * SAND_PACKAGE_OPS 只是未编译开发构建里的网页申请通道开关。 */ final class PackageGate { @@ -19,29 +21,23 @@ final class PackageGate public const COMPILED_PLUGIN_MESSAGE = '这个后台不能在网页上安装或升级插件,要加插件请找负责部署的人。'; - public static function production(): bool + public static function production(?string $buildManifest = null): bool { - $env = getenv('APP_ENV'); - - return is_string($env) && $env === 'production'; + return self::compiled($buildManifest); } - public static function compiled(): bool + public static function compiled(?string $buildManifest = null): bool { - if (self::production()) { - return true; - } - $flag = getenv('SAND_COMPILED'); - if (!is_string($flag) || $flag === '') { - return true; + if ($buildManifest !== null) { + return BuildKind::compiledForFile($buildManifest); } - return $flag !== '0'; + return BuildKind::compiled(); } - public static function opsEnabled(): bool + public static function opsEnabled(?string $buildManifest = null): bool { - if (self::compiled()) { + if (self::compiled($buildManifest)) { return false; } diff --git a/server/src/Module/Package/PackageOps.php b/server/src/Module/Package/PackageOps.php index df8c1cf9..45d9914f 100644 --- a/server/src/Module/Package/PackageOps.php +++ b/server/src/Module/Package/PackageOps.php @@ -19,7 +19,7 @@ /** * 插件与系统升级的网页入口。只登记元数据和生命周期,不执行上传内容,不 include 任何安装包。 - * 生产环境和编译版一律拒绝。官方目录里的条目也只是名称和版本,没有可执行代码。 + * 编译制品(生产)一律拒绝。官方目录里的条目也只是名称和版本,没有可执行代码。 */ final class PackageOps { diff --git a/server/src/Module/Package/PackageSignature.php b/server/src/Module/Package/PackageSignature.php index d5ca83eb..9b09df13 100644 --- a/server/src/Module/Package/PackageSignature.php +++ b/server/src/Module/Package/PackageSignature.php @@ -8,10 +8,9 @@ namespace Sandadmin\Module\Package; /** - * 离线包 Ed25519 分离签名验证。签名格式与信任根细则放行稿待定, - * 当前为「分离签名 + 调用方显式提供公钥」的过渡口径:公钥不内嵌内核, - * 由 CLI 参数传入;验签对 zip 字节整体做且先于解包,验不过一律拒绝。 - * 坏输入返回 false 或问题清单,不向外抛异常。 + * 离线包 Ed25519 分离签名底层验证。信任根、kid 选钥、白名单与吊销 + * 由信任根层负责;本类只按调用方给出的公钥验证 zip 字节。 + * 验签先于解包,坏输入返回 false 或问题清单,不向外抛异常。 */ final class PackageSignature { diff --git a/server/tests/Integration/Module/Org/OrgFlowTest.php b/server/tests/Integration/Module/Org/OrgFlowTest.php index b92025ca..a34ac1b6 100644 --- a/server/tests/Integration/Module/Org/OrgFlowTest.php +++ b/server/tests/Integration/Module/Org/OrgFlowTest.php @@ -628,18 +628,18 @@ public function testUserExportWritesDownloadableFile(): void } } - public function testProductionRefusesCompiledPluginInstall(): void + public function testEnvironmentDoesNotTightenDevelopmentBuild(): void { - $this->withPackageEnv('production', '0', '1', function (): void { + $this->withPackageOpsEnabled(function (): void { $owner = $this->ownerActor('13700009051', 'pkgowner', '甲测安装人'); + putenv('APP_ENV=production'); + putenv('SAND_COMPILED=1'); $ops = new PackageOps(self::$conn); - $refused = $ops->install('flow', $owner, 'req-pkg-prod'); - $this->assertSame(403, $refused['status']); - $this->assertSame('PLUGIN_OPERATION_FORBIDDEN', $refused['body']['code'] ?? null); - $this->assertSame(0, $this->rowsMatching("SELECT COUNT(*) FROM sand_system_plugin WHERE code = 'flow'")); + $accepted = $ops->install('flow', $owner, 'req-pkg-prod'); + $this->assertSame(200, $accepted['status']); $phar = $ops->upload('evil.phar', '{"code":"flow"}', $owner, 'req-pkg-phar'); $this->assertSame(403, $phar['status']); - $this->assertSame(0, $this->rowsMatching("SELECT COUNT(*) FROM sand_system_lifecycle_request WHERE executor_id = 'package-ops'")); + $this->assertSame(1, $this->rowsMatching("SELECT COUNT(*) FROM sand_system_lifecycle_request WHERE executor_id = 'package-ops'")); }); } @@ -649,7 +649,7 @@ public function testPackageInstallAdvancesWithoutExecutingCode(): void $previous = getenv('SAND_FILE_ROOT'); putenv('SAND_FILE_ROOT=' . $root); try { - $this->withPackageEnv('development', '0', '1', function (): void { + $this->withPackageOpsEnabled(function (): void { $owner = $this->ownerActor('13700009061', 'pkgdev', '甲测开发装'); $ops = new PackageOps(self::$conn); $compiled = $ops->upload('pack.json', '{"compiled":true,"code":"flow"}', $owner, 'req-pkg-c'); @@ -704,7 +704,7 @@ public function testPackageInstallAdvancesWithoutExecutingCode(): void public function testReinstallKeepsPluginExtension(): void { - $this->withPackageEnv('development', '0', '1', function (): void { + $this->withPackageOpsEnabled(function (): void { self::$conn->executeStatement("DELETE FROM sand_system_lifecycle_request WHERE target_code = 'flow'"); self::$conn->executeStatement("DELETE FROM sand_system_plugin_extension WHERE plugin_code = 'flow'"); self::$conn->executeStatement("DELETE FROM sand_system_plugin WHERE code = 'flow'"); @@ -747,7 +747,7 @@ public function testReinstallKeepsPluginExtension(): void public function testUninstallWithoutPurgeSuspendsResidueAndReinstallResumes(): void { - $this->withPackageEnv('development', '0', '1', function (): void { + $this->withPackageOpsEnabled(function (): void { $owner = $this->ownerActor('13700009072', 'pkgsusp', '甲测停用人'); $ops = new PackageOps(self::$conn); $accepted = $ops->install('flow', $owner, 'req-pkg-sus'); @@ -825,16 +825,15 @@ private function ownerActor(string $phone, string $username, string $nickname): return new OrgActor(OrgSql::int($user['id']), $nickname, null, true, ['*']); } - private function withPackageEnv(string $appEnv, string $compiled, string $ops, callable $work): void + /** @param callable(): void $work */ + private function withPackageOpsEnabled(callable $work): void { $saved = [ 'APP_ENV' => getenv('APP_ENV'), 'SAND_COMPILED' => getenv('SAND_COMPILED'), 'SAND_PACKAGE_OPS' => getenv('SAND_PACKAGE_OPS'), ]; - putenv('APP_ENV=' . $appEnv); - putenv('SAND_COMPILED=' . $compiled); - putenv('SAND_PACKAGE_OPS=' . $ops); + putenv('SAND_PACKAGE_OPS=1'); try { $work(); } finally { diff --git a/server/tests/Integration/Module/Package/PackageContractLifecycleTest.php b/server/tests/Integration/Module/Package/PackageContractLifecycleTest.php index 62a4ab91..af4f7eb4 100644 --- a/server/tests/Integration/Module/Package/PackageContractLifecycleTest.php +++ b/server/tests/Integration/Module/Package/PackageContractLifecycleTest.php @@ -73,7 +73,7 @@ public function testContractConflictFailsInstallAndRollsBack(): void $repo = $this->makeRepo(); try { $this->writeFragment($repo, 'sand-bad', self::BAD_FRAGMENT); - $this->withPackageEnv('development', '0', '1', function () use ($repo): void { + $this->withPackageOpsEnabled(function () use ($repo): void { $owner = $this->ownerActor('13700088001', 'pkgconflict', '契约冲突人'); $ops = new PackageOps(self::$conn, $repo); $accepted = $ops->install('flow', $owner, 'req-pkg-conflict'); @@ -113,7 +113,7 @@ public function testCleanFragmentInstallSucceedsAndWritesPluginRoutes(): void $repo = $this->makeRepo(); try { self::copyTree(self::fixtureDir('sand-hello'), $repo . '/server/plugin/sand-hello'); - $this->withPackageEnv('development', '0', '1', function () use ($repo): void { + $this->withPackageOpsEnabled(function () use ($repo): void { $owner = $this->ownerActor('13700088002', 'pkgcontract', '契约通过人'); $ops = new PackageOps(self::$conn, $repo); $accepted = $ops->install('flow', $owner, 'req-pkg-contract-ok'); @@ -181,25 +181,18 @@ private function ownerActor(string $phone, string $username, string $nickname): return new OrgActor(OrgSql::int($user['id']), $nickname, null, true, ['*']); } - private function withPackageEnv(string $appEnv, string $compiled, string $ops, callable $work): void + /** @param callable(): void $work */ + private function withPackageOpsEnabled(callable $work): void { - $saved = [ - 'APP_ENV' => getenv('APP_ENV'), - 'SAND_COMPILED' => getenv('SAND_COMPILED'), - 'SAND_PACKAGE_OPS' => getenv('SAND_PACKAGE_OPS'), - ]; - putenv('APP_ENV=' . $appEnv); - putenv('SAND_COMPILED=' . $compiled); - putenv('SAND_PACKAGE_OPS=' . $ops); + $saved = getenv('SAND_PACKAGE_OPS'); + putenv('SAND_PACKAGE_OPS=1'); try { $work(); } finally { - foreach ($saved as $name => $value) { - if (is_string($value) && $value !== '') { - putenv($name . '=' . $value); - } else { - putenv($name); - } + if (is_string($saved) && $saved !== '') { + putenv('SAND_PACKAGE_OPS=' . $saved); + } else { + putenv('SAND_PACKAGE_OPS'); } } } diff --git a/server/tests/Integration/Module/Package/PackageOpsTest.php b/server/tests/Integration/Module/Package/PackageOpsTest.php index a108f508..2681a9b1 100644 --- a/server/tests/Integration/Module/Package/PackageOpsTest.php +++ b/server/tests/Integration/Module/Package/PackageOpsTest.php @@ -60,7 +60,7 @@ private static function wipe(): void protected function setUp(): void { - foreach (['APP_ENV', 'SAND_COMPILED', 'SAND_PACKAGE_OPS'] as $name) { + foreach (['SAND_PACKAGE_OPS'] as $name) { $this->envBackup[$name] = getenv($name); } self::wipe(); @@ -81,8 +81,6 @@ protected function tearDown(): void private function opsOn(): void { - putenv('APP_ENV'); - putenv('SAND_COMPILED=0'); putenv('SAND_PACKAGE_OPS=1'); } diff --git a/server/tests/Unit/Infra/BuildKindTest.php b/server/tests/Unit/Infra/BuildKindTest.php new file mode 100644 index 00000000..b2f66014 --- /dev/null +++ b/server/tests/Unit/Infra/BuildKindTest.php @@ -0,0 +1,165 @@ + */ + private array $envBackup = []; + + private string $file = ''; + + protected function setUp(): void + { + foreach (['APP_ENV', 'SAND_COMPILED', 'SAND_PACKAGE_OPS'] as $name) { + $this->envBackup[$name] = getenv($name); + } + $file = tempnam(sys_get_temp_dir(), 'sand-build-kind-'); + if (!is_string($file)) { + self::fail('无法创建临时构建清单'); + } + $this->file = $file; + } + + protected function tearDown(): void + { + foreach ($this->envBackup as $name => $value) { + if ($value === false) { + putenv($name); + } else { + putenv($name . '=' . $value); + } + } + if ($this->file !== '' && is_file($this->file)) { + unlink($this->file); + } + } + + public function testBuildKindMatrix(): void + { + $cases = [ + 'development 严格命中' => ['{"build_kind":"development"}', false], + 'compiled 是编译制品' => ['{"build_kind":"compiled"}', true], + '未知值按编译制品' => ['{"build_kind":"staging"}', true], + '大小写不放宽' => ['{"build_kind":"Development"}', true], + '缺 build_kind 按编译制品' => ['{}', true], + 'JSON 非法按编译制品' => ['{"build_kind":"development"', true], + '非对象 JSON 按编译制品' => ['["development"]', true], + ]; + foreach ($cases as $label => [$content, $expected]) { + $this->writeManifest($content); + self::assertSame($expected, BuildKind::compiledForFile($this->file), $label); + } + } + + public function testMissingOrUnreadableFileIsCompiled(): void + { + self::assertTrue(BuildKind::compiledForFile($this->file . '.missing')); + $this->writeManifest('{"build_kind":"development"}'); + chmod($this->file, 0000); + try { + // root 忽略权限位时无法模拟不可读;缺失路径的 fail-closed 断言仍生效 + if (!is_readable($this->file)) { + self::assertTrue(BuildKind::compiledForFile($this->file), '不可读按编译制品'); + } + } finally { + chmod($this->file, 0600); + } + } + + public function testEnvironmentCannotChangeResult(): void + { + $development = '{"build_kind":"development"}'; + $compiled = '{"build_kind":"compiled"}'; + $combinations = [ + [null, null, null], + ['production', '0', '1'], + ['local', '1', '0'], + ['testing', '', '1'], + ]; + foreach ($combinations as [$appEnv, $compiledEnv, $opsEnv]) { + $this->setEnv($appEnv, $compiledEnv, $opsEnv); + $this->writeManifest($development); + self::assertFalse(BuildKind::compiledForFile($this->file)); + $this->writeManifest($compiled); + self::assertTrue(BuildKind::compiledForFile($this->file)); + } + } + + public function testDefaultReadsRepositoryManifest(): void + { + self::assertFileExists(dirname(__DIR__, 3) . '/build-manifest.json'); + self::assertFalse(BuildKind::compiled()); + } + + public function testManifestDecisionHasSingleSourceInSrc(): void + { + $root = dirname(__DIR__, 3); + $hits = []; + foreach ($this->phpFiles($root . '/src') as $file) { + $content = file_get_contents($file); + if (is_string($content) && str_contains($content, 'build-manifest.json')) { + $hits[] = substr($file, strlen($root) + 1); + } + } + sort($hits); + + self::assertSame(['src/Infra/BuildKind.php'], $hits); + } + + public function testPackageModuleDoesNotReadEnvironmentForBuildKind(): void + { + $root = dirname(__DIR__, 3); + foreach ($this->phpFiles($root . '/src/Module/Package') as $file) { + $content = file_get_contents($file); + self::assertIsString($content); + self::assertStringNotContainsString('SAND_COMPILED', $content, $file); + self::assertStringNotContainsString('APP_ENV', $content, $file); + } + } + + private function writeManifest(string $content): void + { + if (file_put_contents($this->file, $content) === false) { + self::fail('无法写入临时构建清单'); + } + } + + private function setEnv(?string $appEnv, ?string $compiledEnv, ?string $opsEnv): void + { + foreach (['APP_ENV' => $appEnv, 'SAND_COMPILED' => $compiledEnv, 'SAND_PACKAGE_OPS' => $opsEnv] as $name => $value) { + if ($value === null) { + putenv($name); + } else { + putenv($name . '=' . $value); + } + } + } + + /** @return list */ + private function phpFiles(string $root): array + { + $files = []; + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS), + ); + foreach ($iterator as $item) { + if (!$item instanceof \SplFileInfo || !$item->isFile() || $item->getExtension() !== 'php') { + continue; + } + $files[] = $item->getPathname(); + } + sort($files); + + return $files; + } +} diff --git a/server/tests/Unit/Module/Package/PackageExecutorTest.php b/server/tests/Unit/Module/Package/PackageExecutorTest.php index 04090374..bc0d6cdf 100644 --- a/server/tests/Unit/Module/Package/PackageExecutorTest.php +++ b/server/tests/Unit/Module/Package/PackageExecutorTest.php @@ -16,7 +16,7 @@ /** * 离线包生命周期闭环(无库):临时目录拼迷你仓 + 内存账本。 * 覆盖验签各条拒绝理由、安装闸、落位/记账/契约收集顺序、失败回滚与 journal 恢复。 - * SAND_COMPILED=0 才放行执行器;测试结束恢复环境变量。 + * 迷你仓写入 development 构建清单才放行执行器;测试结束恢复环境变量。 * Ed25519 测试钥在运行时生成、只落测试临时目录,不提交密钥文件。 */ final class PackageExecutorTest extends TestCase @@ -39,14 +39,16 @@ final class PackageExecutorTest extends TestCase /** @var string|false */ private string|false $appEnv = false; + /** @var string|false */ + private string|false $opsEnv = false; + private FakePluginRegistry $registry; protected function setUp(): void { $this->compiledEnv = getenv('SAND_COMPILED'); $this->appEnv = getenv('APP_ENV'); - putenv('SAND_COMPILED=0'); - putenv('APP_ENV'); + $this->opsEnv = getenv('SAND_PACKAGE_OPS'); $this->dir = FileKit::scratchRoot(); $this->repoDir = $this->dir . '/repo'; @@ -59,9 +61,9 @@ protected function setUp(): void if (!copy($source, $this->repoDir . '/contract/openapi.yaml')) { self::fail('无法复制宿主契约到临时仓'); } - // 开发构建标记:与源码检出同口径,临时仓默认带上; - // 需要验证「标记不在按编译版拒绝」的用例自行 unlink - file_put_contents($this->markerPath(), ''); + // 构建清单与源码检出同口径,临时仓默认是 development; + // 需要验证 fail-closed 的用例自行改写或 unlink + $this->writeBuildKind('development'); $this->registry = new FakePluginRegistry(); } @@ -77,6 +79,11 @@ protected function tearDown(): void } else { putenv('APP_ENV=' . $this->appEnv); } + if ($this->opsEnv === false) { + putenv('SAND_PACKAGE_OPS'); + } else { + putenv('SAND_PACKAGE_OPS=' . $this->opsEnv); + } if ($this->dir !== '' && is_dir($this->dir)) { FileKit::removeTree($this->dir); $this->dir = ''; @@ -503,7 +510,7 @@ public function testUninstallReportsFailureWhenWorkdirIsFile(): void if (!is_dir($this->pluginPath('sand-hello')) && !mkdir($this->pluginPath('sand-hello'), 0755, true)) { self::fail('无法创建插件目录'); } - $executor = new PackageExecutor($registry, $this->repoDir, $this->repoDir . '/server/plugin', $workDir, 'pgsql', $this->markerPath()); + $executor = new PackageExecutor($registry, $this->repoDir, $this->repoDir . '/server/plugin', $workDir, 'pgsql', $this->manifestPath()); $result = $executor->uninstall('sand-hello', 'keep'); @@ -516,7 +523,7 @@ public function testInstallReportsFailureWhenWorkdirIsFile(): void $workDir = $this->dir . '/work-file'; file_put_contents($workDir, 'x'); $registry = new FakePluginRegistry(); - $executor = new PackageExecutor($registry, $this->repoDir, $this->repoDir . '/server/plugin', $workDir, 'pgsql', $this->markerPath()); + $executor = new PackageExecutor($registry, $this->repoDir, $this->repoDir . '/server/plugin', $workDir, 'pgsql', $this->manifestPath()); $result = $executor->install($this->zip('hello'), null, allowUnsigned: true); @@ -538,23 +545,58 @@ public function testMemoryRegistryKeepsStateAcrossInstances(): void self::assertSame(['sand-hello' => '0.1.0'], $second->installedVersions()); } - public function testCompiledHostRefusesInstall(): void + public function testCompiledManifestRefusesUnsignedInstallEvenWhenEnvLooksOpen(): void { - putenv('SAND_COMPILED=1'); - // 编译版闸在验签之前整体拒绝,allowUnsigned 的口子进不了生产 + $this->writeBuildKind('compiled'); + putenv('SAND_COMPILED=0'); + putenv('SAND_PACKAGE_OPS=1'); + $zip = $this->zip('hello'); + foreach ([null, 'local'] as $appEnv) { + if ($appEnv === null) { + putenv('APP_ENV'); + } else { + putenv('APP_ENV=' . $appEnv); + } - $result = $this->executor()->install($this->zip('hello'), null, allowUnsigned: true); + $result = $this->executor()->install($zip, null, allowUnsigned: true); + + self::assertSame('failed', $result['result']); + self::assertSame('gate', $result['stage']); + self::assertFalse($result['signature_verified']); + $this->assertNoSideEffects('sand-hello'); + } + } + + public function testCompiledManifestRefusesSignedInstall(): void + { + $this->writeBuildKind('compiled'); + $signed = $this->signedZip('hello-signed-compiled'); + + $result = $this->executor()->install($signed['zip'], null, $signed['signature'], $signed['pubkey']); self::assertSame('failed', $result['result']); self::assertSame('gate', $result['stage']); - self::assertDirectoryDoesNotExist($this->pluginPath('sand-hello')); + self::assertFalse($result['signature_verified']); + $this->assertNoSideEffects('sand-hello'); + } + + public function testCompiledManifestRefusesUninstall(): void + { + $installed = $this->executor()->install($this->zip('hello'), null, allowUnsigned: true); + self::assertSame('ok', $installed['result'], implode("\n", $installed['problems'])); + $this->writeBuildKind('compiled'); + + $result = $this->executor()->uninstall('sand-hello', 'keep'); + + self::assertSame('failed', $result['result']); + self::assertSame('gate', $result['stage']); + self::assertDirectoryExists($this->pluginPath('sand-hello')); + self::assertSame('0.1.0', $this->registry->installedVersion('sand-hello')); } - public function testMissingDevBuildMarkerRefusesUnsignedInstall(): void + public function testMissingBuildManifestRefusesUnsignedInstall(): void { - // 发布制品没有开发构建标记:就算伪造 SAND_COMPILED=0 + --allow-unsigned, - // 也在 gate 阶段拒绝且零副作用 - unlink($this->markerPath()); + unlink($this->manifestPath()); $result = $this->executor()->install($this->zip('hello'), null, allowUnsigned: true); @@ -563,10 +605,10 @@ public function testMissingDevBuildMarkerRefusesUnsignedInstall(): void $this->assertNoSideEffects('sand-hello'); } - public function testMissingDevBuildMarkerRefusesSignedInstall(): void + public function testMissingBuildManifestRefusesSignedInstall(): void { - unlink($this->markerPath()); - $signed = $this->signedZip('hello-signed'); + unlink($this->manifestPath()); + $signed = $this->signedZip('hello-signed-missing'); $result = $this->executor()->install($signed['zip'], null, $signed['signature'], $signed['pubkey']); @@ -576,11 +618,11 @@ public function testMissingDevBuildMarkerRefusesSignedInstall(): void $this->assertNoSideEffects('sand-hello'); } - public function testMissingDevBuildMarkerRefusesUninstall(): void + public function testMissingBuildManifestRefusesUninstall(): void { $installed = $this->executor()->install($this->zip('hello'), null, allowUnsigned: true); self::assertSame('ok', $installed['result'], implode("\n", $installed['problems'])); - unlink($this->markerPath()); + unlink($this->manifestPath()); $result = $this->executor()->uninstall('sand-hello', 'keep'); @@ -647,13 +689,20 @@ private function executor(string $dbDriver = 'pgsql'): PackageExecutor $this->repoDir . '/server/plugin', $this->dir . '/work', $dbDriver, - $this->markerPath(), + $this->manifestPath(), ); } - private function markerPath(): string + private function manifestPath(): string { - return $this->repoDir . '/server/.sand-dev-build'; + return $this->repoDir . '/server/build-manifest.json'; + } + + private function writeBuildKind(string $buildKind): void + { + if (file_put_contents($this->manifestPath(), '{"build_kind":"' . $buildKind . '"}') === false) { + self::fail('无法写入临时构建清单'); + } } private function pluginPath(string $app): string diff --git a/server/tests/Unit/Module/Package/PackageGateTest.php b/server/tests/Unit/Module/Package/PackageGateTest.php index 9e366fec..74418687 100644 --- a/server/tests/Unit/Module/Package/PackageGateTest.php +++ b/server/tests/Unit/Module/Package/PackageGateTest.php @@ -10,17 +10,24 @@ use PHPUnit\Framework\TestCase; use Sandadmin\Module\Package\PackageGate; -/** 网页安装开关:环境变量矩阵,测后原样恢复。 */ +/** 网页安装开关:构建形态只看注入的构建清单,环境变量不能放宽。 */ final class PackageGateTest extends TestCase { /** @var array */ private array $envBackup = []; + private string $file = ''; + protected function setUp(): void { foreach (['APP_ENV', 'SAND_COMPILED', 'SAND_PACKAGE_OPS'] as $name) { $this->envBackup[$name] = getenv($name); } + $file = tempnam(sys_get_temp_dir(), 'sand-package-gate-'); + if (!is_string($file)) { + self::fail('无法创建临时构建清单'); + } + $this->file = $file; } protected function tearDown(): void @@ -32,58 +39,78 @@ protected function tearDown(): void putenv($name . '=' . $value); } } + if ($this->file !== '' && is_file($this->file)) { + unlink($this->file); + } } - private function env(?string $appEnv, ?string $compiled, ?string $ops): void + public function testCompiledOnlyComesFromBuildKind(): void { - foreach (['APP_ENV' => $appEnv, 'SAND_COMPILED' => $compiled, 'SAND_PACKAGE_OPS' => $ops] as $name => $value) { - if ($value === null) { - putenv($name); - } else { - putenv($name . '=' . $value); - } + $combinations = [ + [null, null], + ['production', '0'], + ['local', '1'], + ['local', '0'], + ['testing', '0'], + ]; + foreach ($combinations as [$appEnv, $compiledEnv]) { + $this->setEnv($appEnv, $compiledEnv, null); + $this->writeManifest('{"build_kind":"development"}'); + self::assertFalse(PackageGate::compiled($this->file)); + $this->writeManifest('{"build_kind":"compiled"}'); + self::assertTrue(PackageGate::compiled($this->file)); + } + } + + public function testMalformedUnknownAndMissingManifestAreCompiled(): void + { + foreach (['not-json', '{}', '{"build_kind":"staging"}'] as $content) { + $this->writeManifest($content); + self::assertTrue(PackageGate::compiled($this->file)); } + self::assertTrue(PackageGate::compiled($this->file . '.missing')); } - public function testProductionOnlyWhenEnvSaysSo(): void + public function testProductionAliasesCompiled(): void { - $this->env('production', null, null); - self::assertTrue(PackageGate::production()); - $this->env('local', null, null); - self::assertFalse(PackageGate::production()); - $this->env(null, null, null); - self::assertFalse(PackageGate::production()); + $this->setEnv('production', '0', '1'); + $this->writeManifest('{"build_kind":"development"}'); + self::assertFalse(PackageGate::production($this->file)); + $this->writeManifest('{"build_kind":"compiled"}'); + self::assertTrue(PackageGate::production($this->file)); } - public function testCompiledDefaultsTrue(): void + public function testOpsEnabledRequiresDevelopmentManifestAndOpsFlag(): void { - $this->env('local', null, null); - self::assertTrue(PackageGate::compiled(), '未设置 SAND_COMPILED 按编译版处理'); - $this->env('local', '', null); - self::assertTrue(PackageGate::compiled(), '空串同样按编译版'); - $this->env('local', '1', null); - self::assertTrue(PackageGate::compiled()); - $this->env('local', '0', null); - self::assertFalse(PackageGate::compiled()); + $this->writeManifest('{"build_kind":"development"}'); + $this->setEnv('production', '0', '1'); + self::assertTrue(PackageGate::opsEnabled($this->file), 'APP_ENV 与 SAND_COMPILED 不参与构建判定'); + $this->setEnv(null, null, '0'); + self::assertFalse(PackageGate::opsEnabled($this->file)); + $this->setEnv(null, null, null); + self::assertFalse(PackageGate::opsEnabled($this->file)); + + $this->writeManifest('{"build_kind":"compiled"}'); + $this->setEnv('local', '0', '1'); + self::assertFalse(PackageGate::opsEnabled($this->file), '编译清单下 ops 开关无效'); + self::assertFalse(PackageGate::opsEnabled($this->file . '.missing'), '清单缺失按编译制品'); } - public function testProductionImpliesCompiled(): void + private function writeManifest(string $content): void { - $this->env('production', '0', '1'); - self::assertTrue(PackageGate::compiled(), '生产环境无视 SAND_COMPILED=0'); + if (file_put_contents($this->file, $content) === false) { + self::fail('无法写入临时构建清单'); + } } - public function testOpsEnabledRequiresCompiledOffAndOpsFlag(): void + private function setEnv(?string $appEnv, ?string $compiledEnv, ?string $opsEnv): void { - $this->env('local', '0', '1'); - self::assertTrue(PackageGate::opsEnabled()); - $this->env('local', '0', '0'); - self::assertFalse(PackageGate::opsEnabled()); - $this->env('local', '0', null); - self::assertFalse(PackageGate::opsEnabled()); - $this->env('local', '1', '1'); - self::assertFalse(PackageGate::opsEnabled(), '编译版下 ops 开关无效'); - $this->env('production', '0', '1'); - self::assertFalse(PackageGate::opsEnabled()); + foreach (['APP_ENV' => $appEnv, 'SAND_COMPILED' => $compiledEnv, 'SAND_PACKAGE_OPS' => $opsEnv] as $name => $value) { + if ($value === null) { + putenv($name); + } else { + putenv($name . '=' . $value); + } + } } } diff --git a/server/tests/Unit/Module/Package/PackageOpsTest.php b/server/tests/Unit/Module/Package/PackageOpsTest.php index f976190c..cba04fe0 100644 --- a/server/tests/Unit/Module/Package/PackageOpsTest.php +++ b/server/tests/Unit/Module/Package/PackageOpsTest.php @@ -29,7 +29,7 @@ final class PackageOpsTest extends TestCase protected function setUp(): void { - foreach (['APP_ENV', 'SAND_COMPILED', 'SAND_PACKAGE_OPS'] as $name) { + foreach (['SAND_PACKAGE_OPS'] as $name) { $this->envBackup[$name] = getenv($name); } $this->super = new OrgActor(7, '超管', null, true, ['*']); @@ -48,15 +48,11 @@ protected function tearDown(): void private function opsOn(): void { - putenv('APP_ENV'); - putenv('SAND_COMPILED=0'); putenv('SAND_PACKAGE_OPS=1'); } private function opsOff(): void { - putenv('APP_ENV'); - putenv('SAND_COMPILED'); putenv('SAND_PACKAGE_OPS'); } diff --git a/tools/build-release.sh b/tools/build-release.sh index 43f5b1fc..90d890d0 100755 --- a/tools/build-release.sh +++ b/tools/build-release.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash # 生产发布包构建:git archive 干净导出 HEAD → 按 tools/dev-only-paths.txt -# 物理剔除开发专用代码 → server 下 composer install --no-dev → vendor -# sand-core 与 plugin/sandadmin 载荷剔除 dev-login 链、第三方测试文件 → -# vendor 按 tools/strip-vendor-extra.php 名单剔除非运行文件(tests/docs/ -# 示例/CI 元信息,autoload 覆盖路径豁免)→ web/ 前端构建并把 dist 并入 +# 物理剔除开发专用代码并把 server/build-manifest.json 改写为 compiled → +# server 下 composer install --no-dev → vendor sand-core 与 plugin/sandadmin +# 载荷剔除 dev-login 链、第三方测试文件 → vendor 按 +# tools/strip-vendor-extra.php 名单剔除非运行文件(tests/docs/示例/CI +# 元信息,autoload 覆盖路径豁免)→ web/ 前端构建并把 dist 并入 # server/public → 自检 → 打 tar.gz。 # # tools/build-release.sh [版本号] [--self-check] @@ -40,8 +41,9 @@ mkdir -p "$WORK" git -C "$ROOT" archive --format=tar "--prefix=$PKG/" HEAD | tar -x -C "$WORK" SRC="$WORK/$PKG" -echo "== 2/8 按清单剔除开发专用代码" +echo "== 2/8 按清单剔除开发专用代码并标记编译制品" php "$ROOT/tools/strip-dev.php" "$SRC" +printf '%s\n' '{"build_kind":"compiled"}' > "$SRC/server/build-manifest.json" echo "== 3/8 composer install --no-dev --optimize-autoloader" ( cd "$SRC/server" && composer install --no-dev --optimize-autoloader --no-interaction ) @@ -82,8 +84,18 @@ cp -R "$SRC/web/dist/." "$SRC/server/public/" # msw postinstall 会往 public/ 重新铺 mockServiceWorker.js,一并清掉 rm -rf "$SRC/web/node_modules" "$SRC/web/dist" "$SRC/web/public/mockServiceWorker.js" -echo "== 6/8 自检:清单路径不存在、无开发构建标记、无 .env/密钥残留" +echo "== 6/8 自检:清单路径不存在、compiled 构建清单、无开发构建标记、无 .env/密钥残留" php "$ROOT/tools/strip-dev.php" "$SRC" --verify +php -r ' +$file = $argv[1]; +$content = is_file($file) ? file_get_contents($file) : false; +$decoded = is_string($content) ? json_decode($content, true) : null; +if (!is_array($decoded) || ($decoded["build_kind"] ?? null) !== "compiled") { + fwrite(STDERR, "FAIL server/build-manifest.json 未标记 compiled\n"); + exit(1); +} +echo "PASS server/build-manifest.json 为 compiled\n"; +' "$SRC/server/build-manifest.json" if find "$SRC" -name '.sand-dev-build' | grep -q .; then echo "FAIL 产物含 .sand-dev-build 标记" >&2 exit 1 diff --git a/tools/package-ops b/tools/package-ops index e6c4c6fb..8d3055ae 100644 --- a/tools/package-ops +++ b/tools/package-ops @@ -13,8 +13,8 @@ declare(strict_types=1); // php tools/package-ops uninstall [--data keep|export-delete|delete] // php tools/package-ops recover // 签名:check/install/upgrade 先验 Ed25519 分离签名再解包,验不过一律拒绝。 -// --signature/--pubkey 各给一个文件,内容是 base64 或原样字节; -// 公钥不内嵌内核,由调用方显式提供。缺签名默认拒绝, +// 当前过渡格式由 --signature/--pubkey 各给一个文件,内容是 base64 +// 或原样字节;信任根内嵌与 kid 选钥不在本层实现。缺签名默认拒绝, // 仅本地演练可显式 --allow-unsigned(无值旗标;编译版闸在前, // 此口子进不了生产)。 // 可选项:--db pgsql|mysql(默认按 SAND_DB_URL 协议推断,缺省 pgsql) @@ -162,15 +162,15 @@ if (!in_array($dbDriver, ['pgsql', 'mysql'], true)) { exit(2); } -// 开发构建标记是生命周期闸的一部分:发布制品剔除标记与本工具后 -// 仍有人把工具搬进去跑,也过不了 is_file 这道闸 +// 构建清单是生命周期闸:发布制品把它改写为 compiled;就算有人把本工具 +// 搬进制品运行,也过不了 BuildKind 这道闸 $executor = new PackageExecutor( $registry, $repoRoot, $pluginDir, $workDir, $dbDriver, - $repoRoot . '/server/.sand-dev-build', + $repoRoot . '/server/build-manifest.json', ); if ($command === 'recover') {