Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4ccb77003 |
No files matched your search
+1
-1
@@ -76,7 +76,7 @@ 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,不得自动合入或提升权限。外部不可信 PR、未批准 gitlink 或脚本不得在拥有跨仓库写权限/发版密钥的 runner 中运行;区分只读 checkout/test token、受限 issue/PR token、受保护发布权限。日志不得输出凭证、完整 Analysis 或生产 API key。
|
||||||
|
|
||||||
## 发行与回滚
|
## 发行与回滚
|
||||||
|
|
||||||
|
|||||||
Executable
+317
@@ -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
@@ -23,6 +23,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tomllib
|
import tomllib
|
||||||
@@ -94,9 +95,10 @@ def submodule_urls(repo: Path, revision: str) -> dict[str, str]:
|
|||||||
if not record:
|
if not record:
|
||||||
continue
|
continue
|
||||||
key, _, value = record.decode(errors="replace").partition("\n")
|
key, _, value = record.decode(errors="replace").partition("\n")
|
||||||
parts = key.split(".")
|
match = re.fullmatch(r"submodule\.(.+)\.(path|url)", key)
|
||||||
if len(parts) == 4 and parts[0] == "submodule" and parts[3] in ("path", "url"):
|
if match:
|
||||||
pending.setdefault(parts[1], {})[parts[3]] = value
|
name, field = match.groups()
|
||||||
|
pending.setdefault(name, {})[field] = value
|
||||||
for fields in pending.values():
|
for fields in pending.values():
|
||||||
if "path" in fields and "url" in fields:
|
if "path" in fields and "url" in fields:
|
||||||
urls[fields["path"]] = fields["url"]
|
urls[fields["path"]] = fields["url"]
|
||||||
@@ -249,6 +251,79 @@ def affected_set(
|
|||||||
return sorted(affected), sorted(domains), sorted(co_validation)
|
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:
|
def analyze(accepted_ref: str, candidate_ref: str) -> dict:
|
||||||
accepted_revision = resolve(ROOT, accepted_ref)
|
accepted_revision = resolve(ROOT, accepted_ref)
|
||||||
candidate_revision = resolve(ROOT, candidate_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("--candidate", default="HEAD", help="candidate root revision")
|
||||||
parser.add_argument("--out", default=None)
|
parser.add_argument("--out", default=None)
|
||||||
parser.add_argument("--json", action="store_true")
|
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(
|
parser.add_argument(
|
||||||
"--fail-on-unverified",
|
"--fail-on-unverified",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -297,7 +377,10 @@ def main(argv: list[str]) -> int:
|
|||||||
)
|
)
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
try:
|
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:
|
except ImpactError as error:
|
||||||
print(f"impact: error: {error}", file=sys.stderr)
|
print(f"impact: error: {error}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
@@ -307,16 +390,23 @@ def main(argv: list[str]) -> int:
|
|||||||
if args.json:
|
if args.json:
|
||||||
print(text, end="")
|
print(text, end="")
|
||||||
else:
|
else:
|
||||||
print(
|
if "candidate" in report:
|
||||||
f"accepted {report['accepted']['revision'][:12]} "
|
print(
|
||||||
f"candidate {report['candidate']['revision'][:12]}"
|
f"accepted {report['accepted']['revision'][:12]} "
|
||||||
)
|
f"candidate {report['candidate']['revision'][:12]}"
|
||||||
print(
|
)
|
||||||
f"changed={report['counts']['changed']} "
|
print(
|
||||||
f"affected={report['counts']['affected']}"
|
f"changed={report['counts']['changed']} "
|
||||||
)
|
f"affected={report['counts']['affected']}"
|
||||||
for item in report["changed"]:
|
)
|
||||||
print(f" changed {item['id']}: {item['reason']}")
|
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"]))
|
print("affected: " + ", ".join(report["affected"]))
|
||||||
if report["checks_with"]:
|
if report["checks_with"]:
|
||||||
print("co-validation: " + ", ".join(report["checks_with"]))
|
print("co-validation: " + ", ".join(report["checks_with"]))
|
||||||
|
|||||||
@@ -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()
|
||||||
Reference in new issue
Block a user