#!/usr/bin/env python3 # -*- coding: utf-8 -*- """runner 管理员清单可执行验证(KCP-1.0 Wave 25 W150)。 背景 ---- W144 把“缺什么权限”结构化成 `vde-runner-admin-checklist/1` 的 7 项清单 (API / token scope / runner 标签 / 验收),`runner_access_check.py` 负责 只读探测并诚实给出 `blocked_no_token` 等状态。但清单本身仍是“文档”: 管理员拿到清单后要自己翻译成命令、自己判断响应算不算通过。本工具把它 转成**可执行验证**: * **live 模式**(`--live`):本工具自己按清单逐项发只读 HTTP 请求 (GET,不写仓库、不改 runner),记录 HTTP 状态、token 是否可得、标签 覆盖,并逐项输出 `verified` / `blocked_no_token` / `blocked_no_admin` / `blocked_runner_labels` / `instance_unreachable`;拿不到 token 时诚实 `blocked_no_token`(exit 2),绝不伪造“已就绪”。 * **replay 模式**(`--probe PATH`):回放 `runner_access_check.py` 的探测证据 JSON,把同一份清单映射成逐项 status + 可执行验证命令/ 期望证据(供 nightly 无 secret 时归档“当前卡在哪一项、按什么命令复检”)。 每个清单项同时输出: `verification.command_template`(管理员可直接复制执行、token 用环境变量 占位、不落盘不回显)、`verification.expected`(验收判据)、 `verification.evidence`(本工具记录什么证据)。token 值永不写入输出。 状态与退出码 ------------ * `verified`:7 项全部通过 => exit 0(真实项目 CI 是否绿仍需按 SOP 另行 触发 run,本工具不声称“CI 已绿”)。 * `blocked_no_token` / `blocked_token_invalid` / `blocked_no_admin` / `blocked_runner_labels`:诚实阻塞(环境/权限未就绪)=> exit 2。 * `instance_unreachable` => exit 3(网络/实例不可达)。 * `verify_failed`:出现非预期 HTTP 状态(5xx 等)=> exit 1。 * `usage_error`:参数/输入契约错误(如既无 --live 也无 --probe)=> exit 2。 诚实边界 -------- 本工具只做只读 GET;`registration_token` 项只验证“能不能取到一次性 token” 并立即丢弃响应,不在 JSON/markdown 里保留 token 值。replay 模式不代表 现在仍可访问,只代表“探测证据当时的结论”。真实 CI run 次数不因本工具 而增加。 W150 常驻接线 ------------- `.gitea/workflows/nightly.yml` 的 `runner-access-nightly` job 常驻 `runner_admin_verify.py --self-test`(清单/状态/退出码契约自检)与 `--probe build-runner-access/runner-access-probe.json --json-out ...` (回放探测证据,`blocked_no_token` 时 exit 2 但该步 continue-on-error, 与只读探测一致,不让 nightly 因管理员未就绪变红)。 """ from __future__ import annotations import argparse import datetime import hashlib import json import os import sys TOOL = "tools/ci/runner_admin_verify.py" SCHEMA = "vde-runner-admin-verify/1" POLICY_SCHEMA = "vde-runner-admin-verify-policy/1" POLICY_VERSION = "W168.1" WAVE = "W168" CHECKLIST_SCHEMA = "vde-runner-admin-checklist/1" DEFAULT_BASE_URL = "https://git.hdtime.space" DEFAULT_REPO = "hm/ViewDesignEngine" TOKEN_ENVS = ("VDE_GITEA_TOKEN", "GITEA_TOKEN", "VDE_CI_GITEA_TOKEN") TOKEN_PLACEHOLDER = "$VDE_GITEA_TOKEN" # W168:可执行管理员验证脚本(read-only GET,可直接交给管理员执行)。 VERIFY_SCRIPT_MARKER = "W168 runner admin verification script" VERIFY_SCRIPT_NO_WRITE_MARKER = "WRITE_OPS=none" VERIFY_SCRIPT_REAL_CI_MARKER = "REAL_CI_RUNS=0" VERIFY_SCRIPT_ITEM_IDS = ( "instance_version_readonly", "token_identity", "registration_token", "runners_list", "runner_labels_linux", "runner_labels_windows", "actions_runs_read", ) REQUIRED_LABELSETS = ( {"id": "linux-x64", "labels": ("self-hosted", "linux", "x64"), "jobs": 10, "item": "runner_labels_linux"}, {"id": "windows-x64", "labels": ("self-hosted", "windows", "x64"), "jobs": 7, "item": "runner_labels_windows"}, ) EXIT_OK = 0 EXIT_FAILED = 1 EXIT_BLOCKED = 2 EXIT_UNREACHABLE = 3 STATUS_VERIFIED = "verified" STATUS_BLOCKED_NO_TOKEN = "blocked_no_token" STATUS_BLOCKED_TOKEN_INVALID = "blocked_token_invalid" STATUS_BLOCKED_NO_ADMIN = "blocked_no_admin" STATUS_BLOCKED_LABELS = "blocked_runner_labels" STATUS_BLOCKED_PROBE = "blocked_probe_missing" STATUS_UNREACHABLE = "instance_unreachable" STATUS_FAILED = "verify_failed" STATUS_USAGE = "usage_error" # runner_access_check 里只有拿到 admin 权限后才可能到达的状态;replay 时据此 # 推断“管理员 API 面已通”。 PROBE_ADMIN_PROVEN = ("runner_ready", "token_available_runner_offline", "blocked_runner_labels") class AdminVerifyUsageError(Exception): """参数/输入契约错误(exit 2)。""" def _policy(): return { "schema": POLICY_SCHEMA, "version": POLICY_VERSION, "wave": WAVE, "tool": TOOL, "report_schema": SCHEMA, "checklist_schema": CHECKLIST_SCHEMA, "modes": ["live", "replay"], "read_only": True, "token_envs": list(TOKEN_ENVS), "base_url_default": DEFAULT_BASE_URL, "repo_default": DEFAULT_REPO, "statuses": [ STATUS_VERIFIED, STATUS_BLOCKED_NO_TOKEN, STATUS_BLOCKED_TOKEN_INVALID, STATUS_BLOCKED_NO_ADMIN, STATUS_BLOCKED_LABELS, STATUS_BLOCKED_PROBE, STATUS_UNREACHABLE, STATUS_FAILED, STATUS_USAGE, ], "exit_codes": { "0": "verified", "1": "verify_failed", "2": "blocked_or_usage_error", "3": "instance_unreachable", }, "admin_verification_script": { "emit_flag": "--emit-verify-script", "read_only": True, "http_methods": ["GET"], "real_ci_runs": 0, "item_ids": list(VERIFY_SCRIPT_ITEM_IDS), "note": ("生成的是管理员可执行验证脚本:只发 GET、不写仓库/" "不注册 runner;token 从环境变量读取,不落盘;" "脚本通过不等于真实 CI 已运行"), }, "policy_fingerprint": _fingerprint(), } def _fingerprint(): blob = json.dumps({ "schema": POLICY_SCHEMA, "version": POLICY_VERSION, "wave": WAVE, "statuses": [ STATUS_VERIFIED, STATUS_BLOCKED_NO_TOKEN, STATUS_BLOCKED_TOKEN_INVALID, STATUS_BLOCKED_NO_ADMIN, STATUS_BLOCKED_LABELS, STATUS_BLOCKED_PROBE, STATUS_UNREACHABLE, STATUS_FAILED, STATUS_USAGE, ], "exit_codes": {"0": "verified", "1": "verify_failed", "2": "blocked_or_usage_error", "3": "instance_unreachable"}, "checklist_schema": CHECKLIST_SCHEMA, }, ensure_ascii=False, sort_keys=True, separators=(",", ":")) return hashlib.sha256(blob.encode("utf-8")).hexdigest() def _iso_now(): return datetime.datetime.now().astimezone().isoformat(timespec="seconds") def _read_json(path): try: with open(path, "r", encoding="utf-8") as fh: return json.load(fh), None except OSError as exc: return None, "无法读取 %s:%s" % (path, exc) except ValueError as exc: return None, "%s 不是合法 JSON:%s" % (path, exc) def _sha256_file(path): try: digest = hashlib.sha256() with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(65536), b""): digest.update(chunk) return digest.hexdigest() except OSError: return None def _token_from_env(environ): for name in TOKEN_ENVS: value = environ.get(name) if value and str(value).strip(): return name, str(value).strip() return None, None def _curl(command_url, auth=None): """给管理员的可复制命令模板;token 只以环境变量占位出现。""" if auth: return ("curl -sS -o /dev/null -w '%%{http_code}' " "-H \"Authorization: token %s\" %s" % (TOKEN_PLACEHOLDER, command_url)) return "curl -sS -o /dev/null -w '%%{http_code}' %s" % command_url def _admin_verification_script(base, repo): """生成管理员可直接执行的 read-only 验证脚本(W168)。 只包含 GET 请求;写操作(注册 runner / 触发 workflow_dispatch)只以 echo 提示形式出现,脚本本身绝不执行;token 只从环境变量读取。 """ return """#!/usr/bin/env bash # {marker} # {no_write} # {real_ci} # usage: VDE_GITEA_TOKEN= bash runner_admin_verify_steps.sh # 可选: VDE_GITEA_BASE_URL / VDE_GITEA_REPO 覆盖默认实例与仓库 # 说明:本脚本只做 GET 只读探测;不写仓库、不注册 runner、不触发 CI。 set -u BASE="${{VDE_GITEA_BASE_URL:-{base}}}" REPO="${{VDE_GITEA_REPO:-{repo}}}" TOKEN="${{VDE_GITEA_TOKEN:-}}" fail=0 blocked=0 http_status() {{ # $1=url $2=1 表示带 token;只用 -o /dev/null,绝不把响应体/ token 回显 if [ "$2" = "1" ]; then curl -sS -o /dev/null -w '%{{http_code}}' -H "Authorization: token $TOKEN" "$1" else curl -sS -o /dev/null -w '%{{http_code}}' "$1" fi }} check_status() {{ # $1=item_id $2=url $3=auth(0/1) $4=expect name=$1 url=$2 auth=$3 expect=$4 code=$(http_status "$url" "$auth" || echo "000") if [ "$code" = "$expect" ]; then echo "PASS $name http=$code" elif [ "$code" = "000" ]; then echo "BLOCKED $name instance_unreachable http=000" blocked=1 else echo "FAIL $name http=$code expect=$expect" fail=1 fi }} if [ -z "$TOKEN" ]; then # 无 token:只验证实例可达,其余项按 blocked_no_token 处理 check_status instance_version_readonly "$BASE/api/v1/version" 0 200 echo "BLOCKED blocked_no_token token_identity 与后续 6 项需要 VDE_GITEA_TOKEN" echo "runner_admin_verify_steps: status=blocked_no_token" exit 2 fi check_status instance_version_readonly "$BASE/api/v1/version" 0 200 check_status token_identity "$BASE/api/v1/user" 1 200 check_status registration_token "$BASE/api/v1/admin/runners/registration-token" 1 200 check_status runners_list "$BASE/api/v1/admin/runners?limit=50" 1 200 check_status actions_runs_read "$BASE/api/v1/repos/$REPO/actions/runs?limit=1" 1 200 # 标签覆盖:从 runner 列表读取 labels(只读 GET,不打印 token) runners_json=$(curl -sS -H "Authorization: token $TOKEN" "$BASE/api/v1/admin/runners?limit=50" || echo '{{}}') for labels in "self-hosted,linux,x64" "self-hosted,windows,x64"; do case "$labels" in *windows*) item=runner_labels_windows ;; *) item=runner_labels_linux ;; esac ok=1 echo "$runners_json" | grep -q '"self-hosted"' || ok=0 case "$labels" in *windows*) echo "$runners_json" | grep -q '"windows"' || ok=0 ;; *) echo "$runners_json" | grep -q '"linux"' || ok=0 ;; esac echo "$runners_json" | grep -q '"x64"' || ok=0 if [ "$ok" = "1" ]; then echo "PASS $item labels=$labels (token 级近似;权威判定见 runner_admin_verify label_coverage)" else echo "FAIL $item labels=$labels (runner 列表未覆盖该标签组合)" fail=1 fi done echo "提示:注册 runner 属于管理员写操作,本脚本不执行,示例:" echo " act_runner register --no-interactive --instance $BASE --token --labels self-hosted,linux,x64" if [ "$fail" = "1" ]; then echo "runner_admin_verify_steps: status=verify_failed" exit 1 fi if [ "$blocked" = "1" ]; then echo "runner_admin_verify_steps: status=instance_unreachable" exit 3 fi echo "runner_admin_verify_steps: status=verified 7/7 (仍需真实 workflow_dispatch run)" exit 0 """.format(marker=VERIFY_SCRIPT_MARKER, no_write=VERIFY_SCRIPT_NO_WRITE_MARKER, real_ci=VERIFY_SCRIPT_REAL_CI_MARKER, base=base, repo=repo) def _write_script(path, text): parent = os.path.dirname(os.path.abspath(path)) if parent: os.makedirs(parent, exist_ok=True) with open(path, "w", encoding="utf-8", newline="\n") as fh: fh.write(text) def _checklist(base, repo): """7 项最小管理员清单(与 runner_access_check W144 清单同源同 id)。""" return [ { "id": "instance_version_readonly", "need": "确认 Gitea 实例可达(只读探测)", "api": "GET %s/api/v1/version" % base, "url": "%s/api/v1/version" % base, "auth": False, "scope": "public(无需 token)", "labels": [], "verify": "HTTP 200 且返回 version;本工具 instance 检查 PASS", "command_template": _curl("%s/api/v1/version" % base), "expected": "HTTP 200;JSON 含 version 字段", "evidence": "http_status 与 observed.version", }, { "id": "token_identity", "need": "确认 token 属于哪个账号(不据此判管理员)", "api": "GET %s/api/v1/user" % base, "url": "%s/api/v1/user" % base, "auth": True, "scope": "read:user", "labels": [], "verify": "HTTP 200 且 login 非空;401/403 => blocked_token_invalid", "command_template": _curl("%s/api/v1/user" % base, auth=True), "expected": "HTTP 200;JSON 含 login 字段", "evidence": "http_status 与 observed.login(不含 token 值)", }, { "id": "registration_token", "need": "取一次性 runner registration token", "api": "GET %s/api/v1/admin/runners/registration-token" % base, "url": "%s/api/v1/admin/runners/registration-token" % base, "auth": True, "scope": "write:admin(Site Admin token);仓库级替代 " "GET /api/v1/repos/%s/actions/runners/registration-token " "需 write:repository" % repo, "labels": [], "verify": "HTTP 200 且返回一次性 token(不回显);403/404 => " "blocked_no_admin", "command_template": _curl( "%s/api/v1/admin/runners/registration-token" % base, auth=True), "expected": "HTTP 200;响应含一次性 token(本工具只记录 " "http_status,token 值立即丢弃)", "evidence": "http_status + token_redacted=true", }, { "id": "runners_list", "need": "列出已注册 runner 与在线状态", "api": "GET %s/api/v1/admin/runners?limit=50" % base, "url": "%s/api/v1/admin/runners?limit=50" % base, "auth": True, "scope": "read:admin(仓库级用 GET /api/v1/repos/%s/actions/" "runners)" % repo, "labels": [], "verify": "返回 data[],每项含 status 与 labels;在线数不足或" "标签不覆盖 => blocked_runner_labels", "command_template": _curl( "%s/api/v1/admin/runners?limit=50" % base, auth=True), "expected": "HTTP 200;JSON 含 data[](runner 列表)", "evidence": "http_status + registered_total/online 计数", }, { "id": "runner_labels_linux", "need": "注册 linux x64 self-hosted runner", "api": "act_runner register --no-interactive --instance %s " "--token --labels self-hosted,linux,x64" % base, "url": "%s/api/v1/admin/runners?limit=50" % base, "auth": True, "scope": "write:admin(registration token 一次性)", "labels": list(REQUIRED_LABELSETS[0]["labels"]), "verify": "nightly 10 个 linux job 的 runs-on 全覆盖;" "label_coverage.required[linux-x64].covered=true", "command_template": _curl( "%s/api/v1/admin/runners?limit=50" % base, auth=True), "expected": "runner 列表里存在在线 runner,labels 覆盖 " "self-hosted,linux,x64", "evidence": "label_coverage.required[linux-x64]", }, { "id": "runner_labels_windows", "need": "注册 windows x64 self-hosted runner", "api": "act_runner register --no-interactive --instance %s " "--token --labels self-hosted,windows,x64" % base, "url": "%s/api/v1/admin/runners?limit=50" % base, "auth": True, "scope": "write:admin(registration token 一次性)", "labels": list(REQUIRED_LABELSETS[1]["labels"]), "verify": "nightly 7 个 windows job 的 runs-on 全覆盖;" "label_coverage.required[windows-x64].covered=true", "command_template": _curl( "%s/api/v1/admin/runners?limit=50" % base, auth=True), "expected": "runner 列表里存在在线 runner,labels 覆盖 " "self-hosted,windows,x64", "evidence": "label_coverage.required[windows-x64]", }, { "id": "actions_runs_read", "need": "确认真实项目 CI run 可见(转正证据)", "api": "GET %s/api/v1/repos/%s/actions/runs?limit=1" % (base, repo), "url": "%s/api/v1/repos/%s/actions/runs?limit=1" % (base, repo), "auth": True, "scope": "read:repository", "labels": [], "verify": "HTTP 200 且 total_count>=1;之后按 sop.recheck 触发" "一次真实 workflow_dispatch 才可写“真实 CI 已运行”", "command_template": _curl( "%s/api/v1/repos/%s/actions/runs?limit=1" % (base, repo), auth=True), "expected": "HTTP 200;JSON 含 total_count(可为 0,0 表示历史" "上无 run,仍需 workflow_dispatch 复检)", "evidence": "http_status + observed.total_count", }, ] def _item_status(status, observed, http_status=None, check_id="", extra=None): item = {"status": status, "observed": observed} if http_status is not None: item["http_status"] = http_status if check_id: item["check"] = check_id if extra: item.update(extra) return item # --------------------------------------------------------------------------- # live 模式(真实只读 HTTP) # --------------------------------------------------------------------------- def _live_probe(base, repo, timeout, transport, environ, warnings): token_env, token = _token_from_env(environ) results = {} http_notes = {} def call(url, auth=True): headers = {} if auth and token: headers["Authorization"] = "token " + token try: status, body = transport(url, headers, timeout) except Exception as exc: # noqa: BLE001 - 网络层异常统一降级 return None, None, str(exc) payload = None try: payload = json.loads(body.decode("utf-8")) if body else {} except (ValueError, AttributeError, UnicodeDecodeError): payload = None return status, payload, None version_url = "%s/api/v1/version" % base status, payload, err = call(version_url, auth=False) if status is None: warnings.append("实例版本探测失败:%s" % err) results["instance_version_readonly"] = _item_status( STATUS_UNREACHABLE, "GET /api/v1/version 失败:%s" % err) overall = (STATUS_UNREACHABLE, EXIT_UNREACHABLE) payload = _payload(base, repo, token_env, results, None, overall, warnings, live=True, http_notes=http_notes) return payload, payload["exit_code"] version = None if isinstance(payload, dict): version = payload.get("version") if status == 200: results["instance_version_readonly"] = _item_status( STATUS_VERIFIED, "version=%s" % (version or "unknown"), http_status=status, check_id="instance_reachable") else: results["instance_version_readonly"] = _item_status( STATUS_FAILED, "GET /api/v1/version => HTTP %s" % status, http_status=status) http_notes["version"] = {"http_status": status, "version": version} if not token: for item in _checklist(base, repo)[1:]: results[item["id"]] = _item_status( STATUS_BLOCKED_NO_TOKEN, "环境未提供 %s(%s);无权复检该项" % ( "/".join(TOKEN_ENVS), TOKEN_PLACEHOLDER), check_id="token_missing") overall = (STATUS_BLOCKED_NO_TOKEN, EXIT_BLOCKED) payload = _payload(base, repo, token_env, results, version, overall, warnings, live=True, http_notes=http_notes) return payload, payload["exit_code"] # token_identity status, payload, err = call("%s/api/v1/user" % base) if status == 200 and isinstance(payload, dict) and payload.get("login"): results["token_identity"] = _item_status( STATUS_VERIFIED, "login=%s" % payload.get("login"), http_status=status, check_id="admin_token_valid") http_notes["user"] = {"http_status": status, "login": payload.get("login")} elif status in (401, 403): results["token_identity"] = _item_status( STATUS_BLOCKED_TOKEN_INVALID, "GET /api/v1/user => HTTP %s" % status, http_status=status) # token 已确认无效时不再继续调用管理员 API(避免 401 噪音/误判)。 for item in _checklist(base, repo)[2:]: results[item["id"]] = _item_status( STATUS_BLOCKED_TOKEN_INVALID, "token 校验失败,管理员 API 面未验证") overall = (STATUS_BLOCKED_TOKEN_INVALID, EXIT_BLOCKED) payload = _payload(base, repo, token_env, results, version, overall, warnings, live=True, http_notes=http_notes) return payload, payload["exit_code"] else: results["token_identity"] = _item_status( STATUS_FAILED, "GET /api/v1/user => HTTP %s" % status, http_status=status) # registration_token(只取状态,不落 token 值) status, payload, err = call( "%s/api/v1/admin/runners/registration-token" % base) if status == 200: results["registration_token"] = _item_status( STATUS_VERIFIED, "HTTP 200 一次性 token 已获取并立即丢弃(token_redacted=true)", http_status=status, extra={"token_redacted": True}) http_notes["registration_token"] = {"http_status": status, "token_redacted": True} elif status in (401, 403, 404): results["registration_token"] = _item_status( STATUS_BLOCKED_NO_ADMIN, "GET registration-token => HTTP %s" % status, http_status=status) else: results["registration_token"] = _item_status( STATUS_FAILED, "GET registration-token => HTTP %s" % status, http_status=status) # runners_list + 标签覆盖 status, payload, err = call("%s/api/v1/admin/runners?limit=50" % base) runners = [] if status == 200 and isinstance(payload, dict): data = payload.get("data") if isinstance(data, list): runners = data results["runners_list"] = _item_status( STATUS_VERIFIED, "返回 %d 个 runner(data[])" % len(runners), http_status=status, check_id="registered_runners") http_notes["runners"] = {"http_status": status, "count": len(runners)} elif status in (401, 403, 404): results["runners_list"] = _item_status( STATUS_BLOCKED_NO_ADMIN, "GET admin/runners => HTTP %s" % status, http_status=status) else: results["runners_list"] = _item_status( STATUS_FAILED, "GET admin/runners => HTTP %s" % status, http_status=status) label_coverage = _label_coverage(runners) for row in REQUIRED_LABELSETS: item_id = row["item"] if "runners_list" in results and results[ "runners_list"]["status"] != STATUS_VERIFIED: results[item_id] = _item_status( results["runners_list"]["status"], "runner 列表不可读,标签覆盖无从判定") continue covered = label_coverage["required"][row["id"]]["covered"] if covered: results[item_id] = _item_status( STATUS_VERIFIED, "存在在线 runner 覆盖标签集 %s" % "+".join(row["labels"]), check_id="runner_label_coverage") else: results[item_id] = _item_status( STATUS_BLOCKED_LABELS, "未发现在线 runner 覆盖标签集 %s" % "+".join(row["labels"]), check_id="runner_label_coverage") # actions_runs_read status, payload, err = call( "%s/api/v1/repos/%s/actions/runs?limit=1" % (base, repo)) if status == 200 and isinstance(payload, dict): total = payload.get("total_count") results["actions_runs_read"] = _item_status( STATUS_VERIFIED, "Actions run 可见(total_count=%s)" % total, http_status=status, check_id="actions_runs_read") http_notes["actions_runs"] = {"http_status": status, "total_count": total} elif status in (401, 403, 404): results["actions_runs_read"] = _item_status( STATUS_BLOCKED_NO_ADMIN, "GET actions/runs => HTTP %s" % status, http_status=status) else: results["actions_runs_read"] = _item_status( STATUS_FAILED, "GET actions/runs => HTTP %s" % status, http_status=status) overall = _overall(results) payload = _payload(base, repo, token_env, results, version, overall, warnings, live=True, http_notes=http_notes, label_coverage=label_coverage) return payload, payload["exit_code"] def _label_coverage(runners): required = {} for row in REQUIRED_LABELSETS: need = set(row["labels"]) matched = 0 for runner in runners if isinstance(runners, list) else []: if not isinstance(runner, dict): continue labels = runner.get("labels") names = set() if isinstance(labels, list): for label in labels: if isinstance(label, dict): names.add(str(label.get("name") or "").lower()) else: names.add(str(label).lower()) online = str(runner.get("status") or "").lower() if need.issubset(names) and online not in ("offline", "inactive"): matched += 1 required[row["id"]] = { "labels": list(row["labels"]), "jobs": row["jobs"], "matched_online": matched, "covered": matched > 0, } return { "required": required, "all_covered": all(row["covered"] for row in required.values()) if required else False, "observed": ("%d/%d 标签集覆盖" % (sum(1 for row in required.values() if row["covered"]), len(required))), } # --------------------------------------------------------------------------- # replay 模式(回放 runner_access_check 探测证据) # --------------------------------------------------------------------------- def _replay_probe(probe_path, warnings): if not probe_path or not os.path.exists(probe_path): warnings.append("探测证据不存在:%s" % probe_path) return None, None data, err = _read_json(probe_path) if err: warnings.append("%s(探测证据,无法回放)" % err) return None, None if not isinstance(data, dict): warnings.append("%s 顶层不是 JSON object" % probe_path) return None, None status = str(data.get("status") or "") version = data.get("version") token_env = data.get("token_env") results = {} if not status: warnings.append("%s 缺少 status 字段(不是 runner_access_check 证据?)" % probe_path) status = "" admin_proven = status in PROBE_ADMIN_PROVEN if status in ("instance_unreachable", ""): for item in _checklist(DEFAULT_BASE_URL, DEFAULT_REPO): if item["id"] == "instance_version_readonly": continue results[item["id"]] = _item_status( STATUS_UNREACHABLE, "探测证据 status=%r,实例不可达" % status) overall = (STATUS_UNREACHABLE, EXIT_UNREACHABLE) return results, overall if version: results["instance_version_readonly"] = _item_status( STATUS_VERIFIED, "探测证据记录 version=%s" % version, check_id="instance_reachable") else: results["instance_version_readonly"] = _item_status( STATUS_BLOCKED_NO_TOKEN, "探测证据未记录 version(status=%r)" % status) blocked = None if status == "blocked_no_token": blocked = STATUS_BLOCKED_NO_TOKEN elif status == "blocked_token_invalid": blocked = STATUS_BLOCKED_TOKEN_INVALID if blocked: results["token_identity"] = _item_status( blocked, "探测证据 status=%s" % status) for item in _checklist(DEFAULT_BASE_URL, DEFAULT_REPO)[2:]: results[item["id"]] = _item_status( blocked, "探测证据 status=%s,无管理员权限证据" % status) overall = (blocked, EXIT_BLOCKED) return results, overall if status == "blocked_no_admin": results["token_identity"] = _item_status( STATUS_VERIFIED, "token 有效但非管理员(status=blocked_no_admin)") for item in _checklist(DEFAULT_BASE_URL, DEFAULT_REPO)[2:]: results[item["id"]] = _item_status( STATUS_BLOCKED_NO_ADMIN, "探测证据 status=blocked_no_admin") overall = (STATUS_BLOCKED_NO_ADMIN, EXIT_BLOCKED) return results, overall if admin_proven: results["token_identity"] = _item_status( STATUS_VERIFIED, "探测证据 status=%s(已通过 token 校验)" % status) for item in _checklist(DEFAULT_BASE_URL, DEFAULT_REPO)[2:]: if item["id"].startswith("runner_labels_"): continue results[item["id"]] = _item_status( STATUS_VERIFIED, "探测证据 status=%s(管理员 API 面已通)" % status) label_info = data.get("label_coverage") or {} required = (label_info.get("required") if isinstance(label_info, dict) else None) or [] by_id = {} for row in required: if isinstance(row, dict): by_id[row.get("id")] = row for row in REQUIRED_LABELSETS: state = by_id.get(row["id"]) or {} if state.get("covered"): results[row["item"]] = _item_status( STATUS_VERIFIED, "探测证据 label_coverage 覆盖 %s" % "+".join(row["labels"])) else: results[row["item"]] = _item_status( STATUS_BLOCKED_LABELS, "探测证据 label_coverage 未覆盖 %s" % "+".join(row["labels"])) overall = _overall(results) return results, overall for item in _checklist(DEFAULT_BASE_URL, DEFAULT_REPO)[1:]: results[item["id"]] = _item_status( STATUS_BLOCKED_NO_TOKEN, "探测证据 status=%r 无法判定该项" % status) overall = (STATUS_BLOCKED_NO_TOKEN, EXIT_BLOCKED) return results, overall # --------------------------------------------------------------------------- # 汇总 # --------------------------------------------------------------------------- def _overall(results): statuses = [item.get("status") for item in results.values()] if STATUS_UNREACHABLE in statuses: return (STATUS_UNREACHABLE, EXIT_UNREACHABLE) if STATUS_FAILED in statuses: return (STATUS_FAILED, EXIT_FAILED) if statuses and all(s == STATUS_VERIFIED for s in statuses): return (STATUS_VERIFIED, EXIT_OK) for candidate in (STATUS_BLOCKED_TOKEN_INVALID, STATUS_BLOCKED_NO_TOKEN, STATUS_BLOCKED_NO_ADMIN, STATUS_BLOCKED_LABELS): if candidate in statuses: return (candidate, EXIT_BLOCKED) return (STATUS_FAILED, EXIT_FAILED) def _payload(base, repo, token_env, results, version, overall, warnings, live, http_notes=None, label_coverage=None, probe=None): checklist = _checklist(base, repo) items = [] for entry in checklist: item = dict(entry) item.update(results.get(entry["id"]) or { "status": STATUS_BLOCKED_NO_TOKEN, "observed": "not probed"}) item["verification"] = { "executable": True, "auto": live, "command_template": entry["command_template"], "expected": entry["expected"], "evidence": entry["evidence"], } items.append(item) verified = sum(1 for item in items if item["status"] == STATUS_VERIFIED) status, exit_code = overall return { "schema": SCHEMA, "version": POLICY_VERSION, "wave": WAVE, "tool": TOOL, "generated_at": _payload_now, "mode": "live" if live else "replay", "status": status, "exit_code": exit_code, "base_url": base, "repo": repo, "version_observed": version, "token_env": token_env, "checklist_schema": CHECKLIST_SCHEMA, "items": items, "summary": { "total": len(items), "verified": verified, "blocked": len(items) - verified, }, "label_coverage": label_coverage, "http_notes": http_notes or {}, "warnings": warnings, "provenance": probe or {"mode": "live", "note": "live read-only GET probe"}, "honesty": { "read_only": True, "token_value_redacted": True, "live_network_requests": bool(live), "not_project_ci_green": status != STATUS_VERIFIED, "note": ("本工具只读 GET,不写仓库/不改 runner;token 值不落盘、" "不回显;verified 只代表 7 项管理员权限面在当前探测中" "通过,不等于真实项目 CI 已运行,也不等于覆盖率门禁绿。" "replay 模式的结论属于探测证据生成时刻。"), }, } def render_markdown(payload): lines = [ "# runner 管理员清单可执行验证(W150)", "", "- 生成时间:%s" % payload["generated_at"], "- 模式:`%s`;实例:`%s`;仓库:`%s`" % (payload["mode"], payload["base_url"], payload["repo"]), "- token:%s" % (("env:%s(值已脱敏)" % payload["token_env"]) if payload.get("token_env") else "未提供"), "- **结论:`%s`(exit %d;verified %d/%d 项)**" % (payload["status"], payload["exit_code"], payload["summary"]["verified"], payload["summary"]["total"]), "", "## 逐项可执行验证", "", "| # | 清单项 | 当前 status | 观测 | 可执行验证命令 | 期望 |", "| --- | --- | --- | --- | --- | --- |", ] for idx, item in enumerate(payload["items"], 1): lines.append( "| %d | `%s` | `%s` | %s | `%s` | %s |" % (idx, item["id"], item["status"], str(item.get("observed") or "").replace("|", "\\|"), item["verification"]["command_template"].replace("|", "\\|"), item["verification"]["expected"].replace("|", "\\|"))) if payload.get("label_coverage"): coverage = payload["label_coverage"] lines += ["", "## 标签覆盖(nightly runs-on)", "", "| 标签集 | 需要 job 数 | 在线匹配 | 覆盖 |", "| --- | --- | --- | --- |"] for key, row in (coverage.get("required") or {}).items(): lines.append("| `%s`(%s) | %s | %s | %s |" % ("+".join(row["labels"]), key, row["jobs"], row["matched_online"], "COVERED" if row["covered"] else "MISSING")) if payload.get("warnings"): lines += ["", "## 警告", ""] + ["- %s" % w for w in payload["warnings"]] lines += ["", "## 诚实边界", "", "- %s" % payload["honesty"]["note"], "- token 值不写入本报告;可执行验证命令列用 " "`%s` 占位。" % TOKEN_PLACEHOLDER, ""] return "\n".join(lines) _payload_now = None def _write_text(path, text): parent = os.path.dirname(os.path.abspath(path)) if parent: os.makedirs(parent, exist_ok=True) with open(path, "w", encoding="utf-8") as fh: fh.write(text) # --------------------------------------------------------------------------- # 评估入口 # --------------------------------------------------------------------------- def evaluate(opts, environ=None, transport=None): global _payload_now environ = dict(os.environ if environ is None else environ) if opts.now: _payload_now = opts.now else: _payload_now = _iso_now() if opts.live and opts.probe: raise AdminVerifyUsageError("--live 与 --probe 互斥") if not opts.live and not opts.probe: raise AdminVerifyUsageError( "必须指定 --live(真实只读验证)或 --probe PATH(回放探测证据)") base = (opts.base_url or DEFAULT_BASE_URL).rstrip("/") repo = opts.repo or DEFAULT_REPO warnings = [] if opts.live: import urllib.request # noqa: PLC0415 - 仅 live 模式需要 def _default_transport(url, headers, timeout): request = urllib.request.Request(url, headers=headers) try: with urllib.request.urlopen(request, timeout=timeout) as resp: return resp.getcode(), resp.read() except urllib.error.HTTPError as exc: return exc.code, exc.read() or b"" probe = {"mode": "live", "note": "live read-only GET probe(无 cache)"} return _live_probe(base, repo, opts.timeout, transport or _default_transport, environ, warnings) probe_meta = {"mode": "replay", "path": opts.probe, "sha256": _sha256_file(opts.probe)} results, overall = _replay_probe(opts.probe, warnings) if results is None: overall = (STATUS_BLOCKED_PROBE, EXIT_BLOCKED) results = {} payload = _payload(base, repo, None, results, None, overall, warnings, live=False, probe=probe_meta) return payload, payload["exit_code"] # --------------------------------------------------------------------------- # 自检 # --------------------------------------------------------------------------- def _stub(routes): def transport(url, headers, timeout): for suffix, (status, body) in routes.items(): if url.endswith(suffix): return status, json.dumps(body).encode("utf-8") raise ConnectionError("%s: refused" % url) return transport def _ns(**kwargs): base = { "live": False, "probe": None, "base_url": "https://ci.example.test", "repo": "hm/REPO", "timeout": 5.0, "now": "2026-01-01T00:00:00+00:00", "json_out": None, "md_out": None, "emit_verify_script": None, } base.update(kwargs) return argparse.Namespace(**base) def self_test(): checks = [] def add(name, passed, detail=""): checks.append((name, bool(passed), str(detail))) policy = _policy() add("policy-contract", policy["schema"] == POLICY_SCHEMA and policy["version"] == POLICY_VERSION and policy["wave"] == WAVE and policy["checklist_schema"] == CHECKLIST_SCHEMA and policy["read_only"] is True and policy["token_envs"] == list(TOKEN_ENVS) and policy["policy_fingerprint"], "schema/version/wave/checklist/read_only/env") checklist = _checklist("https://ci.example.test", "hm/REPO") ids = [item["id"] for item in checklist] add("checklist-7-items-executable", ids == ["instance_version_readonly", "token_identity", "registration_token", "runners_list", "runner_labels_linux", "runner_labels_windows", "actions_runs_read"] and all("command_template" in item and item["command_template"] and item.get("expected") and item.get("evidence") for item in checklist) and all(TOKEN_PLACEHOLDER in item["command_template"] for item in checklist if item["auth"]), "items=%d" % len(checklist)) # live 无 token:instance verified,其余 blocked_no_token,exit 2 ok_routes = {"/api/v1/version": (200, {"version": "1.27.1"})} payload, code = evaluate( _ns(live=True), environ={}, transport=_stub(ok_routes)) by_id = {item["id"]: item["status"] for item in payload["items"]} add("live-no-token-blocked-exit2", payload["status"] == STATUS_BLOCKED_NO_TOKEN and code == EXIT_BLOCKED and by_id["instance_version_readonly"] == STATUS_VERIFIED and by_id["token_identity"] == STATUS_BLOCKED_NO_TOKEN and payload["summary"]["verified"] == 1, "%s/%s" % (payload["status"], code)) # live token 无效:blocked_token_invalid exit 2 routes = dict(ok_routes) routes["/api/v1/user"] = (401, {"message": "unauthorized"}) payload, code = evaluate( _ns(live=True), environ={"VDE_GITEA_TOKEN": "dummy"}, transport=_stub(routes)) by_id = {item["id"]: item["status"] for item in payload["items"]} add("live-token-invalid-blocked", payload["status"] == STATUS_BLOCKED_TOKEN_INVALID and code == EXIT_BLOCKED and by_id["token_identity"] == STATUS_BLOCKED_TOKEN_INVALID, "%s/%s" % (payload["status"], code)) # live 非管理员:version 200 + user 200 + admin 端点 403 routes = dict(ok_routes) routes["/api/v1/user"] = (200, {"login": "dev"}) routes["/api/v1/admin/runners/registration-token"] = ( 403, {"message": "forbidden"}) routes["/api/v1/admin/runners?limit=50"] = (403, {"message": "forbidden"}) routes["/api/v1/repos/hm/REPO/actions/runs?limit=1"] = ( 403, {"message": "forbidden"}) payload, code = evaluate( _ns(live=True), environ={"VDE_GITEA_TOKEN": "dummy"}, transport=_stub(routes)) by_id = {item["id"]: item["status"] for item in payload["items"]} add("live-nonadmin-blocked-no-admin", payload["status"] == STATUS_BLOCKED_NO_ADMIN and code == EXIT_BLOCKED and by_id["token_identity"] == STATUS_VERIFIED and by_id["registration_token"] == STATUS_BLOCKED_NO_ADMIN and by_id["runners_list"] == STATUS_BLOCKED_NO_ADMIN, "%s/%s" % (payload["status"], code)) # live 全绿:7 项 verified exit 0 routes = dict(ok_routes) routes["/api/v1/user"] = (200, {"login": "admin"}) routes["/api/v1/admin/runners/registration-token"] = ( 200, {"token": "TOP_SECRET_REG_TOKEN_NEVER_PRINT"}) routes["/api/v1/admin/runners?limit=50"] = (200, {"data": [ {"status": "online", "labels": [{"name": "self-hosted"}, {"name": "linux"}, {"name": "x64"}]}, {"status": "online", "labels": [{"name": "self-hosted"}, {"name": "windows"}, {"name": "x64"}]}, ]}) routes["/api/v1/repos/hm/REPO/actions/runs?limit=1"] = ( 200, {"total_count": 42}) payload, code = evaluate( _ns(live=True), environ={"VDE_GITEA_TOKEN": "dummy"}, transport=_stub(routes)) by_id = {item["id"]: item["status"] for item in payload["items"]} add("live-all-verified-exit0", payload["status"] == STATUS_VERIFIED and code == EXIT_OK and payload["summary"]["verified"] == 7 and all(s == STATUS_VERIFIED for s in by_id.values()) and payload["label_coverage"]["all_covered"] is True, "%s verified=%d" % (payload["status"], payload["summary"]["verified"])) # token 值不得出现在 payload / markdown blob = json.dumps(payload, ensure_ascii=False) + render_markdown(payload) add("registration-token-never-echoed", "TOP_SECRET_REG_TOKEN_NEVER_PRINT" not in blob and payload["items"][2].get("token_redacted") is True, "token_redacted=%r" % payload["items"][2].get("token_redacted")) # live 仅 linux runner:windows 标签 blocked_runner_labels exit 2 routes = dict(routes) routes["/api/v1/admin/runners?limit=50"] = (200, {"data": [ {"status": "online", "labels": [{"name": "self-hosted"}, {"name": "linux"}, {"name": "x64"}]}, ]}) payload, code = evaluate( _ns(live=True), environ={"VDE_GITEA_TOKEN": "dummy"}, transport=_stub(routes)) by_id = {item["id"]: item["status"] for item in payload["items"]} add("live-missing-labels-blocked", payload["status"] == STATUS_BLOCKED_LABELS and code == EXIT_BLOCKED and by_id["runner_labels_linux"] == STATUS_VERIFIED and by_id["runner_labels_windows"] == STATUS_BLOCKED_LABELS, "%s/%s" % (payload["status"], code)) # 不可达:exit 3 def refuse(url, headers, timeout): raise ConnectionError("refused") payload, code = evaluate(_ns(live=True), environ={}, transport=refuse) add("live-unreachable-exit3", payload["status"] == STATUS_UNREACHABLE and code == EXIT_UNREACHABLE, "%s/%s" % (payload["status"], code)) # replay probe:blocked_no_token => exit 2,instance verified tmp = _mk_tmp() try: probe_path = os.path.join(tmp, "probe-blocked.json") _write_json(probe_path, { "schema": "vde-ci-runner-access-check/1", "status": "blocked_no_token", "exit_code": 2, "token_env": None, "version": "1.27.1", "checks": [], "label_coverage": {"required": []}, }) payload, code = evaluate(_ns(probe=probe_path), environ={}) by_id = {item["id"]: item["status"] for item in payload["items"]} add("replay-blocked-no-token-exit2", payload["mode"] == "replay" and payload["status"] == STATUS_BLOCKED_NO_TOKEN and code == EXIT_BLOCKED and by_id["instance_version_readonly"] == STATUS_VERIFIED and by_id["token_identity"] == STATUS_BLOCKED_NO_TOKEN, "%s/%s" % (payload["status"], code)) # replay probe:runner_ready => verified exit 0 probe_ready = os.path.join(tmp, "probe-ready.json") _write_json(probe_ready, { "schema": "vde-ci-runner-access-check/1", "status": "runner_ready", "version": "1.27.1", "token_env": "VDE_GITEA_TOKEN", "label_coverage": {"required": [ {"id": "linux-x64", "covered": True}, {"id": "windows-x64", "covered": True}, ]}, }) payload, code = evaluate(_ns(probe=probe_ready), environ={}) add("replay-ready-verified-exit0", payload["status"] == STATUS_VERIFIED and code == EXIT_OK and payload["summary"]["verified"] == 7, "%s verified=%d" % (payload["status"], payload["summary"]["verified"])) # replay 证据缺失:诚实 blocked_probe_missing exit 2(不编造结论) payload, code = evaluate(_ns(probe=os.path.join(tmp, "nope.json")), environ={}) add("replay-missing-probe-blocked", payload["status"] == STATUS_BLOCKED_PROBE and code == EXIT_BLOCKED and any("不存在" in w for w in payload["warnings"]), "%s/%s" % (payload["status"], code)) finally: import shutil shutil.rmtree(tmp, ignore_errors=True) # usage:既无 --live 也无 --probe => exit 2 / usage_error try: evaluate(_ns(), environ={}) usage_ok = False usage_detail = "no error raised" except AdminVerifyUsageError as exc: usage_ok = True usage_detail = str(exc) add("usage-error-exit2", usage_ok, usage_detail) # 确定性:固定 --now 两次评估 JSON 全等 probe_path = os.path.join(tempfile_dir(), "probe-det.json") _write_json(probe_path, { "schema": "vde-ci-runner-access-check/1", "status": "blocked_no_token", "version": "1.27.1", "token_env": None, "label_coverage": {"required": []}, }) p1, _ = evaluate(_ns(probe=probe_path), environ={}) p2, _ = evaluate(_ns(probe=probe_path), environ={}) add("deterministic-evaluation", json.dumps(p1, sort_keys=True) == json.dumps(p2, sort_keys=True), "固定 --now 下 payload 全等") # markdown 含诚实边界与逐项命令 md = render_markdown(p1) add("markdown-honesty", "诚实边界" in md and "command_template" not in md and TOKEN_PLACEHOLDER in md and "真实项目 CI" in md, "markdown=%d chars" % len(md)) # ---- W168:可执行管理员验证脚本 ---- script = _admin_verification_script("https://ci.example.test", "hm/REPO") add("verify-script-structure", script.startswith("#!/usr/bin/env bash") and VERIFY_SCRIPT_MARKER in script and VERIFY_SCRIPT_NO_WRITE_MARKER in script and VERIFY_SCRIPT_REAL_CI_MARKER in script and all(url in script for url in ( "/api/v1/version", "/api/v1/user", "/api/v1/admin/runners/registration-token", "/api/v1/admin/runners?limit=50", "/api/v1/repos/$REPO/actions/runs?limit=1")) and all(item in script for item in ( "runner_labels_linux", "runner_labels_windows")) and "VDE_GITEA_TOKEN" in script, "script=%d chars" % len(script)) add("verify-script-read-only", "-X POST" not in script and "--request POST" not in script and "-X PUT" not in script and "-X DELETE" not in script and "-f workflow_dispatch" not in script and "--event workflow_dispatch" not in script and 'http_status "$url" "$auth"' in script and "curl -sS -o /dev/null" in script, "只发 GET,写操作仅 echo 提示") add("verify-script-blocked-and-success-paths", "status=blocked_no_token" in script and "exit 2" in script and "status=verified 7/7" in script and "exit 0" in script and "status=instance_unreachable" in script and "exit 3" in script, "blocked/failed/unreachable/verified 四路 exit") emitted = os.path.join(_mk_tmp(), "runner_admin_verify_steps.sh") emit_code = main(["--emit-verify-script", emitted, "--json-out", emitted + ".json"]) emitted_blob = "" if os.path.isfile(emitted): with open(emitted, "r", encoding="utf-8") as fh: emitted_blob = fh.read() meta_ok = False if os.path.isfile(emitted + ".json"): with open(emitted + ".json", "r", encoding="utf-8") as fh: meta = json.load(fh) meta_ok = (meta.get("schema") == "vde-runner-admin-verify-script/1" and meta.get("wave") == "W168" and meta.get("read_only") is True and meta.get("real_ci_runs") == 0 and len(meta.get("script_sha256") or "") == 64) add("verify-script-emit-cli", emit_code == EXIT_OK and VERIFY_SCRIPT_MARKER in emitted_blob and meta_ok, "exit=%s meta=%r" % (emit_code, meta_ok)) import shutil # noqa: PLC0415 - 仅自检用 bash = shutil.which("bash") if bash: import subprocess # noqa: PLC0415 proc = subprocess.run([bash, "-n", emitted], capture_output=True, text=True) syntax_ok = proc.returncode == 0 syntax_detail = (proc.stderr or "").strip()[:160] else: syntax_ok = VERIFY_SCRIPT_MARKER in emitted_blob syntax_detail = "bash 不可用,退化为结构检查" add("verify-script-bash-syntax", syntax_ok, syntax_detail) add("policy-version-wave-w168", POLICY_VERSION == "W168.1" and WAVE == "W168" and policy["admin_verification_script"]["emit_flag"] == "--emit-verify-script" and policy["admin_verification_script"]["read_only"] is True and policy["admin_verification_script"]["real_ci_runs"] == 0 and policy["admin_verification_script"]["item_ids"] == list(VERIFY_SCRIPT_ITEM_IDS), "%s/%s" % (POLICY_VERSION, WAVE)) for directory in _SELFTEST_DIRS: import shutil shutil.rmtree(directory, ignore_errors=True) return _report_checks(checks) _SELFTEST_DIRS = [] def tempfile_dir(): import tempfile directory = tempfile.mkdtemp(prefix="vde-runner-admin-selftest-") _SELFTEST_DIRS.append(directory) return directory def _mk_tmp(): return tempfile_dir() def _write_json(path, payload): parent = os.path.dirname(os.path.abspath(path)) if parent: os.makedirs(parent, exist_ok=True) with open(path, "w", encoding="utf-8") as fh: json.dump(payload, fh, ensure_ascii=False, indent=2) fh.write("\n") def _report_checks(checks): ok_all = True for name, passed, detail in checks: print("%s %s%s" % ("PASS" if passed else "FAIL", name, "" if passed or not detail else " :: " + detail)) if not passed: ok_all = False print("runner_admin_verify self-test: %s (%d checks)" % ("PASS" if ok_all else "FAIL", len(checks))) if ok_all: print("capabilities: checklist_7_items live_read_only " "replay_probe status_exit_codes token_redacted " "blocked_no_token_exit2 admin_verification_script " "read_only_get_script") return 0 if ok_all else 1 # --------------------------------------------------------------------------- # main # --------------------------------------------------------------------------- def _build_parser(): ap = argparse.ArgumentParser( description="runner 管理员清单可执行验证(只读;live 或 replay)") ap.add_argument("--live", action="store_true", help="真实只读 HTTP 验证(无 token 时诚实 blocked_no_token)") ap.add_argument("--probe", default=None, help="回放 runner_access_check.py 探测证据 JSON") ap.add_argument("--base-url", default=None, help="Gitea 实例(默认 %s)" % DEFAULT_BASE_URL) ap.add_argument("--repo", default=None, help="仓库 owner/name(默认 %s)" % DEFAULT_REPO) ap.add_argument("--timeout", type=float, default=10.0, help="单次 HTTP 超时秒数(默认 10)") ap.add_argument("--now", default=None, help="固定 generated_at(自检用)") ap.add_argument("--json-out", default=None, help="JSON 输出路径") ap.add_argument("--md-out", default=None, help="markdown 输出路径") ap.add_argument("--emit-verify-script", default=None, metavar="PATH", help="生成管理员可执行的 read-only 验证脚本(W168)") ap.add_argument("--print-policy", action="store_true", help="输出机器可读策略契约") ap.add_argument("--self-test", action="store_true", help="离线契约自检") return ap def main(argv=None): args = _build_parser().parse_args(argv) if args.self_test: return self_test() if args.emit_verify_script: base = (args.base_url or DEFAULT_BASE_URL).rstrip("/") repo = args.repo or DEFAULT_REPO script = _admin_verification_script(base, repo) _write_script(args.emit_verify_script, script) digest = hashlib.sha256(script.encode("utf-8")).hexdigest() meta = { "schema": "vde-runner-admin-verify-script/1", "version": POLICY_VERSION, "wave": WAVE, "tool": TOOL, "script_path": args.emit_verify_script, "script_sha256": digest, "base_url": base, "repo": repo, "read_only": True, "http_methods": ["GET"], "real_ci_runs": 0, "item_ids": list(VERIFY_SCRIPT_ITEM_IDS), "note": "可执行验证脚本;脚本通过 ≠ 真实 CI 已运行", } if args.json_out: _write_text(args.json_out, json.dumps(meta, ensure_ascii=False, indent=2, sort_keys=True) + "\n") print("runner_admin_verify: verify script -> %s (sha256=%s)" % (args.emit_verify_script, digest)) print(json.dumps(meta, ensure_ascii=False, sort_keys=True)) return EXIT_OK if args.print_policy: print(json.dumps(_policy(), ensure_ascii=False, indent=2, sort_keys=True)) return EXIT_OK try: payload, code = evaluate(args) except AdminVerifyUsageError as exc: print("runner_admin_verify: usage error: %s" % exc, file=sys.stderr) return EXIT_BLOCKED if args.json_out: _write_text(args.json_out, json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n") md = render_markdown(payload) if args.md_out: _write_text(args.md_out, md + "\n") if not args.md_out and not args.json_out: print(md) print("runner_admin_verify: status=%s exit=%d" % (payload["status"], code)) return code if __name__ == "__main__": sys.exit(main())