Compare commits

..
Author SHA1 Message Date
cflmy 277f9c307d release: switch the base release to CLI 3.0.0-rc.5 (c44b0f9)
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was successful
- Pin the root cli gitlink to the released rc.5 source c44b0f9 (tag
  v3.0.0-rc.5) instead of the pre-release Phase B commit.
- Record the published release identity: archive sha256:fd7a313e..., assets
  verified by download, single external Bundle db905508..., deterministic build,
  smoke, archive-only Ubuntu 24.04 cold install, migrated extensions and frozen
  external conformance on the exact artifact.
- MIGRATION records the base-release switch and the explicit limitations
  recorded in the rc.5 release notes: strict L1 UNVERIFIED (no VM/namespaces in
  the release environment) and shared-node G4 below thresholds but not an
  approved-node PASS. Rollback target is rc.4 source 452e9a3.

Refs cflmy/marqdo#2, cflmy/marqdo-cli#11
2026-11-27 11:07:35 +08:00
cflmy 01fb8ff7d0 docs: record the #2 release readiness candidate without publishing
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was successful
Real, unpublished release-candidate verification on the current combination:
root 4a92201, CLI deadf6e (same-SHA CI success), external Bundle
sha256:db905508..., and deterministic archives
sha256:377d2787... built twice from the same inputs. The archive passes smoke,
offline Ubuntu 24.04/glibc 2.39 cold install (no network/Cargo, stdlib missing
fails closed), the std: surface, the three migrated extension suites, and the
external conformance gate through the archive binary and RELEASE_INFO.

The evidence states what is NOT satisfied: the artifact reuses the rc.4 version
so it must never be published, a frozen rc.5 release SHA and version/docs
alignment are not started, strict VM and G4 performance evidence are
UNVERIFIED, and the tag/Release needs maintainer sign-off. No tag or asset was
created and the root release identity is unchanged.

Refs cflmy/marqdo#2
2026-11-27 09:51:13 +08:00
cflmy 4a92201708 feat: trusted candidate webhook adapter and lost-notification reconciliation
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was successful
- scripts/webhook-adapter.py authenticates the raw Gitea body with the repo
  webhook secret (HMAC-SHA256), whitelists push/pull_request candidate actions,
  resolves the repository from the accepted root graph, uses the accepted pin as
  base (payload base is only a hint), aggregates CI strictly, and delegates to
  the existing candidate-notify verifier for reachability, dedupe/replay,
  baseline revalidation and impact.
- --reconcile scans open PRs in allowlisted repositories, recovers candidates
  whose fast notification was lost with the same idempotent state, retries
  transient API errors with bounded backoff, fails closed on 401/403, and
  reports errors without claiming a downstream success.
- 8 focused adapter tests plus the full 79-test integration suite pass on real
  temporary Git fixtures. Docs/evidence record the trust rules and that the
  platform webhook/cron deployment itself is still external (#10 M0).

Refs cflmy/marqdo#3, cflmy/marqdo#10
2026-11-27 09:30:26 +08:00
8 changed files with 781 additions and 6 deletions

No files matched your search

+1 -1
Submodule cli updated: deadf6edee...c44b0f9438.
+3 -1
View File
@@ -76,7 +76,9 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 +
## 自动化权限 ## 自动化权限
先实现人工触发与 PR/CI 门禁,不开发自动 Agent 管理平台。候选通知的授权校验由根 `scripts/candidate-notify.py` 承担:只接受规范化通知(仓库、类型、head/base SHA、CI 状态与 URL),校验仓库在根图远端允许列表内、提交在本地对象库可达、组件候选的 base 必须是 accepted 根图当前固定的 SHA、CI 为允许主机上的 success 且必须是 https;按 `(repository, head SHA)` 去重,拒绝重放,accepted 基线变化时标记 `revalidate` 并要求重跑门禁;影响范围复用 `scripts/impact.py`,无法确定时全量。校验器只输出计划(`auto_promote=false`、`auto_merge=false`、仅创建候选分支需人工评审),不合并、不推送、不扩权。Webhook 只作通知(记录仓库、完整 SHA、CI URL);上级通过 API 验证存在性、审批与权限后再创建候选 PR,不得自动合入或提升权限。外部不可信 PR、未批准 gitlink 或脚本不得在拥有跨仓库写权限/发版密钥的 runner 中运行;区分只读 checkout/test token、受限 issue/PR token、受保护发布权限。日志不得输出凭证、完整 Analysis 或生产 API key。 先实现人工触发与 PR/CI 门禁,不开发自动 Agent 管理平台。候选通知的授权校验由根 `scripts/candidate-notify.py` 承担:只接受规范化通知(仓库、类型、head/base SHA、CI 状态与 URL),校验仓库在根图远端允许列表内、提交在本地对象库可达、组件候选的 base 必须是 accepted 根图当前固定的 SHA、CI 为允许主机上的 success 且必须是 https;按 `(repository, head SHA)` 去重,拒绝重放,accepted 基线变化时标记 `revalidate` 并要求重跑门禁;影响范围复用 `scripts/impact.py`,无法确定时全量。校验器只输出计划(`auto_promote=false`、`auto_merge=false`、仅创建候选分支需人工评审),不合并、不推送、不扩权。Webhook 只作通知(记录仓库、完整 SHA、CI URL);上级通过 API 验证存在性、审批与权限后再创建候选 PR,不得自动合入或提升权限。
经过授权的 webhook 入口由根 `scripts/webhook-adapter.py` 实现:先以仓库 webhook secret 校验 `X-Gitea-Signature`(HMAC-SHA256)原始 body,再只接受 `push`(非删除)与 `pull_request`(opened/synchronized/reopened)事件;仓库必须来自 accepted 根图的远端允许列表,base 使用 accepted 图当前固定 SHA(payload base 只作 hint),CI 聚合要求至少一个状态且全部 success、URL 为允许 CI 主机上的 https。校验通过后交给同一 `candidate-notify.py` 做可达性/去重/重放/基线重验与影响分析,输出计划(不合并、不推送、不建 PR)。通知丢失的恢复由同一脚本 `--reconcile` 承担:扫描允许列表仓库的开放 PR 与 head statuses,对未入账的成功候选执行同一验证(幂等状态文件,重复运行只报 duplicate);API transient 错误有限退避重试,401/403 立即失败,不把触发成功当作下游已处理。外部不可信 PR、未批准 gitlink 或脚本不得在拥有跨仓库写权限/发版密钥的 runner 中运行;区分只读 checkout/test token、受限 issue/PR token、受保护发布权限。日志不得输出凭证、完整 Analysis 或生产 API key。
## 发行与回滚 ## 发行与回滚
+4 -4
View File
@@ -6,7 +6,7 @@
| 已有仓库 | 审计时默认分支 | 发行或证据 | | 已有仓库 | 审计时默认分支 | 发行或证据 |
| --- | --- | --- | | --- | --- | --- |
| [marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) | `master` | v3.0.0-rc.4 | | [marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) | `master` | v3.0.0-rc.5 |
| [marqdo-extension-conformance](https://git.cflmy.cn/cflmy/marqdo-extension-conformance) | `main` | 有独立固定 fixture | | [marqdo-extension-conformance](https://git.cflmy.cn/cflmy/marqdo-extension-conformance) | `main` | 有独立固定 fixture |
| [marqdo-knowledge](https://git.cflmy.cn/cflmy/marqdo-knowledge) | `master` | v0.1.0-beta.3 | | [marqdo-knowledge](https://git.cflmy.cn/cflmy/marqdo-knowledge) | `master` | v0.1.0-beta.3 |
| [marqdo-lint](https://git.cflmy.cn/cflmy/marqdo-lint) | `main` | v0.2.0 | | [marqdo-lint](https://git.cflmy.cn/cflmy/marqdo-lint) | `main` | v0.2.0 |
@@ -16,7 +16,7 @@
| [marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design) | `main` | Web Design 组件,planned;初始开发文档 | | [marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design) | `main` | Web Design 组件,planned;初始开发文档 |
| [marqdo-web-preview](https://git.cflmy.cn/cflmy/marqdo-web-preview) | `main` | Web Preview 组件,planned;初始开发文档 | | [marqdo-web-preview](https://git.cflmy.cn/cflmy/marqdo-web-preview) | `main` | Web Preview 组件,planned;初始开发文档 |
CLI gitlink 采用 RC.4 正式发布源码,以匹配冻结归档和现有 View/Lint 契约。 CLI gitlink 采用 RC.5 正式发布源码(`c44b0f9`,tag `v3.0.0-rc.5`),以匹配冻结归档和现有 View/Lint 契约。
其文档后续提交曾用于 Knowledge 的独立 CI;生态候选以自身测试判定实际组合。 其文档后续提交曾用于 Knowledge 的独立 CI;生态候选以自身测试判定实际组合。
Conformance 使用 CLI 已固定的真实 fixture 提交。 Conformance 使用 CLI 已固定的真实 fixture 提交。
@@ -53,7 +53,7 @@ Conformance 使用 CLI 已固定的真实 fixture 提交。
| --- | --- | --- | | --- | --- | --- |
| M0 盘点 | 自建 Git、历史标签、已有六组件和新仓位 | 通过真实远端候选持续维护台账 | | M0 盘点 | 自建 Git、历史标签、已有六组件和新仓位 | 通过真实远端候选持续维护台账 |
| M1 集成骨架 | 六个 active gitlink,另固定 28 个直属和 2 个 Web 子级的 planned 开发提交 | 查看候选 Woodpecker 运行及各组件独立 CI | | M1 集成骨架 | 六个 active gitlink,另固定 28 个直属和 2 个 Web 子级的 planned 开发提交 | 查看候选 Woodpecker 运行及各组件独立 CI |
| M2 标准库切换 | planned,CLI RC.4 提供官方完整 Bundle | [CLI 外部 Bundle](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11) 和 [九组件切换](https://git.cflmy.cn/cflmy/marqdo/issues/2),包括 HTTP、Regex、Archive 迁出与同步删除旧路径 | | M2 标准库切换 | **已切换基础发行**:CLI/Worker/Stdlib rc.5 归档 + 单一外部 Bundle;HTTP/Regex/Archive 已验证 | [CLI 外部 Bundle](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11) 与 [九组件切换](https://git.cflmy.cn/cflmy/marqdo/issues/2) 完成;strict/perf 门禁限制见 rc.5 release notes |
| M3 跨仓闭环 | 工单、人工候选、同 SHA 门禁 | [跨仓库 CI](https://git.cflmy.cn/cflmy/marqdo/issues/3) 跟踪真实缺陷闭环、候选通知鉴权、去重和影响分析 | | M3 跨仓闭环 | 工单、人工候选、同 SHA 门禁 | [跨仓库 CI](https://git.cflmy.cn/cflmy/marqdo/issues/3) 跟踪真实缺陷闭环、候选通知鉴权、去重和影响分析 |
| M4 领域接入 | Web 领域 active:WEB-00..04 完成,领域 catalog/gitlink 固定 Design/Preview;根 catalog 激活与 gitlink 一次切换 | 根 `check-layout --checkouts`、领域组件入口、`web` Tool 冷安装与既有消费者同候选证据;Stdlib 聚合按 STD-01..04 独立推进 | | M4 领域接入 | Web 领域 active:WEB-00..04 完成,领域 catalog/gitlink 固定 Design/Preview;根 catalog 激活与 gitlink 一次切换 | 根 `check-layout --checkouts`、领域组件入口、`web` Tool 冷安装与既有消费者同候选证据;Stdlib 聚合按 STD-01..04 独立推进 |
| 后续领域 | 空仓和预期职责 | 逐组件开展最小真实功能、独立 CI、制品与接入 | | 后续领域 | 空仓和预期职责 | 逐组件开展最小真实功能、独立 CI、制品与接入 |
@@ -63,7 +63,7 @@ Conformance 使用 CLI 已固定的真实 fixture 提交。
1. CLI 打包器与产品测试接受单一显式外部 Bundle 输入。内核独立编译;制品仍附带一个校验过的标准库。 1. CLI 打包器与产品测试接受单一显式外部 Bundle 输入。内核独立编译;制品仍附带一个校验过的标准库。
2. 标准库在各组件维护唯一生产源码和自测。组装拒绝冲突、符号链接或测试污染,调用 CLI 权威打包器。std-io 维护 print/打印 的别名元数据。 2. 标准库在各组件维护唯一生产源码和自测。组装拒绝冲突、符号链接或测试污染,调用 CLI 权威打包器。std-io 维护 print/打印 的别名元数据。
3. HTTP、Regex、Archive 的真实替代和授权回归先行。候选同时移除 CLI 中旧领域宿主服务和旧导入。 3. HTTP、Regex、Archive 的真实替代和授权回归先行。候选同时移除 CLI 中旧领域宿主服务和旧导入。
4. 验证同输入两次组装结果、摘要及路径负例、C1/C2/C3、独立冷安装和真实工具集成后,再切换基础发行。当前状态为 UNVERIFIED。 4. 验证同输入两次组装结果、摘要及路径负例、C1/C2/C3、独立冷安装和真实工具集成后,再切换基础发行。**2026-11-27 已切换:rc.5 归档(sha256 `fd7a313e...`)发布,CLI gitlink 固定 `c44b0f9`;strict L1 与获批节点 G4 仍为 UNVERIFIED 限制,见根证据 `docs/evidence/2026-11-27-base-release-rc5-switch.md`。**
## 标准库源码归位迁移(marqdo#9,2026-11-26 M0 冻结) ## 标准库源码归位迁移(marqdo#9,2026-11-26 M0 冻结)
@@ -0,0 +1,36 @@
# 基础发行切换:rc.5 发布与根 gitlink 固定(2026-11-27)
父工单:[marqdo#2](https://git.cflmy.cn/cflmy/marqdo/issues/2)。本文件记录实际发布与根组合切换。
## 发布身份
| 对象 | 身份 |
| --- | --- |
| 发布 | [marqdo-cli v3.0.0-rc.5](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.5) |
| tag / 源码 | `v3.0.0-rc.5` → CLI `c44b0f943875d563bb7c170f8ccd3fd56a82360f` |
| CLI 同 SHA CI | pull_request + push pipeline **success**(Woodpecker CLI repo) |
| 归档 | `marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu.tar.gz`,4,907,427 bytes,sha256 `fd7a313e0ddaf38a9b1901ff2a9aa7b9a0a153e65522a9c0c60f01e2549f583b` |
| 归档资产 | release assets:tar.gz + `.sha256`;下载后 sha256 与本地构建一致 |
| Bundle | `marqdo-stdlib@0.2.0`,digest `sha256:db905508...`,外部显式输入 |
| 根 CLI gitlink | `c44b0f94`(本候选切换;旧 rc.4 源码 `452e9a3` 为回滚目标) |
| 平台 | Linux x86_64 / glibc 2.39(Ubuntu 24.04 容器验证) |
## 发布门禁(同一最终归档上真实执行)
- CLI 发布 SHA 的 Woodpecker pull_request/push pipeline **success**。
- 确定性归档:同一 `SOURCE_SHA` + 同一 Bundle 连续两次 package,sha256 完全一致(`fd7a313e...`)。
- `smoke.py` PASS。
- Ubuntu 24.04 / glibc 2.39、`--network none`、非 root、无 Cargo 冷安装 PASS(缺 Bundle fail-closed;语言-only 可运行)。
- 归档 CLI + 归档 Bundle:三个迁出扩展 http/regex/archive PASS;冻结外部 conformance 七类 PASS。
- 发布资产下载校验:下载归档 sha256 = `fd7a313e...`。
- 根同候选:`check-layout --checkouts`、根集成测试与生态 candidate CI(含既有消费者)以 `cli/c44b0f9` 为输入;结果以根 PR CI 为准。
## 已记录的未验证限制(不冒充 PASS)
- Strict L1 独立 VM/非 root:本发布环境无 disposable VM/命名空间,**UNVERIFIED**;release notes 明示无 PASS。
- G4 性能:paired shared-node 比较 9/9 工作负载、最大 p50 +5.15%、最大 RSS +4.87%,低于阈值,但**不是获批节点 PASS**;release notes 记录为 shared-node WARN 限制。
- 维护者已明确批准本次 rc.5 发布并接受上述两项记录限制。
## 回滚
若不接受 rc.5,恢复根 `cli` gitlink 到 `452e9a3`(rc.4 发布源码)并重跑候选;已发布 tag/资产不可变,不回写。
@@ -0,0 +1,32 @@
# 候选 Webhook 可信入口与漏通知对账证据(#3 / #10 GAP-05)
日期:2026-11-27。责任仓:根 `marqdo`。工单:[marqdo#3](https://git.cflmy.cn/cflmy/marqdo/issues/3)、[#10](https://git.cflmy.cn/cflmy/marqdo/issues/10)(发布传播/漏通知恢复 GAP-05/GAP-06 的仓库侧基础)。
## 实现
`scripts/webhook-adapter.py`(无长驻服务、无合并/推送权):
1. **来源认证**:`X-Gitea-Signature` HMAC-SHA256 校验原始 body;secret 仅来自环境变量,缺失/不匹配即拒绝,拒绝前不解析为可信输入。
2. **事件白名单**:`push`(拒绝删除分支)与 `pull_request`(仅 opened/synchronized/reopened);其它事件拒绝。
3. **仓库身份**:从 accepted 根图的远端允许列表解析;未知仓库拒绝;payload 的仓库名只用于匹配该表。
4. **base 语义**:组件候选 base 使用 accepted 根图当前固定 SHA(新基线需重验),payload base/branch 只作 hint;根候选 base 为 accepted revision。
5. **CI 聚合**:至少一个 status 且全部 `success` 才算成功;URL 必须是允许 CI 主机上的 https;pending/failure/空状态拒绝。
6. **复用同一验证器**:交给 `scripts/candidate-notify.py` 做可达性、去重/重放、基线 revalidate 与 `scripts/impact.py` 影响范围;输出计划 `auto_promote=false`/`auto_merge=false`。
7. **漏通知对账**:`--reconcile` 扫描允许列表仓库开放 PR 的 head statuses,对未入账的成功候选执行同一验证并写入幂等状态;重复运行报 duplicate;API transient 错误有限退避重试,401/403 立即失败,报告不写成功。
## 验证(真实临时 Git 仓库,无网络 fixture)
```sh
python3 -m unittest tests.integration.test_webhook_adapter
# 8 tests OK
python3 -m unittest discover -s tests/integration
# 79 tests OK
```
覆盖:签名正确/篡改/缺失 secret、未知事件/删除分支、未知仓库、failure/pending/空 CI、PR 事件、基线固定而非 payload base、重放拒绝、对账恢复丢失通知且第二次幂等、API 失败不写状态。
## 未验证 / 外部依赖
- 未在本环境配置真实 Gitea 仓库 webhook endpoint/secret 与 Woodpecker 触发器;本证据只证明仓库侧可信入口与对账逻辑,不代表平台已部署(不伪造部署 PASS)。
- 长驻接收服务、bot 账号最小权限、cron 工作流与平台并发/限流按 #10 M0 实测后部署;仓库侧不新增第二套协议。
- 受保护发布工作流/制品资产(GAP-05 发布侧)仍属 #10。
@@ -0,0 +1,42 @@
# #2 基础发行切换:发行门禁候选证据(2026-11-27)
工单:[marqdo#2](https://git.cflmy.cn/cflmy/marqdo/issues/2)。本文件记录**未发布**的本地发行候选验证;它不是 release、没有 tag、没有上传资产。按 `cli/docs/releasing.md`,tag/Release 需要维护者在冻结 SHA 上显式批准,自动化只能预备 RC 与证据。
## 候选身份
| 对象 | 身份 |
| --- | --- |
| 根组合 | `cflmy/marqdo@4a922017088490dfe7be75f76f70fa8fd5bb1c54`(本地验证基线) |
| CLI 源码 | `cflmy/marqdo-cli@deadf6edeea6dd0f5abf51c47e80204fd851baf0`(Phase B,无内置 `stdlib/` 源码树) |
| CLI 同 SHA CI | Woodpecker CLI pipeline 122(push)/121(pull_request)**success** |
| Bundle | `marqdo-stdlib@0.2.0`,tree digest `sha256:db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7` |
| 归档(验证用,未发布) | `marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz`,sha256 `377d2787e9cdeeb7c8e70024dacd0e2790fb0752716abeb5c0f72509807644d0` |
| 平台 | Linux x86_64 宿主;冷安装容器 Ubuntu 24.04 / glibc 2.39,`--network none`,无 Cargo |
**版本冲突声明**:该验证归档沿用 Cargo workspace 的 `3.0.0-rc.4` 版本但内容/mtime 组合与已发布 rc.4 不同(sha 不同)。它绝不能上传或作为 rc.4 再发布。正式候选必须先冻结新 SHA 并把版本/README/CHANGELOG/COMPATIBILITY/开发者文档统一提升到 `3.0.0-rc.5`,再重跑全部门禁。
## 已真实执行的本地门禁(PASS)
1. **Bundle 生产**:`scripts/build-stdlib.py` 从固定 gitlinks 生成 Bundle;`digest=sha256:db905508...`。
2. **确定性归档**:`cli/tools/release/package.py` 对同一 `SOURCE_SHA` + 同一 Bundle 连续构建两次,两个 tar.gz sha256 完全一致(`377d2787...`)。
3. **归档 smoke**:`cli/tools/release/smoke.py` PASS;缺少随附 Bundle 时 fail-closed,语言-only 程序可运行。
4. **离线冷安装**:`cli/tools/release/cold-install.sh` 在 Ubuntu 24.04/glibc 2.39、无网络、非 root、无 Cargo 容器内 PASS:`SOURCE_SHA` 与 `--version` 一致,`run`/`check`/`call`/JSONL `run.completed` 正常,移动 `stdlib` 后 `打印` 以 `kernel.unavailable` fail-closed,语言-only `阶乘` 仍可运行。
5. **标准库面**:同一归档 CLI 运行 `std-surface`,text/JSON/FS/path/datetime/table/Console 输出符合预期(实际 `call` 返回数组)。
6. **三个迁出扩展**:`extensions/http`、`extensions/regex`、`extensions/archive` 的 `scripts/test.sh` 使用**归档 CLI + 归档 Bundle** 全部 PASS。
7. **外部 conformance**:`cli/tools/ci/verify_extension_contracts.py --cli <归档 CLI> --release-info <归档 RELEASE_INFO>` 七类结果全部 PASS(plugin/worker/callable/negative-security/foreign-kernel/resource-provider/tool-analysis/package-pinned-git/reference-apps)。
8. **负例**:篡改归档随附 Bundle 的 `stdlib.json.digest` → CLI 退出 2(`stdlib digest mismatch`);缺失 Bundle → fail-closed。
9. **无重复源码**:CLI 源码树 `git ls-tree HEAD stdlib` 为空;归档内只有单一 Bundle。
## 未完成 / BLOCKED(不是 PASS)
| 门禁 | 状态 | 需要 |
| --- | --- | --- |
| 冻结 release SHA + 版本/文档一致性(rc.5) | NOT STARTED | 维护者决定版本与候选 SHA;本次验证归档版本冲突,不可发布 |
| Strict L1 独立 VM、非 root、same-SHA 证据 | UNVERIFIED | 可用的 disposable VM/隔离 runner;本地 bubblewrap 命名空间不可用 |
| G4 性能(固定节点或维护者批准的 shared-node WARN) | UNVERIFIED | 固定/获批节点与正确性基线 |
| 维护者显式 tag/Release 批准 | NOT STARTED | 按 `cli/docs/releasing.md` 由维护者签署 |
| Windows/macOS | UNSUPPORTED | 本 RC 范围只声明 Linux x86_64 glibc |
## 结论
外部 Bundle、确定性归档、离线冷安装、三个迁出扩展与工具/外部 conformance 已在**同一 CLI+Bundle 组合**上通过;基础发行切换所缺的是新版本冻结、strict VM、性能与维护者发布批准。未创建 tag、未上传资产、未修改根发行身份;在获批前根 CLI/Bundle gitlink 与迁移台账保持现状。
+406
View File
@@ -0,0 +1,406 @@
#!/usr/bin/env python3
"""Trusted adapter for candidate webhooks and release/candidate reconciliation.
This turns an authenticated Gitea webhook (push / pull_request) into the
normalized candidate notification verified by `scripts/candidate-notify.py`, and
provides the periodic reconciliation path required when a fast notification is
lost. It is deliberately small: no long-running service, no merge/push rights,
no trust in payload asset URLs or commands.
Trust rules:
* the raw body is authenticated with the repository webhook secret
(`X-Gitea-Signature`, HMAC-SHA256 hex) — an unsigned or wrong-signature body
never reaches verification;
* the repository must be an allowlisted component remote (or the root
repository) discovered from the accepted root graph, never from the payload;
* the candidate base is the SHA currently pinned by the accepted graph (payload
branch/base is only a hint);
* the commit must be reachable in the owning local repository;
* CI aggregation requires at least one status and only `success`; the URL must
be an https URL on an allowlisted CI host;
* replay/duplicate/revalidation is handled by the shared candidate state file;
* reconciliation scans open PRs in allowlisted repositories, so a lost webhook
is recovered by the next successful run (idempotent with the same state).
The adapter outputs a plan only (`auto_promote=false`, `auto_merge=false`);
a human still reviews candidate branches/PRs.
"""
from __future__ import annotations
import argparse
import hashlib
import hmac
import importlib.util
import json
import random
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
ROOT = PROJECT_ROOT
DEFAULT_CI_HOST = "ci.cflmy.cn"
DEFAULT_ROOT_REPOSITORY = "cflmy/marqdo"
class AdapterError(Exception):
pass
def load_notify():
spec = importlib.util.spec_from_file_location(
"marqdo_candidate_notify", PROJECT_ROOT / "scripts" / "candidate-notify.py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.ROOT = ROOT
return module
def resolve_revision(notify, ref: str) -> str:
impact = notify.load_impact()
impact.ROOT = ROOT
return impact.resolve(ROOT, ref)
def verify_signature(raw: bytes, signature: str | None, secret: str) -> None:
if not secret:
raise AdapterError("webhook secret is required")
if not signature:
raise AdapterError("missing X-Gitea-Signature")
expected = hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature.strip().lower()):
raise AdapterError("webhook signature does not match the raw body")
def parse_event(raw: bytes, event: str, signature: str | None, secret: str) -> dict:
verify_signature(raw, signature, secret)
try:
payload = json.loads(raw)
except json.JSONDecodeError as error:
raise AdapterError(f"webhook body is not JSON: {error}") from error
if not isinstance(payload, dict):
raise AdapterError("webhook body must be a JSON object")
repository = (payload.get("repository") or {}).get("full_name")
if not isinstance(repository, str) or not repository:
raise AdapterError("webhook payload has no repository.full_name")
if event == "push":
if payload.get("deleted"):
raise AdapterError("branch deletion is not a candidate")
before = payload.get("before")
after = payload.get("after")
if not isinstance(before, str) or not isinstance(after, str):
raise AdapterError("push payload has no before/after commit")
if set(after) == {"0"}:
raise AdapterError("push payload deletes the branch")
return {
"kind": "push",
"repository": repository,
"head_sha": after.lower(),
"payload_base": before.lower(),
"ref": payload.get("ref"),
}
if event == "pull_request":
action = payload.get("action")
if action not in ("opened", "synchronized", "reopened"):
raise AdapterError(f"pull_request action {action!r} is not a new candidate")
pull = payload.get("pull_request") or {}
head = (pull.get("head") or {}).get("sha")
base = (pull.get("base") or {}).get("sha")
if not isinstance(head, str) or not isinstance(base, str):
raise AdapterError("pull_request payload has no head/base SHA")
return {
"kind": "pull_request",
"repository": repository,
"head_sha": head.lower(),
"payload_base": base.lower(),
"number": pull.get("number"),
"action": action,
}
raise AdapterError(f"unsupported webhook event {event!r}; expected push or pull_request")
def aggregate_ci(statuses: list[dict], ci_hosts: list[str]) -> dict:
if not statuses:
return {"status": "pending", "url": None}
states = [str(item.get("status", "pending")) for item in statuses]
url = None
for item in statuses:
candidate = item.get("target_url") or ""
if isinstance(candidate, str) and candidate.startswith("https://"):
url = candidate
if any(state == "failure" or state == "error" for state in states):
return {"status": "failure", "url": url}
if all(state == "success" for state in states):
return {"status": "success", "url": url}
return {"status": "pending", "url": url}
def build_notification(
event: dict, ci: dict, accepted_revision: str, root_repository: str
) -> dict:
notify = load_notify()
if event["repository"] == root_repository:
kind = "root"
component = None
base_sha = accepted_revision
else:
allowlist = notify.repository_allowlist(accepted_revision)
component_record = allowlist.get(event["repository"])
if component_record is None:
raise AdapterError(
f"unknown repository {event['repository']!r}; allowlist: {sorted(allowlist)}"
)
kind = "component"
component = component_record["id"]
base_sha = component_record.get("sha")
if not isinstance(base_sha, str) or not base_sha:
raise AdapterError(
f"accepted graph has no pinned SHA for {component}; cannot verify a candidate"
)
notification = {
"schema": "marqdo.candidate-notification",
"schema_version": 1,
"repository": event["repository"],
"kind": kind,
"head_sha": event["head_sha"],
"base_sha": base_sha,
"ci": ci,
}
if component is not None:
notification["component"] = component
if event.get("number") is not None:
notification["pull_request"] = event["number"]
return notification
def verify_webhook(
raw: bytes,
event_name: str,
signature: str | None,
secret: str,
statuses: list[dict],
accepted: str,
state_path: Path,
ci_hosts: list[str] | None = None,
root_repository: str = DEFAULT_ROOT_REPOSITORY,
write_state: bool = True,
) -> dict:
event = parse_event(raw, event_name, signature, secret)
notify = load_notify()
accepted_revision = resolve_revision(notify, accepted)
ci = aggregate_ci(statuses, ci_hosts or [DEFAULT_CI_HOST])
notification = build_notification(event, ci, accepted_revision, root_repository)
try:
return notify.verify(
notification,
accepted,
state_path,
ci_hosts or [DEFAULT_CI_HOST],
root_repository,
write_state=write_state,
)
except notify.NotificationError as error:
return {"verified": False, "reason": str(error)}
def http_json(url: str, token: str, attempts: int = 3) -> object:
last: Exception | None = None
for attempt in range(attempts):
request = urllib.request.Request(
url,
headers={"Authorization": f"token {token}", "Accept": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
return json.loads(response.read())
except urllib.error.HTTPError as error:
if error.code in (401, 403):
raise AdapterError(f"authorization rejected for {url}: HTTP {error.code}") from error
last = error
except (urllib.error.URLError, TimeoutError) as error:
last = error
if attempt + 1 < attempts:
time.sleep(min(2 ** attempt, 4) + random.random() * 0.2)
raise AdapterError(f"cannot read {url} after {attempts} attempts: {last}")
def fetch_statuses(api_base: str, repository: str, sha: str, token: str) -> list[dict]:
data = http_json(
f"{api_base}/repos/{repository}/commits/{sha}/statuses", token
)
return data if isinstance(data, list) else []
def list_open_prs(api_base: str, repository: str, token: str) -> list[dict]:
data = http_json(
f"{api_base}/repos/{repository}/pulls?state=open&limit=50", token
)
return data if isinstance(data, list) else []
def reconcile(
accepted: str,
state_path: Path,
repositories: list[str],
accepted_revision: str,
statuses_fetcher,
prs_fetcher,
ci_hosts: list[str] | None = None,
root_repository: str = DEFAULT_ROOT_REPOSITORY,
) -> dict:
notify = load_notify()
ci_hosts = ci_hosts or [DEFAULT_CI_HOST]
results = []
for repository in sorted(set(repositories)):
try:
pulls = prs_fetcher(repository)
except AdapterError as error:
results.append({"repository": repository, "status": "ERROR", "reason": str(error)})
continue
for pull in pulls:
head = ((pull.get("head") or {}).get("sha")) or ""
number = pull.get("number")
if len(head) != 40:
results.append(
{"repository": repository, "status": "ERROR", "reason": "PR has no head SHA"}
)
continue
try:
statuses = statuses_fetcher(repository, head)
ci = aggregate_ci(statuses, ci_hosts)
event = {
"kind": "pull_request",
"repository": repository,
"head_sha": head,
"payload_base": ((pull.get("base") or {}).get("sha")) or "",
"number": number,
}
notification = build_notification(
event, ci, accepted_revision, root_repository
)
plan = notify.verify(
notification,
accepted,
state_path,
ci_hosts,
root_repository,
write_state=True,
)
results.append(
{
"repository": repository,
"pull_request": number,
"head_sha": head,
"status": "VERIFIED",
"revalidate": plan["revalidate"],
"affected": plan["impact"]["affected"],
}
)
except notify.NotificationError as error:
message = str(error)
status = "DUPLICATE" if "duplicate/replay" in message else "REJECTED"
results.append(
{
"repository": repository,
"pull_request": number,
"head_sha": head,
"status": status,
"reason": message,
}
)
return {
"schema": "marqdo.candidate-reconcile",
"schema_version": 1,
"accepted": {"ref": accepted, "revision": accepted_revision},
"repositories": sorted(set(repositories)),
"results": results,
"verified": sum(1 for item in results if item["status"] == "VERIFIED"),
"pending": sum(
1 for item in results if item["status"] in ("DUPLICATE", "REJECTED", "ERROR")
),
}
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--webhook", help="raw webhook body file")
group.add_argument("--reconcile", action="store_true", help="recover lost notifications")
parser.add_argument("--event", default="push", help="X-Gitea-Event value")
parser.add_argument("--signature", default=None, help="X-Gitea-Signature value")
parser.add_argument("--secret-env", default="MARQDO_WEBHOOK_SECRET")
parser.add_argument("--statuses", default=None, help="JSON array of commit statuses")
parser.add_argument("--accepted", required=True)
parser.add_argument("--state", required=True)
parser.add_argument("--ci-host", action="append", default=None)
parser.add_argument("--root-repository", default=DEFAULT_ROOT_REPOSITORY)
parser.add_argument("--api-base", default="https://git.cflmy.cn/api/v1")
parser.add_argument("--token-env", default="MARQDO_GIT_TOKEN")
parser.add_argument("--out", default=None)
parser.add_argument("--json", action="store_true")
args = parser.parse_args(argv)
ci_hosts = args.ci_host or [DEFAULT_CI_HOST]
try:
if args.webhook:
secret = __import__("os").environ.get(args.secret_env, "")
raw = Path(args.webhook).read_bytes()
statuses = []
if args.statuses:
statuses = json.loads(Path(args.statuses).read_text())
plan = verify_webhook(
raw,
args.event,
args.signature,
secret,
statuses,
args.accepted,
Path(args.state),
ci_hosts,
args.root_repository,
)
else:
import os
token = os.environ.get(args.token_env, "")
if not token:
raise AdapterError(f"{args.token_env} is required for reconciliation")
notify = load_notify()
accepted_revision = resolve_revision(notify, args.accepted)
repositories = sorted(notify.repository_allowlist(accepted_revision)) + [
args.root_repository
]
plan = reconcile(
args.accepted,
Path(args.state),
repositories,
accepted_revision,
lambda repository, sha: fetch_statuses(
args.api_base, repository, sha, token
),
lambda repository: list_open_prs(args.api_base, repository, token),
ci_hosts,
args.root_repository,
)
except (AdapterError, json.JSONDecodeError, OSError) as error:
print(f"webhook-adapter: rejected: {error}", file=sys.stderr)
return 1
text = json.dumps(plan, ensure_ascii=False, indent=2) + "\n"
if args.out:
Path(args.out).write_text(text)
if args.json:
print(text, end="")
else:
print(
f"{plan.get('schema')}: verified={plan.get('verified', 0)} "
f"pending={plan.get('pending', 0)}"
)
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
+257
View File
@@ -0,0 +1,257 @@
"""Trusted webhook adapter and reconciliation tests (issue #3 / #10 gap).
The fixtures are real temporary Git repositories. Webhook bodies are signed with
a test secret; the adapter must refuse tampered bodies, unknown repositories,
failed CI and replayed candidates, and reconciliation must recover a candidate
whose fast notification was lost while remaining idempotent.
"""
import hashlib
import hmac
import importlib.util
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
ADAPTER_SPEC = importlib.util.spec_from_file_location(
"marqdo_webhook_adapter", ROOT / "scripts" / "webhook-adapter.py"
)
adapter = importlib.util.module_from_spec(ADAPTER_SPEC)
ADAPTER_SPEC.loader.exec_module(adapter)
GIT_ENV = {
"GIT_AUTHOR_NAME": "test",
"GIT_AUTHOR_EMAIL": "test@example.invalid",
"GIT_COMMITTER_NAME": "test",
"GIT_COMMITTER_EMAIL": "test@example.invalid",
}
SECRET = "test-webhook-secret"
CI_URL = "https://ci.cflmy.cn/repos/1/pipeline/7/1"
CATALOG = """[[component]]
id = "cli"
path = "cli"
kind = "core"
state = "active"
owner = "t"
scope = "s"
requires = []
checks_with = []
release = "base"
entry = "scripts/test.sh"
"""
GITMODULES = """[submodule "cli"]
\tpath = cli
\turl = https://git.cflmy.cn/cflmy/marqdo-cli.git
"""
def git(cwd, *args):
env = os.environ.copy()
env.update(GIT_ENV)
result = subprocess.run(["git", "-C", str(cwd), *args], capture_output=True, env=env)
if result.returncode != 0:
raise AssertionError(f"git {' '.join(args)}: {result.stderr.decode(errors='replace')}")
return result.stdout.decode()
def commit(repo, message="fixture"):
git(repo, "add", "-A")
git(repo, "commit", "-q", "-m", message)
return git(repo, "rev-parse", "HEAD").strip()
def write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
class WebhookAdapterTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.base = Path(self.tmp.name)
self.root = self.base / "root"
self.root.mkdir()
git(self.root, "init", "-q")
write(self.root / "components.toml", CATALOG)
write(self.root / ".gitmodules", GITMODULES)
self.cli = self.root / "cli"
self.cli.mkdir()
git(self.cli, "init", "-q")
write(self.cli / "README.md", "cli")
self.sha1 = commit(self.cli)
git(self.root, "add", "components.toml", ".gitmodules")
git(self.root, "update-index", "--add", "--cacheinfo", f"160000,{self.sha1},cli")
git(self.root, "commit", "-q", "-m", "accepted")
self.accepted = git(self.root, "rev-parse", "HEAD").strip()
write(self.cli / "README.md", "cli v2")
self.sha2 = commit(self.cli, "candidate")
self.state = self.base / "state.json"
self.originals = (adapter.PROJECT_ROOT, adapter.ROOT)
adapter.ROOT = self.root
def tearDown(self):
adapter.PROJECT_ROOT, adapter.ROOT = self.originals
self.tmp.cleanup()
def push_body(self, after=None, before=None, repository="cflmy/marqdo-cli"):
return json.dumps(
{
"repository": {"full_name": repository},
"ref": "refs/heads/candidate",
"before": before or self.sha1,
"after": after or self.sha2,
}
).encode()
def statuses(self, status="success"):
return [{"status": status, "context": "ci/woodpecker/pr/main", "target_url": CI_URL}]
def verify(self, body, event="push", signature=None, statuses=None, write_state=True):
signature = signature if signature is not None else hmac.new(
SECRET.encode(), body, hashlib.sha256
).hexdigest()
return adapter.verify_webhook(
body,
event,
signature,
SECRET,
statuses if statuses is not None else self.statuses(),
self.accepted,
self.state,
["ci.cflmy.cn"],
"cflmy/marqdo",
write_state,
)
def test_signed_push_candidate_is_verified_without_auto_promotion(self):
plan = self.verify(self.push_body())
self.assertTrue(plan["verified"])
self.assertIsNotNone(plan.get("impact"))
self.assertFalse(plan["actions"]["auto_promote"])
self.assertFalse(plan["actions"]["auto_merge"])
self.assertTrue(self.state.is_file())
def test_tampered_body_and_missing_secret_are_refused_before_verification(self):
body = self.push_body()
with self.assertRaises(adapter.AdapterError):
self.verify(body, signature="0" * 64)
with self.assertRaises(adapter.AdapterError):
self.verify(body, signature="")
with self.assertRaises(adapter.AdapterError):
adapter.verify_webhook(
body, "push", None, "", self.statuses(), self.accepted, self.state,
["ci.cflmy.cn"], "cflmy/marqdo",
)
def test_unsupported_events_and_deleted_branches_are_refused(self):
with self.assertRaises(adapter.AdapterError):
self.verify(self.push_body(), event="issues")
body = json.dumps(
{
"repository": {"full_name": "cflmy/marqdo-cli"},
"before": self.sha1,
"after": "0" * 40,
"deleted": True,
}
).encode()
with self.assertRaises(adapter.AdapterError):
self.verify(body)
def test_unknown_repository_and_failed_or_missing_ci_are_rejected(self):
with self.assertRaises(adapter.AdapterError):
self.verify(self.push_body(repository="cflmy/unknown"))
failed = self.verify(self.push_body(), statuses=self.statuses("failure"))
self.assertFalse(failed["verified"])
self.assertIn("CI status", failed["reason"])
pending = self.verify(self.push_body(), statuses=self.statuses("pending"))
self.assertFalse(pending["verified"])
empty = self.verify(self.push_body(), statuses=[])
self.assertFalse(empty["verified"])
def test_pr_event_uses_the_accepted_pin_not_the_payload_base(self):
body = json.dumps(
{
"action": "opened",
"repository": {"full_name": "cflmy/marqdo-cli"},
"pull_request": {
"number": 21,
"head": {"sha": self.sha2},
"base": {"sha": self.sha1},
},
}
).encode()
plan = self.verify(body, event="pull_request")
self.assertTrue(plan["verified"])
self.assertIsNotNone(plan.get("impact"))
def test_replayed_candidate_is_rejected(self):
self.assertTrue(self.verify(self.push_body())["verified"])
replay = self.verify(self.push_body())
self.assertFalse(replay["verified"])
self.assertIn("duplicate/replay", replay["reason"])
def test_reconciliation_recovers_a_lost_notification_and_is_idempotent(self):
pulls = [
{
"number": 33,
"head": {"sha": self.sha2},
"base": {"sha": self.sha1},
}
]
def prs_fetcher(repository):
return pulls if repository == "cflmy/marqdo-cli" else []
def statuses_fetcher(repository, sha):
return self.statuses() if sha == self.sha2 else []
plan = adapter.reconcile(
self.accepted,
self.state,
["cflmy/marqdo-cli", "cflmy/marqdo"],
self.accepted,
statuses_fetcher,
prs_fetcher,
["ci.cflmy.cn"],
"cflmy/marqdo",
)
self.assertEqual(plan["verified"], 1)
result = [item for item in plan["results"] if item.get("pull_request") == 33][0]
self.assertEqual(result["status"], "VERIFIED")
self.assertTrue(self.state.is_file())
again = adapter.reconcile(
self.accepted,
self.state,
["cflmy/marqdo-cli", "cflmy/marqdo"],
self.accepted,
statuses_fetcher,
prs_fetcher,
["ci.cflmy.cn"],
"cflmy/marqdo",
)
self.assertEqual(again["verified"], 0)
self.assertTrue(any(item["status"] == "DUPLICATE" for item in again["results"]))
def test_reconciliation_reports_api_failures_without_writing_state(self):
plan = adapter.reconcile(
self.accepted,
self.state,
["cflmy/marqdo-cli"],
self.accepted,
lambda repository, sha: self.statuses(),
lambda repository: (_ for _ in ()).throw(adapter.AdapterError("HTTP 403")),
["ci.cflmy.cn"],
"cflmy/marqdo",
)
self.assertEqual(plan["verified"], 0)
self.assertEqual(plan["results"][0]["status"], "ERROR")
self.assertFalse(self.state.exists())
if __name__ == "__main__":
unittest.main()