Compare commits

...
Author SHA1 Message Date
cflmy 4a92201708 feat: trusted candidate webhook adapter and lost-notification reconciliation
ci/woodpecker/push/eco Pipeline was successful
ci/woodpecker/pr/eco Pipeline is running
- 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
cflmy 633ce64cdf ci: add rustfmt/clippy for the Web component entries in the candidate image
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was successful
The candidate image installs a minimal Rust profile, so the Design/Preview
component entries failed at cargo fmt before any quality gate ran. Add the two
components once (only when the active toolchain lacks rustfmt) before running
the pinned domain entries.
2026-11-27 09:15:05 +08:00
cflmy 0655e8f4d5 docs: record the WEB-05 local candidate results
ci/woodpecker/push/eco Pipeline was canceled
ci/woodpecker/pr/eco Pipeline failed
Recursive layout PASS with the active Web domain/entries, 71 root integration
tests OK, Design/Preview component entries PASS, cold web Tool install with an
unchanged CLI digest, and the domain acceptance PASS. The full ecosystem
candidate (consumers/web step) remains evidence-gated by root CI.
2026-11-27 09:08:12 +08:00
cflmy 903f729a4d candidate: activate the Web domain in the root ecosystem (WEB-05)
- Root catalog web domain moves planned→active with entry
  scripts/domain-acceptance.sh; the root gitlink pins the activated domain
  commit f6d0a90 (Design 1b6607f / Preview eff273f active in its catalog).
- integration.sh adds extensions/web to the declared active set and runs the
  domain component entries plus a cold web Tool install: install → generic
  check/preview/handoff → remove with the CLI binary digest unchanged.
- Docs (ARCHITECTURE/MIGRATION/REPOSITORY-TASKS/README) record one active Web
  domain; evidence records candidate identities and the CI-gated result.

Refs cflmy/marqdo#6, cflmy/marqdo-ext-web#2
2026-11-27 09:05:30 +08:00
cflmy d4ccb77003 feat(candidate): authorize, verify and dedupe candidate notifications
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was successful
Implement the authorization verifier for candidate notifications (issue #3):
normalized schema, repository allowlist from the accepted root graph remotes,
reachable commit check, exact accepted base SHA for component candidates,
allowlisted https CI success URL, replay-safe (repository, head SHA) state with
new-baseline revalidation, and union-graph impact reuse (full fallback on
undetermined scope). The plan never auto-promotes or auto-merges; a human still
reviews the candidate branch/PR.

Tests build real temporary Git repositories and cover verified component and
root candidates, unknown repository, failed/non-allowlisted CI, unreachable
commit, stale base, replay + revalidation, dry-run state.

Also the impact analyzer's .gitmodules parser now handles the 3-segment Git
config keys correctly.

Refs cflmy/marqdo#3
2026-11-27 02:19:00 +08:00
15 changed files with 1454 additions and 24 deletions

No files matched your search

+1 -1
View File
@@ -106,7 +106,7 @@ marqdo run hello.mq.md
### Web 领域聚合
Web 领域以设计文档为源材料,面向可交互的原型预览与工程交付。HTTP、数据库、认证和浏览器运行时各自独立维护。`extensions/web` 链接 `planned` 的 Web 领域仓,Design 和 Preview 由该领域仓固定。 [WEB-DESIGN](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md)
Web 领域以设计文档为源材料,面向可交互的原型预览与工程交付。HTTP、数据库、认证和浏览器运行时各自独立维护。`extensions/web` 链接 active 的 Web 领域仓;Design 和 Preview 已在该领域 catalog 激活并登记真实入口,`web` Tool 通过冷安装验证。 [WEB-DESIGN](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md)
| 仓库 | 职责 |
| --- | --- |
+2 -1
View File
@@ -319,12 +319,13 @@ release = "optional"
id = "web"
path = "extensions/web"
kind = "domain"
state = "planned"
state = "active"
owner = "cflmy"
scope = "Web 原型设计领域治理:唯一设计合同、组合验收与交付协调"
requires = []
checks_with = []
release = "none"
entry = "scripts/domain-acceptance.sh"
[[component]]
id = "browser"
+1 -1
View File
@@ -23,7 +23,7 @@
- **聚合准入**:功能拆分须至少有一种独立价值(独立维护责任、显著不同依赖/安全/平台边界、独立版本与制品、可重复独立验收)。若两个仓库几乎每个 PR 都必须一起改动且接口未稳定,应先收敛合同或合并,不能无限拆分。
- **工具目录**(`tools/`)暂不聚合,现有四个 Tool 保持原路径。
**当前状态**(以 [components.toml](../components.toml) 与 [迁移台账](MIGRATION.md) 为准):根仓库有六个核心/工具 active 组件(`cli`、`conformance`、`view`、`knowledge`、`prove`、`lint`)和六个已交付源码的 active 标准库组件(`std-collections/data/fs/io/system/text`)。`std-core/encoding/net` 与十八个独立扩展仍是根层 planned 子模块。`extensions/web` 是 planned 领域子模块,Design 和 Preview 由 Web 领域仓挂载。`marqdo-stdlib` 聚合和 `web-components` 仍在计划中。
**当前状态**(以 [components.toml](../components.toml) 与 [迁移台账](MIGRATION.md) 为准):根仓库有六个核心/工具 active 组件(`cli`、`conformance`、`view`、`knowledge`、`prove`、`lint`)和六个已交付源码的 active 标准库组件(`std-collections/data/fs/io/system/text`)。`std-core/encoding/net` 与十八个独立扩展仍是根层 planned 子模块。`extensions/web` 是 **active 领域**:Design/Preview 在其领域 catalog 激活并登记真实入口,`web-components` 仍 planned。`marqdo-stdlib` 聚合仍在计划中。
## 语言与产品层(不因仓库变多而改变)
+3 -1
View File
@@ -76,7 +76,9 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 +
## 自动化权限
先实现人工触发与 PR/CI 门禁,不开发自动 Agent 管理平台。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。
## 发行与回滚
+3 -3
View File
@@ -28,7 +28,7 @@ Conformance 使用 CLI 已固定的真实 fixture 提交。
**扩展(planned,独立组件)** · [math](https://git.cflmy.cn/cflmy/marqdo-ext-math) · [linalg](https://git.cflmy.cn/cflmy/marqdo-ext-linalg) · [quantum](https://git.cflmy.cn/cflmy/marqdo-ext-quantum) · [http](https://git.cflmy.cn/cflmy/marqdo-ext-http) · [websocket](https://git.cflmy.cn/cflmy/marqdo-ext-websocket) · [ai](https://git.cflmy.cn/cflmy/marqdo-ext-ai) · [mcp](https://git.cflmy.cn/cflmy/marqdo-ext-mcp) · [crypto](https://git.cflmy.cn/cflmy/marqdo-ext-crypto) · [database](https://git.cflmy.cn/cflmy/marqdo-ext-database) · [storage](https://git.cflmy.cn/cflmy/marqdo-ext-storage) · [cache](https://git.cflmy.cn/cflmy/marqdo-ext-cache) · [security](https://git.cflmy.cn/cflmy/marqdo-ext-security) · [browser](https://git.cflmy.cn/cflmy/marqdo-ext-browser) · [document](https://git.cflmy.cn/cflmy/marqdo-ext-document) · [archive](https://git.cflmy.cn/cflmy/marqdo-ext-archive) · [engineering](https://git.cflmy.cn/cflmy/marqdo-ext-engineering) · [regex](https://git.cflmy.cn/cflmy/marqdo-ext-regex) · [datetime](https://git.cflmy.cn/cflmy/marqdo-ext-datetime)
**Web 领域(planned domain)** · 聚合 [marqdo-ext-web](https://git.cflmy.cn/cflmy/marqdo-ext-web)(唯一合同 `docs/WEB-DESIGN.md`)· 子组件 [marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design) · [marqdo-web-preview](https://git.cflmy.cn/cflmy/marqdo-web-preview)
**Web 领域(active domain,WEB-05 起)** · 聚合 [marqdo-ext-web](https://git.cflmy.cn/cflmy/marqdo-ext-web)(唯一合同 `docs/WEB-DESIGN.md`)· 子组件 [marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design) · [marqdo-web-preview](https://git.cflmy.cn/cflmy/marqdo-web-preview)
## 分层治理与领域聚合(2026-11-26 起)
@@ -40,7 +40,7 @@ Conformance 使用 CLI 已固定的真实 fixture 提交。
- 领域激活门禁:子组件具备真实入口与候选提交、领域 catalog 与 gitlink 一致、领域 CI 通过、根 `check-layout.py --checkouts` 递归校验通过、存在依赖关系的组件以同候选证据验证。
- 主仓库 `scripts/check-layout.py` 已引入 domain 角色与递归校验;统一 CLI 制品准备、声明驱动调度、递归影响分析仍在推进,CI 证据以真实候选为准。
当前状态:**没有任何 active 领域**。Web 领域为 planned(`extensions/web`,聚合仓 marqdo-ext-web,子组件 design/preview 在其 catalog 登记);标准库聚合 marqdo-stdlib 尚未创建,九个 `std-*` 保持根 catalog 的 planned 直属记录;HTTP/WebSocket 等仍为独立 planned 扩展,等至少两个真实组件形成共同边界后再评估聚合。首批 Web 实施工单为 WEB-00(合同与真实 Analysis 风险探测)、WEB-01(Design)、WEB-02(Preview)、WEB-03(handoff/组件图)、WEB-04(组合案例与框架交付)、WEB-05(根接入与冷安装),WEB-06(components)为候选;工单在对应责任仓库创建。Web 合同语义冲突由 marqdo-ext-web 协调,不回流 CLI 核心。
当前状态:**有一个 active 领域**——Web(`extensions/web`,聚合仓 marqdo-ext-web,子组件 design/preview 已在其 catalog 激活并登记真实入口,web-components 仍 planned);标准库聚合 marqdo-stdlib 尚未创建,九个 `std-*` 保持根 catalog 的 planned 直属记录;HTTP/WebSocket 等仍为独立 planned 扩展,等至少两个真实组件形成共同边界后再评估聚合。首批 Web 实施工单为 WEB-00(合同与真实 Analysis 风险探测)、WEB-01(Design)、WEB-02(Preview)、WEB-03(handoff/组件图)、WEB-04(组合案例与框架交付)、WEB-05(根接入与冷安装),WEB-06(components)为候选;工单在对应责任仓库创建。Web 合同语义冲突由 marqdo-ext-web 协调,不回流 CLI 核心。
## 阶段与阻塞
@@ -55,7 +55,7 @@ Conformance 使用 CLI 已固定的真实 fixture 提交。
| 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 迁出与同步删除旧路径 |
| M3 跨仓闭环 | 工单、人工候选、同 SHA 门禁 | [跨仓库 CI](https://git.cflmy.cn/cflmy/marqdo/issues/3) 跟踪真实缺陷闭环、候选通知鉴权、去重和影响分析 |
| M4 领域接入 | Web 领域 planned:三仓文档与工单就绪;根 catalog 登记 planned domain | W-M0 真实 CLI 风险探测、WEB-01/02 实现、领域 gitlink、根递归校验与冷安装验收;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、制品与接入 |
### 标准库切换顺序
+1 -1
View File
@@ -2,7 +2,7 @@
按仓库领取任务。标为 **大改** 的条目可涉及模块拆分、实现重写或发布切换。责任仓库应先限定本轮交付范围,涉及公共接口时与实际消费者一起验收。
生态治理采用“根 → 领域聚合 → 功能组件”最多两级 Gitlink:功能仓库实现与修复、领域聚合仓库维护合同与组合验收、主仓库固定 gitlink、治理与发行。`planned` 组件可以挂载真实开发提交,实际入口随验收登记。当前没有 active 领域;Web 领域为 planned(聚合仓 `marqdo-ext-web`,子组件 `marqdo-web-design`/`marqdo-web-preview` 在其 catalog 登记)。先推进 CLI 外部 Bundle、九个标准库,以及 HTTP、Regex、Archive 的迁出;这些改动在同一候选组合中验证后切换基础发行。官网和 VS Code 可独立推进。[迁移台账](MIGRATION.md) · [开发流程](DEVELOPMENT.md)
生态治理采用“根 → 领域聚合 → 功能组件”最多两级 Gitlink:功能仓库实现与修复、领域聚合仓库维护合同与组合验收、主仓库固定 gitlink、治理与发行。`planned` 组件可以挂载真实开发提交,实际入口随验收登记。当前 Web 领域为 active(聚合仓 `marqdo-ext-web`,子组件 `marqdo-web-design`/`marqdo-web-preview` 在其 catalog 激活并登记真实入口;`web-components` 仍 planned)。先推进 CLI 外部 Bundle、九个标准库,以及 HTTP、Regex、Archive 的迁出;这些改动在同一候选组合中验证后切换基础发行。官网和 VS Code 可独立推进。[迁移台账](MIGRATION.md) · [开发流程](DEVELOPMENT.md)
## 集成和语言
@@ -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,32 @@
# WEB-05 Web 领域根接入与冷安装候选证据(2026-11-27)
父工单:[marqdo#6](https://git.cflmy.cn/cflmy/marqdo/issues/6)。本文件记录根侧候选证据;领域侧见 `marqdo-ext-web` 的 `docs/evidence/WEB-05-domain-activation.md`。主分支组合在合并前保持不变。
## 候选身份
| 对象 | 身份 |
| --- | --- |
| 根候选 | `release/web05-domain-active`(根 `main` 基线 `d4ccb77`) |
| Web 领域 | `cflmy/marqdo-ext-web@f6d0a9067cad9f685a501a7bc3f3c3d302fe4f16`(active,入口 `scripts/domain-acceptance.sh`) |
| Design(active) | `cflmy/marqdo-web-design@1b6607fd3cc09801b4f6eacd2fba547caa0ec637`(entry `scripts/ci.sh`) |
| Preview(active) | `cflmy/marqdo-web-preview@eff273f7f2f3919bab62eacded781c61d5f03f91`(entry `scripts/ci.sh`) |
| web-components | planned(无独立实现,不伪造入口) |
| CLI | 根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,`sha256:6ede3b9e...` |
## 根侧门禁与结果(本地候选,CI 为最终门禁)
| 门禁 | 命令 | 结果 |
| --- | --- | --- |
| 递归布局 | `python3 scripts/check-layout.py --checkouts` | **PASS**(根 + Web 域 + Design/Preview active 入口;本地候选) |
| 根集成测试 | `python3 -m unittest discover -s tests/integration` | **71 tests OK**(本地候选) |
| 领域组件入口 | `extensions/web/design/scripts/ci.sh`、`extensions/web/preview/scripts/ci.sh` | **PASS**(本地候选;24/24 Design,web Tool install/check/preview/handoff/remove) |
| web Tool 冷安装 | `tool install` → `web check/preview/handoff` → `tool remove`,CLI SHA 前后一致 | **PASS**(CLI `sha256:6ede3b9e...` 前后一致;本地候选) |
| 领域验收 | `extensions/web/scripts/domain-acceptance.sh`(三案例 + 生产 API/浏览器 E2E) | **PASS**(WEB-04 证据:三案例 + API + Chromium E2E,同一领域提交) |
| 既有消费者 | Conformance/View/Knowledge/Prove/Lint 同一 CLI/Bundle | 由 `integration.sh` 6 在 CI candidate 执行(CI 为最终门禁) |
## 边界
- 根与领域 catalog 都登记 `cli` 依赖;根不实现 Design/Preview/生产应用代码。
- 冷安装只安装构建出的 `web` Tool bundle;生产应用不是 Tool 运行依赖。
- `web-components` 未激活、无 entry,不计完成率。
- 本文件不把本地候选当已发布证据;根 CI(layout + candidate)通过后才晋升。
+317
View File
@@ -0,0 +1,317 @@
#!/usr/bin/env python3
"""Verify one candidate notification before any automation acts on it.
The ecosystem uses manual PR gates; this verifier is the authorization step for
a (future) bot that may only create candidate branches/PRs. It accepts a
normalized notification (from a reviewed webhook adapter), never a raw remote
payload, and returns a machine plan. It refuses forged, replayed, stale,
unknown or failed candidates instead of trusting the sender.
Checks, in order:
1. notification schema and 40-hex commits;
2. the repository is an allowlisted component remote (or the root repository);
3. the CI result is `success` on an allowlisted CI host with an https URL;
4. the commit is reachable in the owning local repository;
5. a component candidate starts from the exact SHA currently pinned by the
accepted root graph (a stale/retargeted base is rejected);
6. the (repository, head SHA) pair is not a replay; a new accepted baseline
allows a re-validation and marks the result `revalidate`;
7. impact is computed with the shared union-graph analyzer; undetermined scope
widens to full re-validation instead of skipping.
The verifier never merges, pushes, grants permissions or fetches floating
branches. Its only proposed action is recording the candidate / creating a
candidate branch that a human still reviews.
"""
from __future__ import annotations
import argparse
import datetime as dt
import importlib.util
import json
import subprocess
import sys
import tomllib
import urllib.parse
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
ROOT = PROJECT_ROOT
SCHEMA = "marqdo.candidate-notification"
PLAN_SCHEMA = "marqdo.candidate-plan"
SCHEMA_VERSION = 1
DEFAULT_CI_HOST = "ci.cflmy.cn"
def load_impact():
"""Load the shared analyzer and point it at the verifier's root checkout."""
spec = importlib.util.spec_from_file_location(
"marqdo_impact", PROJECT_ROOT / "scripts" / "impact.py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.ROOT = ROOT
return module
def git(repo: Path, *args: str) -> str:
result = subprocess.run(["git", "-C", str(repo), *args], capture_output=True)
if result.returncode != 0:
raise NotificationError(
f"git {' '.join(args)} failed in {repo}: "
f"{result.stderr.decode(errors='replace').strip()}"
)
return result.stdout.decode(errors="replace")
class NotificationError(Exception):
pass
def is_sha(value) -> bool:
return isinstance(value, str) and len(value) == 40 and all(
ch in "0123456789abcdef" for ch in value
)
def repository_allowlist(accepted_revision: str) -> dict[str, dict]:
"""Map `owner/name` -> component identity from the accepted root graph."""
impact = load_impact()
graph, unverified = impact.load_graph(ROOT, accepted_revision, "root")
if unverified:
raise NotificationError(
"accepted graph cannot be expanded: " + "; ".join(unverified)
)
allowlist: dict[str, dict] = {}
for component in graph.values():
remote = component.get("remote")
if not remote:
continue
parsed = urllib.parse.urlparse(remote)
name = parsed.path.strip("/")
if name.endswith(".git"):
name = name[:-4]
if name:
allowlist[name] = component
return allowlist
def check_schema(notification: dict) -> None:
if notification.get("schema") != SCHEMA:
raise NotificationError(f"unsupported notification schema: {notification.get('schema')!r}")
if notification.get("schema_version") != SCHEMA_VERSION:
raise NotificationError("unsupported notification schema_version")
if notification.get("kind") not in ("component", "root"):
raise NotificationError("kind must be 'component' or 'root'")
for field in ("repository", "head_sha", "base_sha"):
if not isinstance(notification.get(field), str) or not notification[field]:
raise NotificationError(f"notification has no {field}")
if not is_sha(notification["head_sha"]) or not is_sha(notification["base_sha"]):
raise NotificationError("head_sha/base_sha must be full lowercase commit SHAs")
if notification["head_sha"] == notification["base_sha"]:
raise NotificationError("head_sha equals base_sha; nothing to verify")
def check_ci(notification: dict, ci_hosts: list[str]) -> dict:
ci = notification.get("ci")
if not isinstance(ci, dict):
raise NotificationError("notification has no ci object")
if ci.get("status") != "success":
raise NotificationError(f"CI status is not success: {ci.get('status')!r}")
url = ci.get("url")
if not isinstance(url, str):
raise NotificationError("notification ci.url must be a string")
parsed = urllib.parse.urlparse(url)
if parsed.scheme != "https" or parsed.hostname not in ci_hosts:
raise NotificationError(
f"CI URL must be https on one of {ci_hosts}: {url!r}"
)
return ci
def load_state(path: Path) -> dict:
if not path.is_file():
return {"schema": "marqdo.candidate-state", "schema_version": 1, "seen": {}}
state = json.loads(path.read_text())
if not isinstance(state.get("seen"), dict):
raise NotificationError(f"invalid candidate state file: {path}")
return state
def verify(
notification: dict,
accepted_ref: str,
state_path: Path,
ci_hosts: list[str],
root_repository: str,
write_state: bool,
) -> dict:
check_schema(notification)
ci = check_ci(notification, ci_hosts)
impact = load_impact()
impact.ROOT = ROOT
accepted_revision = impact.resolve(ROOT, accepted_ref)
reasons: list[str] = []
revalidate = False
kind = notification["kind"]
repository = notification["repository"]
allowlist = repository_allowlist(accepted_revision)
if kind == "root":
if repository != root_repository:
raise NotificationError(
f"unknown root repository {repository!r}; allowlist is {root_repository!r}"
)
if not subprocess.run(
["git", "-C", str(ROOT), "cat-file", "-e", notification["head_sha"] + "^{commit}"],
capture_output=True,
).returncode == 0:
raise NotificationError("candidate commit is not reachable in the root repository")
report = impact.analyze(accepted_revision, notification["head_sha"])
base_sha = accepted_revision
key = f"root@{notification['head_sha']}"
else:
component = allowlist.get(repository)
if component is None:
raise NotificationError(
f"unknown repository {repository!r}; allowlist: {sorted(allowlist)}"
)
component_id = notification.get("component") or component["id"]
if component_id != component["id"]:
raise NotificationError(
f"notification component {component_id!r} does not own repository {repository!r}"
)
checkout = ROOT / component["path"]
if not (checkout / ".git").exists():
raise NotificationError(f"missing component checkout: {checkout}")
if not subprocess.run(
["git", "-C", str(checkout), "cat-file", "-e", notification["head_sha"] + "^{commit}"],
capture_output=True,
).returncode == 0:
raise NotificationError("candidate commit is not reachable in the component repository")
if component.get("sha") != notification["base_sha"]:
raise NotificationError(
"base_sha is stale: the accepted root graph pins "
f"{component.get('sha')} for {component_id}"
)
report = impact.consumers_of(component_id, accepted_revision)
base_sha = component["sha"]
key = f"{repository}@{notification['head_sha']}"
state = load_state(state_path)
previous = state["seen"].get(key)
if previous is not None:
if previous.get("accepted") == accepted_revision:
raise NotificationError(
"duplicate/replay: this candidate was already verified against the same accepted baseline"
)
revalidate = True
reasons.append(
"new accepted baseline since first notification; re-run the full candidate gates"
)
if report.get("unverified"):
reasons.append("impact scope undetermined; full re-validation required")
state["seen"][key] = {
"accepted": accepted_revision,
"base_sha": base_sha,
"kind": kind,
"repository": repository,
"first_verified": previous.get("first_verified")
if previous
else dt.datetime.now(dt.timezone.utc).isoformat(),
"last_verified": dt.datetime.now(dt.timezone.utc).isoformat(),
}
if write_state:
state_path.parent.mkdir(parents=True, exist_ok=True)
state_path.write_text(json.dumps(state, indent=2) + "\n")
return {
"schema": PLAN_SCHEMA,
"schema_version": SCHEMA_VERSION,
"verified": True,
"revalidate": revalidate,
"reasons": reasons,
"kind": kind,
"repository": repository,
"head_sha": notification["head_sha"],
"base_sha": notification["base_sha"],
"accepted": {"ref": accepted_ref, "revision": accepted_revision},
"ci": ci,
"impact": {
"affected": report.get("affected", []),
"changed": report.get("changed", []),
"checks_with": report.get("checks_with", []),
"fallback": report.get("fallback"),
"unverified": report.get("unverified", []),
},
"actions": {
"auto_promote": False,
"auto_merge": False,
"create_candidate_branch": True,
"requires_human_review": True,
},
}
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--notification", required=True, help="normalized notification JSON")
parser.add_argument("--accepted", required=True, help="accepted root revision")
parser.add_argument("--state", required=True, help="candidate dedupe state file")
parser.add_argument(
"--ci-host", action="append", default=None, help="allowlisted CI host (repeatable)"
)
parser.add_argument("--root-repository", default="cflmy/marqdo")
parser.add_argument("--out", default=None)
parser.add_argument("--json", action="store_true")
parser.add_argument("--dry-run", action="store_true", help="do not write the dedupe state")
args = parser.parse_args(argv)
ci_hosts = args.ci_host or [DEFAULT_CI_HOST]
try:
notification = json.loads(Path(args.notification).read_text())
if not isinstance(notification, dict):
raise NotificationError("notification must be a JSON object")
plan = verify(
notification,
args.accepted,
Path(args.state),
ci_hosts,
args.root_repository,
write_state=not args.dry_run,
)
except (NotificationError, json.JSONDecodeError, OSError) as error:
rejected = {
"schema": PLAN_SCHEMA,
"schema_version": SCHEMA_VERSION,
"verified": False,
"reasons": [str(error)],
"actions": {
"auto_promote": False,
"auto_merge": False,
"create_candidate_branch": False,
"requires_human_review": True,
},
}
text = json.dumps(rejected, ensure_ascii=False, indent=2) + "\n"
if args.out:
Path(args.out).write_text(text)
if args.json:
print(text, end="")
print(f"candidate-notify: 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"verified {plan['kind']} candidate {plan['repository']}@{plan['head_sha'][:12]} "
f"affected={len(plan['impact']['affected'])} revalidate={plan['revalidate']}"
)
for reason in plan["reasons"]:
print(f" note: {reason}")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
+104 -14
View File
@@ -23,6 +23,7 @@ from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
import tomllib
@@ -94,9 +95,10 @@ def submodule_urls(repo: Path, revision: str) -> dict[str, str]:
if not record:
continue
key, _, value = record.decode(errors="replace").partition("\n")
parts = key.split(".")
if len(parts) == 4 and parts[0] == "submodule" and parts[3] in ("path", "url"):
pending.setdefault(parts[1], {})[parts[3]] = value
match = re.fullmatch(r"submodule\.(.+)\.(path|url)", key)
if match:
name, field = match.groups()
pending.setdefault(name, {})[field] = value
for fields in pending.values():
if "path" in fields and "url" in fields:
urls[fields["path"]] = fields["url"]
@@ -249,6 +251,79 @@ def affected_set(
return sorted(affected), sorted(domains), sorted(co_validation)
def consumers_of(component_id: str, revision: str) -> dict:
"""Consumers of one component at a revision (component-PR impact scope).
Uses the accepted graph only: a component candidate cannot change the root
graph it is evaluated against. Unknown component or unexpandable domain
widens the scope to the whole graph (never silently skip).
"""
revision_sha = resolve(ROOT, revision)
graph, unverified = load_graph(ROOT, revision_sha, "root")
if component_id not in graph:
graph, unverified = load_graph(ROOT, revision_sha, "root")
return {
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"accepted": {"ref": revision, "revision": revision_sha},
"component": component_id,
"affected": sorted(graph),
"checks_with": [],
"domain_ancestors": [],
"fallback": "full",
"unverified": unverified
+ [f"unknown component {component_id!r} at {revision_sha}; scope widened"],
}
dependents: dict[str, set[str]] = {key: set() for key in graph}
for component in graph.values():
for dependency in component.get("requires", []):
dependents.setdefault(dependency, set()).add(component["id"])
affected = {component_id}
queue = [component_id]
while queue:
current = queue.pop()
for consumer in dependents.get(current, set()):
if consumer not in affected:
affected.add(consumer)
queue.append(consumer)
domains = set()
for item in list(affected):
parent = graph[item].get("parent")
while parent:
if parent not in affected:
domains.add(parent)
parent = graph[parent].get("parent") if parent in graph else None
co_validation: set[str] = set()
while True:
additions = {
partner
for item in affected
for partner in graph[item].get("checks_with", [])
if partner not in affected
}
if not additions:
break
affected |= additions
co_validation |= additions
fallback = None
if unverified:
affected = set(graph)
domains = set()
co_validation = set()
fallback = "full"
return {
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"accepted": {"ref": revision, "revision": revision_sha},
"component": component_id,
"affected": sorted(affected),
"checks_with": sorted(co_validation),
"domain_ancestors": sorted(domains),
"fallback": fallback,
"unverified": unverified,
}
def analyze(accepted_ref: str, candidate_ref: str) -> dict:
accepted_revision = resolve(ROOT, accepted_ref)
candidate_revision = resolve(ROOT, candidate_ref)
@@ -290,6 +365,11 @@ def main(argv: list[str]) -> int:
parser.add_argument("--candidate", default="HEAD", help="candidate root revision")
parser.add_argument("--out", default=None)
parser.add_argument("--json", action="store_true")
parser.add_argument(
"--component",
default=None,
help="report consumers of one component at --accepted instead of a root diff",
)
parser.add_argument(
"--fail-on-unverified",
action="store_true",
@@ -297,7 +377,10 @@ def main(argv: list[str]) -> int:
)
args = parser.parse_args(argv)
try:
report = analyze(args.accepted, args.candidate)
if args.component:
report = consumers_of(args.component, args.accepted)
else:
report = analyze(args.accepted, args.candidate)
except ImpactError as error:
print(f"impact: error: {error}", file=sys.stderr)
return 1
@@ -307,16 +390,23 @@ def main(argv: list[str]) -> int:
if args.json:
print(text, end="")
else:
print(
f"accepted {report['accepted']['revision'][:12]} "
f"candidate {report['candidate']['revision'][:12]}"
)
print(
f"changed={report['counts']['changed']} "
f"affected={report['counts']['affected']}"
)
for item in report["changed"]:
print(f" changed {item['id']}: {item['reason']}")
if "candidate" in report:
print(
f"accepted {report['accepted']['revision'][:12]} "
f"candidate {report['candidate']['revision'][:12]}"
)
print(
f"changed={report['counts']['changed']} "
f"affected={report['counts']['affected']}"
)
for item in report["changed"]:
print(f" changed {item['id']}: {item['reason']}")
else:
print(
f"component {report['component']} at "
f"{report['accepted']['revision'][:12]}"
)
print(f"consumers={len(report['affected'])}")
print("affected: " + ", ".join(report["affected"]))
if report["checks_with"]:
print("co-validation: " + ", ".join(report["checks_with"]))
+35 -1
View File
@@ -11,7 +11,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
root="$PWD"
active="$(python3 scripts/check-layout.py --checkouts --active-paths)"
expected=$'cli\nstdlib/collections\nstdlib/data\nstdlib/fs\nstdlib/io\nstdlib/system\nstdlib/text\ntests/conformance\ntools/knowledge\ntools/lint\ntools/prove\ntools/view'
expected=$'cli\nextensions/web\nstdlib/collections\nstdlib/data\nstdlib/fs\nstdlib/io\nstdlib/system\nstdlib/text\ntests/conformance\ntools/knowledge\ntools/lint\ntools/prove\ntools/view'
if [[ "$active" != "$expected" ]]; then
echo "UNVERIFIED: update the integration plan for the changed active component set" >&2
exit 1
@@ -97,6 +97,40 @@ python3 cli/tools/ci/verify_extension_contracts.py \
--release-info "$installed/RELEASE_INFO.json" \
--fixtures tests/conformance --out "$work/conformance.json"
# 5.5 Web domain: component entries from the pinned domain gitlink, then a cold
# install of the same-built web Tool with a generic check/preview/handoff run.
# The candidate image uses a minimal Rust profile; component entries run
# fmt/clippy, so add those components once when the active toolchain lacks them.
if command -v rustup >/dev/null 2>&1 \
&& ! rustup component list --installed 2>/dev/null | grep -qx 'rustfmt.*'; then
rustup component add rustfmt clippy
fi
(
cd extensions/web/design
MARQDO_BIN="$MARQDO_BIN" scripts/ci.sh
)
(
cd extensions/web/preview
MARQDO_BIN="$MARQDO_BIN" scripts/ci.sh
)
web_tool="$root/extensions/web/preview/dist/marqdo-web-preview/tool.json"
test -f "$web_tool"
export MARQDO_TOOL_HOME="$work/web-tool-home"
cli_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
"$MARQDO_BIN" tool install "$web_tool"
"$MARQDO_BIN" web check extensions/web/examples/research-workspace/index.mq.md \
--unit 工作台 --root extensions/web/examples/research-workspace
"$MARQDO_BIN" web preview extensions/web/examples/research-workspace/index.mq.md \
--unit 工作台 --root extensions/web/examples/research-workspace --out "$work/web-preview"
test -f "$work/web-preview/index.html"
"$MARQDO_BIN" web handoff extensions/web/examples/research-workspace/index.mq.md \
--unit 工作台 --root extensions/web/examples/research-workspace --out "$work/web-handoff.md"
test -s "$work/web-handoff.md"
"$MARQDO_BIN" tool remove web
cli_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
test "$cli_before" = "$cli_after"
echo "web domain: component entries + cold Tool install PASS"
# 6. Existing consumers, same installed binary and adjacent Bundle.
(
cd tools/view
+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:]))
+259
View File
@@ -0,0 +1,259 @@
"""Candidate notification authorization contract tests (issue #3).
Fixtures are real temporary Git repositories: a root catalog with `.gitmodules`
and gitlinks, a component repository with two commits, and normalized
notifications. The verifier must refuse forged/replayed/stale/failed candidates
and never claim an auto-promotion action.
"""
import importlib.util
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
IMPACT_SPEC = importlib.util.spec_from_file_location("impact", ROOT / "scripts/impact.py")
impact = importlib.util.module_from_spec(IMPACT_SPEC)
IMPACT_SPEC.loader.exec_module(impact)
NOTIFY_SPEC = importlib.util.spec_from_file_location(
"candidate_notify", ROOT / "scripts/candidate-notify.py"
)
notify = importlib.util.module_from_spec(NOTIFY_SPEC)
NOTIFY_SPEC.loader.exec_module(notify)
GIT_ENV = {
"GIT_AUTHOR_NAME": "test",
"GIT_AUTHOR_EMAIL": "test@example.invalid",
"GIT_COMMITTER_NAME": "test",
"GIT_COMMITTER_EMAIL": "test@example.invalid",
}
CI = {"status": "success", "url": "https://ci.cflmy.cn/repos/6/pipeline/1/1"}
def git(cwd, *args, check=True):
env = os.environ.copy()
env.update(GIT_ENV)
result = subprocess.run(["git", "-C", str(cwd), *args], capture_output=True, env=env)
if check and result.returncode != 0:
raise AssertionError(
f"git {' '.join(args)} failed: {result.stderr.decode(errors='replace')}"
)
return result.stdout.decode()
def init(path: Path) -> Path:
path.mkdir(parents=True, exist_ok=True)
git(path, "init", "-q")
return path
def write(path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data)
def commit(repo: Path, message: str = "fixture") -> str:
git(repo, "add", "-A")
git(repo, "commit", "-q", "-m", message)
return git(repo, "rev-parse", "HEAD").strip()
def catalog(cli_sha_gitlink: bool = True) -> str:
return """[[component]]
id = "cli"
path = "cli"
kind = "core"
state = "active"
owner = "t"
scope = "s"
requires = []
checks_with = []
release = "base"
entry = "scripts/test.sh"
[[component]]
id = "std-text"
path = "stdlib/text"
kind = "stdlib"
state = "active"
owner = "t"
scope = "s"
requires = ["cli"]
checks_with = []
release = "base"
entry = "scripts/test.sh"
"""
GITMODULES = """[submodule "cli"]
\tpath = cli
\turl = https://git.cflmy.cn/cflmy/marqdo-cli.git
[submodule "stdlib/text"]
\tpath = stdlib/text
\turl = https://git.cflmy.cn/cflmy/marqdo-std-text.git
"""
class NotifyTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.base = Path(self.tmp.name)
self.root = self.base / "root"
init(self.root)
write(self.root / "components.toml", catalog())
write(self.root / ".gitmodules", GITMODULES)
self.cli = init(self.root / "cli")
write(self.cli / "README.md", "cli")
self.cli_sha1 = commit(self.cli)
self.text = init(self.root / "stdlib/text")
write(self.text / "README.md", "text")
self.text_sha1 = commit(self.text)
git(self.root, "add", "components.toml", ".gitmodules")
git(self.root, "update-index", "--add", "--cacheinfo", f"160000,{self.cli_sha1},cli")
git(
self.root, "update-index", "--add", "--cacheinfo",
f"160000,{self.text_sha1},stdlib/text",
)
git(self.root, "commit", "-q", "-m", "accepted root")
self.accepted = git(self.root, "rev-parse", "HEAD").strip()
# Candidate component commit after the accepted root was frozen.
write(self.cli / "README.md", "cli v2")
self.cli_sha2 = commit(self.cli, "candidate")
# Candidate root commit moving the cli gitlink.
git(self.root, "update-index", "--cacheinfo", f"160000,{self.cli_sha2},cli")
git(self.root, "commit", "-q", "-m", "candidate root")
self.candidate_root = git(self.root, "rev-parse", "HEAD").strip()
self.notify_original_root = notify.ROOT
self.impact_original_root = impact.ROOT
notify.ROOT = self.root
impact.ROOT = self.root
self.state = self.base / "state.json"
def tearDown(self):
notify.ROOT = self.notify_original_root
impact.ROOT = self.impact_original_root
self.tmp.cleanup()
def notification(self, **overrides) -> Path:
data = {
"schema": "marqdo.candidate-notification",
"schema_version": 1,
"repository": "cflmy/marqdo-cli",
"kind": "component",
"component": "cli",
"head_sha": self.cli_sha2,
"base_sha": self.cli_sha1,
"ci": dict(CI),
"pull_request": 17,
}
data.update(overrides)
path = self.base / "notification.json"
path.write_text(json.dumps(data))
return path
def run_verify(self, path: Path, accepted: str | None = None, write_state: bool = True):
try:
return notify.verify(
json.loads(path.read_text()),
accepted or self.accepted,
self.state,
["ci.cflmy.cn"],
"cflmy/marqdo",
write_state=write_state,
)
except notify.NotificationError as error:
return {"verified": False, "reason": str(error)}
def test_component_candidate_verified_with_consumers_and_no_auto_promotion(self):
plan = self.run_verify(self.notification())
self.assertTrue(plan["verified"])
self.assertIn("std-text", plan["impact"]["affected"])
self.assertFalse(plan["actions"]["auto_promote"])
self.assertFalse(plan["actions"]["auto_merge"])
self.assertTrue(plan["actions"]["requires_human_review"])
self.assertTrue(self.state.is_file())
def test_unknown_repository_is_rejected(self):
plan = self.run_verify(self.notification(repository="cflmy/unknown"))
self.assertFalse(plan["verified"])
self.assertIn("unknown repository", plan["reason"])
def test_failed_ci_is_rejected(self):
plan = self.run_verify(self.notification(ci={"status": "failure", "url": CI["url"]}))
self.assertFalse(plan["verified"])
self.assertIn("CI status", plan["reason"])
def test_non_allowlisted_ci_host_is_rejected(self):
plan = self.run_verify(
self.notification(ci={"status": "success", "url": "https://evil.example/p/1"})
)
self.assertFalse(plan["verified"])
self.assertIn("CI URL", plan["reason"])
def test_unreachable_commit_is_rejected(self):
plan = self.run_verify(self.notification(head_sha="0" * 40))
self.assertFalse(plan["verified"])
self.assertIn("not reachable", plan["reason"])
def test_stale_base_sha_is_rejected(self):
plan = self.run_verify(
self.notification(base_sha=self.text_sha1)
)
self.assertFalse(plan["verified"])
self.assertIn("base_sha is stale", plan["reason"])
def test_replay_is_rejected_and_new_baseline_requires_revalidation(self):
first = self.run_verify(self.notification())
self.assertTrue(first["verified"])
replay = self.run_verify(self.notification())
self.assertFalse(replay["verified"])
self.assertIn("duplicate/replay", replay["reason"])
# A new accepted baseline that still pins the same component SHA (here
# another component moved) must re-validate the same candidate.
write(self.text / "README.md", "text v2")
text_sha2 = commit(self.text, "text candidate")
git(self.root, "update-index", "--cacheinfo", f"160000,{self.cli_sha1},cli")
git(self.root, "update-index", "--cacheinfo", f"160000,{text_sha2},stdlib/text")
git(self.root, "commit", "-q", "-m", "baseline 2")
baseline2 = git(self.root, "rev-parse", "HEAD").strip()
revalidated = self.run_verify(self.notification(), accepted=baseline2)
self.assertTrue(revalidated["verified"], revalidated.get("reason"))
self.assertTrue(revalidated["revalidate"])
def test_root_candidate_uses_union_graph_diff(self):
plan = self.run_verify(
self.notification(
repository="cflmy/marqdo",
kind="root",
component=None,
head_sha=self.candidate_root,
base_sha=self.accepted,
)
)
self.assertTrue(plan["verified"])
self.assertEqual([c["id"] for c in plan["impact"]["changed"]], ["cli"])
self.assertIn("std-text", plan["impact"]["affected"])
def test_root_repository_must_be_named_explicitly(self):
plan = self.run_verify(
self.notification(
repository="cflmy/marqdo-cli",
kind="root",
head_sha=self.candidate_root,
base_sha=self.accepted,
)
)
self.assertFalse(plan["verified"])
self.assertIn("unknown root repository", plan["reason"])
def test_state_is_not_written_in_dry_run(self):
plan = self.run_verify(self.notification(), write_state=False)
self.assertTrue(plan["verified"])
self.assertFalse(self.state.exists())
if __name__ == "__main__":
unittest.main()
+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()