onionwire/scripts/arti-watch.py

279 lines
11 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Watch upstream Arti / tor-* releases against OnionWire's Cargo.toml pins.
Runs from .forgejo/workflows/arti-watch.yml (daily cron + workflow_dispatch) on
the self-hosted Forgejo runner. For every `tor-*` / `arti-*` direct dependency
it reads the version requirement in Cargo.toml, asks crates.io for the newest
published versions, and — when the major.minor moved — files ONE Forgejo issue.
The issue title carries the compared pair, e.g.
Arti upstream: tor-hsservice 0.46 -> 0.47
Dedupe is on that title across all issues (open and closed), so a second run is
a no-op: no duplicate issue, no repeated comment. Nothing here bumps a
dependency — that stays a reviewed PR; see docs/ARTI_UPGRADE.md.
What this does NOT cover, by design:
* It does not subscribe to Tor Project security announcements. A fix that
ships without a crates.io version bump is invisible to this script.
* It will not catch a yanked crate, and it will not catch a vulnerability in
a version that has not changed. crates.io `max_stable_version` already
ignores yanks, so a yank alone produces no alert.
Read https://blog.torproject.org/ and https://forum.torproject.org/ yourself.
Usage:
FORGEJO_TOKEN=… REPO_API=https://host/api/v1/repos/owner/repo \
scripts/arti-watch.py --cargo-toml Cargo.toml
scripts/arti-watch.py --dry-run # no API writes, no token
scripts/arti-watch.py --dry-run --simulate-pin arti-client=0.45
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
from dataclasses import dataclass
CRATES_API = "https://crates.io/api/v1/crates/{name}"
# crates.io rejects a request without a User-Agent (HTTP 403), and Cloudflare in
# front of the Forgejo API 403s (error 1010) a python-urllib one. Send our own.
USER_AGENT = "onionwire-arti-watch (+https://forgejo.siriusdevops.com/sirius/onionwire)"
WATCHED = re.compile(r"^(?:tor|arti)-[a-z0-9-]+$")
# "0.46" / "0.46.0" / "0.46.0-alpha.1" — Arti crates publish plain major.minor.patch.
SEMVER = re.compile(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$")
def log(msg: str) -> None:
print(msg, flush=True)
class HardFail(SystemExit):
def __init__(self, msg: str) -> None:
super().__init__(2)
self.msg = msg
def curl_json(url, token=None, method="GET", body=None):
"""curl a JSON endpoint. Returns (http_status, parsed_body_or_None).
curl rather than urllib: the Cloudflare front door 403s a python-urllib
User-Agent, and curl's --retry covers transient 5xx.
"""
cmd = [
"curl", "-sS", "--http1.1",
"--retry", "5", "--retry-all-errors", "--retry-delay", "3",
"--connect-timeout", "20", "--max-time", "60",
"-H", f"User-Agent: {USER_AGENT}",
"-H", "Accept: application/json",
]
if token:
cmd += ["-H", f"Authorization: Bearer {token}"]
if body is not None:
cmd += ["-H", "Content-Type: application/json",
"-X", method, "--data-binary", json.dumps(body)]
cmd += ["-w", "\n%{http_code}", url]
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
if proc.returncode != 0:
raise HardFail(f"curl exited {proc.returncode} for {method} {url}: {proc.stderr.strip()}")
raw, _, code = proc.stdout.rpartition("\n")
try:
parsed = json.loads(raw) if raw.strip() else None
except json.JSONDecodeError:
parsed = None
return int(code or 0), parsed
def ver(text: str):
"""('0.46') -> (0, 46, 0). Hard-fails on anything else, so a surprise
version format upstream is loud rather than silently 'not an upgrade'."""
m = SEMVER.match(text.strip())
if not m:
raise HardFail(f"cannot parse version {text!r}")
return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0))
def parse_pins(cargo_toml: str):
"""{crate: version_requirement} for the [dependencies] table only."""
pins: dict[str, str] = {}
section = ""
for line in cargo_toml.splitlines():
stripped = line.strip()
if stripped.startswith("["):
section = stripped.strip("[]").strip()
continue
if section != "dependencies" or not stripped or stripped.startswith("#"):
continue
m = re.match(r"^([A-Za-z0-9_-]+)\s*=\s*(.+)$", stripped)
if not m:
continue
name, rest = m.group(1), m.group(2).split("#", 1)[0].strip()
if not WATCHED.match(name):
continue
vm = re.match(r'"([^"]+)"', rest) or re.search(r'version\s*=\s*"([^"]+)"', rest)
if vm:
pins[name] = vm.group(1)
return pins
def crates_io(name: str):
"""(stable, newest) version strings for a crate, as crates.io reports them."""
status, data = curl_json(CRATES_API.format(name=name))
if status != 200 or not isinstance(data, dict) or "crate" not in data:
raise HardFail(f"crates.io GET {name} -> HTTP {status} (body: {str(data)[:200]})")
crate = data["crate"]
return crate["max_stable_version"], crate.get("newest_version") or crate["max_stable_version"]
@dataclass
class Row:
name: str
pin: str
pin_triple: tuple
stable: str
newest: str
source: str # "Cargo.toml" or "simulate-pin"
@property
def pin_minor(self) -> str:
return f"{self.pin_triple[0]}.{self.pin_triple[1]}"
@property
def upgrade(self) -> bool:
stable = ver(self.stable)
return (stable[0], stable[1]) > (self.pin_triple[0], self.pin_triple[1])
def issue_title(row: Row) -> str:
stable = ver(row.stable)
return f"Arti upstream: {row.name} {row.pin_minor} \u2192 {stable[0]}.{stable[1]}"
def issue_body(row: Row) -> str:
if row.source == "Cargo.toml":
lead = f"`{row.name}` is pinned at `{row.pin}` in `Cargo.toml`; crates.io now has **{row.stable}**."
else:
lead = (f"`{row.name}` is pinned at `{row.pin}` in the `simulate_pin` test input, "
f"**not** in `Cargo.toml`; crates.io now has **{row.stable}**. This issue came "
f"from a `workflow_dispatch` test run — the repository pin has not changed.")
return f"""{lead}
| | |
|---|---|
| crate | `{row.name}` |
| pinned requirement | `"{row.pin}"` |
| pin source | {row.source} |
| newest stable upstream | `{row.stable}` |
| newest upstream (incl. pre-release) | `{row.newest}` |
| crates.io | https://crates.io/crates/{row.name} |
| releases | https://gitlab.torproject.org/tpo/core/arti/-/releases |
Filed automatically by `.forgejo/workflows/arti-watch.yml`. This is the whole
`tor-*` / `arti-*` set moving together — Arti publishes them in lockstep, so do
not bump this one alone.
Procedure, toolchain floor, and the tests a bump must pass:
[`docs/ARTI_UPGRADE.md`](../blob/main/docs/ARTI_UPGRADE.md). Rust toolchain floor
is rustc 1.91+ (Arti 0.46); a bump may raise it.
The watcher does **not** subscribe to Tor Project security announcements, and it
cannot see a yanked crate or a vulnerability that ships without a version bump.
"""
def existing_titles(repo_api: str, token: str) -> dict:
"""{title: issue_number} over every issue, open and closed, paginated."""
seen: dict[str, int] = {}
page = 1
while True:
url = f"{repo_api}/issues?state=all&type=issues&limit=50&page={page}"
status, data = curl_json(url, token)
if status != 200 or not isinstance(data, list):
raise HardFail(f"GET {url} -> HTTP {status} (body: {str(data)[:200]})")
for item in data:
seen[item["title"]] = item["number"]
if len(data) < 50:
return seen
page += 1
def main() -> int:
ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
ap.add_argument("--cargo-toml", default="Cargo.toml")
ap.add_argument("--dry-run", action="store_true",
help="compare and log only; file no issue and need no token")
ap.add_argument("--simulate-pin", action="append", default=[], metavar="CRATE=VERSION",
help="pretend CRATE is pinned at VERSION (test the alert path "
"against real crates.io data without waiting for upstream)")
args = ap.parse_args()
with open(args.cargo_toml, encoding="utf-8") as fh:
pins = parse_pins(fh.read())
if not pins:
raise HardFail(f"no tor-*/arti-* pin found in [dependencies] of {args.cargo_toml}")
overrides = {}
for pair in args.simulate_pin:
name, _, version = pair.partition("=")
name, version = name.strip(), version.strip()
if name not in pins or not version:
raise HardFail(f"--simulate-pin {pair!r} is not a watched crate in {args.cargo_toml}")
overrides[name] = version
rows = []
for name in sorted(pins):
source = "Cargo.toml"
pin = pins[name]
if name in overrides:
pin, source = overrides[name], "simulate-pin"
pin_triple = ver(pin)
stable, newest = crates_io(name)
rows.append(Row(name, pin, pin_triple, stable, newest, source))
log(f"crates.io comparison ({len(rows)} watched crate(s) from {args.cargo_toml}):")
for row in rows:
log(f" {row.name}: pinned={row.pin} (from {row.source}) "
f"upstream_stable={row.stable} upstream_newest={row.newest} "
f"upgrade={'yes' if row.upgrade else 'no'}")
todo = [row for row in rows if row.upgrade]
if not todo:
log("no upgrade available: every pin already covers the newest upstream release")
return 0
if args.dry_run:
for row in todo:
log(f"dry-run: would file issue {issue_title(row)!r}")
return 0
repo_api = os.environ.get("REPO_API", "").rstrip("/")
token = "".join((os.environ.get("FORGEJO_TOKEN") or "").split())
if not repo_api or not token:
raise HardFail("REPO_API and FORGEJO_TOKEN are required unless --dry-run")
titles = existing_titles(repo_api, token)
filed = 0
for row in todo:
title = issue_title(row)
if title in titles:
log(f"dedupe: issue #{titles[title]} already carries the title {title!r} — not filing a second one")
continue
status, created = curl_json(f"{repo_api}/issues", token, "POST",
{"title": title, "body": issue_body(row)})
if status != 201 or not isinstance(created, dict):
raise HardFail(f"POST {repo_api}/issues -> HTTP {status} (body: {str(created)[:300]})")
filed += 1
log(f"filed issue #{created['number']}: {title} ({created.get('html_url', '')})")
log(f"done: {filed} issue(s) filed, {len(todo) - filed} already tracked")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except HardFail as exc:
log(f"error: {exc.msg}")
sys.exit(exc.code)