#!/usr/bin/env python3 """osv-scanner follow-ups for a Gitea repository (stdlib only). scan osv-scanner over the repo's lockfiles, honouring osv-scanner.toml. Advisories not already listed in an open follow-up issue get a new issue (one per run, or one per package) that asks @claude to fix them or add an osv-scanner.toml entry with a code-specific reason. recheck Entries of osv-scanner.toml whose advisory no longer matches any dependency are removed in a pull request (deterministic, no LLM); the remaining entries go into one @claude issue asking for their reasons to be re-verified. Configuration comes from the environment (see action.yml). Exit status is non-zero only on errors: advisories found is the normal case. """ from __future__ import annotations import datetime as dt import json import os import re import subprocess import sys import tempfile import tomllib import urllib.error import urllib.parse import urllib.request from collections import OrderedDict from pathlib import Path ISSUE_MARKER = "osv-followup" # RECHECK_MARKER = "osv-recheck" PRUNE_BRANCH_PREFIX = "osv/prune-" BODY_LIMIT = 60000 # Gitea stores bodies as TEXT; stay well below SUMMARY_LIMIT = 300 def env(name: str, default: str = "") -> str: return os.environ.get(name, default).strip() def flag(name: str) -> bool: return env(name).lower() in ("1", "true", "yes", "on") def log(msg: str) -> None: print(msg, flush=True) def warn(msg: str) -> None: print(f"::warning::{msg}", flush=True) def today() -> dt.date: override = env("OSV_TODAY") # tests only return dt.date.fromisoformat(override) if override else dt.datetime.now(dt.UTC).date() # -------------------------------------------------------------------------- # Gitea API # -------------------------------------------------------------------------- class Gitea: def __init__(self, server: str, repo: str, token: str, dry_run: bool) -> None: self.base = f"{server.rstrip('/')}/api/v1" self.repo = repo self.token = token self.dry_run = dry_run def call(self, method: str, path: str, body: object | None = None) -> object: if flag("OSV_OFFLINE"): # local tests: no Gitea at all log(f"[offline] {method} {path}") return [] if method == "GET" and "/user" not in path else {} url = path if path.startswith("http") else f"{self.base}{path}" data = None if body is None else json.dumps(body).encode() req = urllib.request.Request(url, data=data, method=method) req.add_header("Accept", "application/json") if self.token: req.add_header("Authorization", f"token {self.token}") if data is not None: req.add_header("Content-Type", "application/json") try: with urllib.request.urlopen(req, timeout=60) as resp: raw = resp.read() except urllib.error.HTTPError as e: detail = e.read().decode(errors="replace")[:500] raise RuntimeError(f"{method} {path}: HTTP {e.code} {detail}") from None return json.loads(raw) if raw else None def paged(self, path: str, limit: int = 50, max_pages: int = 40) -> list[dict]: out: list[dict] = [] sep = "&" if "?" in path else "?" for page in range(1, max_pages + 1): batch = self.call("GET", f"{path}{sep}limit={limit}&page={page}") if not isinstance(batch, list) or not batch: break out.extend(batch) if len(batch) < limit: break return out def write(self, method: str, path: str, body: object) -> dict: if self.dry_run: log(f"[dry-run] {method} {path}") return {"number": 0, "html_url": "(dry run)", "id": 0} res = self.call(method, path, body) return res if isinstance(res, dict) else {} def repo_path(self, suffix: str) -> str: return f"/repos/{self.repo}{suffix}" def label_ids(self, names: list[str]) -> list[int]: if not names: return [] existing = {lab["name"]: lab["id"] for lab in self.paged(self.repo_path("/labels"))} ids = [] palette = {"security": "#e11d48", ISSUE_MARKER: "#f59e0b", RECHECK_MARKER: "#0ea5e9"} for name in names: if name not in existing and not self.dry_run: try: created = self.call( "POST", self.repo_path("/labels"), {"name": name, "color": palette.get(name, "#6b7280")}, ) existing[name] = created["id"] # type: ignore[index] except RuntimeError as e: warn(f"could not create label {name!r}: {e}") if name in existing: ids.append(existing[name]) return ids def open_issues(self, label: str) -> list[dict]: q = urllib.parse.urlencode({"state": "open", "type": "issues", "labels": label}) return self.paged(self.repo_path(f"/issues?{q}")) def open_pulls(self) -> list[dict]: return self.paged(self.repo_path("/pulls?state=open")) def create_issue(self, title: str, body: str, labels: list[int]) -> dict: return self.write("POST", self.repo_path("/issues"), {"title": title, "body": body, "labels": labels}) def comment(self, number: int, body: str) -> dict: return self.write("POST", self.repo_path(f"/issues/{number}/comments"), {"body": body}) def create_pull(self, title: str, body: str, head: str, base: str, labels: list[int]) -> dict: pr = self.write("POST", self.repo_path("/pulls"), {"title": title, "body": body, "head": head, "base": base}) if labels and pr.get("number"): try: self.call("POST", self.repo_path(f"/issues/{pr['number']}/labels"), {"labels": labels}) except RuntimeError as e: warn(f"could not label PR #{pr['number']}: {e}") return pr def login(self) -> str: user = self.call("GET", "/user") return user.get("login", "") if isinstance(user, dict) else "" # -------------------------------------------------------------------------- # osv-scanner # -------------------------------------------------------------------------- def run_osv(config: Path | None, scan_path: str, extra: list[str]) -> dict: osv = env("OSV_SCANNER", "osv-scanner") with tempfile.NamedTemporaryFile("w+", suffix=".json", delete=False) as out: out_path = out.name cmd = [osv, "scan", "source", "-r", "--format", "json", "--output-file", out_path] if config is not None: cmd += ["--config", str(config)] cmd += extra + [scan_path] log("$ " + " ".join(cmd)) proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for line in proc.stderr.splitlines(): if line.strip(): log(f" osv-scanner: {line}") # 0 = clean, 1 = vulnerabilities found, 128 = no packages found. if proc.returncode == 128: log("osv-scanner found no lockfiles/packages to scan") return {"results": []} if proc.returncode not in (0, 1): raise RuntimeError(f"osv-scanner failed with exit code {proc.returncode}") text = Path(out_path).read_text() or '{"results": []}' Path(out_path).unlink(missing_ok=True) return json.loads(text) def fixed_versions(vuln: dict, name: str, ecosystem: str) -> list[str]: fixed: list[str] = [] for aff in vuln.get("affected") or []: pkg = aff.get("package") or {} if pkg.get("name") != name: continue if ecosystem and not str(pkg.get("ecosystem", "")).startswith(ecosystem.split(":")[0]): continue for rng in aff.get("ranges") or []: for ev in rng.get("events") or []: if "fixed" in ev and ev["fixed"] not in fixed: fixed.append(ev["fixed"]) return fixed def severity_label(vulns: list[dict], score: str) -> str: words = [ str((v.get("database_specific") or {}).get("severity", "")).upper() for v in vulns if (v.get("database_specific") or {}).get("severity") ] word = words[0] if words else "" if score and word: return f"{word} ({score})" return word or score or "unknown" def collect(report: dict, root: Path) -> "OrderedDict[str, dict]": """Advisory groups keyed by their first id, merged across lockfiles.""" groups: "OrderedDict[str, dict]" = OrderedDict() for result in report.get("results") or []: src = (result.get("source") or {}).get("path", "") try: src = str(Path(src).resolve().relative_to(root)) except ValueError: pass for pkg in result.get("packages") or []: info = pkg.get("package") or {} name, version, eco = info.get("name", "?"), info.get("version", "?"), info.get("ecosystem", "") vulns = {v["id"]: v for v in pkg.get("vulnerabilities") or [] if "id" in v} for grp in pkg.get("groups") or []: ids = list(grp.get("ids") or []) if not ids: continue aliases = sorted(set(ids) | set(grp.get("aliases") or [])) key = ids[0] gv = [vulns[i] for i in ids if i in vulns] entry = groups.get(key) if entry is None: summary = next((v.get("summary") for v in gv if v.get("summary")), "") or next( (v.get("details", "")[:SUMMARY_LIMIT] for v in gv), "" ) entry = groups[key] = { "key": key, "ids": ids, "aliases": aliases, "cves": [a for a in aliases if a.startswith("CVE-")], "summary": " ".join(str(summary).split())[:SUMMARY_LIMIT], "severity": severity_label(gv, str(grp.get("max_severity") or "")), "score": float(grp.get("max_severity") or 0) if re.fullmatch(r"[0-9.]+", str(grp.get("max_severity") or "")) else 0.0, "fixed": [], "packages": [], } for f in [f for v in gv for f in fixed_versions(v, name, eco)]: if f not in entry["fixed"]: entry["fixed"].append(f) where = {"ecosystem": eco, "name": name, "version": version, "source": src} if where not in entry["packages"]: entry["packages"].append(where) return groups # -------------------------------------------------------------------------- # osv-scanner.toml # -------------------------------------------------------------------------- def read_ignores(path: Path) -> list[dict]: if not path.is_file(): return [] data = tomllib.loads(path.read_text()) out = [] for ent in data.get("IgnoredVulns") or []: if isinstance(ent, dict) and ent.get("id"): until = ent.get("ignoreUntil") or ent.get("effectiveUntil") out.append({"id": str(ent["id"]), "reason": str(ent.get("reason", "")), "until": str(until) if until else ""}) return out HEADER_RE = re.compile(r"^\s*\[") ENTRY_RE = re.compile(r"^\s*\[\[\s*IgnoredVulns\s*\]\]\s*(#.*)?$") ID_RE = re.compile(r"""^\s*id\s*=\s*["']([^"']+)["']""") SECTION_RE = re.compile(r"^\s*#\s*-{2,}.*-{2,}\s*$") def remove_entries(text: str, drop: set[str]) -> str: """Remove [[IgnoredVulns]] blocks whose id is in `drop`, with the comment lines directly above each block; then drop `# --- x ---` section headers left without entries. Line-based so every other comment survives.""" lines = text.splitlines(keepends=True) starts = [i for i, ln in enumerate(lines) if HEADER_RE.match(ln)] remove: set[int] = set() for n, start in enumerate(starts): if not ENTRY_RE.match(lines[start]): continue end = (starts[n + 1] if n + 1 < len(starts) else len(lines)) - 1 # Trailing blank/comment lines belong to whatever follows. while end > start and (not lines[end].strip() or lines[end].lstrip().startswith("#")): end -= 1 ident = next((m.group(1) for ln in lines[start : end + 1] if (m := ID_RE.match(ln))), None) if ident not in drop: continue first = start while first > 0 and lines[first - 1].lstrip().startswith("#") and not SECTION_RE.match(lines[first - 1]): first -= 1 remove.update(range(first, end + 1)) # One blank line after the block goes with it. if end + 1 < len(lines) and not lines[end + 1].strip(): remove.add(end + 1) kept = [ln for i, ln in enumerate(lines) if i not in remove] # Drop `# --- x ---` headers whose section no longer has an entry (the next # non-comment, non-blank line is another section header or the end). out: list[str] = [] for i, ln in enumerate(kept): if SECTION_RE.match(ln): j = i + 1 while j < len(kept) and not SECTION_RE.match(kept[j]) and ( not kept[j].strip() or kept[j].lstrip().startswith("#") ): j += 1 if j >= len(kept) or SECTION_RE.match(kept[j]): continue out.append(ln) result = re.sub(r"\n{3,}", "\n\n", "".join(out)) return result.rstrip("\n") + "\n" # -------------------------------------------------------------------------- # Issue bodies # -------------------------------------------------------------------------- def osv_link(ident: str) -> str: return f"[{ident}](https://osv.dev/vulnerability/{urllib.parse.quote(ident)})" def advisory_block(g: dict, previous: dict | None) -> str: pkgs = ", ".join( f"`{p['name']}@{p['version']}` ({p['ecosystem']}, `{p['source']}`)" for p in g["packages"] ) lines = [ f"#### {osv_link(g['ids'][0])}" + (f" ({', '.join(g['cves'])})" if g["cves"] else ""), "", f"- **Summary:** {g['summary'] or '(none)'}", f"- **Severity:** {g['severity']}", f"- **Affected:** {pkgs}", f"- **Fixed in:** {', '.join(f'`{f}`' for f in g['fixed']) if g['fixed'] else 'no fixed version published'}", ] if len(g["ids"]) > 1: lines.append(f"- **Same advisory:** {', '.join(osv_link(i) for i in g['ids'][1:])}") if previous: lines.append( f"- **Was ignored** until `{previous['until'] or '?'}` (expired) with reason: {previous['reason'] or '(none)'}" ) return "\n".join(lines) def scan_instructions(mention: str, context: str, config_name: str, base: str, days: int) -> str: until = today() + dt.timedelta(days=days) return f"""--- @{mention} please follow up on the advisories above (osv-scanner, weekly). This is this repository's security follow-up, not a code review. **About this repository:** {context} For **each** advisory: 1. **Find out whether it affects us.** Where does the package come from (`bun pm why ` / the lockfile, `go mod why -m `, `pip`/`requirements*.txt`)? Does it end up in what we ship (the image, the binary, the web bundle) or only in dev, test, docs or build tooling? Does our code reach the vulnerable function, option or feature? Read the advisory (links above) to know exactly what is vulnerable, then check the code. 2. **Fix it when you can:** if a fixed version exists and upgrading is compatible, upgrade (the smallest change that brings the fixed version: bump the direct dependency, or pin the transitive one the way this repo already does it). Follow the repo's rules: `CLAUDE.md`, `AGENTS.md`, `FORK.md` and `.claude/agent-instructions.md` where present. `bunfig.toml` `minimumReleaseAge` refuses too-new releases: if the fixed version is younger than that, do not work around it; use step 3 and say when the fix becomes installable. Run the checks CI runs (see `.gitea/workflows/`). 3. **Otherwise add an entry to `{config_name}`** (format in its header), grouped under a `# --- ---` comment, one entry per advisory group (any id of the group works; use the first one listed above): ```toml # CVE-YYYY-NNNNN [[IgnoredVulns]] id = "GHSA-xxxx-xxxx-xxxx" ignoreUntil = {until.isoformat()} reason = "code_not_reachable: " ``` The `reason` must be **specific and true**: name our files, functions or configuration and the dependency path, and say why the vulnerable code is not reached or not exposed. Start it with a CycloneDX justification: `code_not_present`, `code_not_reachable`, `requires_configuration`, `requires_dependency`, `requires_environment`, `protected_by_compiler`, `protected_at_runtime`, `protected_at_perimeter` or `protected_by_mitigating_control`. "Not exploitable" or "dev dependency" alone is not a reason. `ignoreUntil` is {days} days from today ({until.isoformat()}): the monthly re-check refreshes it while the reason still holds. Check the file still parses: `python3 -c 'import tomllib,sys; tomllib.load(open("{config_name}","rb"))'`. If an advisory **does** affect us and there is no fix, do not ignore it: describe the exposure and the options in the PR and in this issue. 4. **Open one pull request** for this issue: branch `osv/issue-` from `{base}`, commit, push, then create the PR against `{base}` (`mcp__local_git_ops__create_pull_request`). Its body starts with `Closes #` and has one line per advisory: the id, and either the fix (package and version) or the justification. Do not merge it; do not close this issue yourself (the PR closes it when merged). If you run short of time, push what is done, open the PR with those advisories and list in this issue the ones still open.""" def recheck_instructions(mention: str, context: str, config_name: str, base: str, days: int, prune_note: str) -> str: until = today() + dt.timedelta(days=days) soon = today() + dt.timedelta(days=45) return f"""--- @{mention} please re-check the `{config_name}` entries above (monthly). Each one claims an advisory does not affect this code; make sure that is still true for the code and dependency versions on `{base}` today. **About this repository:** {context} {prune_note} For **each** entry: - Read the advisory, then the code its `reason` names. Does the dependency path still exist? Is the vulnerable function, option or feature still unused or unreachable? Did a fixed version become available that we can now upgrade to (respect `bunfig.toml` `minimumReleaseAge` and the repo's rules in `CLAUDE.md`, `AGENTS.md`, `FORK.md`, `.claude/agent-instructions.md`)? - **Still holds:** leave it. If its `ignoreUntil` is missing or before {soon.isoformat()}, set `ignoreUntil = {until.isoformat()}`. - **Holds, but the reason is inaccurate** (renamed files, a changed dependency path): rewrite the reason so it is specific and true, and set `ignoreUntil = {until.isoformat()}`. - **No longer holds** (our code now reaches it, or it ships where it didn't): upgrade to the fixed version if there is one and remove the entry; if there is no fix, remove the entry anyway and describe the exposure in the PR. Reasons start with a CycloneDX justification (`code_not_present`, `code_not_reachable`, `requires_configuration`, `requires_dependency`, `requires_environment`, `protected_by_compiler`, `protected_at_runtime`, `protected_at_perimeter`, `protected_by_mitigating_control`). Check the file still parses: `python3 -c 'import tomllib,sys; tomllib.load(open("{config_name}","rb"))'`. If anything changes, open one pull request: branch `osv/recheck-` from `{base}`, PR against `{base}` (`mcp__local_git_ops__create_pull_request`), body starting with `Closes #` and one line per entry (kept / reason rewritten / removed, and why). Do not merge it. If nothing needs changing, comment with one line per entry saying why it still holds; then this issue may be closed.""" def marker(kind: str, ids: list[str]) -> str: return f"" def known_ids(issues: list[dict]) -> set[str]: seen: set[str] = set() pat = re.compile(r"") for issue in issues: for m in pat.finditer(issue.get("body") or ""): seen.update(m.group(1).split()) return seen def discord(text: str, url_link: str) -> None: hook = env("DISCORD_WEBHOOK_URL") if not hook or flag("DRY_RUN"): return payload = { "username": "osv-followup", "allowed_mentions": {"parse": []}, "embeds": [{"title": text[:250], "url": url_link if url_link.startswith("http") else None, "color": 15105570}], } req = urllib.request.Request( hook + ("&" if "?" in hook else "?") + "wait=true", data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}, method="POST", ) try: urllib.request.urlopen(req, timeout=20).read() except Exception as e: # noqa: BLE001 - a notice must never fail the job warn(f"Discord notice failed: {e}") # -------------------------------------------------------------------------- # Modes # -------------------------------------------------------------------------- def do_scan(gitea: Gitea, cfg: dict) -> None: config = cfg["config"] report = run_osv(config if config.is_file() else None, cfg["path"], cfg["extra"]) groups = collect(report, cfg["root"]) log(f"osv-scanner reports {len(groups)} advisory group(s) not ignored by {cfg['config_name']}") if not groups: return issues = gitea.open_issues(ISSUE_MARKER) seen = known_ids(issues) new = [g for g in groups.values() if not (set(g["aliases"]) & seen)] for g in groups.values(): state = "new" if g in new else "already in an open issue" pk = ", ".join(f"{p['name']}@{p['version']}" for p in g["packages"]) log(f" {g['ids'][0]:<22} {g['severity']:<16} {pk} [{state}]") if not new: log("Nothing new: every advisory is already in an open follow-up issue.") return previous = {e["id"]: e for e in read_ignores(config)} new.sort(key=lambda g: (-g["score"], g["packages"][0]["name"], g["key"])) batches: list[tuple[str, list[dict]]] = [] if cfg["group_by"] == "package": by_pkg: "OrderedDict[str, list[dict]]" = OrderedDict() for g in new: p = g["packages"][0] by_pkg.setdefault(f"{p['ecosystem']} {p['name']}", []).append(g) for pkg, gs in by_pkg.items(): batches.append((f"osv-scanner: {len(gs)} advisor{'y' if len(gs) == 1 else 'ies'} in {pkg.split(' ', 1)[1]} ({pkg.split(' ', 1)[0]})", gs)) else: names = list(OrderedDict.fromkeys(g["packages"][0]["name"] for g in new)) shown = ", ".join(names[:4]) + (f" and {len(names) - 4} more" if len(names) > 4 else "") batches.append( (f"osv-scanner: {len(new)} new advisor{'y' if len(new) == 1 else 'ies'} in {shown} ({today().isoformat()})", new) ) labels = gitea.label_ids(cfg["labels"]) created = [] for title, gs in batches: head = ( f"osv-scanner {cfg['osv_version']} found {len(gs)} advisory group(s) in this repository's dependencies " f"that `{cfg['config_name']}` does not cover and no open follow-up issue lists yet " f"(commit `{cfg['sha'][:10]}`, [run]({cfg['run_url']}))." ) by_pkg_lines: "OrderedDict[str, list[str]]" = OrderedDict() for g in gs: p = g["packages"][0] prev = next((previous[a] for a in g["aliases"] if a in previous), None) by_pkg_lines.setdefault(f"{p['name']} ({p['ecosystem']})", []).append(advisory_block(g, prev)) parts = [head] for pkg, blocks in by_pkg_lines.items(): parts.append(f"### {pkg}\n\n" + "\n\n".join(blocks)) body = "\n\n".join(parts) tail = "\n\n" + scan_instructions(cfg["mention"], cfg["context"], cfg["config_name"], cfg["base"], cfg["days"]) tail += "\n\n" + marker(ISSUE_MARKER, sorted({a for g in gs for a in g["aliases"]})) if len(body) + len(tail) > BODY_LIMIT: body = body[: BODY_LIMIT - len(tail) - 200] + "\n\n_(list truncated: see the run log for the rest)_" if cfg["dry_run"]: log(f"\n===== issue (dry run): {title}\n{body}{tail}\n=====") res = gitea.create_issue(title[:250], body + tail, labels) log(f"Opened issue #{res.get('number')}: {res.get('html_url')}") created.append(res) for res in created: discord(f"{cfg['repo']}: osv-scanner follow-up issue #{res.get('number')} opened", str(res.get("html_url", ""))) def git(*args: str, check: bool = True, env_extra: dict | None = None) -> str: e = dict(os.environ) if env_extra: e.update(env_extra) proc = subprocess.run(["git", *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=e) if check and proc.returncode != 0: raise RuntimeError(f"git {args[0]} failed: {proc.stderr.strip()[:500]}") return proc.stdout.strip() def push_branch(cfg: dict, gitea: Gitea, branch: str) -> None: """Push with the bot token through GIT_ASKPASS (never in argv or the remote URL), with checkout's own Authorization header switched off.""" server = cfg["server"].rstrip("/") user = gitea.login() or cfg["bot_name"] with tempfile.TemporaryDirectory() as tmp: askpass = Path(tmp) / "askpass.sh" askpass.write_text('#!/bin/sh\ncase "$1" in Username*) printf %s "$OSV_GIT_USER";; *) printf %s "$OSV_GIT_TOKEN";; esac\n') askpass.chmod(0o700) url = f"{server}/{cfg['repo']}.git" git( "-c", f"http.{server}/.extraheader=", "-c", "credential.helper=", "push", url, f"HEAD:refs/heads/{branch}", env_extra={"GIT_ASKPASS": str(askpass), "GIT_TERMINAL_PROMPT": "0", "OSV_GIT_USER": user, "OSV_GIT_TOKEN": cfg["token"]}, ) def do_recheck(gitea: Gitea, cfg: dict) -> None: config: Path = cfg["config"] entries = read_ignores(config) if not entries: log(f"{cfg['config_name']} has no [[IgnoredVulns]] entries: nothing to re-check.") return # Scan with no ignores at all, to see which entries still match a dependency. with tempfile.NamedTemporaryFile("w", suffix=".toml", delete=False) as empty: empty.write("# no ignores: osv-followup recheck\n") try: groups = collect(run_osv(Path(empty.name), cfg["path"], cfg["extra"]), cfg["root"]) finally: Path(empty.name).unlink(missing_ok=True) matched: dict[str, dict] = {} for g in groups.values(): for a in g["aliases"]: matched[a] = g stale = [e for e in entries if e["id"] not in matched] live = [e for e in entries if e["id"] in matched] log(f"{len(entries)} entr{'y' if len(entries) == 1 else 'ies'}: {len(live)} still match a dependency, {len(stale)} do not") for e in entries: g = matched.get(e["id"]) where = ", ".join(f"{p['name']}@{p['version']}" for p in g["packages"]) if g else "no dependency matches" log(f" {e['id']:<22} {where}") labels = gitea.label_ids(cfg["labels"]) prune_note = "" if stale: pulls = gitea.open_pulls() mine = [p for p in pulls if str((p.get("head") or {}).get("ref", "")).startswith(PRUNE_BRANCH_PREFIX)] if mine: log(f"Prune PR already open: #{mine[0]['number']} — not opening another") prune_note = f"\nEntries for advisories that no longer match any dependency are being removed in #{mine[0]['number']}; leave those alone.\n" else: original = config.read_text() updated = remove_entries(original, {e["id"] for e in stale}) left = {e["id"] for e in read_ignores_text(updated)} if left != {e["id"] for e in live}: raise RuntimeError(f"pruning {cfg['config_name']} went wrong: kept {sorted(left)}") branch = f"{PRUNE_BRANCH_PREFIX}{today().isoformat()}" title = f"osv-scanner.toml: remove {len(stale)} entr{'y' if len(stale) == 1 else 'ies'} no dependency matches" listing = "\n".join(f"- `{e['id']}` — {e['reason'] or '(no reason)'}" for e in stale) body = ( f"osv-scanner {cfg['osv_version']}, run on `{cfg['sha'][:10]}` without any ignores, no longer reports " f"these advisories for any dependency of this repository, so their `{cfg['config_name']}` entries do " f"nothing ([run]({cfg['run_url']})). Removed by the monthly re-check (deterministic, no LLM):\n\n{listing}\n\n" f"If one of them is still needed (an advisory database glitch), close this PR." ) if cfg["dry_run"]: log(f"\n===== prune PR (dry run): {title}\n{body}\n----- diff") import difflib sys.stdout.writelines(difflib.unified_diff(original.splitlines(True), updated.splitlines(True), "a/" + cfg["config_name"], "b/" + cfg["config_name"])) log("=====") else: git("config", "user.name", cfg["bot_name"]) git("config", "user.email", cfg["bot_email"]) git("checkout", "-B", branch) config.write_text(updated) git("add", str(config)) git("commit", "-m", title, "-m", "No dependency matches:\n" + "\n".join(f"- {e['id']}" for e in stale)) push_branch(cfg, gitea, branch) pr = gitea.create_pull(title, body, branch, cfg["base"], labels) log(f"Opened prune PR #{pr.get('number')}: {pr.get('html_url')}") discord(f"{cfg['repo']}: osv-scanner.toml prune PR #{pr.get('number')}", str(pr.get("html_url", ""))) prune_note = f"\nEntries no dependency matches any more are removed in #{pr.get('number')} (not listed here).\n" if not live: return existing = [i for i in gitea.open_issues(RECHECK_MARKER) if f"