diff --git a/.github/workflows/advisories.yml b/.github/workflows/advisories.yml new file mode 100644 index 0000000..e4b3045 --- /dev/null +++ b/.github/workflows/advisories.yml @@ -0,0 +1,59 @@ +# Weekly advisory fetch for the libraries sillybos stands in front of. +# +# Every Monday, an hour after the Security workflow, scripts/advisories.py +# asks OSV.dev for the advisories on the watchlist (Pillow on PyPI; tiff, +# libpng1.6, libjpeg-turbo, zlib, poppler, openjpeg2 and freetype on +# Debian), drops what docs/advisories/seen.json and the existing `advisory` +# issues already know, and opens one issue per new advisory for a +# maintainer to triage. docs/advisories/README.md says how. +# +# Nothing is committed. The issues are the record of what has been seen, +# so the job needs no write access to the repository's contents and no +# bot commit on main (which the ruleset would refuse anyway); seen.json is +# the baseline a maintainer refreshes by hand with +# `python scripts/advisories.py record`. +# +# A dispatch with "dry run" ticked lists what would be opened and opens +# nothing. +name: Advisories + +on: + schedule: + - cron: "0 7 * * 1" # Mondays 07:00 UTC + workflow_dispatch: + inputs: + dry_run: + description: List the new advisories without opening issues + type: boolean + default: false + +permissions: {} + +# Two runs at once could open the same issue twice. +concurrency: + group: advisories + cancel-in-progress: false + +jobs: + fetch: + name: New advisories on the watchlist + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + + # Standard library only; nothing to install. The token reaches the + # script through the environment, never the command line. + - name: Fetch, compare and open issues + env: + GITHUB_TOKEN: ${{ github.token }} + COMMAND: ${{ inputs.dry_run == true && 'fetch' || 'run' }} + run: python scripts/advisories.py "$COMMAND" --repository "$GITHUB_REPOSITORY" --summary "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index b121157..6785f83 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,11 @@ inches wide. Nothing hostile is checked in. The readers are also checked against Pillow's reading of real files, so that they agree with the decoder they stand in front of. +A weekly job fetches the security advisories for the decoders this library +stands in front of and opens an issue for each new one; +[docs/advisories/README.md](docs/advisories/README.md) says how we triage +them. + See [CONTRIBUTING.md](CONTRIBUTING.md) for the checks and the commit style, and [SECURITY.md](SECURITY.md) for how to report a flaw privately. diff --git a/docs/advisories/README.md b/docs/advisories/README.md new file mode 100644 index 0000000..8f46aa3 --- /dev/null +++ b/docs/advisories/README.md @@ -0,0 +1,162 @@ +# Advisories: the weekly fetch and how we triage it + +sillybos stands in front of decoders it does not control. When one of them +publishes a security advisory, the question for this library is narrow: +**would a bounded header check, or what `pdfinfo`, `pdfimages -list` or +`pdffonts` report, have kept the triggering file from the decoder?** A +weekly job fetches the advisories and opens an issue for each; a +maintainer answers that question and files the issue in a bucket. This +page is the procedure. + +The November 2026 backfill of three years of advisories (138 for Pillow, +tiff, libpng1.6, libjpeg-turbo, zlib, poppler, openjpeg2 and freetype) +found about a quarter of the file-reachable ones were preventable from a +header field, and the first two checks that came out of it (JPEG frame +coding; the multi-picture walk) shipped in 1.0.0. That is why the job is +worth running. + +## What runs, and when + +The [Advisories workflow](../../.github/workflows/advisories.yml) runs +`scripts/advisories.py run` every Monday at 07:00 UTC, and on a manual +dispatch (tick *dry run* to list without opening). The script: + +1. asks [OSV.dev](https://osv.dev/) for every record it holds on the + watchlist: `pillow` on PyPI; `tiff`, `libpng1.6`, `libjpeg-turbo`, + `zlib`, `poppler`, `openjpeg2` and `freetype` on Debian; +2. drops Debian's own bulletins (`DSA-`, `DLA-`, `DTSA-`), which repeat + the per-CVE record with a release note attached, and withdrawn records; +3. merges records that describe one CVE (Pillow's GHSA and PYSEC entries, + Debian's `DEBIAN-CVE-…` record) into one advisory, keyed by the CVE; +4. drops what is already known: every key in `seen.json`, and every + identifier named in the marker of an existing `advisory` issue, open or + closed; +5. holds back a reserved CVE, one that has an id but no text yet, as + *pending*; it is listed in the run summary and checked again next week; +6. opens one issue per new advisory, from the fixed template below, with + the label `advisory` and whatever the noise filters add. + +It is standard library only and runs locally: + +```bash +python scripts/advisories.py fetch # what is new; opens nothing +python scripts/advisories.py run # the weekly job; needs GITHUB_TOKEN and --repository +python scripts/advisories.py record # fold everything published so far into seen.json +``` + +`fetch` without a token compares against `seen.json` alone; with +`GITHUB_TOKEN` and `--repository owner/name` it reads the issues too. + +## Where the state lives + +**The issues are the record.** Every issue the job opens starts with a +hidden marker naming the advisory's identifiers, and the next run reads +those markers back. Nothing is committed by the workflow: that keeps it +to `contents: read` and `issues: write`, and spares `main` a bot commit a +week, which its ruleset would refuse in any case. + +[`seen.json`](seen.json) is the baseline: every advisory on the watchlist +up to the backfill, by key, with the reserved CVEs listed as pending. It +is refreshed by hand, when the issue list has grown long enough to be +worth folding in: + +```bash +python scripts/advisories.py record +git commit -m "chore(advisories): refresh the baseline" docs/advisories/seen.json +``` + +## The buckets + +Each issue ends in one bucket, with a line saying why. The bucket is the +answer to the question at the top of this page. + +| Bucket | Meaning | What follows | +|---|---|---| +| **A** | Already refused by an existing check: a format outside the four, a frame coding the policy refuses, a size over a limit | Say which check, and close | +| **B** | Preventable from a header field our readers can see: a marker, a tag, a chunk, a count, a dimension | A policy field and a hostile corpus case (below), then close when it ships | +| **B2** | Preventable only by a coarse policy on a PDF's contents that `pdfimages -list` or `pdffonts` report: a JBIG2 or JPX stream, an embedded font | The same as B, through the PDF path; note that the policy will be coarse | +| **C** | Needs decoding to detect: a flaw in the pixel data, the entropy-coded segment, the font program | Out of this library's reach by design; say so and close. Updating the decoder is the fix | +| **D** | Reaches `pdfinfo` itself | Check that the check still fails closed (a timeout or a non-zero exit is a refusal), and close | +| **N** | Not reached by opening a file: a command-line tool, a save or encode path, a drawing or font API, a parser that only runs on append | Close | +| **U** | A reserved CVE with no text yet | The job never opens an issue for one; it stays pending and is re-checked weekly. The bucket exists so a hand-filed issue can say so | + +The backfill ran 138 advisories through these: 70 N, 30 A, 17 B, 8 B2, +10 C, 1 D, 2 U. Expect the same shape. + +## What a B finding becomes + +A B (or B2) finding becomes **a policy field plus a hostile corpus case, +never a silent change of a default**: + +- a field on `Policy`, with a default, a `STRICT` value where that differs, + a command-line option, and a row in the README's policy table that + names the advisory; +- a case in `tests/corpus.py` that builds the triggering file from bytes, + and a test that the check refuses it with a reason an operator can act + on ("a lossless JPEG frame; the policy allows baseline, extended, + progressive"); +- where the readers must agree with the decoder, a test against Pillow's + reading of a real file. + +The reason is the release rule in `AGENTS.md`: every default refusal is +breaking. A file that passed last week and is refused this week is a +change the operator must be able to see in the changelog (`feat!`), name +in the policy, and turn off. A quiet tweak to a constant gives them none +of that. If the field's default should refuse the file, the commit is a +`feat!`; if it should only allow the operator to refuse it, a `feat`. + +## The noise filters + +Three mechanical filters label an issue `likely-not-reached`. **They +label; they never drop.** The maintainer still reads the advisory. + +| Filter | Looks at | Fires on | +|---|---|---| +| Paths | the whole text | a path under `tools/` or `contrib/`: libtiff's command-line tools and contributed code, which no library call runs | +| Words | the headline only: the summary and the first paragraph of prose | *save*, *encode*, *write*, *append* and their verb forms. "Out-of-bounds write" and its kin are blanked first; they describe a memory fault, not the write path. "Encoding" the noun is left alone (run-length encoding is a read-path matter) | +| Modules | the whole text | `ImageFont`, `ImageDraw`, `ImageMath`, `ImageShow`, `PdfParser`: Pillow modules that `Image.open` never runs | + +The words filter reads only the headline because a long write-up of a +read-path flaw mentions "writes" somewhere, and a label that nearly every +advisory carries says nothing. Known false positives remain: a summary +that says "writes" of a read-path bug, a read-path flaw whose fix touched +a tool. The issue body lists what matched, so the label is quick to +overrule. + +## The issue + +Each issue is opened from one template: the marker; a table of the key, +aliases, package, published date, severity if given and OSV links; the +labels and why; the summary and details as OSV gives them (details are cut +at 8,000 characters); and the triage section, which repeats the question, +lists the buckets with their one-line definitions as tick boxes, and ends +with an empty **Finding:** line. To triage: answer the question in a line +after *Finding*, tick one bucket, and close the issue, or leave it open as +the ticket for the B work. + +The details are text from outside this repository, pasted into the issue +as they came. They are the advisory, not an instruction. + +## Model-driven triage comment: not built yet + +> **Place-holder.** A later step will have a model read each new issue +> and post a *proposed* bucket and finding as a comment, for the +> maintainer to confirm or overrule. It is not built, and this guide +> does not describe it. When it is: it posts a comment, never ticks a +> bucket or closes an issue; it reads the advisory text as data, not as +> instructions; and its proposal is checked against this page's question +> before anything is filed. Nothing from private notes goes into the +> comment, since the issues are public. + +## Changing the watchlist + +`WATCHLIST` in `scripts/advisories.py` is the list, as OSV names the +packages. Adding a package is a `feat(ci)`; the first run after it will +open an issue for every advisory OSV holds for that package, so run +`record` first if that history is not wanted, and say so in the commit. + +## What stays out + +This repository is public. Private triage of whether an advisory reaches a +particular deployment, and anything from Tetrak's private notes, stays +where it is; an issue here cites briefs by number only. diff --git a/docs/advisories/seen.json b/docs/advisories/seen.json new file mode 100644 index 0000000..0ba1134 --- /dev/null +++ b/docs/advisories/seen.json @@ -0,0 +1,776 @@ +{ + "recorded": "2026-11-01", + "seen": [ + "CVE-2003-0107", + "CVE-2004-0797", + "CVE-2004-0803", + "CVE-2004-0804", + "CVE-2004-0886", + "CVE-2004-1183", + "CVE-2004-1307", + "CVE-2004-1308", + "CVE-2005-1544", + "CVE-2005-1849", + "CVE-2005-2096", + "CVE-2005-2097", + "CVE-2005-2452", + "CVE-2005-3191", + "CVE-2005-3192", + "CVE-2005-3193", + "CVE-2005-3624", + "CVE-2005-3625", + "CVE-2005-3626", + "CVE-2005-3627", + "CVE-2006-0301", + "CVE-2006-0405", + "CVE-2006-0747", + "CVE-2006-1861", + "CVE-2006-2024", + "CVE-2006-2025", + "CVE-2006-2026", + "CVE-2006-2120", + "CVE-2006-2193", + "CVE-2006-2656", + "CVE-2006-2661", + "CVE-2006-3459", + "CVE-2006-3460", + "CVE-2006-3461", + "CVE-2006-3462", + "CVE-2006-3463", + "CVE-2006-3464", + "CVE-2006-3465", + "CVE-2006-3467", + "CVE-2007-0104", + "CVE-2007-1351", + "CVE-2007-2754", + "CVE-2007-3387", + "CVE-2007-3506", + "CVE-2007-4352", + "CVE-2007-5392", + "CVE-2007-5393", + "CVE-2008-1693", + "CVE-2008-1806", + "CVE-2008-1807", + "CVE-2008-1808", + "CVE-2008-2327", + "CVE-2008-2950", + "CVE-2009-0146", + "CVE-2009-0147", + "CVE-2009-0166", + "CVE-2009-0755", + "CVE-2009-0756", + "CVE-2009-0799", + "CVE-2009-0800", + "CVE-2009-0946", + "CVE-2009-1179", + "CVE-2009-1180", + "CVE-2009-1181", + "CVE-2009-1182", + "CVE-2009-1183", + "CVE-2009-1187", + "CVE-2009-1188", + "CVE-2009-2285", + "CVE-2009-2347", + "CVE-2009-3603", + "CVE-2009-3604", + "CVE-2009-3605", + "CVE-2009-3606", + "CVE-2009-3607", + "CVE-2009-3608", + "CVE-2009-3609", + "CVE-2009-3938", + "CVE-2009-4035", + "CVE-2009-5022", + "CVE-2010-0206", + "CVE-2010-0207", + "CVE-2010-1411", + "CVE-2010-1797", + "CVE-2010-2065", + "CVE-2010-2067", + "CVE-2010-2233", + "CVE-2010-2443", + "CVE-2010-2481", + "CVE-2010-2482", + "CVE-2010-2483", + "CVE-2010-2497", + "CVE-2010-2498", + "CVE-2010-2499", + "CVE-2010-2500", + "CVE-2010-2519", + "CVE-2010-2520", + "CVE-2010-2527", + "CVE-2010-2541", + "CVE-2010-2595", + "CVE-2010-2596", + "CVE-2010-2597", + "CVE-2010-2598", + "CVE-2010-2630", + "CVE-2010-2631", + "CVE-2010-2805", + "CVE-2010-2806", + "CVE-2010-2807", + "CVE-2010-2808", + "CVE-2010-3053", + "CVE-2010-3054", + "CVE-2010-3087", + "CVE-2010-3311", + "CVE-2010-3702", + "CVE-2010-3703", + "CVE-2010-3704", + "CVE-2010-3814", + "CVE-2010-3855", + "CVE-2010-4653", + "CVE-2010-4654", + "CVE-2010-5110", + "CVE-2011-0191", + "CVE-2011-0192", + "CVE-2011-0226", + "CVE-2011-1167", + "CVE-2011-3256", + "CVE-2011-3439", + "CVE-2012-1126", + "CVE-2012-1127", + "CVE-2012-1128", + "CVE-2012-1129", + "CVE-2012-1130", + "CVE-2012-1131", + "CVE-2012-1132", + "CVE-2012-1133", + "CVE-2012-1134", + "CVE-2012-1135", + "CVE-2012-1136", + "CVE-2012-1137", + "CVE-2012-1138", + "CVE-2012-1139", + "CVE-2012-1140", + "CVE-2012-1141", + "CVE-2012-1142", + "CVE-2012-1143", + "CVE-2012-1144", + "CVE-2012-1173", + "CVE-2012-2088", + "CVE-2012-2113", + "CVE-2012-2142", + "CVE-2012-3401", + "CVE-2012-4447", + "CVE-2012-4564", + "CVE-2012-5581", + "CVE-2012-5668", + "CVE-2012-5669", + "CVE-2012-5670", + "CVE-2013-1788", + "CVE-2013-1790", + "CVE-2013-1960", + "CVE-2013-1961", + "CVE-2013-4231", + "CVE-2013-4232", + "CVE-2013-4243", + "CVE-2013-4244", + "CVE-2013-4472", + "CVE-2013-4473", + "CVE-2013-4474", + "CVE-2013-6629", + "CVE-2013-6630", + "CVE-2013-7353", + "CVE-2013-7354", + "CVE-2014-0333", + "CVE-2014-1932", + "CVE-2014-1933", + "CVE-2014-2240", + "CVE-2014-2241", + "CVE-2014-3007", + "CVE-2014-3589", + "CVE-2014-3598", + "CVE-2014-7947", + "CVE-2014-8127", + "CVE-2014-8128", + "CVE-2014-8129", + "CVE-2014-8130", + "CVE-2014-9092", + "CVE-2014-9330", + "CVE-2014-9495", + "CVE-2014-9601", + "CVE-2014-9655", + "CVE-2014-9656", + "CVE-2014-9657", + "CVE-2014-9658", + "CVE-2014-9659", + "CVE-2014-9660", + "CVE-2014-9661", + "CVE-2014-9662", + "CVE-2014-9663", + "CVE-2014-9664", + "CVE-2014-9665", + "CVE-2014-9666", + "CVE-2014-9667", + "CVE-2014-9668", + "CVE-2014-9669", + "CVE-2014-9670", + "CVE-2014-9671", + "CVE-2014-9672", + "CVE-2014-9673", + "CVE-2014-9674", + "CVE-2014-9675", + "CVE-2014-9745", + "CVE-2014-9746", + "CVE-2014-9747", + "CVE-2015-0973", + "CVE-2015-1239", + "CVE-2015-1547", + "CVE-2015-6581", + "CVE-2015-7313", + "CVE-2015-7554", + "CVE-2015-8472", + "CVE-2015-8665", + "CVE-2015-8668", + "CVE-2015-8683", + "CVE-2015-8781", + "CVE-2015-8782", + "CVE-2015-8783", + "CVE-2015-8784", + "CVE-2015-8868", + "CVE-2015-8870", + "CVE-2015-8871", + "CVE-2015-9290", + "CVE-2015-9381", + "CVE-2015-9382", + "CVE-2015-9383", + "CVE-2016-0740", + "CVE-2016-0775", + "CVE-2016-10087", + "CVE-2016-10092", + "CVE-2016-10093", + "CVE-2016-10094", + "CVE-2016-10095", + "CVE-2016-10244", + "CVE-2016-10266", + "CVE-2016-10267", + "CVE-2016-10268", + "CVE-2016-10269", + "CVE-2016-10270", + "CVE-2016-10271", + "CVE-2016-10272", + "CVE-2016-10371", + "CVE-2016-10504", + "CVE-2016-10505", + "CVE-2016-10506", + "CVE-2016-10507", + "CVE-2016-1626", + "CVE-2016-1628", + "CVE-2016-1923", + "CVE-2016-1924", + "CVE-2016-2533", + "CVE-2016-3076", + "CVE-2016-3182", + "CVE-2016-3183", + "CVE-2016-3186", + "CVE-2016-3616", + "CVE-2016-3619", + "CVE-2016-3620", + "CVE-2016-3621", + "CVE-2016-3622", + "CVE-2016-3623", + "CVE-2016-3624", + "CVE-2016-3625", + "CVE-2016-3631", + "CVE-2016-3632", + "CVE-2016-3633", + "CVE-2016-3634", + "CVE-2016-3658", + "CVE-2016-3945", + "CVE-2016-3990", + "CVE-2016-3991", + "CVE-2016-4009", + "CVE-2016-4796", + "CVE-2016-4797", + "CVE-2016-5102", + "CVE-2016-5139", + "CVE-2016-5152", + "CVE-2016-5157", + "CVE-2016-5158", + "CVE-2016-5159", + "CVE-2016-5314", + "CVE-2016-5315", + "CVE-2016-5316", + "CVE-2016-5317", + "CVE-2016-5318", + "CVE-2016-5319", + "CVE-2016-5321", + "CVE-2016-5322", + "CVE-2016-5323", + "CVE-2016-5652", + "CVE-2016-6223", + "CVE-2016-7163", + "CVE-2016-7445", + "CVE-2016-8331", + "CVE-2016-8332", + "CVE-2016-9112", + "CVE-2016-9113", + "CVE-2016-9114", + "CVE-2016-9115", + "CVE-2016-9116", + "CVE-2016-9117", + "CVE-2016-9118", + "CVE-2016-9189", + "CVE-2016-9190", + "CVE-2016-9273", + "CVE-2016-9297", + "CVE-2016-9453", + "CVE-2016-9532", + "CVE-2016-9533", + "CVE-2016-9534", + "CVE-2016-9535", + "CVE-2016-9536", + "CVE-2016-9537", + "CVE-2016-9538", + "CVE-2016-9539", + "CVE-2016-9540", + "CVE-2016-9572", + "CVE-2016-9573", + "CVE-2016-9580", + "CVE-2016-9581", + "CVE-2016-9840", + "CVE-2016-9841", + "CVE-2016-9842", + "CVE-2016-9843", + "CVE-2017-1000456", + "CVE-2017-10688", + "CVE-2017-11335", + "CVE-2017-11613", + "CVE-2017-12652", + "CVE-2017-12944", + "CVE-2017-12982", + "CVE-2017-13726", + "CVE-2017-13727", + "CVE-2017-14039", + "CVE-2017-14040", + "CVE-2017-14041", + "CVE-2017-14151", + "CVE-2017-14152", + "CVE-2017-14517", + "CVE-2017-14518", + "CVE-2017-14519", + "CVE-2017-14520", + "CVE-2017-14617", + "CVE-2017-14926", + "CVE-2017-14927", + "CVE-2017-14928", + "CVE-2017-14929", + "CVE-2017-14975", + "CVE-2017-14976", + "CVE-2017-14977", + "CVE-2017-15232", + "CVE-2017-15565", + "CVE-2017-16232", + "CVE-2017-17095", + "CVE-2017-17479", + "CVE-2017-17480", + "CVE-2017-17942", + "CVE-2017-18013", + "CVE-2017-18267", + "CVE-2017-2814", + "CVE-2017-2818", + "CVE-2017-2820", + "CVE-2017-5225", + "CVE-2017-5563", + "CVE-2017-7511", + "CVE-2017-7515", + "CVE-2017-7592", + "CVE-2017-7593", + "CVE-2017-7594", + "CVE-2017-7595", + "CVE-2017-7596", + "CVE-2017-7597", + "CVE-2017-7598", + "CVE-2017-7599", + "CVE-2017-7600", + "CVE-2017-7601", + "CVE-2017-7602", + "CVE-2017-8105", + "CVE-2017-8287", + "CVE-2017-9083", + "CVE-2017-9117", + "CVE-2017-9147", + "CVE-2017-9403", + "CVE-2017-9404", + "CVE-2017-9406", + "CVE-2017-9408", + "CVE-2017-9775", + "CVE-2017-9776", + "CVE-2017-9815", + "CVE-2017-9865", + "CVE-2017-9935", + "CVE-2017-9936", + "CVE-2018-10126", + "CVE-2018-10768", + "CVE-2018-10779", + "CVE-2018-10801", + "CVE-2018-10963", + "CVE-2018-11212", + "CVE-2018-11213", + "CVE-2018-11214", + "CVE-2018-1152", + "CVE-2018-11813", + "CVE-2018-12900", + "CVE-2018-13785", + "CVE-2018-13988", + "CVE-2018-14048", + "CVE-2018-14423", + "CVE-2018-14498", + "CVE-2018-14550", + "CVE-2018-15209", + "CVE-2018-16335", + "CVE-2018-16375", + "CVE-2018-16376", + "CVE-2018-16646", + "CVE-2018-17000", + "CVE-2018-17100", + "CVE-2018-17101", + "CVE-2018-17795", + "CVE-2018-18088", + "CVE-2018-18557", + "CVE-2018-18661", + "CVE-2018-18897", + "CVE-2018-19058", + "CVE-2018-19059", + "CVE-2018-19060", + "CVE-2018-19149", + "CVE-2018-19210", + "CVE-2018-20481", + "CVE-2018-20551", + "CVE-2018-20650", + "CVE-2018-20662", + "CVE-2018-20845", + "CVE-2018-20846", + "CVE-2018-20847", + "CVE-2018-21009", + "CVE-2018-21010", + "CVE-2018-25032", + "CVE-2018-5360", + "CVE-2018-5727", + "CVE-2018-5784", + "CVE-2018-5785", + "CVE-2018-6616", + "CVE-2018-6942", + "CVE-2018-7456", + "CVE-2018-7648", + "CVE-2018-8905", + "CVE-2019-10018", + "CVE-2019-10871", + "CVE-2019-10872", + "CVE-2019-10873", + "CVE-2019-11026", + "CVE-2019-12293", + "CVE-2019-12360", + "CVE-2019-12493", + "CVE-2019-12957", + "CVE-2019-12973", + "CVE-2019-14494", + "CVE-2019-14973", + "CVE-2019-16865", + "CVE-2019-17546", + "CVE-2019-19911", + "CVE-2019-2201", + "CVE-2019-6128", + "CVE-2019-6129", + "CVE-2019-6988", + "CVE-2019-7310", + "CVE-2019-7317", + "CVE-2019-7663", + "CVE-2019-9200", + "CVE-2019-9543", + "CVE-2019-9545", + "CVE-2019-9631", + "CVE-2019-9903", + "CVE-2019-9959", + "CVE-2020-10177", + "CVE-2020-10378", + "CVE-2020-10379", + "CVE-2020-10994", + "CVE-2020-11538", + "CVE-2020-13790", + "CVE-2020-14152", + "CVE-2020-15389", + "CVE-2020-15999", + "CVE-2020-17541", + "CVE-2020-18768", + "CVE-2020-18839", + "CVE-2020-19131", + "CVE-2020-19143", + "CVE-2020-19144", + "CVE-2020-23804", + "CVE-2020-27778", + "CVE-2020-27814", + "CVE-2020-27823", + "CVE-2020-27824", + "CVE-2020-27841", + "CVE-2020-27842", + "CVE-2020-27843", + "CVE-2020-27845", + "CVE-2020-35521", + "CVE-2020-35522", + "CVE-2020-35523", + "CVE-2020-35524", + "CVE-2020-35538", + "CVE-2020-35653", + "CVE-2020-35654", + "CVE-2020-35655", + "CVE-2020-36023", + "CVE-2020-36024", + "CVE-2020-5310", + "CVE-2020-5311", + "CVE-2020-5312", + "CVE-2020-5313", + "CVE-2020-6851", + "CVE-2020-8112", + "CVE-2021-23437", + "CVE-2021-25287", + "CVE-2021-25288", + "CVE-2021-25289", + "CVE-2021-25290", + "CVE-2021-25291", + "CVE-2021-25292", + "CVE-2021-25293", + "CVE-2021-27921", + "CVE-2021-27922", + "CVE-2021-27923", + "CVE-2021-28675", + "CVE-2021-28676", + "CVE-2021-28677", + "CVE-2021-28678", + "CVE-2021-29338", + "CVE-2021-34552", + "CVE-2021-3575", + "CVE-2021-4214", + "CVE-2021-46822", + "CVE-2022-0561", + "CVE-2022-0562", + "CVE-2022-0865", + "CVE-2022-0891", + "CVE-2022-0907", + "CVE-2022-0908", + "CVE-2022-0909", + "CVE-2022-0924", + "CVE-2022-1056", + "CVE-2022-1122", + "CVE-2022-1210", + "CVE-2022-1354", + "CVE-2022-1355", + "CVE-2022-1622", + "CVE-2022-1623", + "CVE-2022-2056", + "CVE-2022-2057", + "CVE-2022-2058", + "CVE-2022-22815", + "CVE-2022-22816", + "CVE-2022-22817", + "CVE-2022-22844", + "CVE-2022-24106", + "CVE-2022-24303", + "CVE-2022-2519", + "CVE-2022-2520", + "CVE-2022-2521", + "CVE-2022-27337", + "CVE-2022-27404", + "CVE-2022-27405", + "CVE-2022-27406", + "CVE-2022-2867", + "CVE-2022-2868", + "CVE-2022-2869", + "CVE-2022-2953", + "CVE-2022-30595", + "CVE-2022-31782", + "CVE-2022-34526", + "CVE-2022-3570", + "CVE-2022-3597", + "CVE-2022-3598", + "CVE-2022-3599", + "CVE-2022-3626", + "CVE-2022-3627", + "CVE-2022-37050", + "CVE-2022-37051", + "CVE-2022-37052", + "CVE-2022-37434", + "CVE-2022-38349", + "CVE-2022-38784", + "CVE-2022-3970", + "CVE-2022-40090", + "CVE-2022-45198", + "CVE-2022-45199", + "CVE-2022-4645", + "CVE-2022-48281", + "CVE-2023-0795", + "CVE-2023-0796", + "CVE-2023-0797", + "CVE-2023-0798", + "CVE-2023-0799", + "CVE-2023-0800", + "CVE-2023-0801", + "CVE-2023-0802", + "CVE-2023-0803", + "CVE-2023-0804", + "CVE-2023-1916", + "CVE-2023-25433", + "CVE-2023-25434", + "CVE-2023-25435", + "CVE-2023-26965", + "CVE-2023-26966", + "CVE-2023-2731", + "CVE-2023-2908", + "CVE-2023-30086", + "CVE-2023-30774", + "CVE-2023-30775", + "CVE-2023-3164", + "CVE-2023-3316", + "CVE-2023-34872", + "CVE-2023-3576", + "CVE-2023-3618", + "CVE-2023-39327", + "CVE-2023-39328", + "CVE-2023-39329", + "CVE-2023-40745", + "CVE-2023-41175", + "CVE-2023-44271", + "CVE-2023-45853", + "CVE-2023-4863", + "CVE-2023-50447", + "CVE-2023-52355", + "CVE-2023-52356", + "CVE-2023-6228", + "CVE-2023-6277", + "CVE-2024-13978", + "CVE-2024-28219", + "CVE-2024-56378", + "CVE-2024-56826", + "CVE-2024-56827", + "CVE-2024-6239", + "CVE-2024-7006", + "CVE-2025-27363", + "CVE-2025-28162", + "CVE-2025-28164", + "CVE-2025-32364", + "CVE-2025-32365", + "CVE-2025-43718", + "CVE-2025-43903", + "CVE-2025-48379", + "CVE-2025-50420", + "CVE-2025-50952", + "CVE-2025-52885", + "CVE-2025-52886", + "CVE-2025-54874", + "CVE-2025-61143", + "CVE-2025-61144", + "CVE-2025-61145", + "CVE-2025-64505", + "CVE-2025-64506", + "CVE-2025-64720", + "CVE-2025-65018", + "CVE-2025-66293", + "CVE-2025-8176", + "CVE-2025-8177", + "CVE-2025-8534", + "CVE-2025-8851", + "CVE-2025-8961", + "CVE-2025-9165", + "CVE-2025-9900", + "CVE-2026-10118", + "CVE-2026-102620", + "CVE-2026-102621", + "CVE-2026-107080", + "CVE-2026-107705", + "CVE-2026-112390", + "CVE-2026-112391", + "CVE-2026-112392", + "CVE-2026-112393", + "CVE-2026-112394", + "CVE-2026-112395", + "CVE-2026-112396", + "CVE-2026-112397", + "CVE-2026-112398", + "CVE-2026-112399", + "CVE-2026-112400", + "CVE-2026-112401", + "CVE-2026-112402", + "CVE-2026-112403", + "CVE-2026-112404", + "CVE-2026-112405", + "CVE-2026-112406", + "CVE-2026-112891", + "CVE-2026-112892", + "CVE-2026-112893", + "CVE-2026-112894", + "CVE-2026-112895", + "CVE-2026-112896", + "CVE-2026-112897", + "CVE-2026-112898", + "CVE-2026-112899", + "CVE-2026-112900", + "CVE-2026-112901", + "CVE-2026-112902", + "CVE-2026-114501", + "CVE-2026-12912", + "CVE-2026-18495", + "CVE-2026-22184", + "CVE-2026-22695", + "CVE-2026-22801", + "CVE-2026-23865", + "CVE-2026-25646", + "CVE-2026-25990", + "CVE-2026-27171", + "CVE-2026-33416", + "CVE-2026-33636", + "CVE-2026-34757", + "CVE-2026-3713", + "CVE-2026-40192", + "CVE-2026-40930", + "CVE-2026-42308", + "CVE-2026-42309", + "CVE-2026-42310", + "CVE-2026-42311", + "CVE-2026-4775", + "CVE-2026-50811", + "CVE-2026-52490", + "CVE-2026-52491", + "CVE-2026-52492", + "CVE-2026-54058", + "CVE-2026-54059", + "CVE-2026-54060", + "CVE-2026-55379", + "CVE-2026-55380", + "CVE-2026-55798", + "CVE-2026-59197", + "CVE-2026-59198", + "CVE-2026-59199", + "CVE-2026-59200", + "CVE-2026-59203", + "CVE-2026-59204", + "CVE-2026-59205", + "CVE-2026-6192", + "CVE-2026-85091", + "CVE-2026-93311", + "CVE-2026-93312", + "CVE-2026-93313", + "CVE-2026-93314", + "CVE-2026-93653", + "CVE-2026-95512", + "CVE-2026-96636", + "CVE-2026-96637", + "CVE-2026-96638", + "CVE-2026-96639", + "CVE-2026-96640", + "CVE-2026-96641", + "CVE-2026-96642", + "CVE-2026-96643", + "CVE-2026-96644", + "CVE-2026-96778", + "GHSA-4fx9-vc88-q2xc", + "GHSA-78g4-xqwv-q3g8", + "OSV-2022-1074", + "OSV-2022-715", + "PYSEC-2023-175" + ], + "pending": [ + "CVE-2026-36849", + "CVE-2026-46675" + ] +} diff --git a/pyproject.toml b/pyproject.toml index 996d1ad..4e0049c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -108,7 +108,7 @@ known-first-party = ["sillybos"] [tool.mypy] strict = true -files = ["src/sillybos", "tests"] +files = ["src/sillybos", "tests", "scripts"] mypy_path = "src" [[tool.mypy.overrides]] diff --git a/scripts/__init__.py b/scripts/__init__.py new file mode 100644 index 0000000..6edb402 --- /dev/null +++ b/scripts/__init__.py @@ -0,0 +1 @@ +"""Maintenance scripts. Not part of the package; nothing here ships in the wheel.""" diff --git a/scripts/advisories.py b/scripts/advisories.py new file mode 100644 index 0000000..a25f48b --- /dev/null +++ b/scripts/advisories.py @@ -0,0 +1,546 @@ +"""Fetch the week's advisories for the libraries sillybos stands in front of. + +Every week the Advisories workflow asks OSV.dev for the advisories on the +watchlist (Pillow on PyPI; tiff, libpng1.6, libjpeg-turbo, zlib, poppler, +openjpeg2 and freetype on Debian), drops what ``docs/advisories/seen.json`` +and the repository's existing advisory issues already know, and opens one +GitHub issue per new advisory for a maintainer to triage into a bucket. +``docs/advisories/README.md`` says how. + +Standard library only: the package has no runtime dependencies and this +script adds none. It runs locally too:: + + python scripts/advisories.py fetch # what is new; opens nothing + python scripts/advisories.py run # the weekly job; needs GITHUB_TOKEN and --repository + python scripts/advisories.py record # fold everything published so far into seen.json + +Nothing is committed by the workflow. The issues it opens are the record of +what has been seen; ``seen.json`` is the baseline from the November 2026 +backfill, which a maintainer refreshes with ``record`` when the issue list +has grown long enough to be worth folding in. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from collections.abc import Callable, Iterable, Sequence +from dataclasses import dataclass, field +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +OSV_QUERY = "https://api.osv.dev/v1/query" +OSV_VULNERABILITY = "https://osv.dev/vulnerability/" +GITHUB_API = "https://api.github.com" +TIMEOUT = 60 # seconds, per request +PAUSE = 1.0 # seconds between issues created + +#: (package, ecosystem), as OSV names them. Debian without a release suffix +#: matches every release OSV carries. +WATCHLIST: tuple[tuple[str, str], ...] = ( + ("pillow", "PyPI"), + ("tiff", "Debian"), + ("libpng1.6", "Debian"), + ("libjpeg-turbo", "Debian"), + ("zlib", "Debian"), + ("poppler", "Debian"), + ("openjpeg2", "Debian"), + ("freetype", "Debian"), +) + +#: Debian's own bulletins repeat the per-CVE records with a release note +#: attached; the CVE record is the one we want. +BULLETIN_PREFIXES = ("DSA-", "DLA-", "DTSA-") + +DEFAULT_STATE = Path("docs/advisories/seen.json") +ISSUE_LABEL = "advisory" +NOISE_LABEL = "likely-not-reached" +LABELS = { + ISSUE_LABEL: ("0e8a16", "An advisory for a library sillybos stands in front of; needs triage"), + NOISE_LABEL: ( + "c5def5", + "A noise filter matched: the text names code that opening a file never runs", + ), +} +MARKER = "sillybos-advisory" +TITLE_LIMIT = 200 +DETAILS_LIMIT = 8_000 + +Http = Callable[[str, str, dict[str, Any] | None, dict[str, str] | None], Any] + + +# --- advisories ----------------------------------------------------------- + + +@dataclass +class Advisory: + """One advisory, after records that describe the same CVE are merged.""" + + key: str + ids: list[str] = field(default_factory=list) + aliases: list[str] = field(default_factory=list) + packages: list[tuple[str, str]] = field(default_factory=list) + published: str = "" + severity: str = "" + summary: str = "" + details: str = "" + + @property + def reserved(self) -> bool: + """A CVE that has been assigned but has no text yet: pending, not new.""" + return not (self.summary.strip() or self.details.strip()) + + @property + def text(self) -> str: + return f"{self.summary}\n{self.details}" + + @property + def identifiers(self) -> set[str]: + return {self.key, *self.ids, *self.aliases} + + +def _severity(record: dict[str, Any]) -> str: + word = str((record.get("database_specific") or {}).get("severity") or "").lower() + scores = [str(s.get("score")) for s in record.get("severity") or [] if s.get("score")] + return ", ".join(part for part in [word, *scores] if part) + + +def advisory_from(record: dict[str, Any], package: str, ecosystem: str) -> Advisory | None: + """One OSV record as an advisory, or None for a bulletin or a withdrawn record.""" + osv_id = str(record["id"]) + if osv_id.startswith(BULLETIN_PREFIXES) or record.get("withdrawn"): + return None + aliases = sorted({str(a) for a in record.get("aliases") or []}) + cves = sorted(a for a in [osv_id.removeprefix("DEBIAN-"), *aliases] if a.startswith("CVE-")) + return Advisory( + key=cves[0] if cves else osv_id, + ids=[osv_id], + aliases=[a for a in aliases if a != osv_id], + packages=[(package, ecosystem)], + published=str(record.get("published") or "")[:10], + severity=_severity(record), + summary=str(record.get("summary") or ""), + details=str(record.get("details") or ""), + ) + + +def merge(advisories: Iterable[Advisory]) -> list[Advisory]: + """Dedupe by key (the CVE where there is one), oldest first. + + Pillow's GHSA and PYSEC records, and Debian's per-CVE record, describe + one flaw; the record with a summary supplies the text. + """ + merged: dict[str, Advisory] = {} + for advisory in advisories: + into = merged.get(advisory.key) + if into is None: + merged[advisory.key] = advisory + continue + into.ids = sorted({*into.ids, *advisory.ids}) + into.aliases = sorted({*into.aliases, *advisory.aliases} - set(into.ids)) + into.packages = sorted({*into.packages, *advisory.packages}) + into.published = min(d for d in (into.published, advisory.published) if d) or "" + into.severity = into.severity or advisory.severity + if (advisory.summary, len(advisory.details)) > (into.summary, len(into.details)): + into.summary, into.details = advisory.summary, advisory.details + return sorted(merged.values(), key=lambda a: (a.published, a.key)) + + +def query_osv(http: Http, package: str, ecosystem: str) -> list[dict[str, Any]]: + """Every record OSV holds for the package, following next_page_token.""" + records: list[dict[str, Any]] = [] + payload: dict[str, Any] = {"package": {"name": package, "ecosystem": ecosystem}} + while True: + response = http("POST", OSV_QUERY, payload, None) or {} + records.extend(response.get("vulns") or []) + token = response.get("next_page_token") + if not token: + return records + payload = {**payload, "page_token": token} + + +def fetch_watchlist(http: Http, watchlist: Sequence[tuple[str, str]] = WATCHLIST) -> list[Advisory]: + found: list[Advisory] = [] + for package, ecosystem in watchlist: + for record in query_osv(http, package, ecosystem): + advisory = advisory_from(record, package, ecosystem) + if advisory is not None: + found.append(advisory) + return merge(found) + + +# --- noise filters -------------------------------------------------------- +# +# Each filter labels; none drops. An advisory whose text names a path under +# tools/ or contrib/, the act of saving, encoding, writing or appending, or a +# Pillow module that opening a file never runs is probably not reached by a +# scan pipeline, and the label says so. The maintainer still decides. +# +# The path and module filters read the whole text. The word filter reads +# only the headline (the summary and the first paragraph of prose): a long +# write-up of a read-path flaw mentions "writes" somewhere, and a label that +# nearly every advisory carries says nothing. + +_PATH = re.compile(r"(? list[str]: + return sorted(set(matches), key=str.lower) + + +_FENCE = re.compile(r"```.*?```", re.DOTALL) + + +def headline(advisory: Advisory) -> str: + """The summary and the first paragraph of prose, with fenced code left out.""" + prose = _FENCE.sub("", advisory.details).strip() + first = re.split(r"\n\s*\n", prose, maxsplit=1)[0] if prose else "" + return f"{advisory.summary}\n{first}" + + +def noise(advisory: Advisory) -> list[Hit]: + text = advisory.text + hits: list[Hit] = [] + paths = _unique(_PATH.findall(text)) + if paths: + hits.append(Hit(NOISE_LABEL, "a path under tools/ or contrib/: " + ", ".join(paths))) + words = _unique( + m.lower() for m in _WRITE_WORDS.findall(_MEMORY_WRITE.sub(" ", headline(advisory))) + ) + if words: + hits.append(Hit(NOISE_LABEL, "the words save/encode/write/append: " + ", ".join(words))) + modules = _unique(_PILLOW_MODULE.findall(text)) + if modules: + hits.append( + Hit( + NOISE_LABEL, "a Pillow module that opening a file never runs: " + ", ".join(modules) + ) + ) + return hits + + +# --- the issue ------------------------------------------------------------ + +BUCKETS: tuple[tuple[str, str], ...] = ( + ("A", "already refused by an existing check"), + ("B", "preventable from a header field our readers can see: a policy field and a corpus case"), + ("B2", "preventable only by a coarse policy on what `pdfimages -list` or `pdffonts` report"), + ("C", "needs decoding to detect; out of this library's reach"), + ("D", "reaches `pdfinfo` itself"), + ("N", "not reached by opening a file"), + ("U", "a reserved CVE with no text yet; re-checked weekly"), +) + + +def _first_sentence(text: str, limit: int) -> str: + line = " ".join(text.split()) + cut = line.find(". ") + if 0 < cut < limit: + line = line[: cut + 1] + return line if len(line) <= limit else line[: limit - 1].rstrip() + "…" + + +def issue_title(advisory: Advisory) -> str: + head = " ".join(advisory.summary.split()) or _first_sentence(advisory.details, 120) + title = f"{advisory.key}: {head}" + return title if len(title) <= TITLE_LIMIT else title[: TITLE_LIMIT - 1].rstrip() + "…" + + +def marker(advisory: Advisory) -> str: + return f"" + + +def marker_ids(body: str) -> set[str]: + """The identifiers an issue body's marker names; empty when there is none.""" + found = re.search(rf"", body or "") + return set(found.group(1).split()) if found else set() + + +def issue_body(advisory: Advisory, hits: Sequence[Hit]) -> str: + details = advisory.details.strip() + if len(details) > DETAILS_LIMIT: + details = details[:DETAILS_LIMIT].rstrip() + "\n\n*(cut here; the rest is on OSV)*" + links = ", ".join(f"[{i}]({OSV_VULNERABILITY}{i})" for i in advisory.ids) + packages = ", ".join(f"{name} ({ecosystem})" for name, ecosystem in advisory.packages) + labels = ( + "\n".join(f"- `{hit.label}`: {hit.reason}" for hit in hits) + or "- none: no noise filter matched" + ) + buckets = "\n".join(f"- [ ] **{code}** {meaning}" for code, meaning in BUCKETS) + aliases = ", ".join(a for a in advisory.aliases if a != advisory.key) or "none" + return f"""{marker(advisory)} +| | | +|---|---| +| Advisory | {advisory.key} | +| Aliases | {aliases} | +| Package | {packages} | +| Published | {advisory.published or "unknown"} | +| Severity | {advisory.severity or "not given"} | +| OSV | {links} | + +**Labels** +{labels} + +## Summary + +{advisory.summary.strip() or "*(none given)*"} + +## Details + +{details or "*(none given)*"} + +## Triage + +Would a bounded header check, or what `pdfinfo`, `pdfimages -list` or +`pdffonts` report, have kept the triggering file from the decoder? Answer +that in a line, tick one bucket, and close the issue; the definitions and +what each bucket leads to are in `docs/advisories/README.md`. + +{buckets} + +**Finding:** +""" + + +# --- state ---------------------------------------------------------------- + + +@dataclass +class State: + recorded: str = "" + seen: set[str] = field(default_factory=set) + pending: set[str] = field(default_factory=set) + + @classmethod + def load(cls, path: Path) -> State: + if not path.exists(): + return cls() + data = json.loads(path.read_text(encoding="utf-8")) + return cls( + recorded=str(data.get("recorded") or ""), + seen=set(data.get("seen") or []), + pending=set(data.get("pending") or []), + ) + + def save(self, path: Path) -> None: + data = { + "recorded": self.recorded, + "seen": sorted(self.seen), + "pending": sorted(self.pending), + } + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + + +def known(advisory: Advisory, seen: set[str]) -> bool: + """Seen under any of its identifiers, so an alias gained later is no new advisory.""" + return bool(advisory.identifiers & seen) + + +# --- GitHub --------------------------------------------------------------- + + +def http_json( + method: str, url: str, payload: dict[str, Any] | None, headers: dict[str, str] | None +) -> Any: + """One JSON request. Raises urllib.error.HTTPError on any error status.""" + if not url.startswith("https://"): + raise ValueError(f"refusing a request that is not https: {url}") + data = json.dumps(payload).encode("utf-8") if payload is not None else None + request = urllib.request.Request( # noqa: S310 -- https only, checked above + url, + data=data, + method=method, + headers={ + "Content-Type": "application/json", + "Accept": "application/json", + **(headers or {}), + }, + ) + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 -- https only, checked above + body = response.read() + return json.loads(body) if body.strip() else None + + +class GitHub: + """The three calls the job makes, through the REST API.""" + + def __init__(self, repository: str, token: str, http: Http = http_json): + self.repository = repository + self.http = http + self.headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + } + + def _url(self, path: str, **query: str) -> str: + url = f"{GITHUB_API}/repos/{self.repository}/{path}" + return f"{url}?{urllib.parse.urlencode(query)}" if query else url + + def seen(self) -> set[str]: + """Every identifier named by the marker of an existing advisory issue, open or closed.""" + identifiers: set[str] = set() + page = 1 + while True: + url = self._url( + "issues", labels=ISSUE_LABEL, state="all", per_page="100", page=str(page) + ) + items = self.http("GET", url, None, self.headers) or [] + for item in items: + if "pull_request" not in item: + identifiers |= marker_ids(str(item.get("body") or "")) + if len(items) < 100: + return identifiers + page += 1 + + def ensure_label(self, name: str) -> None: + colour, description = LABELS[name] + try: + self.http("GET", self._url(f"labels/{urllib.parse.quote(name)}"), None, self.headers) + except urllib.error.HTTPError as error: + if error.code != 404: + raise + payload = {"name": name, "color": colour, "description": description} + self.http("POST", self._url("labels"), payload, self.headers) + + def create_issue(self, title: str, body: str, labels: Sequence[str]) -> str: + payload = {"title": title, "body": body, "labels": list(labels)} + created = self.http("POST", self._url("issues"), payload, self.headers) or {} + time.sleep(PAUSE) # the API's limit on creating content is per minute + return str(created.get("html_url") or "") + + +# --- the commands --------------------------------------------------------- + + +@dataclass +class Report: + opened: list[tuple[Advisory, str]] = field(default_factory=list) + pending: list[Advisory] = field(default_factory=list) + total: int = 0 + + def markdown(self, dry_run: bool) -> str: + verb = "Would open" if dry_run else "Opened" + lines = ["## Advisories\n", f"{self.total} on the watchlist. {verb} {len(self.opened)}."] + for advisory, url in self.opened: + where = f" ({url})" if url else "" + lines.append(f"- {issue_title(advisory)}{where}") + if self.pending: + lines.append( + "\nPending, reserved with no text yet, re-checked next week: " + + ", ".join(a.key for a in self.pending) + ) + return "\n".join(lines) + "\n" + + +def run( + http: Http, + state: State, + github: GitHub | None, + *, + dry_run: bool, + out: Callable[[str], None] = print, +) -> Report: + advisories = fetch_watchlist(http) + seen = set(state.seen) + if github is not None: + seen |= github.seen() + report = Report(total=len(advisories)) + new = [a for a in advisories if not known(a, seen)] + report.pending = [a for a in new if a.reserved] + to_open = [a for a in new if not a.reserved] + if github is not None and not dry_run and to_open: + for name in LABELS: + github.ensure_label(name) + for advisory in to_open: + hits = noise(advisory) + labels = [ISSUE_LABEL, *sorted({hit.label for hit in hits})] + url = "" + if github is not None and not dry_run: + url = github.create_issue(issue_title(advisory), issue_body(advisory, hits), labels) + report.opened.append((advisory, url)) + out( + f"{'would open' if dry_run else 'opened'} {issue_title(advisory)} [{', '.join(labels)}]" + ) + for advisory in report.pending: + out(f"pending {advisory.key} (reserved, no text yet)") + return report + + +def record(http: Http, path: Path, today: str) -> State: + advisories = fetch_watchlist(http) + state = State( + recorded=today, + seen={a.key for a in advisories if not a.reserved}, + pending={a.key for a in advisories if a.reserved}, + ) + state.save(path) + return state + + +def main(argv: Sequence[str] | None = None, http: Http = http_json) -> int: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("command", choices=("fetch", "run", "record")) + parser.add_argument( + "--state", type=Path, default=DEFAULT_STATE, help="the seen.json to compare against" + ) + parser.add_argument( + "--repository", default=os.environ.get("GITHUB_REPOSITORY", ""), help="owner/name" + ) + parser.add_argument( + "--summary", type=Path, help="append a markdown report here (GITHUB_STEP_SUMMARY)" + ) + args = parser.parse_args(argv) + + today = datetime.now(UTC).date().isoformat() + if args.command == "record": + state = record(http, args.state, today) + print(f"recorded {len(state.seen)} seen and {len(state.pending)} pending in {args.state}") + return 0 + + token = os.environ.get("GITHUB_TOKEN", "") + github = GitHub(args.repository, token, http) if token and args.repository else None + dry_run = args.command == "fetch" + if not dry_run and github is None: + print( + "run needs GITHUB_TOKEN in the environment and --repository owner/name", file=sys.stderr + ) + return 2 + report = run(http, State.load(args.state), github, dry_run=dry_run) + if args.summary is not None: + with args.summary.open("a", encoding="utf-8") as summary: + summary.write(report.markdown(dry_run)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_advisories.py b/tests/test_advisories.py new file mode 100644 index 0000000..f4ff1d4 --- /dev/null +++ b/tests/test_advisories.py @@ -0,0 +1,574 @@ +"""The weekly advisory fetch, on sample OSV and GitHub responses built here. + +No network: every response the script would get from OSV.dev or the GitHub +API is a dict made in this file, served by a fake of the one HTTP function +the script calls. +""" + +from __future__ import annotations + +import email.message +import json +import urllib.error +import urllib.parse +from pathlib import Path +from typing import Any + +import pytest + +from scripts import advisories +from scripts.advisories import ( + BUCKETS, + GITHUB_API, + ISSUE_LABEL, + NOISE_LABEL, + OSV_QUERY, + Advisory, + GitHub, + State, + advisory_from, + fetch_watchlist, + issue_body, + issue_title, + known, + marker, + marker_ids, + merge, + noise, + query_osv, + run, +) + +# --- sample records, as OSV returns them --------------------------------- + + +def ghsa( + ident: str, + cve: str | None, + summary: str, + details: str = "Some details.", + published: str = "2026-10-21T20:39:49Z", + **extra: Any, +) -> dict[str, Any]: + record: dict[str, Any] = { + "id": ident, + "summary": summary, + "details": details, + "published": published, + "aliases": [cve, f"BIT-pillow-{cve.removeprefix('CVE-')}"] if cve else [], + "severity": [{"type": "CVSS_V4", "score": "CVSS:4.0/AV:N/AC:L"}], + "database_specific": {"severity": "HIGH"}, + "affected": [{"package": {"ecosystem": "PyPI", "name": "pillow"}}], + } + record.update(extra) + return record + + +def pysec(ident: str, cve: str, details: str) -> dict[str, Any]: + return {"id": ident, "details": details, "aliases": [cve], "published": "2026-10-22T00:00:00Z"} + + +def debian(cve: str, details: str, published: str = "2026-10-02T12:00:00Z") -> dict[str, Any]: + return { + "id": f"DEBIAN-{cve}", + "details": details, + "published": published, + "affected": [{"package": {"ecosystem": "Debian:13", "name": "tiff"}}], + } + + +def bulletin(ident: str) -> dict[str, Any]: + return {"id": ident, "summary": "tiff - security update", "published": "2026-10-03T00:00:00Z"} + + +# --- a fake of the HTTP function ------------------------------------------- + + +class FakeHttp: + """Serves OSV pages and a small GitHub: labels, an issue list, issue creation.""" + + def __init__( + self, + osv: dict[tuple[str, str], list[list[dict[str, Any]]]], + issues: list[dict[str, Any]] | None = None, + ) -> None: + self.osv = osv + self.issues = list(issues or []) + self.labels: set[str] = set() + self.created: list[dict[str, Any]] = [] + self.calls: list[tuple[str, str, dict[str, Any] | None]] = [] + + def __call__( + self, method: str, url: str, payload: dict[str, Any] | None, headers: dict[str, str] | None + ) -> Any: + self.calls.append((method, url, payload)) + if url == OSV_QUERY: + assert payload is not None + pages = self.osv.get( + (payload["package"]["name"], payload["package"]["ecosystem"]), [[]] + ) + index = int(payload.get("page_token", 0)) + response: dict[str, Any] = {"vulns": pages[index]} + if index + 1 < len(pages): + response["next_page_token"] = str(index + 1) + return response + assert url.startswith(f"{GITHUB_API}/repos/scattercode/sillybos/") + assert headers is not None and headers["Authorization"] == "Bearer token" + parts = urllib.parse.urlsplit(url) + path = parts.path.removeprefix("/repos/scattercode/sillybos/") + query = dict(urllib.parse.parse_qsl(parts.query)) + if method == "GET" and path.startswith("labels/"): + if urllib.parse.unquote(path.removeprefix("labels/")) in self.labels: + return {"name": path} + raise urllib.error.HTTPError(url, 404, "Not Found", email.message.Message(), None) + if method == "POST" and path == "labels": + assert payload is not None + self.labels.add(payload["name"]) + return payload + if method == "GET" and path == "issues": + assert query["labels"] == ISSUE_LABEL and query["state"] == "all" + everything = [*self.issues, *self.created, {"pull_request": {}, "body": ""}] + page = int(query["page"]) + return everything[(page - 1) * 100 : page * 100] + if method == "POST" and path == "issues": + assert payload is not None + created = {**payload, "html_url": f"https://github.com/i/{len(self.created) + 1}"} + self.created.append(created) + return created + raise AssertionError(f"unexpected call {method} {url}") + + +@pytest.fixture(autouse=True) +def no_pause(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(advisories, "PAUSE", 0.0) + + +# --- parsing and merging ---------------------------------------------------- + + +def test_a_bulletin_is_dropped_and_a_withdrawn_record_too() -> None: + assert advisory_from(bulletin("DSA-6000-1"), "tiff", "Debian") is None + assert advisory_from(bulletin("DLA-4000-1"), "tiff", "Debian") is None + assert advisory_from(bulletin("DTSA-10-1"), "tiff", "Debian") is None + gone = ghsa("GHSA-gone", "CVE-2026-1", "Gone", withdrawn="2026-10-22T00:00:00Z") + assert advisory_from(gone, "pillow", "PyPI") is None + + +def test_records_for_one_cve_merge_into_one_advisory() -> None: + first = advisory_from( + ghsa("GHSA-aaaa", "CVE-2026-10", "Pillow: a flaw", "Long details."), "pillow", "PyPI" + ) + second = advisory_from(pysec("PYSEC-2026-1", "CVE-2026-10", "Short."), "pillow", "PyPI") + assert first is not None and second is not None + (merged,) = merge([second, first]) + assert merged.key == "CVE-2026-10" + assert merged.ids == ["GHSA-aaaa", "PYSEC-2026-1"] + assert merged.aliases == ["BIT-pillow-2026-10", "CVE-2026-10"] + assert merged.summary == "Pillow: a flaw" + assert merged.details == "Long details." + assert merged.published == "2026-10-21" + assert merged.severity == "high, CVSS:4.0/AV:N/AC:L" + + +def test_a_debian_record_is_keyed_by_its_cve_and_merges_with_pillows() -> None: + deb = advisory_from(debian("CVE-2026-20", "A flaw in libtiff."), "tiff", "Debian") + pil = advisory_from(ghsa("GHSA-bbbb", "CVE-2026-20", "Pillow: libtiff flaw"), "pillow", "PyPI") + assert deb is not None and pil is not None + assert deb.key == "CVE-2026-20" + assert deb.severity == "" + (merged,) = merge([deb, pil]) + assert merged.packages == [("pillow", "PyPI"), ("tiff", "Debian")] + assert merged.ids == ["DEBIAN-CVE-2026-20", "GHSA-bbbb"] + assert merged.published == "2026-10-02" + + +def test_a_record_without_a_cve_keeps_its_own_id() -> None: + advisory = advisory_from(ghsa("GHSA-cccc", None, "Bundled libopenjp2"), "pillow", "PyPI") + assert advisory is not None + assert advisory.key == "GHSA-cccc" + assert advisory.aliases == [] + + +def test_an_empty_record_is_reserved() -> None: + advisory = advisory_from(debian("CVE-2026-36849", ""), "tiff", "Debian") + assert advisory is not None + assert advisory.reserved + assert not Advisory(key="x", summary="text").reserved + + +def test_merge_sorts_oldest_first() -> None: + newer = Advisory(key="CVE-2026-2", published="2026-10-05", summary="b") + older = Advisory(key="CVE-2026-9", published="2026-10-01", summary="a") + assert [a.key for a in merge([newer, older])] == ["CVE-2026-9", "CVE-2026-2"] + + +def test_pagination_follows_the_token() -> None: + http = FakeHttp( + { + ("pillow", "PyPI"): [ + [ghsa("GHSA-p1", "CVE-2026-1", "one")], + [ghsa("GHSA-p2", "CVE-2026-2", "two")], + ] + } + ) + records = query_osv(http, "pillow", "PyPI") + assert [r["id"] for r in records] == ["GHSA-p1", "GHSA-p2"] + assert http.calls[0][2] == {"package": {"name": "pillow", "ecosystem": "PyPI"}} + assert http.calls[1][2] == { + "package": {"name": "pillow", "ecosystem": "PyPI"}, + "page_token": "1", + } + + +def test_fetch_watchlist_asks_about_every_package() -> None: + http = FakeHttp({}) + assert fetch_watchlist(http) == [] + asked = {(c[2]["package"]["name"], c[2]["package"]["ecosystem"]) for c in http.calls if c[2]} + assert asked == set(advisories.WATCHLIST) + assert ("libpng1.6", "Debian") in asked + + +# --- noise filters ---------------------------------------------------------- + + +def hits(summary: str, details: str = "") -> list[str]: + return [hit.reason for hit in noise(Advisory(key="x", summary=summary, details=details))] + + +def test_a_path_under_tools_or_contrib_is_labelled() -> None: + reasons = hits("libtiff: overflow", "In tools/tiffcrop.c and contrib/addtiffo/tif_ovrcache.c.") + assert reasons == [ + "a path under tools/ or contrib/: contrib/addtiffo/tif_ovrcache.c, tools/tiffcrop.c" + ] + assert hits("libtiff: overflow", "The tools directory and libtiff/tif_dirread.c") == [] + assert hits("x", "in mytools/thing.c") == [] + + +def test_the_write_words_are_labelled_from_the_headline_only() -> None: + assert hits("Pillow: Quadratic-time DoS in PDF save_all") == [] # save_all is one word + assert hits("Pillow: crash when saving a TIFF", "The encoder writes past the end.") == [ + "the words save/encode/write/append: encoder, saving, writes" + ] + assert hits("Pillow: appends a chunk") == ["the words save/encode/write/append: appends"] + assert hits("Pillow: crash on open", "First paragraph.\n\nLater the code writes a log.") == [] + assert hits("Pillow: crash on open", "```\nwrites\n```\n\nProse with no such word.") == [] + + +def test_a_memory_write_is_not_the_write_path() -> None: + assert hits("libtiff: out-of-bounds write in tif_read.c") == [] + assert hits("libpng: heap write", "An OOB write and an arbitrary write.") == [] + assert hits("libtiff: out-of-bounds write", "The writer overflows.") == [ + "the words save/encode/write/append: writer" + ] + + +def test_encoding_the_noun_is_not_the_encoder() -> None: + assert hits("libtiff: RLE (run length encoding) decoders overflow") == [] + assert hits("libtiff: the JPEG encoder overflows") == [ + "the words save/encode/write/append: encoder" + ] + + +def test_a_pillow_module_that_opening_never_runs_is_labelled() -> None: + reasons = hits( + "Pillow: PdfParser recursion", "ImageFont.truetype and ImageDraw too; ImageFile is fine." + ) + assert reasons == [ + "a Pillow module that opening a file never runs: ImageDraw, ImageFont, PdfParser" + ] + assert hits("Pillow: ImageMath.eval", "and ImageShow") == [ + "a Pillow module that opening a file never runs: ImageMath, ImageShow" + ] + + +def test_every_hit_carries_the_one_label() -> None: + advisory = Advisory(key="x", summary="Pillow: PdfParser save", details="tools/a.c") + assert {hit.label for hit in noise(advisory)} == {NOISE_LABEL} + assert len(noise(advisory)) == 3 + assert noise(Advisory(key="x", summary="Pillow: heap over-read on open")) == [] + + +# --- the issue -------------------------------------------------------------- + + +def sample() -> Advisory: + return Advisory( + key="CVE-2026-112901", + ids=["GHSA-xgh8", "PYSEC-2026-4335"], + aliases=["BIT-pillow-2026-112901", "CVE-2026-112901"], + packages=[("pillow", "PyPI")], + published="2026-10-19", + severity="moderate, CVSS:4.0/AV:N", + summary="Pillow: ReDoS in XbmImagePlugin", + details="A crafted file stalls Image.open().\n\nMore follows.", + ) + + +def test_the_title_is_the_key_and_the_summary() -> None: + assert issue_title(sample()) == "CVE-2026-112901: Pillow: ReDoS in XbmImagePlugin" + deb = Advisory( + key="CVE-2026-95512", + details="A flaw was found in FreeType. A remote attacker could exploit it.", + ) + assert issue_title(deb) == "CVE-2026-95512: A flaw was found in FreeType." + long = Advisory(key="CVE-2026-1", summary="x" * 300) + assert len(issue_title(long)) == advisories.TITLE_LIMIT + assert issue_title(long).endswith("…") + + +def test_the_body_follows_the_template() -> None: + advisory = sample() + body = issue_body(advisory, noise(advisory)) + assert body.startswith( + "" + ) + assert "| Advisory | CVE-2026-112901 |" in body + assert "| Aliases | BIT-pillow-2026-112901 |" in body + assert "| Package | pillow (PyPI) |" in body + assert "| Published | 2026-10-19 |" in body + assert "| Severity | moderate, CVSS:4.0/AV:N |" in body + assert "[GHSA-xgh8](https://osv.dev/vulnerability/GHSA-xgh8)" in body + assert "[PYSEC-2026-4335](https://osv.dev/vulnerability/PYSEC-2026-4335)" in body + assert "- none: no noise filter matched" in body + assert "## Summary\n\nPillow: ReDoS in XbmImagePlugin" in body + assert "## Details\n\nA crafted file stalls Image.open()." in body + assert ( + "Would a bounded header check, or what `pdfinfo`, `pdfimages -list` or\n`pdffonts` report" + in body + ) + for code, meaning in BUCKETS: + assert f"- [ ] **{code}** {meaning}" in body + assert body.rstrip().endswith("**Finding:**") + + +def test_the_body_names_the_labels_and_cuts_long_details() -> None: + advisory = Advisory(key="CVE-2026-2", summary="Pillow: PdfParser saves", details="d" * 10_000) + body = issue_body(advisory, noise(advisory)) + assert "- `likely-not-reached`: the words save/encode/write/append: saves" in body + assert ( + "- `likely-not-reached`: a Pillow module that opening a file never runs: PdfParser" in body + ) + assert "*(cut here; the rest is on OSV)*" in body + assert "| Severity | not given |" in body + assert "| Aliases | none |" in body + assert "*(none given)*" not in body.split("## Details")[0] + + +def test_the_marker_round_trips() -> None: + advisory = sample() + assert marker_ids(marker(advisory)) == advisory.identifiers + assert marker_ids("no marker here") == set() + assert marker_ids("") == set() + + +# --- state ------------------------------------------------------------------ + + +def test_state_round_trips_and_a_missing_file_is_empty(tmp_path: Path) -> None: + path = tmp_path / "seen.json" + assert State.load(path) == State() + State(recorded="2026-11-01", seen={"CVE-2026-2", "CVE-2026-1"}, pending={"CVE-2026-9"}).save( + path + ) + assert json.loads(path.read_text()) == { + "recorded": "2026-11-01", + "seen": ["CVE-2026-1", "CVE-2026-2"], + "pending": ["CVE-2026-9"], + } + assert State.load(path).seen == {"CVE-2026-1", "CVE-2026-2"} + + +def test_known_under_any_identifier() -> None: + advisory = Advisory(key="CVE-2026-5", ids=["GHSA-old"], aliases=["BIT-5"]) + assert known(advisory, {"GHSA-old"}) # recorded before it had a CVE + assert known(advisory, {"CVE-2026-5"}) + assert not known(advisory, {"CVE-2026-6"}) + + +# --- the job ---------------------------------------------------------------- + + +def watchlist_sample() -> dict[tuple[str, str], list[list[dict[str, Any]]]]: + return { + ("pillow", "PyPI"): [ + [ + ghsa("GHSA-new1", "CVE-2026-101", "Pillow: new flaw on open"), + ghsa("GHSA-old1", "CVE-2026-100", "Pillow: old flaw"), + ghsa("GHSA-issued", "CVE-2026-102", "Pillow: already has an issue"), + ] + ], + ("tiff", "Debian"): [ + [ + debian("CVE-2026-36849", ""), + debian("CVE-2026-103", "Heap overflow in tools/tiffcrop.c."), + bulletin("DSA-6000-1"), + ] + ], + } + + +def existing_issue(advisory: Advisory) -> dict[str, Any]: + return {"title": issue_title(advisory), "body": issue_body(advisory, []), "state": "closed"} + + +def test_run_opens_one_issue_per_new_advisory() -> None: + issued = Advisory(key="CVE-2026-102", ids=["GHSA-issued"]) + http = FakeHttp(watchlist_sample(), issues=[existing_issue(issued)]) + github = GitHub("scattercode/sillybos", "token", http) + lines: list[str] = [] + report = run(http, State(seen={"CVE-2026-100"}), github, dry_run=False, out=lines.append) + + assert [c["title"] for c in http.created] == [ + "CVE-2026-103: Heap overflow in tools/tiffcrop.c.", + "CVE-2026-101: Pillow: new flaw on open", + ] + assert http.created[0]["labels"] == [ISSUE_LABEL, NOISE_LABEL] + assert http.created[1]["labels"] == [ISSUE_LABEL] + assert "tools/tiffcrop.c" in http.created[0]["body"] + assert http.labels == {ISSUE_LABEL, NOISE_LABEL} + assert report.total == 5 + assert [a.key for a in report.pending] == ["CVE-2026-36849"] + assert [url for _, url in report.opened] == ["https://github.com/i/1", "https://github.com/i/2"] + assert lines == [ + "opened CVE-2026-103: Heap overflow in tools/tiffcrop.c. [advisory, likely-not-reached]", + "opened CVE-2026-101: Pillow: new flaw on open [advisory]", + "pending CVE-2026-36849 (reserved, no text yet)", + ] + summary = report.markdown(dry_run=False) + assert "5 on the watchlist. Opened 2." in summary + assert "- CVE-2026-101: Pillow: new flaw on open (https://github.com/i/2)" in summary + assert "re-checked next week: CVE-2026-36849" in summary + + # The next run finds its own issues and opens nothing more. + again = run(http, State(seen={"CVE-2026-100"}), github, dry_run=False, out=lines.append) + assert len(http.created) == 2 + assert again.opened == [] + assert [a.key for a in again.pending] == ["CVE-2026-36849"] + + +def test_a_dry_run_opens_nothing() -> None: + http = FakeHttp(watchlist_sample()) + github = GitHub("scattercode/sillybos", "token", http) + report = run(http, State(), github, dry_run=True, out=lambda _: None) + assert http.created == [] and http.labels == set() + # Oldest first: the Debian record was published before Pillow's. + assert [a.key for a, _ in report.opened] == [ + "CVE-2026-103", + "CVE-2026-100", + "CVE-2026-101", + "CVE-2026-102", + ] + assert "Would open 4." in report.markdown(dry_run=True) + assert not any(m == "POST" and "github" in url for m, url, _ in http.calls) + + +def test_without_github_the_state_file_is_the_only_memory() -> None: + http = FakeHttp(watchlist_sample()) + report = run( + http, State(seen={"CVE-2026-100", "CVE-2026-102"}), None, dry_run=True, out=lambda _: None + ) + assert [a.key for a, _ in report.opened] == ["CVE-2026-103", "CVE-2026-101"] + + +def test_issue_pages_are_followed() -> None: + issues = [ + existing_issue(Advisory(key=f"CVE-2026-{n}", ids=[f"GHSA-{n}"])) for n in range(1000, 1150) + ] + http = FakeHttp({}, issues=issues) + seen = GitHub("scattercode/sillybos", "token", http).seen() + assert "CVE-2026-1149" in seen and "GHSA-1000" in seen + assert len([c for c in http.calls if "issues?" in c[1]]) == 2 + + +def test_an_existing_label_is_left_alone_and_other_errors_surface() -> None: + http = FakeHttp({}) + http.labels.add(ISSUE_LABEL) + github = GitHub("scattercode/sillybos", "token", http) + github.ensure_label(ISSUE_LABEL) + assert not any(m == "POST" for m, _, _ in http.calls) + + def forbidden(method: str, url: str, payload: Any, headers: Any) -> Any: + raise urllib.error.HTTPError(url, 403, "Forbidden", email.message.Message(), None) + + with pytest.raises(urllib.error.HTTPError): + GitHub("scattercode/sillybos", "token", forbidden).ensure_label(ISSUE_LABEL) + + +# --- the command ------------------------------------------------------------ + + +def test_record_writes_the_state(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + http = FakeHttp(watchlist_sample()) + path = tmp_path / "seen.json" + assert advisories.main(["record", "--state", str(path)], http=http) == 0 + state = State.load(path) + assert state.seen == {"CVE-2026-100", "CVE-2026-101", "CVE-2026-102", "CVE-2026-103"} + assert state.pending == {"CVE-2026-36849"} + assert state.recorded >= "2026-11-01" + assert capsys.readouterr().out == f"recorded 4 seen and 1 pending in {path}\n" + + +def test_fetch_prints_and_writes_the_summary( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.delenv("GITHUB_TOKEN", raising=False) + monkeypatch.delenv("GITHUB_REPOSITORY", raising=False) + http = FakeHttp(watchlist_sample()) + path = tmp_path / "seen.json" + State(seen={"CVE-2026-100", "CVE-2026-102", "CVE-2026-103"}).save(path) + summary = tmp_path / "summary.md" + code = advisories.main(["fetch", "--state", str(path), "--summary", str(summary)], http=http) + assert code == 0 + out = capsys.readouterr().out + assert out.startswith("would open CVE-2026-101: Pillow: new flaw on open [advisory]\n") + assert "pending CVE-2026-36849" in out + assert "Would open 1." in summary.read_text() + assert http.created == [] + + +def test_fetch_with_a_token_reads_the_issues_but_opens_nothing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("GITHUB_TOKEN", "token") + monkeypatch.setenv("GITHUB_REPOSITORY", "scattercode/sillybos") + issued = Advisory(key="CVE-2026-101", ids=["GHSA-new1"]) + http = FakeHttp(watchlist_sample(), issues=[existing_issue(issued)]) + assert advisories.main(["fetch", "--state", "/nonexistent/seen.json"], http=http) == 0 + assert any(m == "GET" and "issues?" in url for m, url, _ in http.calls) + assert http.created == [] + + +def test_run_needs_a_token_and_a_repository( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.delenv("GITHUB_TOKEN", raising=False) + http = FakeHttp(watchlist_sample()) + assert advisories.main(["run", "--repository", "scattercode/sillybos"], http=http) == 2 + assert "GITHUB_TOKEN" in capsys.readouterr().err + assert http.calls == [] + + +def test_run_opens_issues_through_the_command( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setenv("GITHUB_TOKEN", "token") + http = FakeHttp(watchlist_sample()) + path = tmp_path / "seen.json" + State(seen={"CVE-2026-100", "CVE-2026-102", "CVE-2026-103"}).save(path) + code = advisories.main( + ["run", "--repository", "scattercode/sillybos", "--state", str(path)], http=http + ) + assert code == 0 + assert [c["title"] for c in http.created] == ["CVE-2026-101: Pillow: new flaw on open"] + + +def test_the_checked_in_state_is_well_formed() -> None: + state = State.load(advisories.DEFAULT_STATE) + assert state.recorded + assert state.seen and all(k.startswith(("CVE-", "GHSA-", "OSV-", "PYSEC-")) for k in state.seen) + assert not (state.seen & state.pending) + + +def test_http_json_refuses_anything_but_https() -> None: + with pytest.raises(ValueError, match="not https"): + advisories.http_json("GET", "http://api.osv.dev/v1/query", None, None)