fix(materials): audit historical previews and gate production releases
Preserve known legacy failures by reviewed identity, probe material delivery before and after releases, and retain originals and downloads.
This commit is contained in:
parent
eabcff40f8
commit
a890660853
@ -1,6 +1,68 @@
|
||||
# 素材预览只读验收
|
||||
|
||||
当前为独立、显式执行的验收命令,尚未接入发布流程或定时任务。不会修复图片、修改引用、执行 Schema DDL 或调用模型。
|
||||
正式发布入口 `scripts/git-incremental-deploy.ps1` 已接入只读预览门禁,Mac 入口抽取同一份模板。它不修复图片、不修改引用、不执行 Schema DDL、不调用模型,也不改原素材或下载文件。新增脚本提交并推送只证明代码已纳入发布;是否已在生产安装首份审核基线、实际执行哪个阶段,必须以对应私有回执为准,不能用离线测试代替生产验收。
|
||||
|
||||
## 实际发布门禁
|
||||
|
||||
每次真实发布均执行三阶段:`capture` 在旧容器停止前,`candidate` 在切流前,`post` 在代理目标验证通过后、写入当前版本记录前。direct replacement 的 candidate/post 失败调用现有 `fail_direct_replace_with_restore`;保留的蓝绿代码分别调用已有的切流前失败处理和切流后回滚处理。没有跳过开关。Mac 与 PowerShell 都从构建机**精确 Git checkout**生成门禁模块,并通过现有 SSH stdin 执行,不要求旧镜像内已有新脚本,不向应用目录复制代码。
|
||||
|
||||
`material-preview-release-gate.mjs` 复用现有清点器、直连网络防护和 Sharp 全像素解码。在只读 RepeatableRead 事务中枚举全部未删除 `Material.previewUrl`,包含缺地址或不支持检查的记录,不用 `HISTORY_IMPORT`。全元数据索引与 SHA 保留在每份回执;图片 GET 仅覆盖:
|
||||
|
||||
- **全部仍指向独立旧桶的活跃引用**,本轮预计 472 项,实时枚举,不硬编码数量掩盖新增或遗漏。
|
||||
- 十二项关键材质,按固定素材 ID 核对,不允许减少或改成其它样本。
|
||||
- 与上次已接受全元数据索引相比,新增或预览源地址改变的当前素材。
|
||||
|
||||
其余未变化的当前源与原有不受支持的预览明确登记为 `unverified`,不能记健康。新增或变化后变成不可检查的引用直接阻止发布。并发上传/删除造成候选或 post 库存 SHA 与 capture 不同,也停止并保留旧版本;不会通过重新抽样、忽略新记录或无限重试来抹平差异。
|
||||
|
||||
固定预算为每阶段最多 768 次单次 GET、4 并发、正文总量 128 MiB、总时长 360 秒;单项仍受 8 MiB、10 秒、2500 万像素限制,不重试、不跟随跳转。范围超过预算时停止,需另行安排独立全量验收,不能临时提高预算或清空基线。
|
||||
|
||||
候选与 post 使用 capture 的**同一份探测清单及 SHA**,逐项核对素材 ID、源地址 SHA、角色、结果数量、解码与正文 SHA;同时比较规范化索引和原始登记值的库存摘要。既有健康 URL 的内容在未改地址时变化、新失败、原失败类型或完整失败正文改变、漏项、检测器不可用均不通过。472 项既有 FRP 404 可以作为人工审核的事故基线保留,但每个阶段均实际重读并明确报告 `knownFailures`、`allSelectedHealthy=false`;它们不能成为正常图片,也不能自动容纳新失败。某项已恢复健康后若下一阶段再次失败,会阻止发布。
|
||||
|
||||
首次故障准入还绑定版本化 `scripts/fixtures/material-preview-known-legacy-20261023.json` 的 **472 对精确素材 ID + 规范化源地址 SHA**,并固定 489 字节、正文 SHA `967e369d3be4fab5eb1229ec015b2923abf6bc81ebe3aaa662cb095cbec81023` 的已核实 FRP 页。集合 SHA 固定为 `953e6b1c9e10ea05e30e289ebbd5364569d918b5dd4a1273af52abc531fe475c`,生成依据是独立只读逐项审计原文件 SHA `40eb8d834d5c6bd9edcdc49e69ae227a83be2374bb9b525a0cec0bcd652c4e0d`。proof 只有 ID/摘要,没有名称、URL 或凭据;构建时校验后内联,不能在首次 bootstrap 时根据现场新失败自动重建。第 473 项、删一项换入另一 ID、同 ID 变更源,均不能混入已知故障,即使返回完全相同的 FRP 页。
|
||||
|
||||
登记源与实际同桶 canonical 交付地址分别探测、分别保留结果。只复用现有“当前桶的旧兼容域名交付到当前公开入口”语义,不改变桶或 key;独立旧桶永远保持原址,不使用域名替换掩盖故障。新花色01的旧登记域名网络失败,只能在其固定素材 ID 的 canonical 图片完整解码为 768×1600、原正文 SHA `b40687cac0cbd537e209f8caa56c642bf501a658d0c3585140e8b9950937da53` 一致时单列;不能把前者改写为健康,也不能将其它当前源失败一概豁免。
|
||||
|
||||
URL 重写、代理、S3 或网络识别五个源码文件的精确指纹,与**上次接受基线、当前容器、目标 checkout**三方比较。即使现场已被绕过门禁改成 B、此次目标也为 B,旧基线 A 仍会触发扩大范围。非秘密配置 `S3_ENDPOINT`、`S3_BUCKET`、`S3_FILE_PATH`、`S3_PUBLIC_DOMAIN`、`S3_REGION`、`SERVER_IP`、`MINIO_API_PORT`、`APP_PUBLIC_URL` 同样做三方指纹比较;目标来自真实部署 env 文件的白名单,脚本控制的公开 URL 按真正 Docker 参数覆盖,不读取或记录 access key/secret 字段,拒绝 URL userinfo、query、片段和重复目标键。缺少完整目标配置直接停止;candidate/post 实际配置必须与 capture 记录的目标一致,不能只靠公开 URL 仍然可读放行内部回源变化。这些交付代码/配置变化会扩大为全部当前预览;超预算会 fail-closed,要求独立全量验收后再安排该类发布。本入口不提供跳过保护的维护参数。
|
||||
|
||||
审计位置固定属于本项目:
|
||||
|
||||
```text
|
||||
/mnt/PoolOne/apps/youyidian-3d/local-proxy/youyidian-3d-material/material-preview-health/
|
||||
accepted-pointer.json
|
||||
bootstrap-<审核编号>/bootstrap.json
|
||||
release-<commit前12位>-<随机串>/
|
||||
accepted.json
|
||||
accepted-pointer-before.json
|
||||
gate-module.url
|
||||
capture.json
|
||||
candidate.json
|
||||
post.json
|
||||
```
|
||||
|
||||
根目录和单次目录为 0700,文件为 0600。`accepted-pointer.json` 是唯一原子更新的指针,包含已审核/已接受文件的相对路径和**原文件字节 SHA**。读取时拒绝软链接、越界路径、摘要不符或超过 32 MiB 的基线。首次缺少指针或基线时,在停止旧容器前失败;不自动创建“全部正常”的基线。完整发布验收后才原子推进指针;旧回执、旧指针快照、失败报告仍留存,不混入素材或客户端临时目录。
|
||||
|
||||
### 首次审核基线(独立、显式步骤)
|
||||
|
||||
首次不把两万余条未探测的当前源伪装为健康,也不因它们全是“新索引项”而自动下载两万张图片。由已核对的项目运维操作者完成一次 bootstrap:读取全库存元数据,探测全部独立旧桶和十二项关键材质,审核其结果后固定原文件 SHA。正常发布永远不能自动重建 bootstrap。
|
||||
|
||||
1. 在已审核的精确 checkout 中生成模块 URL:`node scripts/material-preview-release-gate.mjs bundle`。模块不含 Key 或数据库 URL。通过已核对的本项目 SSH 将输出作为 0600 文件存入新的私有 `bootstrap-<审核编号>/gate-module.url`,不要写入镜像或源码目录。
|
||||
2. 使用本项目当前容器的依赖和环境运行下面的**只读** bootstrap。调用前仍需核对 NAS、当前容器、部署 SHA 和目录身份;`<已核对40位SHA>` 必须替换为真实值。创建新目录与审计文件属于保存证据,不是修改数据库。
|
||||
|
||||
```sh
|
||||
python3 - <新的bootstrap目录>/gate-module.url <已核对40位SHA> <<'PY' | docker exec -i -w /app <已核对当前容器> node --input-type=module - > <新的bootstrap目录>/bootstrap.json
|
||||
import json, pathlib, sys
|
||||
module = pathlib.Path(sys.argv[1]).read_text()
|
||||
request = dict(version=1, stage='bootstrap', commit=sys.argv[2])
|
||||
print('const {runReleaseStage}=await import('+json.dumps(module)+');')
|
||||
print('try {const r=await runReleaseStage('+json.dumps(request)+');console.log(JSON.stringify(r));process.exitCode=r.passed?0:1;} catch(e) {console.log(JSON.stringify({passed:false,code:"bootstrap_failed"}));process.exitCode=1;}')
|
||||
PY
|
||||
```
|
||||
|
||||
3. 独立审核该文件的库存数量、完整性、十二项材质、旧桶全部引用数量、每项失败类型、正文 SHA/尺寸、`knownFailures`、`unverified` 和预算。`passed=true` 只表示满足有明确已知事故基线的发布比较要求,不代表旧桶已恢复。原登记 URL 或数据库链接不应粘贴到公开日志。
|
||||
4. 用 `sha256sum bootstrap.json` 获得精确原文件 SHA,审核后以相对路径及该**已核对 SHA**写入 0600 的 `accepted-pointer.json`。指针结构示例:`{"version":1,"file":"bootstrap-审核编号/bootstrap.json","sha256":"<已核对64位SHA>"}`。不得把示例 SHA、空结果或重新运行后的不同文件替代已审核基线;正常发布只读取,不自动安装。
|
||||
5. 用相同精确门禁模块执行当前容器的 capture→candidate→post 只读演练,并保留三个实际回执。程序化调用后三阶段时除 `accepted`、`capture`、`candidate` 对应回执外,还必须传 `targetDeliveryConfig`;当前容器演练可用审核后的 `accepted.deliveryConfig`,正式发布则由 PS1 白名单解析待部署 env 与实际 Docker 覆盖值。演练没有替换镜像/切换代理,不能写成真实候选切流验收。正式发布时同三个函数自动执行,审计清单由 capture 固定。
|
||||
|
||||
跨平台演练须核对目标 checkout 与同一 Git 提交的原始 blob 字节。Windows 的 CRLF 工作副本可能与生产 LF 不同,应在新的受限目录按 Git blob 构建匹配字节快照;不能通过忽略或归一化行尾放宽门禁。正式构建的模块指纹与 Docker 上下文均来自同一精确 checkout。
|
||||
|
||||
## 导出并逐批检查
|
||||
|
||||
@ -17,7 +79,7 @@ node scripts/check-material-preview-health.mjs --manifest <新目录>/manifest-0
|
||||
|
||||
检查器按清单中的精确登记地址执行有界单次 GET,不重试、不跟随跳转,并核对 HTTP、MIME、图片魔数及 **Sharp 完整像素解码**;仅头部可识别不足以通过。8 MiB、10 秒、2500 万像素上限保持固定,解码器按运行环境惰性 `createRequire` 加载,不执行安装。保留清单、清单哈希和全部批次报告。`audit.batches[].sha256` 对应原文件字节,`manifestSha256` 对应检查器的同名字段(紧凑 JSON 哈希),二者须分别核对。单批 50 项通过、或 12 项材质通过,均不能写成“全库存通过”。
|
||||
|
||||
完整图片验收需另行安排流量预算,逐一运行所有 `audit.batches` 并对齐哈希、素材 ID、数量及退出码。当前修复验收仅运行材质 12 项的已审核清单;**不因导出了两万余项元数据而自动发出全库存图片 GET**。未运行的批次保留为未检查。
|
||||
完整图片验收需另行安排流量预算,逐一运行所有 `audit.batches` 并对齐哈希、素材 ID、数量及退出码。2026-10-23 已完成 472 项旧源单次 GET,以及发布检查三阶段每次 485 个固定地址的实际探测;没有执行两万余张当前源全量 GET。**不因导出了两万余项元数据而将它们标记为健康**,未运行的批次保留为未检查。首次基线安装、三阶段原文件 SHA、已知失败与现场范围见 `docs/material-preview-incident-2026-10-23.md`。
|
||||
|
||||
## 尚未部署脚本时的 stdin 适配
|
||||
|
||||
@ -51,22 +113,23 @@ try { const r=await main(${JSON.stringify(args)});
|
||||
|
||||
stdin 中的 `createRequire('file:///app/package.json')` 使用容器已有的 `@prisma/client`/Sharp;不是读取本机另一套数据库配置。若依赖不存在、数据库事务失败或输出中途失败,退出非零,不能把残留文件当完整清单。导出器在所有批次成功写入后才写 `audit.json`。导出完成后再由调用方按需取回只读审计文件,本命令不清理文件。
|
||||
|
||||
## 发布接入位置(待实施)
|
||||
## 发布接入函数
|
||||
|
||||
当前发布采用 direct replacement;本轮不修改共享发布脚本。后续接入 `scripts/git-incremental-deploy.ps1` 时按函数语义定位,行号仅供参考:
|
||||
当前正式策略仍为 direct replacement,没有恢复蓝绿发布入口。接入点按函数语义定位:
|
||||
|
||||
| 位置 | 应保留的验收证据 |
|
||||
| --- | --- |
|
||||
| `direct_replace_active_container` 中 `docker stop` 前,约 2839–2842 行 | 导出全活跃库存,记录旧容器基线及所有批次结果 |
|
||||
| `verify_candidate_brand_and_storage_dependencies` 后、切流前,约 2882–2897 行 | 新容器检查同一份清单;核对新增失败,不能重新抽样替换基线 |
|
||||
| `verify_proxy_target` 成功后、`write_current_container` 前,约 2897–2900 行 | 从公网路径确认同一份清单,保留结果后再记录当前版本 |
|
||||
| `direct_replace_active_container` 中 `docker stop` 前 | `prepare_material_preview_release` 验证已审核指针;`run_material_preview_release_gate ... capture` 清点全库存并固定探测清单 |
|
||||
| `verify_candidate_brand_and_storage_dependencies` 后、切流前 | `run_material_preview_release_gate ... candidate` 验证同清单与库存;失败走现有 immutable image 恢复 |
|
||||
| `verify_proxy_target` 成功后、`write_current_container` 前 | `run_material_preview_release_gate ... post` 通过公开存储 URL 实际 GET/解码同清单;失败走现有恢复 |
|
||||
| 当前版本记录成功后 | `accept_material_preview_release` 核对三个阶段同 commit/清单/库存,原子推进指针 |
|
||||
|
||||
macOS wrapper 从同一 PowerShell 源码抽取发布逻辑,接入时需同时回归,不另复制一套条件。既有故障必须在报告中保留,不将未检查项当通过,也不因独立检查命令存在就宣称发布门禁已启用。
|
||||
macOS wrapper 从同一 PowerShell 源码抽取发布逻辑,不另复制一套条件。已有 shell 回归验证 capture 失败时没有 stop/switch、candidate 失败时没有 switch、post 失败时调用一次现有回滚,且失败不推进基线。该只读探测验证公开存储交付路径,不能代替登录态页面、私有下载资格或客户端实际 UI 的单独验收。
|
||||
|
||||
11 项材质预览恢复属于独立的精确 CAS 数据补丁:先验证新对象,再以原值为条件更新并保留回退记录;不得混入本只读检查器,也不代表高清原件或其余历史依赖已恢复。
|
||||
|
||||
相关离线回归:
|
||||
|
||||
```sh
|
||||
node --test scripts/check-material-preview-health.test.mjs scripts/export-material-preview-health-manifest.test.mjs
|
||||
node --test scripts/check-material-preview-health.test.mjs scripts/export-material-preview-health-manifest.test.mjs scripts/material-preview-release-gate.test.mjs scripts/git-incremental-deploy.test.mjs
|
||||
```
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# 旧素材预览失效核查(2026-10-23)
|
||||
|
||||
状态:已确认旧域名入口路由失败、存量迁移覆盖缺口及 11 份真实材质缩略图的转换来源。**11 项临时 160px 预览已恢复,正式 Web 与现有客户端均复核为 12 张缩略图、0 失败;高清源仍未恢复,旧入口的具体触发变更尚未归因,不能记为事故完全解决。**
|
||||
状态:已确认旧域名入口路由失败、存量迁移覆盖缺口及 11 份真实材质缩略图的转换来源。**11 项临时 160px 预览已恢复,正式 Web 与现有客户端均复核为 12 张缩略图、0 失败;高清源未恢复。剩余 472 项已逐一核查并确认属于 2025 年旧批次,用户确认旧桶素材无法找回,停止继续追源。具体路由变更仍未归因,不冒充已找回原件或已查明触发者。**
|
||||
|
||||
## 已确认的事实
|
||||
|
||||
@ -63,13 +63,25 @@ sharp(original)
|
||||
- 复用现有唯一客户端窗口(PID `9260`、HWND `2363054`),没有另开窗口、没有更改项目资料;逐项执行 11 次素材图片只读重读,滚动检查上、下区域并截图,汇总确认 12 张真实缩略图、0 个失败标记。
|
||||
- 本轮没有重新验收悬停大图;先前的悬停证据不计作这次恢复后的验证。已通过的范围是 Web 与客户端的临时缩略预览,`originalSourceRestored=false`。
|
||||
|
||||
因此“11 项临时 160px 缩略预览恢复”已通过;高清源、原件可取回性、旧入口故障的具体触发变更及其余旧依赖仍是开放事项。本次未重发结果未知的模型请求。
|
||||
因此“11 项临时 160px 缩略预览恢复”已通过;高清源没有恢复,旧入口故障的具体触发变更仍未查明。本次未重发结果未知的模型请求。关于旧批次无法找回的用户确认及停止追源范围,见下文。
|
||||
|
||||
## 剩余 472 项的完整核查与用户确认
|
||||
|
||||
2026-10-23 对剩余 472 个独立登记 URL 分十批完成只读 GET,无重试。全部返回 HTTP 404、489 字节 FRP 默认页,正文 SHA 均为 `967e369d3be4fab5eb1229ec015b2923abf6bc81ebe3aaa662cb095cbec81023`,没有一项被记为健康。类型为 3D场景 305、详情模板 87、其他 61、模特 7、实拍图片 6、买家秀图片 6。
|
||||
|
||||
按数据库 `createdAt`(UTC+8)核对,这 472 条记录建档于 **2025-10-27 16:43:57.805 至 2025-12-20 17:59:08.983**,其中 10 月 8 条、11 月 363 条、12 月 101 条。这是记录建档时间,不是原文件生成时间。先前恢复临时预览的 11 项材质均建档于 2025-11-07,属于同一旧桶。用户据此确认该批旧桶素材无法找回,本次停止继续寻找旧桶服务器或扩大扫描;保留素材记录、缓存、原登记来源和下载文件,不以空图覆盖、不删除素材。
|
||||
|
||||
106 条记录含 2215 个 `displayImages` 候选,仍全部指向同一旧入口;MaterialAsset 与 SKU 元数据未提供可校验的替代预览来源。该元数据核对没有下载 ZIP 或原素材。后续仅在本项目当前桶的受限范围扫描 250000 条对象元数据,对 27 个尺寸候选读取 452568 字节,没有原 SHA 命中;达到预算时游标尚未耗尽,故**不据此声称整个桶不存在原图**。用户的历史说明与本次未找到可校验副本分别保留,不把 404 等同于物理删除证明。
|
||||
|
||||
对当前旧入口的 NAS 直连核查证实 FRP 404;本机 TUN 下按 IP/SNI 探测可能被转发,不能单凭本机相似响应归因历史主机。既有访问记录只能确定成功与失败的观测时间,缺少该入口的 DNS/FRPS 审计,仍无法精确指出哪次配置变更触发故障。已排除的本项目变更和迁移筛选缺口见前文,不将后续安全升级认定为首次故障原因。
|
||||
|
||||
## 防复发检查及操作边界
|
||||
|
||||
新增独立只读工具 `scripts/check-material-preview-health.mjs`,输入显式审阅的素材 ID 与登记图片 URL 清单。它限制项目既有域名、公网 DNS 地址、字节数与时间;不跟随跳转、不重试,检查真实 GET、Content-Type、图片魔数和 Sharp 完整像素解码,区分 FRP/HTML 路由失败、S3 缺桶、S3 缺对象及网络异常。只有图片头、损坏正文或像素炸弹不能通过。
|
||||
|
||||
`scripts/export-material-preview-health-manifest.mjs` 在只读 RepeatableRead 事务中清点所有未删除的 Material,按最多 50 项分批,不再用 `HISTORY_IMPORT` 筛选;缺 URL 或不支持地址仍计入审计,不会被静默遗漏。与安全恢复工具合计 31 项离线测试通过。执行方式、生产 stdin 适配与发布前后接入点见 `docs/material-preview-health.md`。目前为显式执行工具,**尚未接入自动发布或定时监控**,不能声称自动防回归已部署。
|
||||
`scripts/export-material-preview-health-manifest.mjs` 在只读 RepeatableRead 事务中清点所有未删除的 Material,按最多 50 项分批,不再用 `HISTORY_IMPORT` 筛选;缺 URL 或不支持地址仍计入审计,不会被静默遗漏。新增 `scripts/material-preview-release-gate.mjs` 已接入 `git-incremental-deploy.ps1` 实际发布路径,Mac wrapper 共用该模板:停旧容器前 capture,候选切流前 candidate,切流后 post;失败停止或进入原有回滚,不推进已接受基线。相关离线回归 68/68 通过。执行方式、首次审核和实际函数位置见 `docs/material-preview-health.md`,不将其声称为定时监控。
|
||||
|
||||
已知事故基线严格绑定 472 个素材 ID 与规范化源 SHA 的固定集合(集合 SHA `953e6b1c9e10ea05e30e289ebbd5364569d918b5dd4a1273af52abc531fe475c`);新增第 473 条、等量替换 ID 或同 ID 改源均不能混入。全库存元数据每次重读,新增或变更预览必须进入同一固定验收清单;交付代码或八项非秘密配置在已接受基线、现场、目标之间变化则扩大检查范围,预算不足时拒绝发布,不能跳过检查。已知旧失败仍记录为失败,不计入健康率。
|
||||
|
||||
恢复后生产只读清点共 23467 条活跃记录,其中 23263 条为检查器支持的 URL,204 条缺地址或不受该图片检查器支持(不等于 204 条图片损坏)。旧入口引用由 483 减少到 472,只有本次 11 项材质改变;未对其余库存发起全量图片 GET。11 个新对象的实际公网 GET、完整解码及 SHA 均通过。
|
||||
|
||||
@ -77,7 +89,19 @@ sharp(original)
|
||||
|
||||
下次涉及存储域名、代理、运行时或 frpc 维护,维护前后需要同时检查当前入口和仍有活跃引用的历史入口,并保留前后报告;仅进程在线、首页健康或配置 SHA 未变,不算素材交付验证。桶退役之前必须清点所有活跃引用,并核对“对象真实存在且内容一致,再改引用”,不能只按导入日志标签判断迁移完成。
|
||||
|
||||
下一步仍需要旧入口故障窗口内的 DNS/FRPS/客户端变更证据,以及原对象或经过校验的迁移清单。恢复时保留原文件,使用精确条件更新和可回退记录;临时 160px 预览必须保留尺寸与来源记录,不能掩盖高清源未恢复或扩大为其它素材已恢复的结论。
|
||||
若后续另有旧入口历史审计或可信原件,才能继续精确归因或恢复高清;当前按用户确认停止追源。临时 160px 预览继续保留尺寸与来源记录,不能掩盖高清源未恢复或扩大为其它素材已恢复的结论。所有原素材、现有下载文件和元数据均保留。
|
||||
|
||||
## 生产发布检查实测(2026-10-23)
|
||||
|
||||
已核对当前生产容器 ID `71b756a0f44a0f7b68733f7245290b629d6e78305f77bac2a0274c4575cfe22e`、不可变镜像及 `/app/DEPLOYMENT_COMMIT=df90e6f4799fcdf69b3b22f9910d8f4b4a596e77`。使用容器已有依赖运行 bootstrap,逐项对照独立 472 项审计及固定集合后,明确审核原文件 SHA `baa10b14036c9a48bd23739d7583c3273fac935d77891fc523373fce289978fc`,安装到本项目私有审计目录的 `bootstrap-20261023-reviewed-472/bootstrap.json` 与 0600 原子指针。
|
||||
|
||||
随后直接抽取实际 PS1 的 `prepare_material_preview_release` 与 `run_material_preview_release_gate` 函数,针对同一当前容器依次执行 capture、candidate、post:每阶段全量清点 23467 条元数据,按同清单实际 GET 485 次、0 重试。12 项关键材质的交付地址完整解码;472 项旧桶失败及 1 项旧兼容登记域名失败继续如实记录,22983 条未探测库存明确为未验证。`passed=true` 表示未发现较已审核事故基线的新回归,**不代表 472 项恢复、所有库存健康或高清原图找回**。
|
||||
|
||||
三阶段计划 SHA 均为 `1502a140ddd5f52339f591ad903434617e5274b1b2b6a8d34706b3eabdf5a4f7`;capture、candidate、post 原文件 SHA 分别为 `1cd8fd4cc9a4f51a0445c36d8237c5fb2e6356151c7247befee11094ea54c59a`、`f9ab48db352ec35565269a9da9418dc1bb7efe5bc79188fdfe3ad294e9f6800a`、`469733dda2411817af842d4925bb6621c3aba1dd1f25b5f5fe2c36f21ba6bf5c`。
|
||||
|
||||
首次从 Windows 工作副本打包时,五个交付文件的 CRLF 与生产 LF 字节不同,capture 在停服务前因扩大范围超预算而拒绝,保留失败回执;逐项核对 Git blob 与生产 SHA 一致后,才从原始 blob 的受限快照生成模块重演,没有忽略行尾或放宽规则。该现场负例没有触发容器停止。
|
||||
|
||||
本次是对当前容器的真实只读检查演练,**没有替换镜像、切换代理、运行生产回滚或推进到 post 基线**。前后容器、启动时间及 restartCount=0 均一致;原有故障回滚分支由离线部署测试验证。生产只新增本项目的审计文件和已审核 bootstrap 指针,数据库与存储对象零写入,模型调用零次,客户端窗口零新增。成功及失败演练的临时模块 URL/非秘密传输 env,以及本机字节快照均已清理;必要审计回执保留。
|
||||
|
||||
## 证据
|
||||
|
||||
@ -93,4 +117,14 @@ sharp(original)
|
||||
- `material-previews-ui-acceptance.json`:单个现有客户端窗口与正式 Web 的 12 张缩略图、0 失败验收回执。
|
||||
- `material-previews-native-restored-top.png`、`material-previews-native-restored-bottom.png`、`material-previews-web-restored.png`:恢复后的客户端上、下区域及正式 Web 实际截图。
|
||||
|
||||
本地 `output/material-preview-recovery-20261023/` 下另保留:
|
||||
|
||||
- `remaining-472-audit/`:完整元数据、候选映射、十批实际 GET、独立汇总与文件哈希。
|
||||
- `original-preview-after-prefix-audit.json`:受限 250000 条元数据、27 个候选的原 SHA 核对及预算边界。
|
||||
- `recorded-entry-probes-from-production.json`:NAS 直连旧入口结果,避免本机 TUN 误归因。
|
||||
- `release-gate-live/legacy-472-created-at.json`:472 项建档范围与逐月数量的只读数据库复核。
|
||||
- `release-gate-live/bootstrap.json`、`bootstrap-review.json`、`production-bootstrap-install.json`:首次已审核基线及生产安装回执。
|
||||
- `release-gate-live/capture.json`、`candidate.json`、`post.json`、`final-validation.json`:实际发布函数的三阶段同清单探测及容器身份未变证据。
|
||||
- `release-gate-live/failed-rehearsal-diagnosis.json`、`exact-snapshot-manifest.json`、`cleanup.json`:行尾差异负例、原始 Git 字节快照摘要及临时文件收尾。
|
||||
|
||||
本轮生产恢复范围为 11 个新增临时预览对象、11 项精确预览引用更新及 11 条同事务审计日志;没有修改原文件、下载路径、桶或 FRP 配置,也未重发结果未知的模型请求。本文件此次更新只登记已有实施与验收证据,没有另行执行生产操作。
|
||||
|
||||
237
scripts/audit-legacy-material-previews.mjs
Normal file
237
scripts/audit-legacy-material-previews.mjs
Normal file
@ -0,0 +1,237 @@
|
||||
// Opt-in, read-only audit of one exact registered legacy dependency inventory.
|
||||
// No database/object writes, source substitution, retries or original-file GETs.
|
||||
import { createHash } from 'node:crypto'
|
||||
import * as fs from 'node:fs/promises'
|
||||
import { spawn } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { checkMaterialPreviewHealth, directFetch, LIMITS, registeredSource } from './check-material-preview-health.mjs'
|
||||
import { LEGACY_DOMAINS } from './check-legacy-storage-boundaries.mjs'
|
||||
|
||||
export const AUDIT_LIMITS = Object.freeze({ expectedCount: 472, batchSize: 50, concurrency: 2 })
|
||||
const sha = value => createHash('sha256').update(value).digest('hex')
|
||||
const assert = (value, code) => { if (!value) throw new Error(code) }
|
||||
const previewRoles = new Set(['preview', 'main-preview', 'sku-preview', 'detail-preview', 'report-image'])
|
||||
const imageExtension = /\.(png|jpe?g|webp)$/i
|
||||
|
||||
export function metadataCandidates(row) {
|
||||
const candidates = [], excludedAssets = []
|
||||
const add = (source, origin, identity, size) => {
|
||||
let url
|
||||
try { url = new URL(source) } catch { return }
|
||||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || !imageExtension.test(url.pathname)) return
|
||||
let publicCheckable = false
|
||||
try { registeredSource(source); publicCheckable = true } catch {}
|
||||
candidates.push({ source, origin, identity, ...(size === undefined ? {} : { declaredBytes: String(size) }),
|
||||
sameAsRegistered: source === row.previewUrl, legacyHost: LEGACY_DOMAINS.includes(url.hostname), publicCheckable,
|
||||
metadataOnly: true, bytesRead: 0, originalIdentityVerified: false })
|
||||
}
|
||||
for (const [index, source] of (row.displayImages || []).entries()) add(source, 'displayImages', String(index))
|
||||
for (const asset of row.assets || []) {
|
||||
if (!previewRoles.has(asset.assetType)) {
|
||||
excludedAssets.push({ assetId: asset.id, assetType: asset.assetType, reason: 'not_a_preview_role', bytesRead: 0 })
|
||||
continue
|
||||
}
|
||||
const before = candidates.length
|
||||
add(asset.fileUrl, 'MaterialAsset', asset.id, asset.fileSize)
|
||||
if (before === candidates.length) excludedAssets.push({ assetId: asset.id, assetType: asset.assetType, reason: 'not_a_supported_image_url', bytesRead: 0 })
|
||||
}
|
||||
for (const sku of row.skus || []) if (sku.previewUrl) add(sku.previewUrl, 'MaterialSku.previewUrl', sku.id)
|
||||
return { materialId: row.id, materialType: row.materialType, candidates, excludedAssets }
|
||||
}
|
||||
|
||||
export function validateAuditSnapshot(snapshot, { host, expectedCount = AUDIT_LIMITS.expectedCount } = {}) {
|
||||
assert(LEGACY_DOMAINS.includes(host), 'registered_legacy_host_required')
|
||||
assert(snapshot?.readOnly === true && snapshot.count === expectedCount && Array.isArray(snapshot.materials)
|
||||
&& snapshot.materials.length === expectedCount, 'exact_inventory_count_required')
|
||||
const seen = new Set()
|
||||
for (const row of snapshot.materials) {
|
||||
assert(typeof row.id === 'string' && /^[A-Za-z0-9._-]{1,128}$/.test(row.id) && !seen.has(row.id), 'unique_material_identity_required')
|
||||
seen.add(row.id)
|
||||
assert(typeof row.previewUrl === 'string', 'source_required')
|
||||
const url = new URL(row.previewUrl)
|
||||
assert(url.hostname === host && ['https:', 'http:'].includes(url.protocol), 'inventory_host_changed')
|
||||
}
|
||||
return snapshot.materials
|
||||
}
|
||||
|
||||
// Hash every fully consumed response, including the explicit FRP HTML 404 body.
|
||||
// The checker still owns the byte/time budgets and cancels rejected streams.
|
||||
export async function auditPreviewBatch(manifest, { fetchImpl = directFetch, ...options } = {}) {
|
||||
const proofs = new Map()
|
||||
const capture = async (url, fetchOptions) => {
|
||||
const response = await fetchImpl(url, fetchOptions)
|
||||
if (!response.body) return response
|
||||
const reader = response.body.getReader(), digest = createHash('sha256')
|
||||
let count = 0
|
||||
const stream = new ReadableStream({
|
||||
async pull(controller) {
|
||||
try {
|
||||
const item = await reader.read()
|
||||
if (item.done) {
|
||||
proofs.set(url, { responseBodySha256: digest.digest('hex'), responseBytes: count, responseBodyComplete: true })
|
||||
controller.close()
|
||||
} else {
|
||||
count += item.value.byteLength
|
||||
digest.update(item.value)
|
||||
controller.enqueue(item.value)
|
||||
}
|
||||
} catch (error) { controller.error(error) }
|
||||
},
|
||||
cancel(reason) { return reader.cancel(reason) },
|
||||
})
|
||||
const wrapped = new Response(stream, { status: response.status, statusText: response.statusText, headers: response.headers })
|
||||
Object.defineProperties(wrapped, { url: { value: response.url }, redirected: { value: response.redirected } })
|
||||
return wrapped
|
||||
}
|
||||
const report = await checkMaterialPreviewHealth(manifest, { ...options, fetchImpl: capture })
|
||||
return { ...report, results: report.results.map(result => ({ ...result,
|
||||
...(proofs.get(manifest.materials.find(entry => entry.materialId === result.materialId).registeredSource)
|
||||
|| { responseBodySha256: null, responseBodyComplete: false }) })) }
|
||||
}
|
||||
|
||||
export async function auditUniquePreviews(materials, { onBatch = async () => {}, ...options } = {}) {
|
||||
const byUrl = new Map(), rejected = []
|
||||
for (const row of materials) {
|
||||
try {
|
||||
const source = registeredSource(row.previewUrl).href
|
||||
if (!byUrl.has(source)) byUrl.set(source, { materialId: row.id, registeredSource: source, materialIds: [] })
|
||||
byUrl.get(source).materialIds.push(row.id)
|
||||
} catch (error) {
|
||||
rejected.push({ materialId: row.id, ok: false, classification: 'source_rejected', code: error.code || 'invalid_url', attempts: 0 })
|
||||
}
|
||||
}
|
||||
const entries = [...byUrl.values()], batches = []
|
||||
for (let index = 0; index < entries.length; index += AUDIT_LIMITS.batchSize) {
|
||||
batches.push({ version: 1, reviewed: true, materials: entries.slice(index, index + AUDIT_LIMITS.batchSize)
|
||||
.map(({ materialId, registeredSource }) => ({ materialId, registeredSource })) })
|
||||
}
|
||||
const reports = new Array(batches.length)
|
||||
let next = 0
|
||||
await Promise.all(Array.from({ length: Math.min(AUDIT_LIMITS.concurrency, batches.length) }, async () => {
|
||||
while (next < batches.length) {
|
||||
const index = next++
|
||||
reports[index] = await auditPreviewBatch(batches[index], options)
|
||||
await onBatch({ index, manifest: batches[index], report: reports[index] })
|
||||
}
|
||||
}))
|
||||
const byRepresentative = new Map(reports.flatMap(report => report.results).map(result => [result.materialId, result]))
|
||||
const byId = new Map(rejected.map(result => [result.materialId, result]))
|
||||
for (const entry of entries) for (const materialId of entry.materialIds) {
|
||||
byId.set(materialId, { ...byRepresentative.get(entry.materialId), materialId, checkedRepresentativeId: entry.materialId,
|
||||
sharedRegisteredSource: entry.materialIds.length > 1 })
|
||||
}
|
||||
return { readOnly: true, limits: AUDIT_LIMITS, materialCount: materials.length, uniqueRegisteredSources: entries.length,
|
||||
actualGetAttempts: entries.length, rejectedBeforeGet: rejected.length, retries: 0, allRowsAccounted: byId.size === materials.length,
|
||||
deduplication: entries, batches, reports, results: materials.map(row => ({ ...byId.get(row.id), materialType: row.materialType })) }
|
||||
}
|
||||
|
||||
async function sshStdin(command, input, onLine) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn('ssh.exe', ['-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o',
|
||||
'UserKnownHostsFile=C:/Users/54972/.ssh/gongxiangp2-prod.known_hosts', 'gongxiangp2-prod-legacy-freenas', command],
|
||||
{ stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
|
||||
let output = '', errors = '', pending = '', lineFailure
|
||||
child.stdout.on('data', bytes => {
|
||||
output += bytes
|
||||
if (Buffer.byteLength(output) > 32 * 1024 * 1024) { child.kill(); lineFailure = new Error('ssh_output_budget_exceeded'); return }
|
||||
if (onLine) {
|
||||
pending += bytes
|
||||
let end
|
||||
while ((end = pending.indexOf('\n')) !== -1) {
|
||||
const line = pending.slice(0, end); pending = pending.slice(end + 1)
|
||||
if (line.trim()) { try { onLine(JSON.parse(line)) } catch (error) { lineFailure = error; child.kill() } }
|
||||
}
|
||||
}
|
||||
})
|
||||
child.stderr.on('data', bytes => { if (errors.length < 4000) errors += bytes })
|
||||
child.on('error', reject)
|
||||
child.on('close', code => lineFailure ? reject(lineFailure) : code === 0 ? resolve(output) : reject(new Error('read_only_remote_audit_failed')))
|
||||
child.stdin.on('error', () => {})
|
||||
child.stdin.end(input)
|
||||
})
|
||||
}
|
||||
|
||||
export async function main(args = process.argv.slice(2)) {
|
||||
if (!args.includes('--run')) return { planOnly: true, readOnly: true, expectedCount: AUDIT_LIMITS.expectedCount,
|
||||
metadata: ['Material.id', 'materialType', 'previewUrl', 'displayImages', 'MaterialAsset preview metadata', 'active MaterialSku.previewUrl'],
|
||||
health: { ...AUDIT_LIMITS, ...LIMITS }, modelCalls: 0, productionWrites: 0 }
|
||||
assert(args.length === 3 && args[0] === '--run' && args[1] === '--output-dir' && path.isAbsolute(args[2]), 'run_requires_new_absolute_output_directory')
|
||||
const directory = path.resolve(args[2])
|
||||
await fs.mkdir(directory, { recursive: false, mode: 0o700 })
|
||||
const write = (file, value) => fs.writeFile(path.join(directory, file), JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
|
||||
const receipt = JSON.parse(await fs.readFile('output/native-brief-panel-20261023/preview-recovery-reviewed-manifest.json', 'utf8'))
|
||||
const host = new URL(receipt.materials[0].oldPreviewUrl).hostname
|
||||
assert(LEGACY_DOMAINS.includes(host), 'reviewed_legacy_host_required')
|
||||
const identityWire = `import json,subprocess\nc=json.loads(subprocess.check_output(['docker','inspect','youyidian-3d-material-blue']))[0]\nf=subprocess.check_output(['docker','exec',c['Id'],'cat','/app/DEPLOYMENT_COMMIT'],text=True).strip()\nprint(json.dumps({'containerId':c['Id'],'containerName':c['Name'].lstrip('/'),'imageName':c['Config']['Image'],'imageId':c['Image'],'running':c['State']['Running'],'deploymentCommit':f}))\n`
|
||||
const identity = JSON.parse(await sshStdin('python3 -u -', identityWire))
|
||||
assert(identity.running && /^[a-f0-9]{64}$/.test(identity.containerId) && /^[a-f0-9]{40}$/.test(identity.deploymentCommit), 'running_production_identity_required')
|
||||
await write('production-identity.json', { readOnly: true, checkedAt: new Date().toISOString(), ...identity })
|
||||
const command = `docker exec -i -w /app ${identity.containerId} node --input-type=module`
|
||||
const metadataWire = `import {createRequire} from 'node:module';const require=createRequire(import.meta.url),fs=require('node:fs'),assert=require('node:assert/strict');
|
||||
assert.equal(fs.readFileSync('/app/DEPLOYMENT_COMMIT','utf8').trim(),${JSON.stringify(identity.deploymentCommit)});
|
||||
const {PrismaClient}=require('@prisma/client');const p=new PrismaClient({log:[]});
|
||||
try{const result=await p.$transaction(async tx=>{
|
||||
await tx.$executeRawUnsafe('SET TRANSACTION READ ONLY');
|
||||
const where={deletedAt:null,OR:[{previewUrl:{startsWith:${JSON.stringify('https://' + host + '/')},mode:'insensitive'}},{previewUrl:{startsWith:${JSON.stringify('http://' + host + '/')},mode:'insensitive'}}]};
|
||||
const count=await tx.material.count({where});assert.equal(count,${AUDIT_LIMITS.expectedCount});const materials=[];let cursor;
|
||||
while(true){const rows=await tx.material.findMany({where,orderBy:{id:'asc'},take:100,...(cursor?{cursor:{id:cursor},skip:1}:{}),select:{id:true,materialType:true,previewUrl:true,displayImages:true,
|
||||
assets:{orderBy:[{sortOrder:'asc'},{id:'asc'}],select:{id:true,assetType:true,fileUrl:true,fileSize:true,sortOrder:true}},
|
||||
skus:{where:{deletedAt:null},orderBy:{id:'asc'},select:{id:true,previewUrl:true}}}});if(!rows.length)break;materials.push(...rows);assert.ok(materials.length<=count);cursor=rows.at(-1).id;}
|
||||
assert.equal(materials.length,count);return{readOnly:true,capturedAt:new Date().toISOString(),count,host:${JSON.stringify(host)},isolationLevel:'RepeatableRead',historyImportFilter:false,materials};
|
||||
},{isolationLevel:'RepeatableRead',timeout:60000,maxWait:5000});console.log(JSON.stringify(result,(_,v)=>typeof v==='bigint'?v.toString():v));}finally{await p.$disconnect();}`
|
||||
const snapshot = JSON.parse(await sshStdin(command, metadataWire))
|
||||
const materials = validateAuditSnapshot(snapshot, { host })
|
||||
await write('material-metadata.json', snapshot)
|
||||
const candidateMapping = materials.map(metadataCandidates)
|
||||
await write('preview-candidate-mapping.json', { readOnly: true, metadataOnly: true, candidateGets: 0, materials: candidateMapping })
|
||||
const checker = await fs.readFile('scripts/check-material-preview-health.mjs', 'utf8')
|
||||
const own = await fs.readFile(fileURLToPath(import.meta.url), 'utf8')
|
||||
const checkSource = checker.replace("import { LEGACY_DOMAINS } from './check-legacy-storage-boundaries.mjs'", `const LEGACY_DOMAINS=${JSON.stringify(LEGACY_DOMAINS)}`)
|
||||
const helperSource = own.slice(own.indexOf('export async function auditPreviewBatch'), own.indexOf('async function sshStdin'))
|
||||
const wire = checkSource + `\nconst AUDIT_LIMITS=${JSON.stringify(AUDIT_LIMITS)};\n` + helperSource + `
|
||||
const fsRuntime=createRequire(import.meta.url)('node:fs');
|
||||
if(fsRuntime.readFileSync('/app/DEPLOYMENT_COMMIT','utf8').trim()!==${JSON.stringify(identity.deploymentCommit)})throw Error('production_changed');
|
||||
console.log(JSON.stringify({event:'started',expectedCount:${materials.length},checkerSha256:${JSON.stringify(sha(checker))}}));
|
||||
const audit=await auditUniquePreviews(${JSON.stringify(materials.map(({ id, materialType, previewUrl }) => ({ id, materialType, previewUrl })))},
|
||||
{onBatch:async value=>console.log(JSON.stringify({event:'batch',...value}))});
|
||||
if(fsRuntime.readFileSync('/app/DEPLOYMENT_COMMIT','utf8').trim()!==${JSON.stringify(identity.deploymentCommit)})throw Error('production_changed');
|
||||
console.log(JSON.stringify({event:'complete',audit}));`
|
||||
await write('dispatch-audit.json', { readOnly: true, startedAt: new Date().toISOString(), host, materialCount: materials.length,
|
||||
checkerSha256: sha(checker), helperSha256: sha(own), wireSha256: sha(wire), maxConcurrentGets: 2, retries: 0, productionWrites: 0, candidateGets: 0 })
|
||||
const batchWrites = []
|
||||
let completed
|
||||
try {
|
||||
await sshStdin(command, wire, event => {
|
||||
if (event.event === 'batch') batchWrites.push(write(`batch-${String(event.index + 1).padStart(3, '0')}.json`, event))
|
||||
else if (event.event === 'complete') completed = event.audit
|
||||
})
|
||||
await Promise.all(batchWrites)
|
||||
assert(completed?.allRowsAccounted && completed.results.length === materials.length, 'complete_response_mapping_required')
|
||||
const summary = { readOnly: true, completedAt: new Date().toISOString(), ...identity, materialCount: materials.length,
|
||||
uniqueRegisteredSources: completed.uniqueRegisteredSources, actualGetAttempts: completed.actualGetAttempts,
|
||||
results: completed.results, healthyCount: completed.results.filter(item => item.ok).length,
|
||||
failedCount: completed.results.filter(item => !item.ok).length, statusCounts: {}, classificationCounts: {},
|
||||
candidateMetadataCount: candidateMapping.reduce((n, row) => n + row.candidates.length, 0), candidateGets: 0,
|
||||
allRowsAccounted: true, fullImageAuditExecuted: true, retries: 0, databaseWrites: 0, storageWrites: 0, modelCalls: 0 }
|
||||
for (const item of completed.results) {
|
||||
summary.statusCounts[item.status ?? 'not_dispatched'] = (summary.statusCounts[item.status ?? 'not_dispatched'] || 0) + 1
|
||||
summary.classificationCounts[item.classification] = (summary.classificationCounts[item.classification] || 0) + 1
|
||||
}
|
||||
await write('unique-url-audit.json', completed)
|
||||
await write('audit-summary.json', summary)
|
||||
return { ...summary, results: undefined, outputDirectory: directory }
|
||||
} catch (error) {
|
||||
await Promise.allSettled(batchWrites)
|
||||
await write('audit-incomplete.json', { readOnly: true, complete: false, code: 'read_only_audit_incomplete', completedBatches: batchWrites.length,
|
||||
noAutomaticRetry: true, metadataCount: materials.length })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
main().then(result => console.log(JSON.stringify(result, null, 2)), () => {
|
||||
console.log(JSON.stringify({ readOnly: true, complete: false, code: 'read_only_audit_failed', retries: 0 }))
|
||||
process.exitCode = 1
|
||||
})
|
||||
}
|
||||
91
scripts/audit-legacy-material-previews.test.mjs
Normal file
91
scripts/audit-legacy-material-previews.test.mjs
Normal file
@ -0,0 +1,91 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { createHash } from 'node:crypto'
|
||||
import test from 'node:test'
|
||||
import { AUDIT_LIMITS, auditPreviewBatch, auditUniquePreviews, main, metadataCandidates, validateAuditSnapshot } from './audit-legacy-material-previews.mjs'
|
||||
import { LEGACY_DOMAINS } from './check-legacy-storage-boundaries.mjs'
|
||||
|
||||
const host = LEGACY_DOMAINS[0]
|
||||
const source = n => `https://${host}/jsxiangche/preview-${n}.webp`
|
||||
const row = (id, index = id) => ({ id, materialType: '详情模板', previewUrl: source(index) })
|
||||
const html = '<!doctype html><html><body>Not Found. The server is powered by frp. Faithfully yours, frp.</body></html>'
|
||||
const response = () => new Response(html, { status: 404, headers: { 'content-type': 'text/html' } })
|
||||
|
||||
test('snapshot must match exact count, identity, and registered legacy host before any GET', () => {
|
||||
const value = { readOnly: true, count: 2, materials: [row('a'), row('b')] }
|
||||
assert.equal(validateAuditSnapshot(value, { host, expectedCount: 2 }).length, 2)
|
||||
assert.throws(() => validateAuditSnapshot(value, { host }), /exact_inventory_count_required/)
|
||||
assert.throws(() => validateAuditSnapshot({ ...value, materials: [row('a'), row('a')] }, { host, expectedCount: 2 }), /unique_material_identity_required/)
|
||||
assert.throws(() => validateAuditSnapshot({ ...value, materials: [row('a'), { ...row('b'), previewUrl: 'https://evil.example/a.webp' }] }, { host, expectedCount: 2 }), /inventory_host_changed/)
|
||||
})
|
||||
|
||||
test('candidate mapping keeps same-material display/preview evidence and excludes ZIP-like main role', () => {
|
||||
const material = { ...row('a'), displayImages: [source('display'), 'https://s3.jiansun.vip/gongxiangpan/p.png'],
|
||||
assets: [{ id: 'main', assetType: 'main', fileUrl: source('looks-like-image'), fileSize: '10' },
|
||||
{ id: 'good', assetType: 'main-preview', fileUrl: source('real-preview'), fileSize: '0' },
|
||||
{ id: 'bad', assetType: 'preview', fileUrl: 'https://s3.jiansun.vip/gongxiangpan/download.zip', fileSize: '1000000000' }],
|
||||
skus: [{ id: 'sku', previewUrl: source('sku'), filePath: 'https://s3.jiansun.vip/gongxiangpan/big.zip' }] }
|
||||
const result = metadataCandidates(material)
|
||||
assert.equal(result.materialId, 'a')
|
||||
assert.equal(result.candidates.length, 4)
|
||||
assert.equal(result.candidates.find(item => item.identity === 'good').declaredBytes, '0')
|
||||
assert.ok(result.candidates.every(item => item.metadataOnly && item.bytesRead === 0 && item.originalIdentityVerified === false))
|
||||
assert.deepEqual(result.excludedAssets.map(item => item.assetId), ['main', 'bad'])
|
||||
assert.ok(!JSON.stringify(result.candidates).includes('big.zip'))
|
||||
})
|
||||
|
||||
test('FRP failure still retains hash of the complete actual response body', async () => {
|
||||
let calls = 0
|
||||
const report = await auditPreviewBatch({ version: 1, reviewed: true, materials: [{ materialId: 'a', registeredSource: source('a') }] },
|
||||
{ fetchImpl: async () => { calls++; return response() } })
|
||||
assert.equal(calls, 1)
|
||||
assert.equal(report.results[0].code, 'frp_default_404')
|
||||
assert.equal(report.results[0].responseBodyComplete, true)
|
||||
assert.equal(report.results[0].responseBodySha256, createHash('sha256').update(html).digest('hex'))
|
||||
assert.equal(report.results[0].responseBytes, Buffer.byteLength(html))
|
||||
})
|
||||
|
||||
test('batches stay at fifty, duplicate URLs map every ID, and at most two GETs run concurrently', async () => {
|
||||
const materials = Array.from({ length: 103 }, (_, n) => row(`m-${n}`, n % 53))
|
||||
let active = 0, maxActive = 0
|
||||
const gets = new Map(), events = []
|
||||
const result = await auditUniquePreviews(materials, { fetchImpl: async url => {
|
||||
gets.set(url, (gets.get(url) || 0) + 1)
|
||||
active++; maxActive = Math.max(maxActive, active)
|
||||
await new Promise(resolve => setTimeout(resolve, 1))
|
||||
active--
|
||||
return response()
|
||||
}, onBatch: async event => events.push(event) })
|
||||
assert.equal(maxActive, 2)
|
||||
assert.equal(result.actualGetAttempts, 53)
|
||||
assert.equal(gets.size, 53)
|
||||
assert.ok([...gets.values()].every(value => value === 1))
|
||||
assert.deepEqual(result.batches.map(item => item.materials.length), [50, 3])
|
||||
assert.equal(events.length, 2)
|
||||
assert.equal(result.results.length, 103)
|
||||
assert.equal(new Set(result.results.map(item => item.materialId)).size, 103)
|
||||
assert.equal(result.allRowsAccounted, true)
|
||||
assert.ok(result.results.every(item => item.code === 'frp_default_404' && item.responseBodyComplete))
|
||||
assert.equal(result.results.find(item => item.materialId === 'm-53').checkedRepresentativeId, 'm-0')
|
||||
assert.equal(AUDIT_LIMITS.concurrency, 2)
|
||||
})
|
||||
|
||||
test('a non-preview source is recorded without GET and a timeout is never automatically retried', async () => {
|
||||
const materials = [row('a'), { ...row('b'), previewUrl: 'http://127.0.0.1/private' }]
|
||||
let calls = 0
|
||||
const result = await auditUniquePreviews(materials, { timeoutMs: 5, fetchImpl: () => { calls++; return new Promise(() => {}) } })
|
||||
assert.equal(calls, 1)
|
||||
assert.equal(result.results[0].classification, 'timeout')
|
||||
assert.equal(result.results[0].responseBodySha256, null)
|
||||
assert.equal(result.results[1].attempts, 0)
|
||||
assert.equal(result.results[1].classification, 'source_rejected')
|
||||
assert.equal(result.allRowsAccounted, true)
|
||||
assert.equal(result.retries, 0)
|
||||
})
|
||||
|
||||
test('default invocation is plan-only without SSH, database, images or file writes', async () => {
|
||||
const result = await main([])
|
||||
assert.equal(result.planOnly, true)
|
||||
assert.equal(result.expectedCount, 472)
|
||||
assert.equal(result.productionWrites, 0)
|
||||
await assert.rejects(main(['--run']), /run_requires_new_absolute_output_directory/)
|
||||
})
|
||||
@ -177,7 +177,9 @@ async function checkOne(entry, { fetchImpl, decodeImage, timeoutMs, maxBytes })
|
||||
let status = null
|
||||
let contentType = ''
|
||||
let bytesRead = 0
|
||||
const failure = (classification, code) => ({ ...base, ok: false, classification, code, status, contentType, bytes: bytesRead })
|
||||
let bodySha256
|
||||
const failure = (classification, code) => ({ ...base, ok: false, classification, code, status, contentType, bytes: bytesRead,
|
||||
...(bodySha256 ? { bodySha256 } : {}) })
|
||||
try {
|
||||
const response = await withAbort(fetchImpl(entry.url.href, {
|
||||
method: 'GET', cache: 'no-store', redirect: 'manual', signal: controller.signal,
|
||||
@ -200,6 +202,9 @@ async function checkOne(entry, { fetchImpl, decodeImage, timeoutMs, maxBytes })
|
||||
chunks.push(Buffer.from(value))
|
||||
}
|
||||
const bytes = Buffer.concat(chunks)
|
||||
// A fully read failure body can identify the known incident without storing
|
||||
// its contents. Partial, oversized and unavailable bodies have no digest.
|
||||
bodySha256 = sha256(bytes)
|
||||
const prefix = bytes.subarray(0, 4096).toString('utf8').replace(/^\uFEFF/, '').trimStart()
|
||||
const html = contentType === 'text/html' || /^(?:<!doctype\s+html|<html|<head|<body|<center)\b/i.test(prefix)
|
||||
const frpMarker = /(?:powered\s+by\s+frp\b|faithfully\s+yours,\s*frp\b|<center>\s*frp\s*<\/center>)/i.test(prefix)
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { createHash } from 'node:crypto'
|
||||
import test from 'node:test'
|
||||
import { createRequire } from 'node:module'
|
||||
import { checkMaterialPreviewHealth, createSharpPreviewDecoder, directFetch, isPublicAddress, LIMITS, registeredSource, validateManifest } from './check-material-preview-health.mjs'
|
||||
@ -12,6 +13,14 @@ const source = 'https://s3.jiansun.vip/gongxiangpan/public-display/example.png'
|
||||
const manifest = (url = source) => ({ version: 1, reviewed: true, materials: [{ materialId: 'material-a', registeredSource: url }] })
|
||||
const response = (body, type, status = 200, extra = {}) => new Response(body, { status, headers: { 'content-type': type, ...extra } })
|
||||
|
||||
test('complete failure bodies retain a digest for exact incident baselines without retaining raw contents', async () => {
|
||||
const body = '<html>Faithfully yours, frp.</html>'
|
||||
const report = await checkMaterialPreviewHealth(manifest(), { fetchImpl: async () => response(body, 'text/html', 404) })
|
||||
assert.equal(report.results[0].ok, false)
|
||||
assert.equal(report.results[0].bodySha256, createHash('sha256').update(body).digest('hex'))
|
||||
assert.equal(JSON.stringify(report).includes(body), false)
|
||||
})
|
||||
|
||||
test('normal PNG/JPEG/WebP use one actual uncached GET with no redirects or credentials', async () => {
|
||||
for (const [body, mime, format] of [[PNG, 'image/png', 'png'], [JPEG, 'image/jpeg', 'jpeg'], [WEBP, 'image/webp', 'webp']]) {
|
||||
const calls = []
|
||||
|
||||
1896
scripts/fixtures/material-preview-known-legacy-20261023.json
Normal file
1896
scripts/fixtures/material-preview-known-legacy-20261023.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -1052,6 +1052,11 @@ if [ "$SKIP_DEPLOY" != "1" ]; then
|
||||
fi
|
||||
ok "Production image revision label matches $COMMIT_SHA"
|
||||
|
||||
# Bundle from the exact fetched checkout, not workstation WIP or old image files.
|
||||
MATERIAL_PREVIEW_GATE_MODULE="$(node scripts/material-preview-release-gate.mjs bundle)" || fail "Material preview release gate could not be bundled from the exact checkout"
|
||||
[[ "$MATERIAL_PREVIEW_GATE_MODULE" = data:text/javascript\;base64,* ]] || fail "Material preview release gate bundle is invalid"
|
||||
[ "${#MATERIAL_PREVIEW_GATE_MODULE}" -le 524288 ] || fail "Material preview gate bundle exceeds its fixed transport budget"
|
||||
|
||||
IFS= read -r -d '' PROD_PAYLOAD <<'PROD_SCRIPT' || true
|
||||
set -Eeuo pipefail
|
||||
|
||||
@ -1809,6 +1814,104 @@ verify_candidate_brand_and_storage_dependencies() {
|
||||
verify_candidate_configured_brand_assets "$name" "$candidate_ip" || return 1
|
||||
}
|
||||
|
||||
# Every real release uses the same old/candidate/post probe plan. The only
|
||||
# mutable state is this project's private audit directory; no material, download,
|
||||
# bucket, or database value is written. A missing first baseline stops deployment.
|
||||
prepare_material_preview_release() {
|
||||
MATERIAL_PREVIEW_AUDIT_ROOT="${PROXY_ROOT}/material-preview-health"
|
||||
[ -n "${MATERIAL_PREVIEW_GATE_MODULE:-}" ] || return 1
|
||||
[ -d "$MATERIAL_PREVIEW_AUDIT_ROOT" ] && [ ! -L "$MATERIAL_PREVIEW_AUDIT_ROOT" ] || return 1
|
||||
[ -f "$MATERIAL_PREVIEW_AUDIT_ROOT/accepted-pointer.json" ] && [ ! -L "$MATERIAL_PREVIEW_AUDIT_ROOT/accepted-pointer.json" ] || return 1
|
||||
MATERIAL_PREVIEW_AUDIT_RUN="$(mktemp -d "${MATERIAL_PREVIEW_AUDIT_ROOT}/release-${COMMIT_SHA:0:12}-XXXXXXXX")" || return 1
|
||||
chmod 700 "$MATERIAL_PREVIEW_AUDIT_RUN" || return 1
|
||||
printf '%s' "$MATERIAL_PREVIEW_GATE_MODULE" >"$MATERIAL_PREVIEW_AUDIT_RUN/gate-module.url" || return 1
|
||||
chmod 600 "$MATERIAL_PREVIEW_AUDIT_RUN/gate-module.url" || return 1
|
||||
python3 - "$MATERIAL_PREVIEW_AUDIT_ROOT" "$MATERIAL_PREVIEW_AUDIT_RUN" <<'PY'
|
||||
import hashlib, json, os, pathlib, re, sys
|
||||
root, run = map(pathlib.Path, sys.argv[1:])
|
||||
try:
|
||||
pointer_raw = (root / 'accepted-pointer.json').read_bytes()
|
||||
pointer = json.loads(pointer_raw)
|
||||
relative = pointer['file']
|
||||
if pointer.get('version') != 1 or not re.fullmatch(r'(?:bootstrap-[A-Za-z0-9._-]+/bootstrap|release-[A-Za-z0-9._-]+/post)\.json', relative): raise ValueError()
|
||||
if not re.fullmatch(r'[0-9a-f]{64}', pointer['sha256']): raise ValueError()
|
||||
source = root / relative
|
||||
if source.is_symlink() or source.parent.is_symlink() or not source.is_file() or source.resolve().parent.parent != root.resolve(): raise ValueError()
|
||||
raw = source.read_bytes()
|
||||
if len(raw) > 32 * 1024 * 1024 or hashlib.sha256(raw).hexdigest() != pointer['sha256']: raise ValueError()
|
||||
for filename, content in [('accepted.json', raw), ('accepted-pointer-before.json', pointer_raw)]:
|
||||
with open(run / filename, 'xb') as f: f.write(content)
|
||||
os.chmod(run / filename, 0o600)
|
||||
except Exception:
|
||||
sys.stderr.write('Reviewed material preview baseline missing, changed, or outside its private audit root\n')
|
||||
sys.exit(1)
|
||||
PY
|
||||
}
|
||||
|
||||
run_material_preview_release_gate() {
|
||||
local name="$1" phase="$2" output_file="${MATERIAL_PREVIEW_AUDIT_RUN}/${2}.json" status=0
|
||||
case "$phase" in capture|candidate|post) ;; *) return 1 ;; esac
|
||||
[ ! -e "$output_file" ] && [ -f "$MATERIAL_PREVIEW_AUDIT_RUN/gate-module.url" ] || return 1
|
||||
# The program and input travel on stdin; no credentials or large JSON appear in
|
||||
# process arguments, environment variables, the image filesystem, or logs.
|
||||
if ! python3 - "$MATERIAL_PREVIEW_AUDIT_RUN" "$phase" "$COMMIT_SHA" "$S3_PUBLIC_DOMAIN" "$ENV_FILE_PATH" "$PUBLIC_APP_URL" <<'PY' | docker exec -i -w /app "$name" node --input-type=module - >"$output_file"
|
||||
import json, pathlib, sys
|
||||
run = pathlib.Path(sys.argv[1]); phase, commit, public_domain, env_file, app_url = sys.argv[2:]
|
||||
read = lambda name: json.loads((run / (name + '.json')).read_bytes())
|
||||
keys = ['S3_ENDPOINT','S3_BUCKET','S3_FILE_PATH','S3_PUBLIC_DOMAIN','S3_REGION','SERVER_IP','MINIO_API_PORT','APP_PUBLIC_URL']
|
||||
target = {key: '' for key in keys}; seen = set()
|
||||
for line in pathlib.Path(env_file).read_text().splitlines():
|
||||
if not line.strip() or line.lstrip().startswith('#') or '=' not in line: continue
|
||||
key, value = line.split('=', 1); key = key.strip()
|
||||
if key not in target or key in ('S3_PUBLIC_DOMAIN','APP_PUBLIC_URL'): continue
|
||||
if key in seen: raise ValueError('duplicate nonsecret delivery key')
|
||||
seen.add(key); target[key] = value
|
||||
target['S3_PUBLIC_DOMAIN'] = public_domain; target['APP_PUBLIC_URL'] = app_url
|
||||
payload = dict(version=1, stage=phase, commit=commit, accepted=read('accepted'), targetDeliveryConfig=target)
|
||||
if phase in ('candidate', 'post'): payload['capture'] = read('capture')
|
||||
if phase == 'post': payload['candidate'] = read('candidate')
|
||||
print('const {runReleaseStage}=await import(' + json.dumps((run / 'gate-module.url').read_text()) + ');')
|
||||
print('try { const r=await runReleaseStage(' + json.dumps(payload, separators=(',', ':')) + '); console.log(JSON.stringify(r)); process.exitCode=r.passed?0:1; } catch(e) { console.log(JSON.stringify({version:1,readOnly:true,passed:false,stage:' + json.dumps(phase) + ',code:typeof e?.code==="string"&&/^[a-z_]+$/.test(e.code)?e.code:"release_preview_detector_failed"}));process.exitCode=1; }')
|
||||
PY
|
||||
then status=1; fi
|
||||
chmod 600 "$output_file" || return 1
|
||||
if ! python3 - "$output_file" "$phase" <<'PY'
|
||||
import json, sys
|
||||
try:
|
||||
r = json.load(open(sys.argv[1])); phase = sys.argv[2]
|
||||
if r.get('stage') != phase or r.get('passed') is not True or r.get('readOnly') is not True:
|
||||
sys.stderr.write('Material preview release gate failed; retain the private receipt for diagnosis\n'); sys.exit(1)
|
||||
print('[OK] Material preview '+phase+': '+str(len(r['inventory']))+' metadata rows, '+str(len(r['checks']))+' fixed probes, '+str(len(r['knownFailures']))+' known failures retained, '+str(len(r['plan']['unverified']))+' explicitly unverified rows')
|
||||
except Exception:
|
||||
sys.stderr.write('Material preview release receipt is missing or incomplete\n'); sys.exit(1)
|
||||
PY
|
||||
then status=1; fi
|
||||
[ "$status" = 0 ] || return 1
|
||||
}
|
||||
|
||||
accept_material_preview_release() {
|
||||
# Promote only after the complete existing release acceptance, using one atomic
|
||||
# pointer. Immutable pre/post receipts and the previous pointer remain intact.
|
||||
python3 - "$MATERIAL_PREVIEW_AUDIT_ROOT" "$MATERIAL_PREVIEW_AUDIT_RUN" "$COMMIT_SHA" <<'PY'
|
||||
import hashlib, json, os, pathlib, sys
|
||||
root, run = map(pathlib.Path, sys.argv[1:3]); commit = sys.argv[3]
|
||||
try:
|
||||
if (root / 'accepted-pointer.json').read_bytes() != (run / 'accepted-pointer-before.json').read_bytes(): raise ValueError()
|
||||
reports = [json.loads((run / (stage + '.json')).read_bytes()) for stage in ('capture', 'candidate', 'post')]
|
||||
for stage, report in zip(('capture', 'candidate', 'post'), reports):
|
||||
if report.get('stage') != stage or report.get('commit') != commit or report.get('passed') is not True: raise ValueError()
|
||||
if len({r['planSha256'] for r in reports}) != 1 or len({r['inventorySha256'] for r in reports}) != 1 or len({r['metadataAudit']['inventorySha256'] for r in reports}) != 1: raise ValueError()
|
||||
raw = (run / 'post.json').read_bytes()
|
||||
pointer = dict(version=1, file=str((run / 'post.json').relative_to(root)), sha256=hashlib.sha256(raw).hexdigest())
|
||||
temporary = run / 'accepted-pointer.new'
|
||||
with open(temporary, 'xb') as f:
|
||||
os.chmod(temporary, 0o600); f.write((json.dumps(pointer, separators=(',', ':'))+'\n').encode()); f.flush(); os.fsync(f.fileno())
|
||||
os.replace(temporary, root / 'accepted-pointer.json')
|
||||
except Exception:
|
||||
sys.stderr.write('Material preview baseline was not promoted; previous release evidence retained\n'); sys.exit(1)
|
||||
PY
|
||||
}
|
||||
|
||||
verify_ready_bootstrap_handoff_evidence() {
|
||||
local handoff="$1"
|
||||
local evidence_name=""
|
||||
@ -2835,6 +2938,8 @@ direct_replace_active_container() {
|
||||
[[ "$previous_image" =~ ^sha256:[0-9a-f]{64}$ ]] || fail "Active container immutable image could not be determined: $name"
|
||||
verify_container_uploads_storage "$name" || fail "Active container uploads storage could not be verified before direct replacement"
|
||||
verify_image_revision_label "$REGISTRY_COMMIT" "$COMMIT_SHA" || fail "Direct replacement image label does not match the exact Git commit"
|
||||
prepare_material_preview_release || fail "Reviewed material preview baseline is unavailable; active container was not stopped"
|
||||
run_material_preview_release_gate "$name" capture || fail "Material preview pre-release gate failed; active container was not stopped"
|
||||
prepare_worker_runtime_directories || fail "Worker runtime directories could not be prepared"
|
||||
prepare_detail_generator_release || fail "Detail generator configuration or private persistent storage is invalid"
|
||||
|
||||
@ -2882,6 +2987,9 @@ direct_replace_active_container() {
|
||||
if ! verify_candidate_brand_and_storage_dependencies "$name" "$replacement_ip"; then
|
||||
fail_direct_replace_with_restore "New direct container cannot authenticate to S3 or decode configured brand images" "$name" "$previous_image"
|
||||
fi
|
||||
if ! run_material_preview_release_gate "$name" candidate; then
|
||||
fail_direct_replace_with_restore "Material previews regressed or inventory changed before traffic switch" "$name" "$previous_image"
|
||||
fi
|
||||
if ! wait_for_direct_worker_capabilities "$name"; then
|
||||
fail_direct_replace_with_restore "New direct container workers did not become ready within the bounded startup window" "$name" "$previous_image"
|
||||
fi
|
||||
@ -2897,7 +3005,11 @@ direct_replace_active_container() {
|
||||
if ! write_proxy_config "${replacement_ip}:3000" "$name" || ! switch_proxy || ! verify_proxy_target "$name" "$COMMIT_SHA"; then
|
||||
fail_direct_replace_with_restore "New direct container could not become the verified proxy target" "$name" "$previous_image"
|
||||
fi
|
||||
if ! run_material_preview_release_gate "$name" post; then
|
||||
fail_direct_replace_with_restore "Public material preview post-release gate failed" "$name" "$previous_image"
|
||||
fi
|
||||
write_current_container "$name" || fail "Direct replacement traffic is healthy but the current-slot record could not be written"
|
||||
accept_material_preview_release || fail_direct_replace_with_restore "Material preview accepted baseline could not be atomically recorded" "$name" "$previous_image"
|
||||
retire_inactive_direct_slot "$name" || warn "The inactive historical slot could not be removed; the active direct container remains healthy"
|
||||
rm -f -- "$(transcode_drain_file "$name")" "$(task_detail_drain_file "$name")" || true
|
||||
ok "Direct replacement completed: $name"
|
||||
@ -3724,6 +3836,10 @@ fi
|
||||
|
||||
ensure_public_traffic_rollup_token
|
||||
|
||||
[ -n "$CURRENT_CONTAINER" ] || fail "Material preview baseline requires an existing verified active container"
|
||||
prepare_material_preview_release || fail "Reviewed material preview baseline is unavailable; traffic was not changed"
|
||||
run_material_preview_release_gate "$CURRENT_CONTAINER" capture || fail "Material preview pre-release gate failed; traffic was not changed"
|
||||
|
||||
TRANSCODE_DRAIN_SOURCES=""
|
||||
if [ -n "$CURRENT_CONTAINER" ]; then
|
||||
TRANSCODE_DRAIN_SOURCES="$CURRENT_CONTAINER"
|
||||
@ -3848,6 +3964,9 @@ fi
|
||||
if ! verify_candidate_brand_and_storage_dependencies "$NEXT_CONTAINER" "$NEXT_IP"; then
|
||||
fail_candidate_before_traffic "Candidate cannot authenticate to S3 or fully decode its configured and baked brand images; traffic was not switched"
|
||||
fi
|
||||
if ! run_material_preview_release_gate "$NEXT_CONTAINER" candidate; then
|
||||
fail_candidate_before_traffic "Material previews regressed or inventory changed; traffic was not switched"
|
||||
fi
|
||||
if ! verify_video_transcode_capability "$NEXT_CONTAINER"; then
|
||||
fail_candidate_before_traffic "Candidate did not publish the required video transcode drain capability"
|
||||
fi
|
||||
@ -3885,6 +4004,10 @@ if [ "$SWITCH_REPORTED_FAILURE" = "1" ]; then
|
||||
warn "Proxy switch command reported failure, but the runtime candidate target was independently verified"
|
||||
fi
|
||||
|
||||
if ! run_material_preview_release_gate "$NEXT_CONTAINER" post; then
|
||||
abort_after_uncertain_switch "Public material preview post-release gate failed"
|
||||
fi
|
||||
|
||||
if ! write_current_container "$NEXT_CONTAINER"; then
|
||||
abort_after_uncertain_switch "Candidate traffic was verified but the committed target record could not be written"
|
||||
fi
|
||||
@ -4032,6 +4155,8 @@ const fs = require("fs");
|
||||
ok "Public commit, target, database, Redis, authenticated S3, and all Logo images passed acceptance"
|
||||
fi
|
||||
|
||||
accept_material_preview_release || abort_after_uncertain_switch "Material preview accepted baseline could not be atomically recorded"
|
||||
|
||||
[ -z "$READY_BOOTSTRAP_HANDOFF" ] || {
|
||||
mv -- "$READY_BOOTSTRAP_HANDOFF/handoff.ready" "$READY_BOOTSTRAP_HANDOFF/consumed" || \
|
||||
abort_after_uncertain_switch "Bootstrap handoff could not be atomically consumed after acceptance"
|
||||
@ -4040,7 +4165,7 @@ fi
|
||||
}
|
||||
PROD_SCRIPT
|
||||
|
||||
printf '%s' "$PROD_PAYLOAD" | prod_ssh_script \
|
||||
printf '%s\n%s' "MATERIAL_PREVIEW_GATE_MODULE=$(printf '%q' "$MATERIAL_PREVIEW_GATE_MODULE")" "$PROD_PAYLOAD" | prod_ssh_script \
|
||||
"$TARGET" "$CONTAINER_NAME" "$PORT" "$REGISTRY_COMMIT" "$EXPECTED_IMAGE_ID" "$COMMIT_SHA" \
|
||||
"/mnt/PoolOne/apps/youyidian-3d/$ENV_FILE" "$PUBLIC_APP_URL" "$CORS_ALLOWED_ORIGINS" \
|
||||
"$DINGTALK_CALLBACK_ORIGIN" "$DINGTALK_INTERNAL_RETURN_ORIGINS" "$S3_PUBLIC_DOMAIN" \
|
||||
|
||||
@ -127,6 +127,69 @@ function shellFunction(name) {
|
||||
return source.slice(start, end + 3)
|
||||
}
|
||||
|
||||
test('preview inventory and fixed probes guard direct stop, switch, and baseline promotion in both wrappers', () => {
|
||||
const direct = shellFunction('direct_replace_active_container')
|
||||
const stop = direct.indexOf('docker stop --time 10')
|
||||
const switchTraffic = direct.indexOf('write_proxy_config "${replacement_ip}:3000"')
|
||||
const record = direct.indexOf('write_current_container "$name"')
|
||||
assert.ok(direct.indexOf('prepare_material_preview_release') < stop)
|
||||
assert.ok(direct.indexOf('run_material_preview_release_gate "$name" capture') < stop)
|
||||
assert.ok(direct.indexOf('run_material_preview_release_gate "$name" candidate') > stop)
|
||||
assert.ok(direct.indexOf('run_material_preview_release_gate "$name" candidate') < switchTraffic)
|
||||
assert.ok(direct.indexOf('run_material_preview_release_gate "$name" post') > switchTraffic)
|
||||
assert.ok(direct.indexOf('run_material_preview_release_gate "$name" post') < record)
|
||||
assert.ok(direct.indexOf('accept_material_preview_release') > record)
|
||||
const payload = extractRemoteTemplate(deploySource())
|
||||
assert.match(payload, /node scripts\/material-preview-release-gate\.mjs bundle/)
|
||||
assert.match(payload, /run_material_preview_release_gate "\$NEXT_CONTAINER" candidate/)
|
||||
assert.match(payload, /run_material_preview_release_gate "\$NEXT_CONTAINER" post/)
|
||||
assert.match(payload, /MATERIAL_PREVIEW_GATE_MODULE=\$\(printf '%q'/)
|
||||
assert.doesNotMatch(payload, /SKIP_MATERIAL_PREVIEW|IGNORE_MATERIAL_PREVIEW|ALLOW_PREVIEW_FAILURE/)
|
||||
})
|
||||
|
||||
test('real direct shell control flow stops before replacement or uses existing rollback exactly once on preview regression', () => {
|
||||
const direct = shellFunction('direct_replace_active_container')
|
||||
const inert = ['verify_container_uploads_storage', 'verify_image_revision_label', 'prepare_worker_runtime_directories', 'prepare_detail_generator_release',
|
||||
'create_container', 'verify_container_uploads_mount_metadata', 'verify_container_upload_dir_config', 'verify_container_baked_revision',
|
||||
'verify_transcode_lease_schema', 'verify_task_detail_upload_lease_schema', 'verify_detail_generator_schema', 'verify_detail_generator_dependencies',
|
||||
'verify_brand_logo_defaults', 'verify_material_upload_idempotency_schema', 'verify_candidate_database_identity', 'verify_candidate_brand_and_storage_dependencies',
|
||||
'wait_for_direct_worker_capabilities', 'verify_video_transcode_capability', 'verify_task_detail_upload_capability', 'verify_proxy_target', 'retire_inactive_direct_slot']
|
||||
for (const phase of ['capture', 'candidate', 'post', 'none']) {
|
||||
const input = `set -u
|
||||
BLUE_CONTAINER=material-blue
|
||||
GREEN_CONTAINER=material-green
|
||||
REGISTRY_COMMIT=registry/exact-image
|
||||
COMMIT_SHA=${'a'.repeat(40)}
|
||||
log() { :; }
|
||||
ok() { :; }
|
||||
warn() { :; }
|
||||
fail() { printf 'blocked:%s\n' "$*"; exit 82; }
|
||||
docker() { case "$1" in inspect) printf 'sha256:${'b'.repeat(64)}\n' ;; *) printf 'docker:%s\n' "$1" ;; esac; }
|
||||
${inert.map(name => `${name}() { return 0; }`).join('\n')}
|
||||
prepare_material_preview_release() { printf 'prepare\n'; }
|
||||
run_material_preview_release_gate() { printf 'probe:%s\n' "$2"; [ "$2" != '${phase}' ]; }
|
||||
fail_direct_replace_with_restore() { printf 'existing-rollback-once\n'; exit 81; }
|
||||
wait_for_container_health() { printf '172.18.0.9\n'; }
|
||||
write_proxy_config() { printf 'traffic-prepared\n'; }
|
||||
switch_proxy() { printf 'traffic-switched\n'; }
|
||||
write_current_container() { printf 'current-recorded\n'; }
|
||||
accept_material_preview_release() { printf 'baseline-promoted\n'; }
|
||||
transcode_drain_file() { printf '/not-a-real-drain-file\n'; }
|
||||
task_detail_drain_file() { printf '/not-a-real-upload-file\n'; }
|
||||
rm() { return 0; }
|
||||
${direct}
|
||||
direct_replace_active_container material-blue
|
||||
`
|
||||
const result = spawnSync(bash, ['-s'], { input, encoding: 'utf8' })
|
||||
assert.equal(result.status, phase === 'none' ? 0 : phase === 'capture' ? 82 : 81, result.stderr || result.stdout)
|
||||
assert.equal((result.stdout.match(/existing-rollback-once/g) || []).length, ['candidate', 'post'].includes(phase) ? 1 : 0)
|
||||
if (phase === 'capture') assert.doesNotMatch(result.stdout, /docker:stop|traffic-switched|baseline-promoted/)
|
||||
if (phase === 'candidate') assert.doesNotMatch(result.stdout, /traffic-switched|baseline-promoted/)
|
||||
if (phase === 'post') { assert.match(result.stdout, /traffic-switched/); assert.doesNotMatch(result.stdout, /current-recorded|baseline-promoted/) }
|
||||
if (phase === 'none') assert.ok(result.stdout.indexOf('probe:post') < result.stdout.indexOf('baseline-promoted'))
|
||||
}
|
||||
})
|
||||
|
||||
test('storage deployment gate rejects broken public bucket URLs before authenticating', async () => {
|
||||
const fn = shellFunction('verify_candidate_authenticated_s3')
|
||||
const code = fn.slice(fn.indexOf("node -e '\n") + "node -e '\n".length, fn.lastIndexOf("\n'"))
|
||||
|
||||
309
scripts/material-preview-release-gate.mjs
Normal file
309
scripts/material-preview-release-gate.mjs
Normal file
@ -0,0 +1,309 @@
|
||||
// Read-only release inventory and bounded probes. No writes to materials or storage.
|
||||
import { createHash } from 'node:crypto'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { checkMaterialPreviewHealth, directFetch } from './check-material-preview-health.mjs'
|
||||
import { collectMaterialPreviewInventory } from './export-material-preview-health-manifest.mjs'
|
||||
import { LEGACY_DOMAINS } from './check-legacy-storage-boundaries.mjs'
|
||||
|
||||
export const POLICY = Object.freeze({ version: 1, concurrency: 4, probes: 768, bytes: 128 * 1024 * 1024, wallMs: 360_000 })
|
||||
export const CRITICAL_MATERIAL_IDS = Object.freeze([
|
||||
'6e763f52-a21f-4b4e-99fb-634478f68eed', '82f3a6b7-6323-4cf5-a741-d990182f382c',
|
||||
'd3a0addb-b4f0-4110-958d-3f897490fa4c', '72a39203-7f61-43b5-b243-73fe19ffde99',
|
||||
'a6b97e8a-bd68-483f-b8f8-743e8baef850', '0329debe-054d-4ee7-9411-59f7cb2cdcc1',
|
||||
'b9a9947c-ef68-4616-9144-a0d1fd912799', 'ac19c78a-c09f-4ed9-a3c3-12bf9c950a56',
|
||||
'ea4cb1d2-fd25-46cb-aeba-93508c0793f8', '6c2675ab-c495-4c63-8d63-24ddee9e6535',
|
||||
'c9abdd91-a666-4f36-a475-6e082906a94e', 'd0e929f7-1186-4eac-acef-3af74a9567ee',
|
||||
])
|
||||
export const DELIVERY_FILES = Object.freeze(['lib/url-rewrite.ts', 'lib/proxy-media-security.ts', 'app/api/proxy-media/route.ts', 'lib/s3.ts', 'lib/network-detection.ts'])
|
||||
export const KNOWN_FRP_FAILURE = Object.freeze({ bytes: 489, bodySha256: '967e369d3be4fab5eb1229ec015b2923abf6bc81ebe3aaa662cb095cbec81023' })
|
||||
export const KNOWN_COMPATIBILITY_PROOF = Object.freeze({ materialId: '6e763f52-a21f-4b4e-99fb-634478f68eed',
|
||||
bodySha256: 'b40687cac0cbd537e209f8caa56c642bf501a658d0c3585140e8b9950937da53', width: 768, height: 1600 })
|
||||
export const KNOWN_LEGACY_MEMBERS_SHA256 = '953e6b1c9e10ea05e30e289ebbd5364569d918b5dd4a1273af52abc531fe475c'
|
||||
export const DELIVERY_CONFIG_KEYS = Object.freeze(['S3_ENDPOINT', 'S3_BUCKET', 'S3_FILE_PATH', 'S3_PUBLIC_DOMAIN', 'S3_REGION', 'SERVER_IP', 'MINIO_API_PORT', 'APP_PUBLIC_URL'])
|
||||
// bundleReleaseGate replaces this literal with hashes from the exact build checkout.
|
||||
const PINNED_TARGET_DELIVERY_CODE = null
|
||||
const sha = value => createHash('sha256').update(value).digest('hex')
|
||||
const digest = value => sha(JSON.stringify(value))
|
||||
const runtimeRequire = createRequire(import.meta.url)
|
||||
export class GateError extends Error { constructor(code) { super(code); this.code = code } }
|
||||
const fail = code => { throw new GateError(code) }
|
||||
const sourceKey = row => `${row.materialId}:${row.sourceSha256}`
|
||||
const probeKey = row => `${row.materialId}:${row.role}:${row.sourceSha256}`
|
||||
|
||||
async function readKnownLegacyProof(root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')) {
|
||||
const policy = JSON.parse(await readFile(path.join(root, 'scripts/fixtures/material-preview-known-legacy-20261023.json'), 'utf8'))
|
||||
if (policy?.version !== 1 || policy.reviewedAuditSha256 !== '40eb8d834d5c6bd9edcdc49e69ae227a83be2374bb9b525a0cec0bcd652c4e0d'
|
||||
|| policy.members?.length !== 472 || new Set(policy.members.map(row => row.materialId)).size !== 472
|
||||
|| digest(policy.members) !== KNOWN_LEGACY_MEMBERS_SHA256 || policy.membersSha256 !== KNOWN_LEGACY_MEMBERS_SHA256) fail('reviewed_legacy_membership_proof_changed')
|
||||
return policy.members
|
||||
}
|
||||
// The exact-checkout bundler inlines this reviewed ID/hash-only proof.
|
||||
const PINNED_KNOWN_LEGACY_MEMBERS = await readKnownLegacyProof()
|
||||
|
||||
export function normalizeDeliveryConfig(raw) {
|
||||
if (!raw || Object.keys(raw).sort().join('|') !== [...DELIVERY_CONFIG_KEYS].sort().join('|')) fail('complete_delivery_configuration_required')
|
||||
const values = Object.fromEntries(DELIVERY_CONFIG_KEYS.map(key => {
|
||||
if (typeof raw[key] !== 'string' || raw[key].length > 2048 || /[\x00-\x1f\x7f]/.test(raw[key])) fail('invalid_delivery_configuration')
|
||||
return [key, raw[key].trim()]
|
||||
}))
|
||||
for (const key of ['S3_ENDPOINT', 'S3_PUBLIC_DOMAIN', 'APP_PUBLIC_URL']) {
|
||||
let url
|
||||
try { url = new URL(values[key]) } catch { fail('invalid_delivery_configuration_url') }
|
||||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) fail('credential_or_query_in_delivery_configuration')
|
||||
values[key] = url.href.replace(/\/$/, '')
|
||||
}
|
||||
if (!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(values.S3_BUCKET) || values.S3_BUCKET.includes('..')) fail('invalid_delivery_bucket')
|
||||
if (values.SERVER_IP && !/^[A-Za-z0-9.:\[\]-]+$/.test(values.SERVER_IP)) fail('invalid_delivery_server')
|
||||
values.MINIO_API_PORT ||= '9000'
|
||||
if (!/^\d{1,5}$/.test(values.MINIO_API_PORT) || Number(values.MINIO_API_PORT) < 1 || Number(values.MINIO_API_PORT) > 65535) fail('invalid_delivery_port')
|
||||
values.S3_REGION ||= 'us-east-1'
|
||||
return values
|
||||
}
|
||||
|
||||
export function canonicalDeliverySource(source, publicDomain) {
|
||||
const current = new URL(publicDomain)
|
||||
if (current.href.replace(/\/$/, '') !== 'https://s3.jiansun.vip/gongxiangpan') fail('untrusted_public_bucket_configuration')
|
||||
const url = new URL(source)
|
||||
// Independent historical bucket is deliberately never mapped to the current bucket.
|
||||
if (url.hostname === LEGACY_DOMAINS[0] && url.pathname.startsWith('/jsxiangche/')) return url.href
|
||||
if (!url.pathname.startsWith('/gongxiangpan/')) return url.href
|
||||
url.protocol = current.protocol; url.hostname = current.hostname; url.port = ''
|
||||
return url.href
|
||||
}
|
||||
|
||||
export function inventoryIndex(inventory) {
|
||||
const { audit, manifests } = inventory
|
||||
if (audit?.inventoryComplete !== true || audit.activeCount !== audit.exportedCount + audit.uncheckableCount
|
||||
|| manifests.reduce((n, batch) => n + batch.materials.length, 0) !== audit.exportedCount) fail('inventory_coverage_incomplete')
|
||||
const index = [
|
||||
...manifests.flatMap(batch => batch.materials.map(row => ({ materialId: row.materialId, sourceSha256: sha(row.registeredSource), registeredSource: row.registeredSource }))),
|
||||
...audit.uncheckable.map(row => ({ materialId: row.materialId, sourceSha256: row.sourceSha256, uncheckable: { classification: row.classification, code: row.code } })),
|
||||
].sort((a, b) => a.materialId.localeCompare(b.materialId, 'en'))
|
||||
if (index.length !== audit.activeCount || new Set(index.map(row => row.materialId)).size !== index.length) fail('inventory_coverage_incomplete')
|
||||
return index
|
||||
}
|
||||
|
||||
function validateIndex(index) {
|
||||
if (!Array.isArray(index) || new Set(index.map(row => row.materialId)).size !== index.length
|
||||
|| index.some(row => typeof row.materialId !== 'string' || !/^[a-f0-9]{64}$/.test(row.sourceSha256)
|
||||
|| (row.registeredSource ? sha(row.registeredSource) !== row.sourceSha256 : !row.uncheckable))) fail('invalid_inventory_index')
|
||||
}
|
||||
|
||||
export function buildPlan(index, prior, { publicDomain, criticalIds = CRITICAL_MATERIAL_IDS, expandedScope = false, bootstrap = false } = {}) {
|
||||
validateIndex(index)
|
||||
if (!bootstrap) validateAccepted(prior)
|
||||
const previous = new Map((prior?.inventory || []).map(row => [row.materialId, row]))
|
||||
const required = new Set(criticalIds), selected = [], unverified = [], changedUncheckable = []
|
||||
for (const row of index) {
|
||||
const old = previous.get(row.materialId)
|
||||
const changed = !old || sourceKey(old) !== sourceKey(row)
|
||||
if (!row.registeredSource) {
|
||||
if (!bootstrap && changed) changedUncheckable.push(row.materialId)
|
||||
unverified.push({ materialId: row.materialId, reason: 'unsupported_or_missing_registered_source' })
|
||||
continue
|
||||
}
|
||||
const source = new URL(row.registeredSource)
|
||||
const independentLegacy = source.hostname === LEGACY_DOMAINS[0] && source.pathname.startsWith('/jsxiangche/')
|
||||
const reasons = [...(independentLegacy ? ['independent_legacy_storage'] : []), ...(required.has(row.materialId) ? ['critical_material'] : []),
|
||||
...(!bootstrap && changed ? ['new_or_changed_source'] : []), ...(expandedScope ? ['delivery_dependency_changed'] : [])]
|
||||
if (!reasons.length) { unverified.push({ materialId: row.materialId, reason: 'unchanged_current_source_outside_bounded_scope' }); continue }
|
||||
const delivery = canonicalDeliverySource(row.registeredSource, publicDomain)
|
||||
selected.push({ materialId: row.materialId, registeredSource: row.registeredSource, sourceSha256: row.sourceSha256, reasons,
|
||||
deliverySource: delivery, independentLegacy })
|
||||
}
|
||||
const present = new Set(selected.map(row => row.materialId))
|
||||
if ([...required].some(id => !present.has(id))) fail('critical_material_coverage_missing')
|
||||
if (changedUncheckable.length) fail('new_or_changed_uncheckable_preview')
|
||||
const probes = selected.flatMap(row => [
|
||||
{ materialId: row.materialId, role: 'registered', registeredSource: row.registeredSource, sourceSha256: row.sourceSha256 },
|
||||
...(row.deliverySource === row.registeredSource ? [] : [{ materialId: row.materialId, role: 'canonical', registeredSource: row.deliverySource, sourceSha256: sha(row.deliverySource) }]),
|
||||
])
|
||||
if (!probes.length || probes.length > POLICY.probes) fail('probe_budget_requires_independent_full_acceptance')
|
||||
return { selected, probes, unverified, expandedScope, publicDomain, criticalIds: [...criticalIds] }
|
||||
}
|
||||
|
||||
function failureSignature(result) {
|
||||
return digest([result.classification, result.code, result.status, result.contentType, result.bytes, result.bodySha256 ?? null])
|
||||
}
|
||||
function validateChecks(plan, checks) {
|
||||
if (!Array.isArray(checks) || checks.length !== plan.probes.length) fail('probe_coverage_incomplete')
|
||||
const expected = new Set(plan.probes.map(probeKey)), seen = new Set()
|
||||
for (const check of checks) {
|
||||
const key = probeKey(check)
|
||||
if (!expected.has(key) || seen.has(key) || check.result?.source?.sha256 !== check.sourceSha256 || check.result.attempts !== 1
|
||||
|| check.result.materialId !== check.materialId || typeof check.result.ok !== 'boolean') fail('probe_identity_or_coverage_mismatch')
|
||||
if (check.result.ok && (!/^[a-f0-9]{64}$/.test(check.result.bodySha256) || check.result.classification !== 'healthy'
|
||||
|| check.result.status < 200 || check.result.status >= 300 || !Number.isSafeInteger(check.result.decoded?.width) || !Number.isSafeInteger(check.result.decoded?.height)
|
||||
|| check.result.decoded.width < 1 || check.result.decoded.height < 1 || check.result.decoded.width * check.result.decoded.height > 25_000_000)) fail('undecoded_healthy_probe')
|
||||
seen.add(key)
|
||||
}
|
||||
}
|
||||
|
||||
export function validateAccepted(artifact) {
|
||||
if (artifact?.version !== 1 || artifact.policyVersion !== POLICY.version || artifact.passed !== true
|
||||
|| !['bootstrap', 'post'].includes(artifact.stage) || !/^[a-f0-9]{64}$/.test(artifact.inventorySha256)) fail('reviewed_baseline_required')
|
||||
validateIndex(artifact.inventory)
|
||||
if (digest(normalizeDeliveryConfig(artifact.deliveryConfig)) !== artifact.deliveryConfigSha256
|
||||
|| artifact.knownLegacyMembersSha256 !== KNOWN_LEGACY_MEMBERS_SHA256) fail('baseline_delivery_or_legacy_proof_mismatch')
|
||||
if (digest(artifact.inventory) !== artifact.inventorySha256 || digest(artifact.plan) !== artifact.planSha256) fail('baseline_digest_mismatch')
|
||||
validateChecks(artifact.plan, artifact.checks)
|
||||
if (digest(artifact.checks) !== artifact.checksSha256) fail('baseline_checks_digest_mismatch')
|
||||
}
|
||||
|
||||
export function compareChecks(plan, checks, baseline, { bootstrap = false, legacyFailureProof = KNOWN_FRP_FAILURE, compatibilityProof = KNOWN_COMPATIBILITY_PROOF,
|
||||
legacyMembers = PINNED_KNOWN_LEGACY_MEMBERS } = {}) {
|
||||
validateChecks(plan, checks)
|
||||
const known = new Map((baseline?.checks || []).map(row => [probeKey(row), row.result]))
|
||||
const checksMap = new Map(checks.map(row => [probeKey(row), row.result]))
|
||||
const legacyIdentities = new Set(legacyMembers.map(sourceKey))
|
||||
const problems = [], knownFailures = []
|
||||
for (const check of checks) {
|
||||
const row = plan.selected.find(item => item.materialId === check.materialId)
|
||||
const old = known.get(probeKey(check)), result = check.result
|
||||
if (['decoder_unavailable', 'invalid_manifest', 'source_rejected'].includes(result.classification)) { problems.push({ materialId: check.materialId, role: check.role, code: 'detector_or_source_validation_failure' }); continue }
|
||||
if (result.ok) {
|
||||
if (old?.ok && result.bodySha256 !== old.bodySha256) problems.push({ materialId: check.materialId, role: check.role, code: 'unchanged_url_content_changed' })
|
||||
continue
|
||||
}
|
||||
// Bootstrap is explicitly installed by a human after reviewing its exact artifact SHA.
|
||||
// It may document the incident's known FRP misses, never arbitrary new failures.
|
||||
const legacyFrp = row.independentLegacy && result.classification === 'routing_failure' && result.code === 'frp_default_404' && result.status === 404
|
||||
&& result.bytes === legacyFailureProof.bytes && result.bodySha256 === legacyFailureProof.bodySha256
|
||||
&& legacyIdentities.has(sourceKey(row))
|
||||
const canonical = checksMap.get(probeKey({ materialId: row.materialId, role: 'canonical', sourceSha256: sha(row.deliverySource) }))
|
||||
const rawCompatUnavailable = check.role === 'registered' && row.deliverySource !== row.registeredSource && canonical?.ok
|
||||
&& row.materialId === compatibilityProof.materialId && canonical.bodySha256 === compatibilityProof.bodySha256
|
||||
&& canonical.decoded.width === compatibilityProof.width && canonical.decoded.height === compatibilityProof.height
|
||||
&& ['network_failure', 'timeout'].includes(result.classification)
|
||||
if (bootstrap ? (legacyFrp || rawCompatUnavailable) : old && !old.ok && failureSignature(result) === failureSignature(old)) {
|
||||
knownFailures.push({ materialId: check.materialId, role: check.role, classification: result.classification, code: result.code, status: result.status })
|
||||
} else problems.push({ materialId: check.materialId, role: check.role, code: 'new_or_changed_failure' })
|
||||
}
|
||||
// Canonical delivery must be healthy except for the explicitly documented independent legacy incident.
|
||||
for (const row of plan.selected) {
|
||||
const role = row.deliverySource === row.registeredSource ? 'registered' : 'canonical'
|
||||
const result = checksMap.get(probeKey({ materialId: row.materialId, role, sourceSha256: sha(row.deliverySource) }))
|
||||
if (!result?.ok && !row.independentLegacy) problems.push({ materialId: row.materialId, role, code: 'delivery_preview_unavailable' })
|
||||
}
|
||||
return { passed: problems.length === 0, problems, knownFailures, allSelectedHealthy: checks.every(row => row.result.ok) }
|
||||
}
|
||||
|
||||
export async function runProbes(plan, { fetchImpl = directFetch, decodeImage, now = Date.now } = {}) {
|
||||
if (!Array.isArray(plan?.probes) || !plan.probes.length || plan.probes.length > POLICY.probes) fail('probe_budget_requires_independent_full_acceptance')
|
||||
const start = now(), controller = new AbortController()
|
||||
let bytes = 0, cursor = 0, budgetFailure = null
|
||||
const timer = setTimeout(() => { budgetFailure = 'release_probe_wall_budget'; controller.abort() }, POLICY.wallMs)
|
||||
const checks = new Array(plan.probes.length)
|
||||
const guardedFetch = async (url, options) => {
|
||||
const response = await fetchImpl(url, { ...options, signal: AbortSignal.any([options.signal, controller.signal]) })
|
||||
if (!response.body) return response
|
||||
const guarded = new Response(response.body.pipeThrough(new TransformStream({ transform(chunk, output) {
|
||||
bytes += chunk.byteLength
|
||||
if (bytes > POLICY.bytes) { budgetFailure = 'release_probe_byte_budget'; controller.abort(); throw new GateError(budgetFailure) }
|
||||
output.enqueue(chunk)
|
||||
} })), { status: response.status, headers: response.headers })
|
||||
Object.defineProperties(guarded, { redirected: { value: response.redirected }, url: { value: response.url } })
|
||||
return guarded
|
||||
}
|
||||
try {
|
||||
await Promise.all(Array.from({ length: Math.min(POLICY.concurrency, plan.probes.length) }, async () => {
|
||||
while (cursor < plan.probes.length && !controller.signal.aborted) {
|
||||
if (now() - start >= POLICY.wallMs) { budgetFailure = 'release_probe_wall_budget'; controller.abort(); break }
|
||||
const index = cursor++, probe = plan.probes[index]
|
||||
const manifest = { version: 1, reviewed: true, materials: [{ materialId: probe.materialId, registeredSource: probe.registeredSource }] }
|
||||
const report = await checkMaterialPreviewHealth(manifest, { fetchImpl: guardedFetch, ...(decodeImage ? { decodeImage } : {}) })
|
||||
checks[index] = { ...probe, result: report.results[0] }
|
||||
}
|
||||
}))
|
||||
} finally { clearTimeout(timer); controller.abort() }
|
||||
if (budgetFailure) fail(budgetFailure)
|
||||
validateChecks(plan, checks)
|
||||
return { checks, budget: { ...POLICY, actualBytes: bytes, elapsedMs: now() - start, requests: checks.length, retries: 0 } }
|
||||
}
|
||||
|
||||
async function deliveryCode(root) {
|
||||
return Object.fromEntries(await Promise.all(DELIVERY_FILES.map(async file => [file, sha(await readFile(path.join(root, file)))])))
|
||||
}
|
||||
|
||||
export async function runReleaseStage(input, { prismaClient, collectInventory = collectMaterialPreviewInventory, probe = runProbes,
|
||||
root = '/app', readDeliveryCode = deliveryCode, environment = process.env, targetDeliveryCode = PINNED_TARGET_DELIVERY_CODE,
|
||||
legacyFailureProof = KNOWN_FRP_FAILURE, compatibilityProof = KNOWN_COMPATIBILITY_PROOF, legacyMembers = PINNED_KNOWN_LEGACY_MEMBERS } = {}) {
|
||||
if (input?.version !== 1 || !['bootstrap', 'capture', 'candidate', 'post'].includes(input.stage)
|
||||
|| !/^[a-f0-9]{40}$/.test(input.commit)) fail('invalid_release_stage')
|
||||
const bootstrap = input.stage === 'bootstrap'
|
||||
if (!bootstrap) validateAccepted(input.accepted)
|
||||
const owned = !prismaClient
|
||||
const prisma = prismaClient || new (runtimeRequire('@prisma/client').PrismaClient)({ log: [] })
|
||||
let collected
|
||||
try { collected = await collectInventory(prisma) } finally { if (owned) await prisma.$disconnect() }
|
||||
const inventory = inventoryIndex(collected), inventorySha256 = digest(inventory)
|
||||
const code = await readDeliveryCode(root)
|
||||
if (Object.keys(code).sort().join('|') !== [...DELIVERY_FILES].sort().join('|') || Object.values(code).some(v => !/^[a-f0-9]{64}$/.test(v))) fail('delivery_code_identity_unavailable')
|
||||
const deliveryConfig = normalizeDeliveryConfig(Object.fromEntries(DELIVERY_CONFIG_KEYS.map(key => [key, environment[key] ?? ''])))
|
||||
const publicDomain = deliveryConfig.S3_PUBLIC_DOMAIN
|
||||
const targetConfig = bootstrap ? deliveryConfig : normalizeDeliveryConfig(input.targetDeliveryConfig)
|
||||
let plan, expected
|
||||
if (bootstrap || input.stage === 'capture') {
|
||||
const expandedScope = !bootstrap && (!targetDeliveryCode || digest(code) !== digest(targetDeliveryCode)
|
||||
|| digest(input.accepted.deliveryCode) !== digest(code) || digest(input.accepted.deliveryConfig) !== digest(deliveryConfig)
|
||||
|| digest(targetConfig) !== digest(deliveryConfig))
|
||||
plan = buildPlan(inventory, input.accepted, { publicDomain, expandedScope, bootstrap })
|
||||
expected = input.accepted
|
||||
} else {
|
||||
const before = input.capture
|
||||
if (before?.stage !== 'capture' || before.passed !== true || before.commit !== input.commit || before.inventorySha256 !== inventorySha256
|
||||
|| before.metadataAudit?.inventorySha256 !== collected.audit.inventorySha256
|
||||
|| digest(before.inventory) !== inventorySha256 || digest(before.plan) !== before.planSha256
|
||||
|| before.acceptedArtifactSha256 !== digest(input.accepted)) fail('inventory_or_capture_drift')
|
||||
if (!targetDeliveryCode || digest(code) !== digest(targetDeliveryCode) || digest(deliveryConfig) !== digest(before.targetDeliveryConfig)
|
||||
|| digest(targetConfig) !== digest(before.targetDeliveryConfig) || publicDomain !== before.plan.publicDomain) fail('candidate_delivery_identity_mismatch')
|
||||
validateChecks(before.plan, before.checks)
|
||||
if (digest(before.checks) !== before.checksSha256) fail('capture_checks_digest_mismatch')
|
||||
plan = before.plan
|
||||
expected = before
|
||||
if (input.stage === 'post') {
|
||||
if (input.candidate?.stage !== 'candidate' || input.candidate.passed !== true || input.candidate.planSha256 !== before.planSha256
|
||||
|| input.candidate.commit !== input.commit || input.candidate.acceptedArtifactSha256 !== digest(input.accepted)
|
||||
|| digest(input.candidate.plan) !== before.planSha256 || digest(input.candidate.inventory) !== inventorySha256
|
||||
|| input.candidate.metadataAudit?.inventorySha256 !== collected.audit.inventorySha256
|
||||
|| input.candidate.inventorySha256 !== inventorySha256 || digest(input.candidate.checks) !== input.candidate.checksSha256) fail('candidate_receipt_required')
|
||||
validateChecks(plan, input.candidate.checks)
|
||||
expected = input.candidate
|
||||
}
|
||||
}
|
||||
const { checks, budget } = await probe(plan)
|
||||
const comparison = compareChecks(plan, checks, expected, { bootstrap, legacyFailureProof, compatibilityProof, legacyMembers })
|
||||
const artifact = { version: 1, policyVersion: POLICY.version, readOnly: true, stage: input.stage, commit: input.commit,
|
||||
capturedAt: new Date().toISOString(), ...comparison, inventory, inventorySha256, metadataAudit: collected.audit,
|
||||
plan, planSha256: digest(plan), checks, checksSha256: digest(checks), budget, deliveryCode: code,
|
||||
deliveryConfig, deliveryConfigSha256: digest(deliveryConfig), targetDeliveryConfig: targetConfig,
|
||||
knownLegacyMembersSha256: KNOWN_LEGACY_MEMBERS_SHA256,
|
||||
...(bootstrap ? { bootstrapRequiresExplicitShaReview: true } : { acceptedArtifactSha256: digest(input.accepted) }),
|
||||
scopeNotice: 'Only selected previews were fetched; all remaining metadata rows are explicitly unverified. Known incident failures are not healthy.' }
|
||||
return artifact
|
||||
}
|
||||
|
||||
/** Package only exact-checkout code, with dependency hashes; old images need no new files. */
|
||||
export async function bundleReleaseGate(root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'), { runtimeBase = 'file:///app/package.json' } = {}) {
|
||||
const moduleUrl = source => 'data:text/javascript;base64,' + Buffer.from(source).toString('base64')
|
||||
const adapt = source => source.replaceAll('import.meta.url', JSON.stringify(runtimeBase))
|
||||
const registry = moduleUrl(`export const LEGACY_DOMAINS=${JSON.stringify(LEGACY_DOMAINS)}`)
|
||||
const checker = moduleUrl(adapt(await readFile(path.join(root, 'scripts/check-material-preview-health.mjs'), 'utf8')).replace("'./check-legacy-storage-boundaries.mjs'", JSON.stringify(registry)))
|
||||
const exporter = moduleUrl(adapt(await readFile(path.join(root, 'scripts/export-material-preview-health-manifest.mjs'), 'utf8'))
|
||||
.replace("'./check-legacy-storage-boundaries.mjs'", JSON.stringify(registry)).replace("'./check-material-preview-health.mjs'", JSON.stringify(checker)))
|
||||
const gate = adapt((await readFile(path.join(root, 'scripts/material-preview-release-gate.mjs'), 'utf8'))
|
||||
.replace('const PINNED_KNOWN_LEGACY_MEMBERS = await readKnownLegacyProof()', `const PINNED_KNOWN_LEGACY_MEMBERS = ${JSON.stringify(await readKnownLegacyProof(root))}`))
|
||||
.replace('const PINNED_TARGET_DELIVERY_CODE = null', `const PINNED_TARGET_DELIVERY_CODE = ${JSON.stringify(await deliveryCode(root))}`)
|
||||
.replace("'./check-legacy-storage-boundaries.mjs'", JSON.stringify(registry))
|
||||
.replace("'./check-material-preview-health.mjs'", JSON.stringify(checker))
|
||||
.replace("'./export-material-preview-health-manifest.mjs'", JSON.stringify(exporter))
|
||||
return moduleUrl(gate)
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
if (process.argv.length === 3 && process.argv[2] === 'bundle') process.stdout.write(await bundleReleaseGate())
|
||||
else { console.error('Usage: node scripts/material-preview-release-gate.mjs bundle'); process.exitCode = 1 }
|
||||
}
|
||||
236
scripts/material-preview-release-gate.test.mjs
Normal file
236
scripts/material-preview-release-gate.test.mjs
Normal file
@ -0,0 +1,236 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createRequire } from 'node:module'
|
||||
import test from 'node:test'
|
||||
import { bundleReleaseGate, buildPlan, canonicalDeliverySource, compareChecks, CRITICAL_MATERIAL_IDS, DELIVERY_FILES, KNOWN_LEGACY_MEMBERS_SHA256, normalizeDeliveryConfig, POLICY, runProbes, runReleaseStage, validateAccepted } from './material-preview-release-gate.mjs'
|
||||
import { LEGACY_DOMAINS } from './check-legacy-storage-boundaries.mjs'
|
||||
|
||||
const sharp = createRequire(import.meta.url)('sharp')
|
||||
const PNG = await sharp({ create: { width: 3, height: 2, channels: 3, background: '#4d5e6f' } }).png().toBuffer()
|
||||
const hash = value => createHash('sha256').update(value).digest('hex')
|
||||
const digest = value => hash(JSON.stringify(value))
|
||||
const current = id => `https://s3.jiansun.vip/gongxiangpan/${id}.png`
|
||||
const independent = id => `https://${LEGACY_DOMAINS[0]}/jsxiangche/${id}.png`
|
||||
const compatible = id => `https://${LEGACY_DOMAINS[1]}/gongxiangpan/${id}.png`
|
||||
const FRP = '<html><p>The server is powered by <a href="https://github.com/fatedier/frp">frp</a>.</p><p>Faithfully yours, frp.</p></html>'
|
||||
const row = (materialId, registeredSource = current(materialId)) => ({ materialId, registeredSource, sourceSha256: hash(registeredSource) })
|
||||
const code = Object.fromEntries(DELIVERY_FILES.map(file => [file, 'c'.repeat(64)]))
|
||||
const config = { S3_ENDPOINT: 'http://192.168.58.20:9000', S3_BUCKET: 'gongxiangpan', S3_FILE_PATH: '由壹点AI/',
|
||||
S3_PUBLIC_DOMAIN: 'https://s3.jiansun.vip/gongxiangpan', S3_REGION: 'us-east-1', SERVER_IP: '192.168.58.20', MINIO_API_PORT: '9000', APP_PUBLIC_URL: 'https://sc.jiansun.vip' }
|
||||
const initial = () => [...CRITICAL_MATERIAL_IDS.map((id, i) => row(id, i ? current(id) : compatible(id))), row('legacy', independent('legacy')), row('untested-current'),
|
||||
{ materialId: 'private-source', sourceSha256: hash('uploads/materials/private'), uncheckable: { classification: 'source_rejected', code: 'invalid_url' } }]
|
||||
|
||||
function database(rows) {
|
||||
const events = []
|
||||
const normalized = rows.map(r => ({ id: r.materialId, previewUrl: r.registeredSource || 'uploads/materials/private', materialType: '材质' })).sort((a, b) => a.id.localeCompare(b.id, 'en'))
|
||||
return { events, prisma: { async $transaction(fn, options) {
|
||||
events.push(options)
|
||||
return fn({ async $executeRawUnsafe(sql) { events.push(sql) }, material: {
|
||||
async count(query) { events.push(query); return normalized.length }, async findMany(query) {
|
||||
events.push(query)
|
||||
const start = query.cursor ? normalized.findIndex(r => r.id === query.cursor.id) + 1 : 0
|
||||
return normalized.slice(start, start + query.take)
|
||||
},
|
||||
} })
|
||||
} } }
|
||||
}
|
||||
|
||||
const fixtureFetch = async url => {
|
||||
const parsed = new URL(url)
|
||||
if (parsed.hostname === LEGACY_DOMAINS[0]) return new Response(FRP, { status: 404, headers: { 'Content-Type': 'text/html' } })
|
||||
if (parsed.hostname === LEGACY_DOMAINS[1]) throw new Error('old same-bucket route unavailable')
|
||||
return new Response(PNG, { status: 200, headers: { 'Content-Type': 'image/png' } })
|
||||
}
|
||||
|
||||
async function stage(stageName, rows, { accepted, capture, candidate, probeFetch = fixtureFetch, actualCode = code, targetCode = code, ...input } = {}) {
|
||||
const db = database(rows)
|
||||
const report = await runReleaseStage({ version: 1, stage: stageName, commit: 'b'.repeat(40), accepted, capture, candidate,
|
||||
targetDeliveryConfig: config, ...input }, {
|
||||
prismaClient: db.prisma, readDeliveryCode: async () => actualCode, targetDeliveryCode: targetCode,
|
||||
environment: config, probe: plan => runProbes(plan, { fetchImpl: probeFetch }),
|
||||
// Synthetic offline fixture proofs; the production stdin runner cannot supply
|
||||
// these dependency injections and uses the fixed incident/original SHA values.
|
||||
legacyFailureProof: { bytes: Buffer.byteLength(FRP), bodySha256: hash(FRP) },
|
||||
compatibilityProof: { materialId: CRITICAL_MATERIAL_IDS[0], bodySha256: hash(PNG), width: 3, height: 2 },
|
||||
legacyMembers: [row('legacy', independent('legacy'))],
|
||||
})
|
||||
assert.equal(db.events[1], 'SET TRANSACTION READ ONLY')
|
||||
assert.deepEqual(db.events[0], { isolationLevel: 'RepeatableRead', timeout: 60_000, maxWait: 5000 })
|
||||
return report
|
||||
}
|
||||
|
||||
test('bootstrap records all metadata, exact 12 materials and all independent legacy rows without inventing health for omitted sources', async () => {
|
||||
const report = await stage('bootstrap', initial())
|
||||
assert.equal(report.passed, true)
|
||||
assert.equal(report.allSelectedHealthy, false)
|
||||
assert.equal(report.bootstrapRequiresExplicitShaReview, true)
|
||||
assert.equal(report.inventory.length, 15)
|
||||
assert.equal(report.plan.selected.length, 13)
|
||||
assert.equal(report.checks.length, 14)
|
||||
assert.equal(report.knownFailures.length, 2)
|
||||
assert.equal(report.plan.unverified.length, 2)
|
||||
assert.equal(report.plan.unverified.find(r => r.materialId === 'private-source').reason, 'unsupported_or_missing_registered_source')
|
||||
assert.equal(report.budget.retries, 0)
|
||||
validateAccepted(report)
|
||||
assert.equal(report.checks.find(r => r.materialId === CRITICAL_MATERIAL_IDS[0] && r.role === 'registered').result.ok, false)
|
||||
assert.equal(report.checks.find(r => r.materialId === CRITICAL_MATERIAL_IDS[0] && r.role === 'canonical').result.bodySha256, hash(PNG))
|
||||
})
|
||||
|
||||
test('fixed same plan is checked before and after candidate with no metadata or content writes', async () => {
|
||||
const accepted = await stage('bootstrap', initial())
|
||||
const rows = [...initial(), row('new-current')]
|
||||
const capture = await stage('capture', rows, { accepted })
|
||||
const candidate = await stage('candidate', rows, { accepted, capture })
|
||||
const post = await stage('post', rows, { accepted, capture, candidate })
|
||||
assert.equal(capture.plan.selected.some(r => r.materialId === 'new-current' && r.reasons.includes('new_or_changed_source')), true)
|
||||
assert.equal(post.passed, true)
|
||||
assert.equal(post.planSha256, capture.planSha256)
|
||||
assert.equal(candidate.planSha256, capture.planSha256)
|
||||
assert.equal(post.inventorySha256, capture.inventorySha256)
|
||||
validateAccepted(post)
|
||||
})
|
||||
|
||||
test('missing or forged first baseline stops capture before image GET', async () => {
|
||||
let calls = 0
|
||||
await assert.rejects(stage('capture', initial(), { probeFetch: async () => { calls++; return fixtureFetch(current('x')) } }), /reviewed_baseline_required/)
|
||||
const accepted = await stage('bootstrap', initial())
|
||||
accepted.inventory.pop()
|
||||
await assert.rejects(stage('capture', initial(), { accepted }), /baseline_digest_mismatch/)
|
||||
assert.equal(calls, 0)
|
||||
})
|
||||
|
||||
test('new failure or changed failure type blocks candidate; existing FRP incident remains explicit', async () => {
|
||||
const accepted = await stage('bootstrap', initial()), capture = await stage('capture', initial(), { accepted })
|
||||
const bad = await stage('candidate', initial(), { accepted, capture, probeFetch: async url => url === current(CRITICAL_MATERIAL_IDS[1])
|
||||
? new Response('<html>failed</html>', { status: 200, headers: { 'Content-Type': 'text/html' } }) : fixtureFetch(url) })
|
||||
assert.equal(bad.passed, false)
|
||||
assert.ok(bad.problems.some(r => r.code === 'new_or_changed_failure'))
|
||||
assert.ok(bad.knownFailures.some(r => r.materialId === 'legacy' && r.code === 'frp_default_404'))
|
||||
const legacyChange = await stage('candidate', initial(), { accepted, capture, probeFetch: async url => url === independent('legacy')
|
||||
? new Response('<Error><Code>NoSuchKey</Code></Error>', { status: 404, headers: { 'Content-Type': 'application/xml' } }) : fixtureFetch(url) })
|
||||
assert.equal(legacyChange.passed, false)
|
||||
})
|
||||
|
||||
test('a newly registered legacy failure cannot join the known baseline automatically', async () => {
|
||||
const accepted = await stage('bootstrap', initial())
|
||||
const capture = await stage('capture', [...initial(), row('new-legacy', independent('new-legacy'))], { accepted })
|
||||
assert.equal(capture.passed, false)
|
||||
assert.ok(capture.problems.some(r => r.materialId === 'new-legacy' && r.code === 'new_or_changed_failure'))
|
||||
})
|
||||
|
||||
test('bootstrap only permits the exact documented FRP body and original canonical compatibility proof', async () => {
|
||||
const wrongLegacy = await stage('bootstrap', initial(), { probeFetch: async url => url === independent('legacy')
|
||||
? new Response(FRP + 'changed', { status: 404, headers: { 'Content-Type': 'text/html' } }) : fixtureFetch(url) })
|
||||
assert.equal(wrongLegacy.passed, false)
|
||||
const wrongCanonical = await stage('bootstrap', initial(), { probeFetch: async url => {
|
||||
if (url !== current(CRITICAL_MATERIAL_IDS[0])) return fixtureFetch(url)
|
||||
const different = await sharp({ create: { width: 3, height: 2, channels: 3, background: '#112233' } }).png().toBuffer()
|
||||
return new Response(different, { headers: { 'Content-Type': 'image/png' } })
|
||||
} })
|
||||
assert.equal(wrongCanonical.passed, false)
|
||||
})
|
||||
|
||||
test('bootstrap rejects an extra historical row, a replacement ID at equal count, and a changed historical source', async () => {
|
||||
for (const rows of [
|
||||
[...initial(), row('unreviewed-old', independent('unreviewed-old'))],
|
||||
initial().map(r => r.materialId === 'legacy' ? row('replacement-old', independent('legacy')) : r),
|
||||
initial().map(r => r.materialId === 'legacy' ? row('legacy', independent('different-source')) : r),
|
||||
]) {
|
||||
const bootstrap = await stage('bootstrap', rows)
|
||||
assert.equal(bootstrap.passed, false)
|
||||
assert.ok(bootstrap.problems.some(r => r.code === 'new_or_changed_failure'))
|
||||
}
|
||||
})
|
||||
|
||||
test('healthy same URL with different bytes requires review rather than silently rebaselining', async () => {
|
||||
const accepted = await stage('bootstrap', initial()), capture = await stage('capture', initial(), { accepted })
|
||||
const variant = await sharp({ create: { width: 3, height: 2, channels: 3, background: '#ffffff' } }).png().toBuffer()
|
||||
const candidate = await stage('candidate', initial(), { accepted, capture, probeFetch: async url => url === current(CRITICAL_MATERIAL_IDS[1])
|
||||
? new Response(variant, { headers: { 'Content-Type': 'image/png' } }) : fixtureFetch(url) })
|
||||
assert.equal(candidate.passed, false)
|
||||
assert.ok(candidate.problems.some(r => r.code === 'unchanged_url_content_changed'))
|
||||
})
|
||||
|
||||
test('inventory drift, missing coverage, missing candidate, and detector failure all fail closed', async () => {
|
||||
const accepted = await stage('bootstrap', initial()), capture = await stage('capture', initial(), { accepted })
|
||||
await assert.rejects(stage('candidate', [...initial(), row('concurrent-upload')], { accepted, capture }), /inventory_or_capture_drift/)
|
||||
await assert.rejects(stage('post', initial(), { accepted, capture }), /candidate_receipt_required/)
|
||||
const broken = structuredClone(capture); broken.checks.pop(); broken.checksSha256 = digest(broken.checks)
|
||||
await assert.rejects(stage('candidate', initial(), { accepted, capture: broken }), /probe_coverage_incomplete/)
|
||||
const faulty = structuredClone(capture.checks)
|
||||
faulty[0].result.ok = false; faulty[0].result.classification = 'decoder_unavailable'; faulty[0].result.code = 'image_decoder_unavailable'
|
||||
assert.equal(compareChecks(capture.plan, faulty, capture).passed, false)
|
||||
})
|
||||
|
||||
test('new unsupported source, absent key material and changes beyond budget cannot be dropped', async () => {
|
||||
const accepted = await stage('bootstrap', initial())
|
||||
await assert.rejects(stage('capture', [...initial(), { materialId: 'unsupported-new', sourceSha256: hash('x'), uncheckable: { code: 'invalid_url' } }], { accepted }), /new_or_changed_uncheckable_preview/)
|
||||
assert.throws(() => buildPlan(initial().slice(1), accepted, { publicDomain: 'https://s3.jiansun.vip/gongxiangpan' }), /critical_material_coverage_missing/)
|
||||
assert.throws(() => buildPlan([...initial(), ...Array.from({ length: POLICY.probes }, (_, i) => row(`new-${i}`))], accepted,
|
||||
{ publicDomain: 'https://s3.jiansun.vip/gongxiangpan' }), /probe_budget_requires_independent_full_acceptance/)
|
||||
})
|
||||
|
||||
test('delivery source or storage code changes expand scope and cannot skip large inventory', async () => {
|
||||
const accepted = await stage('bootstrap', initial())
|
||||
const changed = { ...code, [DELIVERY_FILES[0]]: 'd'.repeat(64) }
|
||||
const capture = await stage('capture', initial(), { accepted, targetCode: changed })
|
||||
assert.equal(capture.plan.expandedScope, true)
|
||||
assert.ok(capture.plan.selected.some(r => r.materialId === 'untested-current'))
|
||||
await assert.rejects(stage('candidate', initial(), { accepted, capture, targetCode: changed }), /candidate_delivery_identity_mismatch/)
|
||||
const many = [...initial(), ...Array.from({ length: POLICY.probes }, (_, i) => row(`unchanged-${i}`))]
|
||||
const largeBase = await stage('bootstrap', many)
|
||||
await assert.rejects(stage('capture', many, { accepted: largeBase, targetCode: changed }), /probe_budget_requires_independent_full_acceptance/)
|
||||
const outOfBand = await stage('capture', initial(), { accepted, actualCode: changed, targetCode: changed })
|
||||
assert.equal(outOfBand.plan.expandedScope, true, 'a change since the accepted code baseline cannot disappear when target already equals current')
|
||||
})
|
||||
|
||||
test('nonsecret delivery configuration changes expand scope and inconsistent candidate settings stop before GET', async () => {
|
||||
const accepted = await stage('bootstrap', initial())
|
||||
for (const [key, value] of [['S3_ENDPOINT', 'http://192.168.58.21:9000'], ['S3_BUCKET', 'other-bucket'], ['S3_FILE_PATH', 'other/'],
|
||||
['SERVER_IP', '192.168.58.21'], ['MINIO_API_PORT', '9001'], ['S3_REGION', 'other-region']]) {
|
||||
const targetDeliveryConfig = { ...config, [key]: value }
|
||||
const capture = await stage('capture', initial(), { accepted, targetDeliveryConfig })
|
||||
assert.equal(capture.plan.expandedScope, true, key)
|
||||
await assert.rejects(stage('candidate', initial(), { accepted, capture, targetDeliveryConfig }), /candidate_delivery_identity_mismatch/)
|
||||
}
|
||||
await assert.rejects(stage('capture', initial(), { accepted, targetDeliveryConfig: undefined }), /complete_delivery_configuration_required/)
|
||||
assert.throws(() => normalizeDeliveryConfig({ ...config, S3_ENDPOINT: 'http://user:secret@192.168.58.20:9000' }), /credential_or_query_in_delivery_configuration/)
|
||||
assert.throws(() => normalizeDeliveryConfig({ ...config, S3_ACCESS_KEY_ID: 'must-not-be-logged' }), /complete_delivery_configuration_required/)
|
||||
})
|
||||
|
||||
test('versioned historical membership proof exactly matches the independently reviewed 472 IDs and normalized source digests', async () => {
|
||||
const { readFile } = await import('node:fs/promises')
|
||||
const policy = JSON.parse(await readFile(new URL('./fixtures/material-preview-known-legacy-20261023.json', import.meta.url), 'utf8'))
|
||||
assert.equal(policy.members.length, 472)
|
||||
assert.equal(digest(policy.members), KNOWN_LEGACY_MEMBERS_SHA256)
|
||||
assert.deepEqual(Object.keys(policy.members[0]).sort(), ['materialId', 'sourceSha256'])
|
||||
assert.equal(JSON.stringify(policy).includes('https://'), false)
|
||||
})
|
||||
|
||||
test('canonical mapping preserves bucket and key and never rewrites independent old storage', () => {
|
||||
assert.equal(canonicalDeliverySource(independent('original'), 'https://s3.jiansun.vip/gongxiangpan'), independent('original'))
|
||||
assert.equal(canonicalDeliverySource(compatible('%E4%B8%AD%E6%96%87'), 'https://s3.jiansun.vip/gongxiangpan'), current('%E4%B8%AD%E6%96%87'))
|
||||
assert.throws(() => canonicalDeliverySource(compatible('x'), 'https://elsewhere.invalid/gongxiangpan'), /untrusted_public_bucket_configuration/)
|
||||
})
|
||||
|
||||
test('read-only probe queue is bounded to four requests and one attempt with a fixed wall budget', async () => {
|
||||
const accepted = await stage('bootstrap', initial()), plan = buildPlan(initial(), accepted, { publicDomain: 'https://s3.jiansun.vip/gongxiangpan' })
|
||||
let active = 0, peak = 0, calls = 0
|
||||
await runProbes(plan, { fetchImpl: async (url, options) => {
|
||||
calls++; peak = Math.max(peak, ++active)
|
||||
assert.equal(options.method, 'GET'); assert.equal(options.redirect, 'manual'); assert.equal(options.cache, 'no-store')
|
||||
await new Promise(resolve => setTimeout(resolve, 2)); active--
|
||||
return fixtureFetch(url)
|
||||
} })
|
||||
assert.equal(calls, plan.probes.length); assert.equal(peak, POLICY.concurrency)
|
||||
let time = 0
|
||||
await assert.rejects(runProbes(plan, { now: () => (time += POLICY.wallMs), fetchImpl: () => { throw Error('must not fetch') } }), /release_probe_wall_budget/)
|
||||
})
|
||||
|
||||
test('exact-checkout bundle loads without an old image containing new scripts', async () => {
|
||||
const bundle = await bundleReleaseGate(undefined, { runtimeBase: new URL('../package.json', import.meta.url).href })
|
||||
assert.ok(bundle.length < 524288)
|
||||
const gate = await import(bundle)
|
||||
assert.equal(typeof gate.runReleaseStage, 'function')
|
||||
assert.deepEqual(gate.POLICY, POLICY)
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user