Compare commits

...
Author SHA1 Message Date
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
5 changed files with 740 additions and 1 deletions

No files matched your search

+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。
## 发行与回滚 ## 发行与回滚
@@ -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()