8 Commits
Author SHA1 Message Date
janhouse 7827c60fb8 scan: run cyclonedx-cli with invariant globalization (no libicu on some runners -> exit 134) 2026-11-20 11:04:49 +02:00
janhouse 313da60c78 README, osv-followup: point the examples at v2.4.1 2026-11-19 18:32:58 +02:00
janhouse f6a5ec2331 osv-followup: PRs from osv/ branches (the runner deletes its claude/ branch at the end of a run) 2026-11-19 18:32:46 +02:00
janhouse d133a60b0b osv-followup: link the run by its id (Gitea run URLs use the id, not the number) 2026-11-19 18:12:39 +02:00
janhouse 5a7bade11c osv-followup: survive label-less API answers and an existing prune branch 2026-11-19 17:40:03 +02:00
janhouse 7f264b64fa osv-followup: weekly osv-scanner issues for Claude, monthly osv-scanner.toml re-check
Composite action next to scan: osv-scanner (pinned + sha256) over every lockfile with --config osv-scanner.toml; advisories no open osv-followup issue lists go into one @claude issue (fix or an entry with a code-specific reason, one PR); monthly, a deterministic PR removes entries no dependency matches and an osv-recheck issue asks Claude to re-verify the rest.
2026-11-19 17:38:37 +02:00
janhouse 0e5054f5d0 scan, vex: pass collected files through disk, not argv
A 230-statement VEX file (234 KB) made jq fail with 'Argument list too long'
(--argjson of the accumulated array). Each file is now one JSON object in an
ndjson file, slurped into the report.
2026-11-19 12:49:32 +02:00
janhouse 2b4b140200 scan: report .vex/ files and print VEX re-checks; vex: action for the central VEX repo
dtrack-panel now applies OpenVEX / CycloneDX VEX files as well as
osv-scanner.toml [[IgnoredVulns]], and sends a statement's findings back to
IN_TRIAGE when its review date passes, the package version moves on, or the
CVE turns KEV. scan sends .vex/**/*.json with the report and turns the
panel's answer into job annotations (re-check due, review date within 14
days, skipped statements). vex/ posts a whole repo's VEX files to
/panel-ci/vex for statements about third-party images.
2026-11-19 10:55:07 +02:00
6 changed files with 1099 additions and 14 deletions

No files matched your search

+127 -2
View File
@@ -38,6 +38,131 @@ reports to dtrack-panel which images the repo builds and its
`osv-scanner.toml` `[[IgnoredVulns]]`. The panel's auto-triage then marks
those NOT_AFFECTED in Dependency-Track — for the CI project and for the app's
own dependency tree in the running images — and closes CI-project findings for
dependencies that never reach the image (dev/build-time). Inputs and an example
are in `scan/action.yml`. Authenticates with the same
dependencies that never reach the image (dev/build-time). VEX files under
`.vex/` (OpenVEX or CycloneDX VEX, `*.json`) are reported too. Inputs and an
example are in `scan/action.yml`. Authenticates with the same
`DEPENDENCY_TRACK_API_KEY` the upload uses; no extra secret.
Every decision holds for the package versions present when it was written,
until its `ignoreUntil` / `review_by` (default 90 days after it was added or
last changed), and while the CVE is not known-exploited (CISA KEV). Then the
panel reopens the findings (IN_TRIAGE) and the job log warns "VEX re-check
due". Re-check; editing the entry (e.g. a new `ignoreUntil`) re-confirms it.
## `vex` — the central VEX repo
`uses: https://git.janhouse.lv/janhouse/sbom-tools-action/[email protected]` posts every
`*.json` under `vex/` (OpenVEX or CycloneDX VEX) to dtrack-panel
(`/panel-ci/vex`): statements about third-party images and packages, applied
to the images they name, or wherever the package appears. The repo's complete
set each run; a removed statement withdraws its decisions. A rejected file
(invalid JSON, `not_affected` without justification or reason) fails the job.
## `osv-followup` — weekly advisories to Claude, monthly re-check (v2.4.1)
`uses: https://git.janhouse.lv/janhouse/sbom-tools-action/[email protected]`
is the follow-up half of `scan`: `scan` reports, `osv-followup` gets every
advisory decided.
- **Weekly (`scan`).** osv-scanner (pinned version + sha256) scans every
lockfile in the repo (`bun.lock`, `go.mod`, `requirements.txt`, ...) with
`--config osv-scanner.toml`, so one file at the root covers them all.
Advisories that the file does not cover and that no **open** issue labelled
`osv-followup` lists (hidden `<!-- osv-followup: ids -->` marker, every
alias counts) go into one new issue: per advisory the summary, severity,
package, version, lockfile and fixed versions, then a `@claude` request
with the repo's `context`. Claude (gitea-claude-bot → gitea-claude-runner)
either upgrades to a fixed version (within the repo's rules: CLAUDE.md,
AGENTS.md, FORK.md, bunfig `minimumReleaseAge`) or adds an entry whose
`reason` names the code and why it is safe, and opens one PR that closes the
issue. Nothing is merged automatically. An issue closed without its PR
being merged comes back the next week: the way to silence an advisory is an
entry, never closing the issue.
- **Monthly (`recheck`).** osv-scanner runs again with **no** ignores. Entries
whose advisory no longer matches any dependency are removed in a PR from
`osv/prune-<date>` (line-based, the rest of the file and its comments stay;
re-parsed before pushing; pushed with the token through `GIT_ASKPASS`).
The remaining entries go into one `osv-recheck` issue asking `@claude` to
verify each reason against today's code, refresh `ignoreUntil` on the ones
that still hold, rewrite inaccurate ones and remove the ones that no longer
hold. Neither is opened twice while one is open.
- `group-by: run` (default) puts all new advisories of a run in one issue:
one Claude run, one PR, no `osv-scanner.toml` merge conflicts between PRs.
`group-by: package` opens one issue per package (parallel PRs that each
append to the file will conflict).
### Entry format
```toml
# --- better-auth ---
# CVE-2026-110861
[[IgnoredVulns]]
id = "GHSA-44jh-23m7-hpcf"
ignoreUntil = 2027-02-17
reason = "code_not_reachable: only database-stored rate-limit records race; server/auth.ts keeps them in memory (no storage, no secondaryStorage)."
```
`reason` starts 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`), which
dtrack-panel maps to the Dependency-Track analysis. `ignoreUntil` (90 days
by default) is read by both osv-scanner and dtrack-panel: when it passes,
the panel reopens the findings and the weekly scan reports the advisory as
new (with the old reason quoted), so an entry nobody re-confirms expires
instead of hiding an advisory forever. osv-scanner 2.7 prints a deprecation
warning for `ignoreUntil` (its new name is `effectiveUntil`); keep
`ignoreUntil` until dtrack-panel reads the new key.
### Consumer workflow
```yaml
name: Security
on:
schedule:
- cron: '17 5 * * 1' # weekly: new advisories (Monday 05:17 UTC)
- cron: '47 6 1 * *' # monthly: re-check osv-scanner.toml (the 1st, 06:47 UTC)
workflow_dispatch:
inputs:
recheck:
description: Re-check osv-scanner.toml instead of scanning
type: boolean
default: false
dry_run:
description: Print instead of opening issues / PRs
type: boolean
default: false
concurrency:
group: security
cancel-in-progress: false
jobs:
osv:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: https://git.janhouse.lv/janhouse/sbom-tools-action/[email protected]
with:
mode: ${{ (inputs.recheck == true || inputs.recheck == 'true') && 'recheck' || 'auto' }}
recheck-cron: '47 6 1 * *'
dry-run: ${{ inputs.dry_run == true || inputs.dry_run == 'true' }}
token: ${{ secrets.DEPS_BOT_TOKEN }}
discord-webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
context: >-
What the app is, how and where it runs, what is exposed to whom,
which parts are build/test-only, and repo-specific rules.
```
`mode: auto` tells the two crons apart by `github.event.schedule`; when the
Gitea version sends none, a scheduled run on the 1st at or after
`recheck-hour` (default 6) UTC is the re-check, so keep the weekly cron
before 06:00 UTC and the monthly one after it, on different hours.
Requirements: the token's account (`bot`, `DEPS_BOT_TOKEN`) has write access
to the repo, and the repo is in gitea-claude-bot's allowlist (the bot only
acts on `@claude` from writers). The runner may not edit `.gitea/workflows`
or `.claude/`, so a fix that needs a workflow change ends as a comment.
Local test: `OSV_OFFLINE=1 DRY_RUN=true MODE=scan SERVER_URL=https://git.janhouse.lv REPOSITORY=owner/repo OSV_SCANNER=/path/to/osv-scanner python3 -I osv-followup/followup.py`
in the repo prints the issue it would open without talking to Gitea.
Binary file not shown.
+151
View File
@@ -0,0 +1,151 @@
name: 'osv-scanner follow-ups'
description: >
osv-scanner over the repo's lockfiles. Weekly (scan): advisories that
osv-scanner.toml does not cover and no open follow-up issue lists get an
issue asking @claude for a pull request with a fix or an osv-scanner.toml
entry whose reason names the code. Monthly (recheck): a pull request removes
entries no dependency matches any more (deterministic), and an @claude issue
asks for the remaining reasons to be re-verified.
author: 'janhouse'
# Usage (a repo's .gitea/workflows/security.yml; full example in README.md):
#
# on:
# schedule:
# - cron: '17 5 * * 1' # weekly scan
# - cron: '47 6 1 * *' # monthly re-check
# workflow_dispatch:
# inputs:
# recheck: {type: boolean, default: false}
# jobs:
# osv:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4
# - uses: https://git.janhouse.lv/janhouse/sbom-tools-action/[email protected]
# with:
# mode: ${{ (inputs.recheck == true || inputs.recheck == 'true') && 'recheck' || 'auto' }}
# recheck-cron: '47 6 1 * *'
# token: ${{ secrets.DEPS_BOT_TOKEN }}
# discord-webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
# context: >-
# What the app is, how it runs, what is exposed.
#
# The token's account (the `bot` account behind DEPS_BOT_TOKEN) opens the
# issues, so gitea-claude-bot dispatches gitea-claude-runner for them: it
# needs write access to the repository, and the repository must be in the
# bot's allowlist. Issues carry the label `osv-followup` (dedupe) and a
# hidden `<!-- osv-followup: ids -->` marker; an advisory listed in any OPEN
# follow-up issue is not reported again.
inputs:
mode:
description: >
scan, recheck, or auto: on a schedule, recheck when github.event.schedule
equals recheck-cron (or, when Gitea sends no schedule, on the 1st of the
month at or after recheck-hour UTC), otherwise scan; any other event scans.
default: 'auto'
recheck-cron:
description: 'The monthly cron line of the calling workflow (auto mode)'
default: ''
recheck-hour:
description: 'auto mode without github.event.schedule: a run on the 1st at or after this UTC hour is the re-check'
default: '6'
token:
description: 'Token of the account that opens issues and the prune PR (secrets.DEPS_BOT_TOKEN)'
required: true
context:
description: 'What the repository is, how it runs and what is exposed: quoted to Claude in every issue'
required: true
labels:
description: 'Labels for follow-up issues, comma separated (osv-followup is always added)'
default: 'security,osv-followup'
mention:
description: 'Account to @-mention'
default: 'claude'
base-branch:
description: 'Branch the pull requests target'
default: 'main'
path:
description: 'Directory to scan (recursively)'
default: '.'
config:
description: 'osv-scanner config, relative to the repo root; passed with --config, so it covers every lockfile'
default: 'osv-scanner.toml'
group-by:
description: 'run: one issue per scan (one Claude run, one PR: no osv-scanner.toml conflicts); package: one issue per package'
default: 'run'
ignore-days:
description: 'ignoreUntil Claude sets on new or re-confirmed entries, in days from today'
default: '90'
extra-args:
description: 'Extra osv-scanner arguments (space separated), e.g. --experimental-exclude=fixtures'
default: ''
osv-scanner-version:
default: 'v2.7.1'
osv-scanner-sha256:
description: 'sha256 of osv-scanner_linux_amd64 for osv-scanner-version (from its osv-scanner_SHA256SUMS)'
default: 'fb7dab19a8bd9bbe5c3189f09d4b7ee1820c9553a23bac202648a56efd2f6ee8'
bot-name:
description: 'git author of the prune commit'
default: 'bot'
bot-email:
default: '[email protected]'
discord-webhook-url:
description: 'Optional: a Discord notice for every issue / PR opened'
default: ''
dry-run:
description: 'Print the issues and the prune diff instead of creating them (reads still use the token)'
default: 'false'
runs:
using: composite
steps:
- name: Install osv-scanner
shell: bash
env:
OSV_VERSION: ${{ inputs.osv-scanner-version }}
OSV_SHA256: ${{ inputs.osv-scanner-sha256 }}
run: |
set -euo pipefail
d="$RUNNER_TEMP/osv-followup-bin"; mkdir -p "$d"
curl -sSfL --connect-timeout 20 --max-time 300 --retry 3 --retry-all-errors \
"https://github.com/google/osv-scanner/releases/download/${OSV_VERSION}/osv-scanner_linux_amd64" -o "$d/osv-scanner"
echo "${OSV_SHA256} $d/osv-scanner" | sha256sum -c -
chmod +x "$d/osv-scanner"
"$d/osv-scanner" --version | head -1
echo "OSV_SCANNER=$d/osv-scanner" >> "$GITHUB_ENV"
- name: osv-scanner follow-ups
shell: bash
env:
MODE: ${{ inputs.mode }}
RECHECK_CRON: ${{ inputs.recheck-cron }}
RECHECK_HOUR: ${{ inputs.recheck-hour }}
EVENT_NAME: ${{ github.event_name }}
EVENT_SCHEDULE: ${{ github.event.schedule }}
TOKEN: ${{ inputs.token }}
CONTEXT: ${{ inputs.context }}
LABELS: ${{ inputs.labels }}
MENTION: ${{ inputs.mention }}
BASE_BRANCH: ${{ inputs.base-branch }}
SCAN_PATH: ${{ inputs.path }}
CONFIG: ${{ inputs.config }}
GROUP_BY: ${{ inputs.group-by }}
IGNORE_DAYS: ${{ inputs.ignore-days }}
EXTRA_ARGS: ${{ inputs.extra-args }}
OSV_VERSION: ${{ inputs.osv-scanner-version }}
BOT_NAME: ${{ inputs.bot-name }}
BOT_EMAIL: ${{ inputs.bot-email }}
DISCORD_WEBHOOK_URL: ${{ inputs.discord-webhook-url }}
DRY_RUN: ${{ inputs.dry-run }}
SERVER_URL: ${{ github.server_url }}
REPOSITORY: ${{ github.repository }}
SHA: ${{ github.sha }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
ACTION_DIR: ${{ github.action_path }}
run: |
set -euo pipefail
dir="${GITHUB_ACTION_PATH:-$ACTION_DIR}"
git config --global --add safe.directory "$PWD"
python3 -I "$dir/followup.py"
+723
View File
@@ -0,0 +1,723 @@
#!/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" # <!-- osv-followup: ID ID ... -->
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")},
)
if isinstance(created, dict) and created.get("id"):
existing[name] = created["id"]
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 <pkg>` / the lockfile, `go mod why -m <module>`, `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 `# --- <package> ---` 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: <which code, which dependency path, and why the vulnerable part is never used>"
```
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 from a branch named `osv/issue-<this issue's number>`, created from `{base}` (`git checkout -b osv/issue-<n> origin/{base}`). Do not use the `claude/issue-…` branch the runner checked out: its end-of-run cleanup deletes that branch, which closes a PR made from it. Commit, push, then create the PR against `{base}` (`mcp__local_git_ops__create_pull_request`). Its body starts with `Closes #<this issue's number>` 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 from a branch named `osv/recheck-<this issue's number>`, created from `{base}` (not the runner's `claude/issue-…` branch: its end-of-run cleanup deletes it, which closes a PR made from it), PR against `{base}` (`mcp__local_git_ops__create_pull_request`), body starting with `Closes #<this issue's number>` 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"<!-- {kind}: {' '.join(ids)} -->"
def known_ids(issues: list[dict]) -> set[str]:
seen: set[str] = set()
pat = re.compile(r"<!--\s*" + ISSUE_MARKER + r":\s*([^>]*?)\s*-->")
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:
sub = next((a for i, a in enumerate(args) if not a.startswith("-") and (i == 0 or args[i - 1] != "-c")), "?")
raise RuntimeError(f"git {sub} 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))
try:
push_branch(cfg, gitea, branch)
except RuntimeError as e:
# A branch of that name exists already (an earlier, closed PR today).
warn(f"push to {branch} failed ({e}); retrying under a new name")
branch = f"{branch}-{dt.datetime.now(dt.UTC).strftime('%H%M%S')}"
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"<!-- {RECHECK_MARKER}" in (i.get("body") or "")]
if existing:
log(f"Re-check issue already open: #{existing[0]['number']} — not opening another")
return
rows = []
for e in live:
g = matched[e["id"]]
pk = ", ".join(f"`{p['name']}@{p['version']}` (`{p['source']}`)" for p in g["packages"])
rows.append(
f"#### {osv_link(e['id'])}" + (f" ({', '.join(g['cves'])})" if g["cves"] else "")
+ f"\n\n- **Advisory:** {g['summary'] or '(none)'}\n- **Severity:** {g['severity']}\n- **Matches:** {pk}"
+ f"\n- **Fixed in:** {', '.join(f'`{f}`' for f in g['fixed']) if g['fixed'] else 'no fixed version published'}"
+ f"\n- **ignoreUntil:** {e['until'] or '(none)'}\n- **Reason:** {e['reason'] or '(none)'}"
)
title = f"osv-scanner.toml: monthly re-check of {len(live)} entr{'y' if len(live) == 1 else 'ies'} ({today().strftime('%Y-%m')})"
body = (
f"The monthly re-check of `{cfg['config_name']}` (commit `{cfg['sha'][:10]}`, [run]({cfg['run_url']})). "
f"These entries still match a dependency:\n\n" + "\n\n".join(rows)
)
tail = "\n\n" + recheck_instructions(cfg["mention"], cfg["context"], cfg["config_name"], cfg["base"], cfg["days"], prune_note)
tail += "\n\n" + marker(RECHECK_MARKER, [e["id"] for e in live])
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===== recheck issue (dry run): {title}\n{body}{tail}\n=====")
recheck_labels = gitea.label_ids([lab for lab in cfg["labels"] if lab != ISSUE_MARKER] + [RECHECK_MARKER])
res = gitea.create_issue(title, body + tail, recheck_labels)
log(f"Opened re-check issue #{res.get('number')}: {res.get('html_url')}")
discord(f"{cfg['repo']}: osv-scanner.toml re-check issue #{res.get('number')}", str(res.get("html_url", "")))
def read_ignores_text(text: str) -> list[dict]:
with tempfile.NamedTemporaryFile("w", suffix=".toml", delete=False) as f:
f.write(text)
try:
return read_ignores(Path(f.name))
finally:
Path(f.name).unlink(missing_ok=True)
def pick_mode() -> str:
mode = env("MODE", "auto").lower()
if mode in ("scan", "recheck"):
return mode
if mode != "auto":
raise RuntimeError(f"unknown mode {mode!r} (scan, recheck, auto)")
if env("EVENT_NAME") != "schedule":
return "scan"
sched, recheck_cron = env("EVENT_SCHEDULE"), env("RECHECK_CRON")
if sched and recheck_cron:
return "recheck" if sched == recheck_cron else "scan"
# No github.event.schedule: the monthly cron runs on the 1st at or after
# RECHECK_HOUR (UTC), the weekly one before it.
now = dt.datetime.now(dt.UTC)
hour = int(env("RECHECK_HOUR", "6") or 6)
return "recheck" if now.day == 1 and now.hour >= hour else "scan"
def main() -> int:
root = Path.cwd().resolve()
config_name = env("CONFIG", "osv-scanner.toml")
cfg = {
"root": root,
"server": env("SERVER_URL"),
"repo": env("REPOSITORY"),
"token": env("TOKEN"),
"sha": env("SHA") or git("rev-parse", "HEAD", check=False),
"run_url": env("RUN_URL"),
"context": " ".join(env("CONTEXT").split()) or "(no context given)",
"labels": [s.strip() for s in env("LABELS", f"security,{ISSUE_MARKER}").split(",") if s.strip()],
"mention": env("MENTION", "claude").lstrip("@"),
"base": env("BASE_BRANCH", "main"),
"path": env("SCAN_PATH", "."),
"config": (root / config_name),
"config_name": config_name,
"group_by": env("GROUP_BY", "run"),
"days": int(env("IGNORE_DAYS", "90") or 90),
"extra": env("EXTRA_ARGS").split(),
"osv_version": env("OSV_VERSION", "?"),
"bot_name": env("BOT_NAME", "bot"),
"bot_email": env("BOT_EMAIL", "[email protected]"),
"dry_run": flag("DRY_RUN"),
}
if ISSUE_MARKER not in cfg["labels"]:
cfg["labels"].append(ISSUE_MARKER) # dedupe relies on it
if not cfg["server"] or not cfg["repo"]:
raise RuntimeError("SERVER_URL and REPOSITORY are required")
if not cfg["token"] and not cfg["dry_run"]:
raise RuntimeError("TOKEN is required (the bot account's token, e.g. secrets.DEPS_BOT_TOKEN)")
gitea = Gitea(cfg["server"], cfg["repo"], cfg["token"], cfg["dry_run"])
mode = pick_mode()
log(f"mode: {mode}{' (dry run)' if cfg['dry_run'] else ''}; repo {cfg['repo']}; config {config_name}"
f" ({'present' if cfg['config'].is_file() else 'absent'})")
if cfg["config"].is_file():
read_ignores(cfg["config"]) # fail early on a broken file
(do_recheck if mode == "recheck" else do_scan)(gitea, cfg)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except RuntimeError as err:
print(f"::error::{err}", flush=True)
sys.exit(1)
+30 -12
View File
@@ -15,12 +15,16 @@ author: 'janhouse'
# dtrack-url: ${{ secrets.DEPENDENCY_TRACK_URL }}
# dtrack-api-key: ${{ secrets.DEPENDENCY_TRACK_API_KEY }}
#
# osv-scanner.toml [[IgnoredVulns]] are NOT_AFFECTED decisions: dtrack-panel
# writes them to Dependency-Track for this repo's own dependencies (the CI
# project, and the app's dependency tree in the images). A reason may start
# with a CycloneDX justification: "code_not_reachable: we never parse XML".
# They don't expire unless ignoreUntil says so — re-check them when the code
# that uses the package changes (see the repo's AGENTS.md).
# osv-scanner.toml [[IgnoredVulns]] and VEX files under .vex/ (OpenVEX or
# CycloneDX VEX, *.json) are NOT_AFFECTED decisions: dtrack-panel writes them
# to Dependency-Track for this repo's own dependencies (the CI project, and
# the app's dependency tree in the images), or for the images a VEX statement
# names. A reason may start with a CycloneDX justification:
# "code_not_reachable: we never parse XML". Each holds for the package
# versions present when it was written, until ignoreUntil / review_by
# (default 90 days after it was added or last changed), and while the CVE is
# not known-exploited; then the panel reopens the findings for a re-check —
# editing the entry re-confirms it (see the repo's AGENTS.md / CLAUDE.md).
inputs:
project:
@@ -100,6 +104,10 @@ runs:
CONTAINER_IMAGE: ${{ inputs.container-image }}
CONTAINER_SKIP: ${{ inputs.container-skip-files }}
TRIVY_TIMEOUT: ${{ inputs.trivy-timeout }}
# cyclonedx-cli is .NET: without libicu on the runner (gamer) it aborts with
# "Couldn't find a valid ICU package" (exit 134). It only merges JSON, so
# invariant globalization is all it needs.
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "1"
run: |
set -euo pipefail
trivy fs "$SCAN_PATH" --quiet --timeout "$TRIVY_TIMEOUT" --format cyclonedx --output source-sbom.json
@@ -141,7 +149,7 @@ runs:
# analysis runs when the Go toolchain is on the runner.
osv-scanner scan source -r "$SCAN_PATH" --format table || true
- name: Report to dtrack-panel (images + osv-scanner.toml)
- name: Report to dtrack-panel (images + osv-scanner.toml + .vex/)
shell: bash
continue-on-error: true
env:
@@ -157,15 +165,25 @@ runs:
set -euo pipefail
url=${PANEL_URL:-${DTRACK_URL%/}/panel-ci/report}
images=$(printf '%s' "$IMAGES" | tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | { grep -v '^$' || true; } | jq -R . | jq -s .) # no images is fine
tomls='[]'
# Files go through disk, never argv (a big VEX file blows the limit).
: > tomls.ndjson
while IFS= read -r f; do
tomls=$(jq --arg p "$f" --rawfile c "$f" '. + [{path: $p, content: $c}]' <<<"$tomls")
jq -n --arg p "$f" --rawfile c "$f" '{path: $p, content: $c}' >> tomls.ndjson
done < <(find "$SCAN_PATH" -name osv-scanner.toml -not -path '*/node_modules/*' -not -path '*/.git/*' | head -20)
: > vex.ndjson
while IFS= read -r f; do
jq -n --arg p "$f" --rawfile c "$f" '{path: $p, content: $c}' >> vex.ndjson
done < <(find "$SCAN_PATH" -path '*/.vex/*' -name '*.json' -not -path '*/node_modules/*' -not -path '*/.git/*' | sort | head -200)
jq -n --arg repo "$REPO" --arg commit "$COMMIT" --arg project "$PROJECT" \
--argjson images "$images" --argjson tomls "$tomls" \
'{repo: $repo, commit: $commit, project: $project, images: $images, osvScannerToml: $tomls}' > report.json
echo "Reporting $(jq '.images | length' report.json) image(s), $(jq '.osvScannerToml | length' report.json) osv-scanner.toml file(s) to ${url}"
--argjson images "$images" --slurpfile tomls tomls.ndjson --slurpfile vex vex.ndjson \
'{repo: $repo, commit: $commit, project: $project, images: $images, osvScannerToml: $tomls, vexFiles: $vex}' > report.json
echo "Reporting $(jq '.images | length' report.json) image(s), $(jq '.osvScannerToml | length' report.json) osv-scanner.toml file(s), $(jq '.vexFiles | length' report.json) VEX file(s) to ${url}"
curl -fsS -X POST "$url" -H "X-Api-Key: ${DTRACK_API_KEY}" -H "Content-Type: application/json" \
--data-binary @report.json -o response.json
jq -r '.vex // empty | "VEX statements: \(.statements) (\(.added) new, \(.changed) changed, \(.removed) removed)"' response.json || true
jq -r '.vex.skipped[]? | "::notice file=\(.path)::\(.id) skipped: \(.why)"' response.json || true
# Statements that need a re-check: their findings are back IN_TRIAGE.
jq -r '.reviewDue[]? | "::warning::VEX re-check due — \(.vulnId) in \(.package) (\(.image)): \(.detail)"' response.json || true
jq -r '.expiringSoon[]? | "::notice file=\(.path)::\(.vulnId): review date \(.reviewBy[0:10]) is within 14 days"' response.json || true
echo "Applied on the panel's next sync. Still open (not triaged):"
jq -r '.open[] | " \(.project): \(.n) \(.severity)"' response.json || true
+68
View File
@@ -0,0 +1,68 @@
name: 'VEX statements to dtrack-panel'
description: >
Post every OpenVEX / CycloneDX VEX file of a repo (the central VEX repo) to
dtrack-panel, which applies them as NOT_AFFECTED decisions in
Dependency-Track: to the images a statement names, or wherever the package
appears. The repo's complete set each time — a removed file or statement
withdraws its decisions.
author: 'janhouse'
# Usage (janhouse/vex .gitea/workflows/vex.yml, on push to main + weekly):
# - uses: actions/checkout@v4
# - uses: https://git.janhouse.lv/janhouse/sbom-tools-action/[email protected]
# with:
# dtrack-url: ${{ secrets.DEPENDENCY_TRACK_URL }}
# dtrack-api-key: ${{ secrets.DEPENDENCY_TRACK_API_KEY }}
inputs:
dtrack-url:
description: 'Dependency-Track base URL (the panel answers on <dtrack-url>/panel-ci/)'
required: true
dtrack-api-key:
description: 'Dependency-Track API key that may upload BOMs (authenticates the report)'
required: true
panel-url:
description: 'dtrack-panel VEX URL (default: <dtrack-url>/panel-ci/vex)'
required: false
default: ''
path:
description: 'Directory to collect *.json VEX files from'
required: false
default: 'vex'
runs:
using: 'composite'
steps:
- name: Post VEX statements
shell: bash
env:
DTRACK_URL: ${{ inputs.dtrack-url }}
DTRACK_API_KEY: ${{ inputs.dtrack-api-key }}
PANEL_URL: ${{ inputs.panel-url }}
VEX_PATH: ${{ inputs.path }}
REPO: ${{ github.repository }}
COMMIT: ${{ github.sha }}
run: |
set -euo pipefail
url=${PANEL_URL:-${DTRACK_URL%/}/panel-ci/vex}
# One JSON object per file on disk (never as an argument: a big VEX
# file blows the argv limit), slurped into the report.
: > vex-files.ndjson
while IFS= read -r f; do
jq -n --arg p "$f" --rawfile c "$f" '{path: $p, content: $c}' >> vex-files.ndjson
done < <(find "$VEX_PATH" -name '*.json' -not -path '*/.git/*' | sort | head -500)
jq -n --arg repo "$REPO" --arg commit "$COMMIT" --slurpfile files vex-files.ndjson \
'{repo: $repo, commit: $commit, files: $files}' > vex-report.json
echo "Posting $(jq '.files | length' vex-report.json) VEX file(s) to ${url}"
# -f: a rejected file (bad JSON, no justification) fails the job.
code=$(curl -sS -o response.json -w '%{http_code}' -X POST "$url" \
-H "X-Api-Key: ${DTRACK_API_KEY}" -H "Content-Type: application/json" \
--data-binary @vex-report.json)
if [ "$code" != 200 ]; then
echo "::error::dtrack-panel answered HTTP $code: $(jq -r '.message // .' response.json 2>/dev/null || cat response.json)"
exit 1
fi
jq -r '.vex | "VEX statements: \(.statements) (\(.added) new, \(.changed) changed, \(.removed) removed)"' response.json
jq -r '.vex.skipped[]? | "::notice file=\(.path)::\(.id) skipped: \(.why)"' response.json || true
jq -r '.reviewDue[]? | "::warning::VEX re-check due — \(.vulnId) in \(.package) (\(.image)): \(.detail)"' response.json || true
jq -r '.expiringSoon[]? | "::notice file=\(.path)::\(.vulnId): review date \(.reviewBy[0:10]) is within 14 days"' response.json || true