Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
241b480a34 | ||
|
|
96418b3ff5 | ||
|
|
22a1b0b293 | ||
|
|
d28ed9d00d | ||
|
|
43fa9008a9 | ||
|
|
de10e135ed | ||
|
|
b47cf440b7 | ||
|
|
a8a8098b9a |
No files matched your search
@@ -15,7 +15,14 @@ steps:
|
||||
environment:
|
||||
MARQDO_GIT_TOKEN:
|
||||
from_secret: gitea_reconcile_token
|
||||
MARQDO_WOODPECKER_DISPATCH_TOKEN:
|
||||
from_secret: woodpecker_reconcile_token
|
||||
commands:
|
||||
- python3 scripts/check-layout.py
|
||||
- git submodule update --init
|
||||
- |
|
||||
set -eu
|
||||
domains="$(python3 scripts/check-layout.py --root-domain-paths)"
|
||||
for domain in $domains; do
|
||||
git submodule update --init -- "$domain"
|
||||
done
|
||||
- python3 scripts/check-layout.py --domain-paths
|
||||
- python3 scripts/reconcile-releases.py --apply --published-after 2026-11-27T02:00:00Z --report-out reconcile-report.json
|
||||
+1
-1
Submodule cli updated: 13affa76dd...63776735e9.
+3
-1
@@ -82,7 +82,9 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 +
|
||||
|
||||
经过授权的 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。
|
||||
|
||||
正式发布对账使用 `python3 scripts/reconcile-releases.py --plan --published-after <ISO-8601 时间>`。从固定根及领域 tree 解析受管仓库,核对 Gitea tag、`release-evidence.json`、同 SHA Woodpecker 组件 CI 和资产字节摘要。根 `reconcile` 工作流从当前受保护的 `main` 串行运行,使用 `gitea_reconcile_token` 以专用非管理员账号写追踪工单。`historical-baseline` 表示已登记历史输入,`blocked` 表示发布验证未通过,`tracked` 表示已记录经验证的发布。消费者验收和父级接受均需各自的 CI 与 PR 证据。
|
||||
正式发布对账使用 `python3 scripts/reconcile-releases.py --plan --published-after <ISO-8601 时间>`。从固定根及领域 tree 解析受管仓库,核对 Gitea tag、`release-evidence.json`、同 SHA Woodpecker 组件 CI 和资产字节摘要。根 `reconcile` 工作流从当前受保护的 `main` 串行运行,只检出领域聚合仓,使用 `gitea_reconcile_token` 以专用非管理员账号写追踪工单。`historical-baseline` 表示已登记历史输入,`blocked` 表示发布验证未通过,`tracked` 表示已记录经验证的发布。扫描完整且追踪写入成功时,已报告的发布阻塞保留为 `blocked`,工作流仍成功结束。消费者验收和父级接受均需各自的 CI 与 PR 证据。
|
||||
|
||||
消费者通过已接受 Git 树里的 `.woodpecker/upstream.yml` 接入派发。根只在该消费者的受保护默认分支精确匹配 gitlink 时触发,发送本仓任务编号和幂等键。Woodpecker 原生触发要求项目级 push 权限,该角色同时可以管理该项目的 CI secret。仅把这一角色授予专用非管理员 `marqdo-reconcile` 在已接入的消费者仓,并通过 Woodpecker 登录为该账号生成 token。根仓 `woodpecker_reconcile_token` 限于受保护 `main` 的 manual/cron 配置,部署时核对账号和具体仓权限。触发凭据只在根协调步骤使用,消费者测试无需该凭据。根报告通过已存在的同任务 Woodpecker 流水线识别重复或失联的触发结果。派发身份未配置或权限未就绪时,报告记录 `dispatch_status=unavailable` 和 `dispatch_error`,扫描与发布追踪仍完成且不被该基础设施限制判失败;权限阻塞单独登记,不能据此伪造已派发。
|
||||
|
||||
对已验证的发布,`--plan` 计算直接 active 消费者的输入摘要。受保护 `--apply` 按发布和消费者登记一条任务,基线变化时在原任务中记录新输入。输入附精确资产、依赖、消费者基线和根追踪编号。下游独立 CI 及批准后的晋升基于各自的真实结果。
|
||||
|
||||
|
||||
@@ -452,6 +452,7 @@ def main():
|
||||
paths.add_argument("--active-paths", action="store_true", help="print only direct active component paths")
|
||||
paths.add_argument("--active-entries", action="store_true", help="print validated active entries in dependency order")
|
||||
paths.add_argument("--domain-paths", action="store_true", help="validate domain URLs and print domain paths")
|
||||
paths.add_argument("--root-domain-paths", action="store_true", help="print root domain gitlinks before checkout")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
revision = git("rev-parse", "--verify", args.revision + "^{commit}").strip()
|
||||
@@ -463,7 +464,7 @@ def main():
|
||||
for path, component in sorted(layers[0].linked.items()):
|
||||
if component["state"] == "active":
|
||||
print(path)
|
||||
elif args.domain_paths:
|
||||
elif args.domain_paths or args.root_domain_paths:
|
||||
for path, component in sorted(layers[0].linked.items()):
|
||||
if component["kind"] == "domain":
|
||||
print(path)
|
||||
|
||||
+139
-25
@@ -44,46 +44,62 @@ class ReconcileError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ApiUnavailable(ReconcileError):
|
||||
"""The API could not supply the facts needed to complete the scan."""
|
||||
|
||||
|
||||
def http_error(method, path, status):
|
||||
error = ApiUnavailable if status in {401, 403, 429} or status >= 500 else ReconcileError
|
||||
return error(f"{method} {path}: HTTP {status}")
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, request, fp, code, message, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
class Gitea:
|
||||
def __init__(self, token: str):
|
||||
def __init__(self, token: str, dispatch_token: str = ""):
|
||||
self.token = token
|
||||
self.dispatch_token = dispatch_token
|
||||
self.opener = urllib.request.build_opener(NoRedirect())
|
||||
|
||||
def open(self, method, url, data=None, authenticated=False):
|
||||
def open(self, method, url, data=None, authorization=None):
|
||||
headers = {}
|
||||
if authenticated and self.token:
|
||||
headers["Authorization"] = f"token {self.token}"
|
||||
if authorization:
|
||||
headers["Authorization"] = authorization
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
return self.opener.open(request, timeout=30)
|
||||
|
||||
def request(self, method, base, path, data=None, authenticated=False):
|
||||
def request(self, method, base, path, data=None, authorization=None):
|
||||
try:
|
||||
with self.open(method, base + path, data, authenticated) as response:
|
||||
with self.open(method, base + path, data, authorization) as response:
|
||||
payload = response.read(8 * MAX_INDEX_BYTES + 1)
|
||||
require(len(payload) <= 8 * MAX_INDEX_BYTES, "API response exceeds size limit")
|
||||
return json.loads(payload)
|
||||
except urllib.error.HTTPError as error:
|
||||
raise ReconcileError(f"{method} {path}: HTTP {error.code}") from error
|
||||
raise http_error(method, path, error.code) from error
|
||||
except (OSError, ValueError, http.client.HTTPException) as error:
|
||||
raise ReconcileError(f"{method} {path}: {error}") from error
|
||||
raise ApiUnavailable(f"{method} {path}: {error}") from error
|
||||
|
||||
def get(self, path):
|
||||
return self.request("GET", FORGE + "/api/v1", path, authenticated=True)
|
||||
return self.request("GET", FORGE + "/api/v1", path,
|
||||
authorization=f"token {self.token}" if self.token else None)
|
||||
|
||||
def post(self, path, data):
|
||||
return self.request("POST", FORGE + "/api/v1", path,
|
||||
json.dumps(data).encode(), authenticated=True)
|
||||
json.dumps(data).encode(), f"token {self.token}")
|
||||
|
||||
def ci(self, path):
|
||||
return self.request("GET", CI + "/api", path)
|
||||
|
||||
def dispatch_ci(self, path, data=None):
|
||||
return self.request("GET" if data is None else "POST", CI + "/api", path,
|
||||
None if data is None else json.dumps(data).encode(),
|
||||
f"Bearer {self.dispatch_token}")
|
||||
|
||||
def asset(self, path, size, *, index=False):
|
||||
limit = MAX_INDEX_BYTES if index else MAX_ASSET_BYTES
|
||||
require(type(size) is int and 0 < size <= limit, "invalid asset size")
|
||||
@@ -99,9 +115,9 @@ class Gitea:
|
||||
if index:
|
||||
payload.extend(chunk)
|
||||
except urllib.error.HTTPError as error:
|
||||
raise ReconcileError(f"GET {path}: HTTP {error.code}") from error
|
||||
raise http_error("GET", path, error.code) from error
|
||||
except (OSError, http.client.HTTPException) as error:
|
||||
raise ReconcileError(f"GET {path}: {error}") from error
|
||||
raise ApiUnavailable(f"GET {path}: {error}") from error
|
||||
require(received == size, f"asset {path} size mismatch")
|
||||
return digest.hexdigest(), bytes(payload)
|
||||
|
||||
@@ -171,12 +187,7 @@ def managed_repositories(root):
|
||||
return revision, graph, managed
|
||||
|
||||
|
||||
def verify_pipeline(client, repository, source_sha, evidence):
|
||||
require(exact_fields(evidence, {"pipeline_number", "url", "source_sha"}),
|
||||
"invalid component CI evidence")
|
||||
number = evidence["pipeline_number"]
|
||||
require(type(number) is int and number > 0 and evidence["source_sha"] == source_sha,
|
||||
"release has no component CI evidence for its exact SHA")
|
||||
def ci_repository(client, repository):
|
||||
repo = client.ci(f"/repos/lookup/{repository}")
|
||||
forge_repo = client.get(f"/repos/{repository}")
|
||||
require(isinstance(repo, dict) and repo.get("full_name") == repository
|
||||
@@ -184,9 +195,19 @@ def verify_pipeline(client, repository, source_sha, evidence):
|
||||
and isinstance(forge_repo, dict) and type(forge_repo.get("id")) is int
|
||||
and repo.get("forge_remote_id") == str(forge_repo["id"]),
|
||||
"CI repository identity mismatch")
|
||||
expected_url = f"{CI}/repos/{repo['id']}/pipeline/{number}"
|
||||
return repo["id"], forge_repo
|
||||
|
||||
|
||||
def verify_pipeline(client, repository, source_sha, evidence):
|
||||
require(exact_fields(evidence, {"pipeline_number", "url", "source_sha"}),
|
||||
"invalid component CI evidence")
|
||||
number = evidence["pipeline_number"]
|
||||
require(type(number) is int and number > 0 and evidence["source_sha"] == source_sha,
|
||||
"release has no component CI evidence for its exact SHA")
|
||||
repo_id, _ = ci_repository(client, repository)
|
||||
expected_url = f"{CI}/repos/{repo_id}/pipeline/{number}"
|
||||
require(evidence["url"] == expected_url, "component CI URL mismatch")
|
||||
pipeline = client.ci(f"/repos/{repo['id']}/pipelines/{number}")
|
||||
pipeline = client.ci(f"/repos/{repo_id}/pipelines/{number}")
|
||||
workflow = "main" if repository == "cflmy/marqdo-cli" else "ci"
|
||||
require(isinstance(pipeline, dict) and pipeline.get("number") == number
|
||||
and pipeline.get("commit") == source_sha and pipeline.get("status") == "success"
|
||||
@@ -416,13 +437,90 @@ def register_consumer_tasks(client, root_sha, entry, issue_cache):
|
||||
task.update(registration="blocked", error=str(error))
|
||||
|
||||
|
||||
def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=None):
|
||||
def verify_dispatch_identity(client):
|
||||
actor = client.dispatch_ci("/user")
|
||||
require(isinstance(actor, dict) and actor.get("login") == RECONCILE_ACCOUNT
|
||||
and not actor.get("admin") and not actor.get("admin_env"),
|
||||
"dispatch requires the non-admin reconcile account in Woodpecker")
|
||||
|
||||
|
||||
def dispatch_consumer(client, root_sha, task, published_at, can_start):
|
||||
repo_id, forge_repo = ci_repository(client, task["repository"])
|
||||
branch = forge_repo.get("default_branch")
|
||||
require(match(BASENAME, branch), "consumer has an unsupported default branch name")
|
||||
protected = client.get(f"/repos/{task['repository']}/branches/{branch}")
|
||||
require(protected.get("protected") is True
|
||||
and (protected.get("commit") or {}).get("id") == task["baseline_sha"],
|
||||
"consumer default branch is unprotected or differs from the accepted gitlink")
|
||||
ref = urllib.parse.urlencode({"ref": task["baseline_sha"]})
|
||||
try:
|
||||
config = client.get(f"/repos/{task['repository']}/contents/.woodpecker/upstream.yml?{ref}")
|
||||
except ReconcileError as error:
|
||||
if str(error).endswith(": HTTP 404"):
|
||||
task["dispatch_status"] = "no-upstream-workflow"
|
||||
return False
|
||||
raise
|
||||
require(config.get("type") == "file", "consumer upstream workflow is not a repository file")
|
||||
|
||||
api = f"/repos/{repo_id}"
|
||||
permissions = client.dispatch_ci(f"{api}/permissions")
|
||||
require(permissions.get("push") is True and permissions.get("admin") is False,
|
||||
"dispatch needs project-level push permission without project admin")
|
||||
require(type(task["issue"]) is int and task["issue"] > 0, "invalid consumer issue number")
|
||||
key = hashlib.sha256(f"{root_sha}\n{task['key']}".encode()).hexdigest()
|
||||
variables = {"MARQDO_UPSTREAM_ISSUE": str(task["issue"]), "MARQDO_UPSTREAM_TASK": key}
|
||||
|
||||
def corresponds(pipeline):
|
||||
return (type(pipeline.get("number")) is int and pipeline["number"] > 0
|
||||
and pipeline.get("event") == "manual" and pipeline.get("branch") == branch
|
||||
and pipeline.get("selected_workflow") == "upstream"
|
||||
and pipeline.get("author") == RECONCILE_ACCOUNT
|
||||
and pipeline.get("commit") == task["baseline_sha"]
|
||||
and pipeline.get("variables") == variables)
|
||||
|
||||
# Check Woodpecker's actual runs, including an accepted POST whose response
|
||||
# was lost. A failed run remains evidence until the task inputs change.
|
||||
pipelines = f"{api}/pipelines"
|
||||
for page in range(1, MAX_PAGES + 1):
|
||||
query = urllib.parse.urlencode(dict(event="manual", branch=branch, after=published_at,
|
||||
page=page, perPage=PAGE_SIZE))
|
||||
records = client.dispatch_ci(f"{pipelines}?{query}")
|
||||
require(isinstance(records, list) and len(records) <= PAGE_SIZE, "invalid CI pipeline page")
|
||||
existing = next((pipeline for pipeline in records if corresponds(pipeline)), None)
|
||||
if existing or len(records) < PAGE_SIZE:
|
||||
break
|
||||
else:
|
||||
raise ReconcileError("CI pipeline pagination limit reached")
|
||||
started = False
|
||||
if existing is None:
|
||||
if not can_start:
|
||||
task["dispatch_status"] = "queued-for-dispatch"
|
||||
return False
|
||||
verify_root_base(client, root_sha)
|
||||
existing = client.dispatch_ci(pipelines, {"branch": branch, "workflow": "upstream",
|
||||
"variables": variables})
|
||||
require(isinstance(existing, dict) and corresponds(existing),
|
||||
"dispatched pipeline differs from the intended consumer task")
|
||||
started = True
|
||||
task["dispatch_status"] = existing["status"]
|
||||
task["pipeline"] = f"{CI}/repos/{repo_id}/pipeline/{existing['number']}"
|
||||
return started
|
||||
|
||||
|
||||
def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=None, dispatch=False):
|
||||
root_sha, graph, managed = managed_repositories(root)
|
||||
cutoff_time = timestamp(cutoff) if cutoff else None
|
||||
issues_url = f"/repos/{ROOT_REPOSITORY}/issues"
|
||||
issues = list(pages(client, issues_url, state="all", type="issues", labels=LABEL))
|
||||
if apply:
|
||||
verify_apply_context(client, root_sha)
|
||||
dispatch_status, dispatch_error, starts = "disabled", None, 0
|
||||
if apply and dispatch:
|
||||
try:
|
||||
verify_dispatch_identity(client)
|
||||
dispatch_status = "enabled"
|
||||
except ReconcileError as error:
|
||||
dispatch_status, dispatch_error = "unavailable", str(error)
|
||||
labels = f"/repos/{ROOT_REPOSITORY}/labels"
|
||||
label_id = next((x["id"] for x in pages(client, labels) if x.get("name") == LABEL), None) if apply else None
|
||||
results, errors, consumer_issues = [], {}, {}
|
||||
@@ -472,6 +570,8 @@ def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=No
|
||||
require(not old or old == {identity_marker(entry)},
|
||||
"published release identity or index digest changed")
|
||||
entry["release_key"], entry["consumer_tasks"] = consumer_inputs(entry, graph)
|
||||
except ApiUnavailable:
|
||||
raise
|
||||
except ReconcileError as error:
|
||||
entry.update(status="blocked", error=str(error))
|
||||
|
||||
@@ -495,6 +595,15 @@ def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=No
|
||||
and entry["status"] in {"created", "pending", "tracked"}
|
||||
and (not trackers or trackers[0]["state"] == "open")):
|
||||
register_consumer_tasks(client, root_sha, entry, consumer_issues)
|
||||
if dispatch_status == "enabled":
|
||||
for task in entry["consumer_tasks"]:
|
||||
if task["status"] != "pending" or task["registration"] != "recorded":
|
||||
continue
|
||||
try:
|
||||
starts += dispatch_consumer(client, root_sha, task, entry["published_at"],
|
||||
can_start=starts < 4)
|
||||
except ReconcileError as error:
|
||||
task.update(dispatch_status="blocked", dispatch_error=str(error))
|
||||
results.append(entry)
|
||||
prefix = f"<!-- marqdo:release-reconcile repository={repository} tag="
|
||||
for issue in issues:
|
||||
@@ -518,10 +627,13 @@ def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=No
|
||||
"root_repository": ROOT_REPOSITORY, "root_sha": root_sha,
|
||||
"apply": apply, "repositories": len(managed), "releases": len(results),
|
||||
"scan_complete": not errors, "scan_errors": errors, "results": results,
|
||||
"dispatch_status": dispatch_status,
|
||||
"counts": {status: sum(item["status"] == status for item in results)
|
||||
for status in sorted({item["status"] for item in results})},
|
||||
"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
}
|
||||
if dispatch_error:
|
||||
report["dispatch_error"] = dispatch_error
|
||||
if report_out:
|
||||
report_out.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
@@ -538,6 +650,7 @@ def main(argv):
|
||||
parser.add_argument("--published-after", default=os.environ.get("MARQDO_RECONCILE_PUBLISHED_AFTER"))
|
||||
args = parser.parse_args(argv)
|
||||
token = os.environ.get("MARQDO_GIT_TOKEN", "")
|
||||
dispatch_token = os.environ.get("MARQDO_WOODPECKER_DISPATCH_TOKEN", "")
|
||||
if args.apply and not token:
|
||||
parser.error("--apply requires MARQDO_GIT_TOKEN")
|
||||
try:
|
||||
@@ -546,15 +659,16 @@ def main(argv):
|
||||
except ReconcileError as error:
|
||||
parser.error(str(error))
|
||||
try:
|
||||
report = reconcile(Gitea(token), args.root.resolve(), args.apply,
|
||||
args.report_out, args.published_after)
|
||||
report = reconcile(Gitea(token, dispatch_token), args.root.resolve(), args.apply,
|
||||
args.report_out, args.published_after, dispatch=bool(dispatch_token))
|
||||
except (OSError, ReconcileError) as error:
|
||||
print(f"reconcile: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
return int(not report["scan_complete"] or any(
|
||||
item["status"] == "blocked" or "tracking_update" in item
|
||||
or any(task.get("registration") == "blocked" for task in item.get("consumer_tasks", []))
|
||||
"tracking_update" in item
|
||||
or any(task.get("registration") == "blocked" or task.get("dispatch_status") == "blocked"
|
||||
for task in item.get("consumer_tasks", []))
|
||||
for item in report["results"]))
|
||||
|
||||
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
@@ -137,6 +140,65 @@ class ReconcileTest(unittest.TestCase):
|
||||
def run_scan(self, **kwargs):
|
||||
return reconcile.reconcile(self.forge, **kwargs)
|
||||
|
||||
def test_native_dispatch_reuses_a_run_for_the_same_task_and_root(self):
|
||||
task = {"repository": REPO, "baseline_sha": BASE, "issue": 42, "key": "c" * 64}
|
||||
routes = {
|
||||
f"/repos/{REPO}/branches/master": {"protected": True, "commit": {"id": BASE}},
|
||||
f"/repos/{REPO}/contents/.woodpecker/upstream.yml?ref={BASE}": {"type": "file"},
|
||||
"/repos/cflmy/marqdo/branches/main": {"protected": True, "commit": {"id": BASE}},
|
||||
}
|
||||
runs = []
|
||||
posts = []
|
||||
|
||||
def dispatch(path, data=None):
|
||||
if path == "/repos/8/permissions":
|
||||
return {"push": True, "admin": False}
|
||||
if data is None:
|
||||
self.assertTrue(path.startswith("/repos/8/pipelines?"))
|
||||
return runs
|
||||
self.assertEqual(path, "/repos/8/pipelines")
|
||||
self.assertEqual(data["branch"], "master")
|
||||
self.assertEqual(data["workflow"], "upstream")
|
||||
self.assertEqual(data["variables"]["MARQDO_UPSTREAM_ISSUE"], "42")
|
||||
posts.append(data)
|
||||
runs.append({"number": 15, "status": "pending", "author": ACTOR["login"],
|
||||
"event": "manual", "branch": data["branch"], "commit": BASE,
|
||||
"selected_workflow": data["workflow"], "variables": data["variables"]})
|
||||
return runs[-1]
|
||||
|
||||
with (patch.object(reconcile, "ci_repository", return_value=(8, {"default_branch": "master"})),
|
||||
patch.object(self.forge, "get", side_effect=routes.__getitem__),
|
||||
patch.object(self.forge, "dispatch_ci", side_effect=dispatch, create=True)):
|
||||
self.assertTrue(reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True))
|
||||
self.assertFalse(reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True))
|
||||
self.assertEqual(task["pipeline"], f"{reconcile.CI}/repos/8/pipeline/15")
|
||||
self.assertEqual(len(posts), 1)
|
||||
routes[f"/repos/{REPO}/branches/master"]["protected"] = False
|
||||
with self.assertRaisesRegex(reconcile.ReconcileError, "unprotected"):
|
||||
reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True)
|
||||
self.assertEqual(len(posts), 1)
|
||||
|
||||
def test_dispatch_rejects_owner_or_admin_identity_before_writing_to_ci(self):
|
||||
for identity in ({"login": "cflmy"}, {**ACTOR, "admin": True}):
|
||||
with patch.object(self.forge, "dispatch_ci", return_value=identity, create=True) as ci:
|
||||
report = self.run_scan(apply=True, dispatch=True)
|
||||
ci.assert_called_once_with("/user")
|
||||
self.assertTrue(report["scan_complete"])
|
||||
self.assertEqual(report["dispatch_status"], "unavailable")
|
||||
|
||||
def test_unavailable_dispatch_does_not_fail_a_complete_scan(self):
|
||||
with (patch.dict(os.environ, {"MARQDO_GIT_TOKEN": "fixture",
|
||||
"MARQDO_WOODPECKER_DISPATCH_TOKEN": "fixture"}),
|
||||
patch.object(reconcile, "Gitea", return_value=self.forge),
|
||||
patch.object(self.forge, "dispatch_ci", return_value={"login": "cflmy"}, create=True),
|
||||
redirect_stdout(io.StringIO()) as stdout):
|
||||
result = reconcile.main(["--apply"])
|
||||
self.assertEqual(result, 0)
|
||||
report = json.loads(stdout.getvalue())
|
||||
self.assertTrue(report["scan_complete"])
|
||||
self.assertEqual(report["dispatch_status"], "unavailable")
|
||||
self.assertIn("non-admin reconcile account", report["dispatch_error"])
|
||||
|
||||
def test_dry_run_fully_verifies_without_writing(self):
|
||||
report = self.run_scan()
|
||||
self.assertEqual(self.forge.writes, [])
|
||||
@@ -229,6 +291,25 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertEqual(entry["status"], "blocked")
|
||||
self.assertIn("cover the published assets", entry["error"])
|
||||
|
||||
def test_recorded_release_block_does_not_fail_a_complete_operational_scan(self):
|
||||
self.forge.pipeline_sha = BASE
|
||||
with (patch.dict(os.environ, {"MARQDO_GIT_TOKEN": "fixture"}),
|
||||
patch.object(reconcile, "Gitea", return_value=self.forge),
|
||||
redirect_stdout(io.StringIO()) as stdout):
|
||||
result = reconcile.main(["--apply"])
|
||||
self.assertEqual(result, 0)
|
||||
report = json.loads(stdout.getvalue())
|
||||
self.assertTrue(report["scan_complete"])
|
||||
self.assertEqual(report["results"][0]["status"], "blocked")
|
||||
self.assertEqual(len(self.forge.issues), 1)
|
||||
|
||||
def test_asset_api_outage_leaves_the_scan_incomplete(self):
|
||||
with patch.object(self.forge, "asset", side_effect=reconcile.http_error("GET", "/asset", 503)):
|
||||
report = self.run_scan(apply=True)
|
||||
self.assertFalse(report["scan_complete"])
|
||||
self.assertEqual(report["scan_errors"][REPO], "GET /asset: HTTP 503")
|
||||
self.assertEqual(self.forge.writes, [])
|
||||
|
||||
def test_validated_tracker_detects_an_updated_index_and_disappearing_release(self):
|
||||
self.run_scan(apply=True)
|
||||
self.forge.evidence["assets"][0]["target"] = "x86_64-unknown-linux-gnu"
|
||||
|
||||
+1
-1
Submodule tools/knowledge updated: a1a223f53f...3cc477de60.
Reference in new issue
Block a user