Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions .crabcode-plugin/latest-green-main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""「哪个 commit 可以被发布 / 被审计」的**唯一**判据 —— W-PUBLISH-PROVENANCE-GATE PR-1。

立项真源:acosmi/crabcode-source `docs/audit/2026-08-17-发布来源门缺失-立项审计与实施路径.md`

## 它解决的病

那份立项的一句话是:**这个系统有一套发育完整的「产物来源」纪律,和一个完全不存在的
「源码质量来源」纪律**;而唯一存在的那个源码质量门长在**消费侧**(审计器
`notify-mirror.yml` 只接受绿 SHA),生产侧(发布器)一个字都没有 —— 它发的是
`${GITHUB_SHA}`,此刻是什么就发什么。两边各自演化的判据正是这条链坏过三次的形状。

修法不是「给发布器加一道会挡人的门」(本仓 main 若哪天红了,fail-closed 就是永远发不
出去),而是 **把「加一道门」翻转成「两边用同一条规则算同一个答案」**:发布器与审计器
都调用**本文件**来回答「最新的绿 SHA 是哪个」。门会挡人,同源不会。

## 判据(逐条都是可复算的)

一次 run 算「绿」当且仅当四条同时成立:
* `status == "completed"`
* `conclusion == "success"`
* `event == "push"` —— PR 上的绿证明不了 main 上的绿
* `head_branch == "main"`
缺字段即**不算绿**(fail-closed)。发布器宁可不发也不发错:不发会被审计器的
freshness SLO 在 8 小时内喊出来,发错则落进 `immutable` 一年缓存里收不回来。

排序取 `created_at` 倒序 —— 这一条**逐字沿用审计器 2026-08-17 之前的既有行为**,
本次改动是「同源化」不是「改语义」。已知局限:重跑一个旧 commit 的 CI 会把它排到前面
(run 创建时刻不是 commit 顺序)。要根治得引入 git 祖先关系,那是另一件事;在这里
写死一个**两边共用**的近似,比两边各写一个**不同**的近似严格更好。

## 调用形态

latest-green-main.py --runs runs.json # -> "<sha> <html_url>"
latest-green-main.py --runs runs.json --format json # -> 过滤+排序后的完整数组
latest-green-main.py --runs runs.json --extra-run r.json

`--runs` 吃的就是 GitHub REST
`/actions/workflows/ci.yml/runs?branch=main&event=push&per_page=100` 的原样响应。

`--extra-run` 吃一个**单个 run 对象**(发布器由 `workflow_run` 事件触发时,把
`github.event.workflow_run` 原样丢进来)。为什么需要它:触发发布的正是那次 run,而
REST 列表未必立刻能看见它 —— 少了这一手,最坏情况是「新绿 commit 永远轮不到发布」这种
**静默漏发**。内容为 `null` / 空 / 不满足上面四条判据时静默忽略(手动 dispatch 那条腿
本来就没有事件)。合并后按 (head_sha, created_at) 去重。

出口码:0 = 选出来了;1 = 没有任何一次绿 run(调用方必须当作硬失败,不许兜底发 HEAD)。
"""

from __future__ import annotations

import argparse
import json
import re
import sys
from typing import Any

SHA_RE = re.compile(r"^[0-9a-f]{40}$")
REQUIRED_EVENT = "push"
REQUIRED_BRANCH = "main"


def is_green(run: Any) -> bool:
"""四条判据全成立才算绿;任一字段缺失即 False(fail-closed)。"""
if not isinstance(run, dict):
return False
return (
run.get("status") == "completed"
and run.get("conclusion") == "success"
and run.get("event") == REQUIRED_EVENT
and run.get("head_branch") == REQUIRED_BRANCH
and isinstance(run.get("head_sha"), str)
and SHA_RE.fullmatch(run["head_sha"]) is not None
)


def green_runs(payload: Any, extra: Any = None) -> list[dict]:
"""过滤 + 合并 --extra-run + 按 created_at 倒序 + 去重。"""
runs = []
if isinstance(payload, dict):
listed = payload.get("workflow_runs")
if isinstance(listed, list):
runs.extend(listed)
elif isinstance(payload, list):
runs.extend(payload)
if extra is not None:
runs.append(extra)

selected = [run for run in runs if is_green(run)]
selected.sort(key=lambda run: str(run.get("created_at", "")), reverse=True)

deduped: list[dict] = []
seen: set[tuple[str, str]] = set()
for run in selected:
key = (run["head_sha"], str(run.get("created_at", "")))
if key in seen:
continue
seen.add(key)
deduped.append(run)
return deduped


def load_json(path: str) -> Any:
with open(path, encoding="utf-8") as handle:
text = handle.read().strip()
if text == "" or text == "null":
return None
return json.loads(text)


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--runs", required=True, help="GitHub REST workflow-runs 响应的 JSON 文件")
parser.add_argument("--extra-run", default=None, help="额外的单个 run 对象(workflow_run 事件载荷)")
parser.add_argument("--format", choices=["sha", "json"], default="sha")
args = parser.parse_args(argv)

payload = load_json(args.runs)
extra = load_json(args.extra_run) if args.extra_run else None
# `github.event.workflow_run` 直接给的就是 run 对象;但如果调用方丢来的是整个事件
# 载荷,也接住它的 workflow_run 字段 —— 两种形态都不该让发布链静默漏发。
if isinstance(extra, dict) and "workflow_run" in extra and "head_sha" not in extra:
extra = extra.get("workflow_run")

runs = green_runs(payload, extra)
if not runs:
print(
"no successful main push CI run with a valid SHA",
file=sys.stderr,
)
return 1

if args.format == "json":
print(json.dumps(runs, ensure_ascii=False))
return 0

newest = runs[0]
print(f"{newest['head_sha']} {newest.get('html_url', '')}".rstrip())
return 0


if __name__ == "__main__":
raise SystemExit(main())
2 changes: 1 addition & 1 deletion .crabcode-plugin/mirror-distribution.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"comment": "镜像分发裁剪清单(W-PLUGIN-MIRROR-SLIM, 2026-08-16)。列出的目录前缀不进 CN 镜像 zip(客户端运行时零消费的测试资产;git clone 回退路径仍是全仓)。发布器 acosmi/crabcode-source .github/workflows/sync-plugins-to-mirror.yml 与本仓审计器 .github/workflows/notify-mirror.yml 从同一 SHA 的 checkout 读本文件推导各自的文件集,两侧构造上不可能分叉。安全栅:前缀必须含 /tests/(两侧都强制),清单永远裁不掉运行时内容。改本文件无需改任何 workflow。",
"comment": "镜像分发裁剪清单(W-PLUGIN-MIRROR-SLIM, 2026-08-16)。列出的目录前缀不进 CN 镜像 zip(客户端运行时零消费的测试资产;git clone 回退路径仍是全仓)。发布器 .github/workflows/publish-to-cn-mirror.yml 与审计器 .github/workflows/notify-mirror.yml(2026-08-17 起同住本仓)从同一 SHA 的 checkout 读本文件推导各自的文件集,两侧构造上不可能分叉。安全栅:前缀必须含 /tests/(两侧都强制),清单永远裁不掉运行时内容。改本文件无需改任何 workflow。",
"excludePrefixes": [
"plugins/crabcode-media-ops/tests/browser/__screenshots__/",
"plugins/crabcode-media-publisher/tests/browser/snapshots/"
Expand Down
148 changes: 148 additions & 0 deletions .crabcode-plugin/verify-mirror-bundle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""镜像上某个 SHA 的一整套字节是否**自洽**且 `latest` 正指向它 —— 一个判据,两处调用。

W-PUBLISH-PROVENANCE-GATE PR-1(2026-08-17)。
立项真源:acosmi/crabcode-source `docs/audit/2026-08-17-发布来源门缺失-立项审计与实施路径.md` §3.5 / §4

## 为什么要把它抽出来

`publish-to-cn-mirror.yml` 现在有两个地方问同一个问题:

1. **发布前的幂等早退** —— 目标 SHA 的东西已经在镜像上且自洽?那就一个字节都别再传。
2. **发布后的验收** —— 刚传上去的东西自洽吗?

它们必须是**同一个判据**。写两份就是本立项在治的那个病(生产侧与消费侧各写一份判据,
各自演化),只不过缩小到一个文件之内。

## 幂等早退不是省事项,是关掉一条危害链(§3.5)

zip 按**源 SHA 定址**(`${SHA}.zip`)⇒ 重跑同一个 SHA = **同名对象重写**;而 zip 字节
对 mtime 敏感(checkout 的 mtime 就是本次 checkout 的时刻,同内容不同 mtime ⇒ sha256
必不同);而镜像给 `*.zip` 发 `Cache-Control: public, max-age=31536000, immutable`
⇒ 缓存层可以永远持有旧字节,而 `.sha256` sidecar 已经换成新的 ⇒ **「缓存 zip × 新
sidecar」撕裂对**,客户端摘要校验 fail-closed 回退 git。校验侧没错,是发布侧逼它触发。

旧发布器(acosmi/crabcode-source `sync-plugins-to-mirror.yml`,2026-08-17 退役)确有一个
早退 guard,但整段包在 `if github.event_name == "schedule"` 里,而那个 schedule 早在
2026-07-27 就被删了 —— **guard 是死代码**。载体死了,危害没死:迁到本仓的新发布器
`workflow_dispatch` 补发轨原样继承了它。所以早退必须对**全部触发路径**生效。

## 判据(与发布后验收逐条同一套)

* `latest`(带 `Cache-Control: no-cache` 取)逐字节等于目标 SHA
* `${SHA}.zip`、`${SHA}.zip.sha256`、`marketplace.json`、`marketplace.json.sha256` 全部可达
* 两个 `.sha256` 的形态过审计器同款正则 `([0-9a-f]{64})␠␠([A-Za-z0-9._-]+)\n?`
(**恰两个空格 + 纯 basename**),且记录里的文件名就是它自己的载荷名
* 两个摘要与镜像上**真实字节**逐位相符 —— 只断言 HTTP 200 只能证明「有个文件在那」
* `marketplace.json` 的 `plugins` 非空(防半包发布给网站)

出口码:0 = 全过;1 = 任一条不过(原因打到 stderr)。
调用方自己决定 1 意味着什么:发布前 = 「还得发」,发布后 = 「这次发版红」。
"""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import sys
import time
import urllib.error
import urllib.request

CHECKSUM_RE = re.compile(r"([0-9a-f]{64}) ([A-Za-z0-9._-]+)\n?")
SHA_RE = re.compile(r"^[0-9a-f]{40}$")


def fetch(url: str, *, no_cache: bool = False, attempts: int = 4) -> bytes:
"""取一个 URL。**4xx 不重试** —— 它是确定性答案不是瞬态。

这条很重要:发布前的幂等预检在「这个 SHA 还没发过」时命中的正是 404,而那是
最常见的一条路径。把 404 当瞬态退避重试,既白等十几秒,又把「还没发」说成
「不可达」—— 判据的语义会跟着退化。
"""
last: Exception | None = None
for attempt in range(1, attempts + 1):
request = urllib.request.Request(url)
if no_cache:
request.add_header("Cache-Control", "no-cache")
request.add_header("Pragma", "no-cache")
try:
with urllib.request.urlopen(request, timeout=120) as response:
return response.read()
except urllib.error.HTTPError as error:
if 400 <= error.code < 500:
raise RuntimeError(f"{url} → HTTP {error.code}") from error
last = error
except (urllib.error.URLError, TimeoutError, OSError) as error:
last = error
if attempt < attempts:
time.sleep(attempt * 2)
raise RuntimeError(f"不可达 {url}: {last}")


def verify(base: str, sha: str) -> list[str]:
problems: list[str] = []
base = base.rstrip("/")
if SHA_RE.fullmatch(sha) is None:
return [f"目标 SHA 形态不合法: {sha!r}"]

try:
pointer = fetch(f"{base}/latest", no_cache=True)
except RuntimeError as error:
return [str(error)]
if pointer.strip() != sha.encode("ascii"):
problems.append(f"latest = {pointer!r},不等于目标 {sha}")

payloads: dict[str, bytes] = {}
for name in (f"{sha}.zip", "marketplace.json"):
for suffix in ("", ".sha256"):
url = f"{base}/{name}{suffix}"
try:
payloads[f"{name}{suffix}"] = fetch(url)
except RuntimeError as error:
problems.append(str(error))
if problems:
return problems

for name in (f"{sha}.zip", "marketplace.json"):
record = payloads[f"{name}.sha256"].decode("ascii", errors="replace")
match = CHECKSUM_RE.fullmatch(record)
if match is None:
problems.append(f"{name}.sha256 形态不合审计器正则: {record!r}")
continue
if match.group(2) != name:
problems.append(f"{name}.sha256 指向了别的文件名: {match.group(2)}")
continue
actual = hashlib.sha256(payloads[name]).hexdigest()
if actual != match.group(1):
problems.append(f"{name} 的摘要与镜像字节不符(记录 {match.group(1)},实际 {actual})")

try:
index = json.loads(payloads["marketplace.json"].decode("utf-8"))
if not isinstance(index.get("plugins"), list) or not index["plugins"]:
problems.append("镜像 marketplace.json 的 plugins 为空")
except (ValueError, AttributeError) as error:
problems.append(f"镜像 marketplace.json 不是合法 JSON: {error}")

return problems


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base", required=True, help="镜像插件前缀(不带尾斜杠)")
parser.add_argument("--sha", required=True, help="目标源 SHA(40 位小写十六进制)")
args = parser.parse_args(argv)

problems = verify(args.base, args.sha)
if problems:
for problem in problems:
print(f"✗ {problem}", file=sys.stderr)
return 1
print(f"✓ 镜像在 {args.sha} 上自洽:latest 指针 / zip / marketplace.json / 两个摘要全部相符")
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading