From 386747bb5524cba14cf1cdb7c182f5c568fa382a Mon Sep 17 00:00:00 2001 From: Ayla Croft Date: Sun, 29 Nov 2026 16:13:14 -0500 Subject: [PATCH] Watch the lock on main every week, against OSV and each dependency's repository A lock goes bad by the calendar: from late October main's lock carried fourteen published advisories and only Dependabot's pull requests went red. And the audit reads OSV, which imports a repository's advisory some time after the repository publishes it. tools/advisory_watch.exs reads each locked hex package's GitHub repository from the registry, that repository's published advisories, and holds the locked version to each range; each finding says whether OSV lists it for that version yet. Run on the lock before #106 it finds fifteen, two of them (GHSA-j9wq-h5xx-5qx5, GHSA-fmr8-qrvr-4ww5) not in OSV for bandit 1.13.1, which the audit alone passed. It exits 0, 1 or 2 (not measured) as tools/audit.sh does, and --self-test holds its range reader offline. advisory-watch.yml runs both readers every Monday and by hand, never on a push or a pull request, with read-only permissions: a finding is a failed scheduled run, which GitHub reports to the maintainer. A governance test holds the triggers and both readers. Signed-off-by: Ayla Croft --- .github/workflows/advisory-watch.yml | 64 +++++ CHANGELOG.md | 12 + test/beam_mcp/governance_test.exs | 14 ++ tools/advisory_watch.exs | 357 +++++++++++++++++++++++++++ 4 files changed, 447 insertions(+) create mode 100644 .github/workflows/advisory-watch.yml create mode 100644 tools/advisory_watch.exs diff --git a/.github/workflows/advisory-watch.yml b/.github/workflows/advisory-watch.yml new file mode 100644 index 0000000..10dc632 --- /dev/null +++ b/.github/workflows/advisory-watch.yml @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: 2026 Sudo Apt Holdings LLC +# SPDX-License-Identifier: Apache-2.0 +# +# THE ADVISORY WATCH: the lock on main, held every week to every advisory published against it, +# by two readers. A lock goes bad by the calendar alone: nothing in this tree moves when a +# dependency publishes an advisory, and the gate's audit runs only on a push or a pull request. +# From late October to 2026-11-29 main's lock carried fourteen published advisories (bandit +# 1.13.1, plug 1.20.3, plug_crypto 2.2.0) and nobody was told: only Dependabot's pull requests +# went red, and a red pull request alerts nobody. +# +# Two readers, because neither sees everything: +# - tools/audit.sh: `mix hex.audit`, retired packages and OSV's advisories (the EEF CNA's +# among them, which a package's repository may never publish); +# - tools/advisory_watch.exs: each locked package's own GitHub repository's published +# advisories, held to the locked version, each finding saying whether OSV has it yet. +# Bandit's GHSA-j9wq-h5xx-5qx5 and GHSA-fmr8-qrvr-4ww5 were in its repository and not in +# OSV for 1.13.1 on 2026-11-29: the audit alone passed a lock both cover. +# +# NOT A REQUIRED CHECK, BY DESIGN, as the flake hunt: it runs on a schedule and by hand, never +# on a push or a pull request (the gate's own audit covers those). A finding is a failed +# scheduled run, which GitHub reports to the maintainer; its log names each advisory, its +# range and the version that fixes it. + +name: advisory-watch + +on: + schedule: + - cron: "47 5 * * 1" + workflow_dispatch: + +permissions: + contents: read + +jobs: + watch: + name: Advisory watch - the lock against OSV and each dependency's repository + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: erlef/setup-beam@54075bcc5e249e4758d363f27d099f55d843f124 # v1.24.1 + with: + otp-version: "28" + elixir-version: "1.18" + - run: mix deps.get + - name: the range reader against fixed cases (offline) + run: elixir tools/advisory_watch.exs --self-test + - name: the audit (OSV, retired packages) + id: audit + continue-on-error: true + run: bash tools/audit.sh + - name: each dependency's repository advisories + id: repos + continue-on-error: true + env: + GITHUB_TOKEN: ${{ github.token }} + run: elixir tools/advisory_watch.exs + - name: the verdict, both readers measured and clean + env: + AUDIT: ${{ steps.audit.outcome }} + REPOS: ${{ steps.repos.outcome }} + run: | + echo "audit: ${AUDIT}; repositories: ${REPOS}" + [ "${AUDIT}" = "success" ] && [ "${REPOS}" = "success" ] diff --git a/CHANGELOG.md b/CHANGELOG.md index c7c564f..dbbb8c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,18 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added: a weekly advisory watch on main (instruments; no public entry) + +- `.github/workflows/advisory-watch.yml` reads the lock on `main` every Monday, and by hand, + with two readers: `mix hex.audit` (OSV and retired packages, `tools/audit.sh`), and + `tools/advisory_watch.exs`, which reads each locked package's GitHub repository's published + advisories and holds the locked version to each one's range. The second exists because OSV + imports a repository's advisory some time after the repository publishes it: on 2026-11-29 two + of Bandit's advisories against 1.13.1 were in its repository and not in OSV, so the audit + alone passed a lock they cover. Each finding says whether OSV has it yet. A finding is a failed + scheduled run, which GitHub reports to the maintainer; it never runs on a push or a pull + request, where the gate's own audit runs. + ## [0.11.0] - 2026-11-29 Freeze-readiness, and a security floor. Two documented breaks, each with how to tell whether diff --git a/test/beam_mcp/governance_test.exs b/test/beam_mcp/governance_test.exs index eff8720..0343eaf 100644 --- a/test/beam_mcp/governance_test.exs +++ b/test/beam_mcp/governance_test.exs @@ -124,6 +124,20 @@ defmodule BeamMCP.GovernanceTest do refute triggers =~ ~r/^\s+(push|pull_request)/m end + # The lock goes bad by the calendar, not by a commit: the advisory watch is the one run that + # reads it on main when nothing is pushed, and it must read both sources (G-164's lift). + test "the advisory watch runs weekly, never on a push or a pull request, and reads both the audit and each repository" do + wf = File.read!(".github/workflows/advisory-watch.yml") + [triggers, _] = String.split(wf, ~r/^permissions:/m, parts: 2) + + assert triggers =~ ~r/^\s+schedule:/m + refute triggers =~ ~r/^\s+(push|pull_request)/m + assert wf =~ "run: bash tools/audit.sh" + assert wf =~ "run: elixir tools/advisory_watch.exs --self-test" + assert wf =~ ~r/run: elixir tools\/advisory_watch\.exs\s*$/m + assert wf =~ ~r/\[ "\$\{AUDIT\}" = "success" \] && \[ "\$\{REPOS\}" = "success" \]/ + end + test "every workflow declares top-level permissions, and write permissions live on the job that needs them" do for wf <- @workflows do text = File.read!(wf) diff --git a/tools/advisory_watch.exs b/tools/advisory_watch.exs new file mode 100644 index 0000000..56b8d20 --- /dev/null +++ b/tools/advisory_watch.exs @@ -0,0 +1,357 @@ +# SPDX-FileCopyrightText: 2026 Sudo Apt Holdings LLC +# SPDX-License-Identifier: Apache-2.0 +# +# The advisories the dependency audit cannot see yet. +# +# elixir tools/advisory_watch.exs read mix.lock, the registry and each source +# repository; print one line per finding +# elixir tools/advisory_watch.exs --self-test the range reader against fixed cases, offline +# +# WHY. `mix hex.audit` (tools/audit.sh) reads OSV, and OSV imports a package repository's +# GitHub advisory some time after the repository publishes it. On 2026-11-29 Bandit's +# GHSA-j9wq-h5xx-5qx5 (published by its repository 2026-11-16, `<= 1.14.1`, fixed 1.15.0) was +# a 404 from api.osv.dev and from GitHub's global advisory database, and an OSV query for +# bandit 1.14.1 listed nothing: the audit would have passed a lock on a version it covers. So +# this reads the source of the advisory itself: for every hex package in the lock, its GitHub +# repository from the registry's `links`, and that repository's published security advisories +# from GitHub's API, and it holds the locked version to each advisory's vulnerable range. +# +# It is the audit's second half, not a replacement: the audit sees advisories filed in OSV +# that a repository never published (the EEF CNA's, for one), and this sees the repository's +# before OSV does. Each finding says whether OSV knows its GHSA yet. +# +# Exit codes, as tools/audit.sh's: +# 0 measured, clean: every locked hex package read, no advisory covers its version +# 1 measured, not clean: one "advised:" line per finding +# 2 NOT MEASURED: a fetch failed, or a range could not be read; the reason is printed +# A package whose registry entry names no GitHub repository is listed as "unwatched" and does +# not change the exit: it is a hole in this instrument's reach, said, not a failure of the +# lock. Needs Erlang/OTP 27 or later (`:json`) and network access; no Mix project, no deps. + +defmodule AdvisoryWatch do + @ua ~c"beam_mcp-advisory-watch (+https://github.com/ScriptKittyOS/beam_mcp)" + + # ---- the range reader -------------------------------------------------------------------- + + # GitHub writes a vulnerable range in the ecosystem's own words: ">= 0.3.7, <= 1.14.1", + # "< 1.14.0", ">= 0.6.0 and < 1.13.0", "<=1.12.4", or a bare version for one release. Each + # clause becomes an Elixir requirement clause; a version with fewer than three numbers is + # padded ("1.13" is "1.13.0"). Anything else is unreadable, and unreadable is NOT MEASURED. + def requirement(range) when is_binary(range) do + clauses = + range + |> String.split([",", " and "], trim: true) + |> Enum.map(&String.trim/1) + |> Enum.reject(&(&1 == "")) + + with [_ | _] <- clauses, + {:ok, parts} <- clauses |> Enum.map(&clause/1) |> collect(), + {:ok, req} <- Version.parse_requirement(Enum.join(parts, " and ")) do + {:ok, req} + else + _ -> {:error, {:unreadable_range, range}} + end + end + + defp clause(text) do + case Regex.run(~r/^(>=|<=|>|<|==|=)?\s*v?([0-9][0-9A-Za-z.\-+]*)$/, text) do + [_, op, v] -> with {:ok, v} <- pad(v), do: {:ok, "#{op(op)} #{v}"} + _ -> :error + end + end + + defp op(""), do: "==" + defp op("="), do: "==" + defp op(op), do: op + + defp pad(v) do + {core, rest} = + case Regex.run(~r/^([0-9.]+)(.*)$/, v) do + [_, core, rest] -> {core, rest} + _ -> {v, ""} + end + + nums = String.split(core, ".", trim: true) + + if nums != [] and length(nums) <= 3 and Enum.all?(nums, &(&1 =~ ~r/^[0-9]+$/)) do + padded = Enum.join(nums ++ List.duplicate("0", 3 - length(nums)), ".") <> rest + if match?({:ok, _}, Version.parse(padded)), do: {:ok, padded}, else: :error + else + :error + end + end + + defp collect(results) do + if Enum.all?(results, &match?({:ok, _}, &1)), + do: {:ok, Enum.map(results, fn {:ok, p} -> p end)}, + else: :error + end + + def covers?(range, version) do + with {:ok, req} <- requirement(range), {:ok, v} <- Version.parse(version) do + {:ok, Version.match?(v, req, allow_pre: true)} + end + end + + # ---- the self-test ------------------------------------------------------------------------- + + @cases [ + {">= 0.3.7, <= 1.14.1", "1.14.1", true}, + {">= 0.3.7, <= 1.14.1", "1.15.0", false}, + {">= 0.3.7, <= 1.14.1", "0.3.6", false}, + {"< 1.14.0", "1.13.1", true}, + {"< 1.14.0", "1.14.0", false}, + {">= 0.6.0 and < 1.13.0", "1.12.5", true}, + {">= 0.6.0 and < 1.13.0", "1.13.0", false}, + {"<=1.12.4", "1.12.4", true}, + {"1.12.4", "1.12.4", true}, + {"1.12.4", "1.12.5", false}, + {">= 1.0.0-pre.7, < 1.14.0", "1.0.0-pre.8", true}, + {">= 1.13, < 1.14", "1.13.1", true}, + {">= 1.13, < 1.14", "1.14.0", false} + ] + + @unreadable ["", "<= ", "~> 1.0", "1.2.3.4", "everything", ">= 1.x"] + + def self_test do + bad = + Enum.reject(@cases, fn {range, v, want} -> covers?(range, v) == {:ok, want} end) ++ + Enum.reject(@unreadable, &match?({:error, _}, requirement(&1))) + + if bad == [] do + IO.puts( + "advisory-watch self-test ok: #{length(@cases)} ranges held, #{length(@unreadable)} unreadable refused" + ) + + 0 + else + IO.puts("advisory-watch self-test FAIL: #{inspect(bad)}") + 1 + end + end + + # ---- the watch ----------------------------------------------------------------------------- + + def run(lock_path) do + {:ok, _} = Application.ensure_all_started([:inets, :ssl]) + # Read, not evaluated: a lock is Elixir terms, and evaluating a file is running it. Every + # hex entry is `{:hex, :, "", ...}`; nothing else in a lock has that shape. + hex = + for [_, pkg, v] <- + Regex.scan(~r/\{:hex,\s*:"?([A-Za-z0-9_]+)"?,\s*"([^"]+)"/, File.read!(lock_path)), + into: %{}, + do: {pkg, v} + + results = hex |> Enum.sort() |> Enum.map(fn {pkg, v} -> {pkg, v, watch(pkg, v)} end) + + for {pkg, v, {:unwatched, why}} <- results, do: IO.puts("unwatched: #{pkg} #{v} (#{why})") + failures = for {pkg, v, {:not_measured, why}} <- results, do: {pkg, v, why} + findings = for {pkg, v, {:advised, list}} <- results, f <- list, do: {pkg, v, f} + + for {pkg, v, why} <- failures, do: IO.puts("NOT MEASURED: #{pkg} #{v}: #{why}") + + for {pkg, v, f} <- findings do + IO.puts( + "advised: #{pkg} #{v} is in #{f.ghsa} (#{f.severity}, range \"#{f.range}\", " <> + "patched #{f.patched || "none"}, #{f.osv}): #{f.summary} #{f.url}" + ) + end + + watched = + Enum.count(results, fn {_, _, r} -> match?({:clean, _}, r) or match?({:advised, _}, r) end) + + cond do + failures != [] -> + IO.puts( + "advisory-watch NOT MEASURED: #{length(failures)} of #{map_size(hex)} packages could not be read" + ) + + 2 + + findings != [] -> + IO.puts("advisory-watch FAIL: #{length(findings)} advisory finding(s) against the lock") + 1 + + true -> + IO.puts( + "advisory-watch ok: #{map_size(hex)} locked hex packages, #{watched} watched at their " <> + "repositories, no published advisory covers a locked version" + ) + + 0 + end + end + + defp watch(pkg, version) do + with {:ok, meta} <- get_json("https://hex.pm/api/packages/#{pkg}"), + {:ok, repo} <- github_repo(meta), + {:ok, advisories} <- advisories(repo), + {:ok, osv_ids} <- osv_ids(pkg, version) do + Enum.reduce_while(advisories, {:clean, repo}, fn adv, acc -> + case affecting(adv, pkg, version, osv_ids) do + {:error, why} -> {:halt, {:not_measured, why}} + [] -> {:cont, acc} + hits -> {:cont, add(acc, hits)} + end + end) + else + {:unwatched, why} -> {:unwatched, why} + {:error, why} -> {:not_measured, inspect(why)} + end + end + + defp add({:clean, _}, hits), do: {:advised, hits} + defp add({:advised, list}, hits), do: {:advised, list ++ hits} + + defp github_repo(%{"meta" => %{"links" => links}}) when is_map(links) do + links + |> Map.values() + |> Enum.find_value(fn url -> + case Regex.run(~r{^https?://(?:www\.)?github\.com/([^/\s]+)/([^/\s#?]+)}i, to_string(url)) do + [_, owner, repo] -> "#{owner}/#{String.replace_suffix(repo, ".git", "")}" + _ -> nil + end + end) + |> case do + nil -> {:unwatched, "its registry links name no GitHub repository"} + repo -> {:ok, repo} + end + end + + defp github_repo(_), do: {:unwatched, "its registry entry has no links"} + + # Published advisories only (a draft is not public); up to 100 per repository, which every + # repository in this lock is far under -- more is said, not truncated silently. + defp advisories(repo) do + url = "https://api.github.com/repos/#{repo}/security-advisories?state=published&per_page=100" + + case get_json(url, github_headers()) do + {:ok, list} when is_list(list) and length(list) < 100 -> + {:ok, list} + + {:ok, list} when is_list(list) -> + {:error, "#{repo}: 100 or more advisories, paging not read"} + + {:ok, other} -> + {:error, "#{repo}: unexpected answer #{inspect(other) |> String.slice(0, 120)}"} + + {:error, why} -> + {:error, "#{repo}: #{inspect(why)}"} + end + end + + defp affecting(adv, pkg, version, osv_ids) do + vulns = + for v <- adv["vulnerabilities"] || [], + p = v["package"] || %{}, + p["ecosystem"] in ["erlang", "hex", nil], + p["name"] in [pkg, nil, ""], + do: v + + Enum.reduce_while(vulns, [], fn v, acc -> + range = v["vulnerable_version_range"] || "" + + case covers?(range, version) do + {:ok, true} -> {:cont, [finding(adv, v, range, osv_ids) | acc]} + {:ok, false} -> {:cont, acc} + {:error, why} -> {:halt, {:error, "#{adv["ghsa_id"]}: #{inspect(why)}"}} + end + end) + end + + defp finding(adv, v, range, osv_ids) do + ghsa = adv["ghsa_id"] + + %{ + ghsa: ghsa, + severity: adv["severity"] || "unrated", + range: range, + patched: v["patched_versions"], + summary: adv["summary"] || "", + url: adv["html_url"] || "", + osv: + if(MapSet.member?(osv_ids, ghsa), + do: "in OSV, so the audit sees it too", + else: "NOT in OSV for this version yet: the audit cannot see it" + ) + } + end + + # What OSV, the feed `mix hex.audit` reads, lists against this exact version: every id and + # alias. OSV files a hex.pm advisory under the EEF CNA's id with the GHSA as an alias, so a + # lookup by GHSA id answers 404 for one it holds (measured 2026-11-29 on GHSA-c3g7-2pg5-qvwh, + # held as EEF-CVE-2026-108525); asking by package and version and reading aliases does not. + defp osv_ids(pkg, version) do + body = + :json.encode(%{"package" => %{"name" => pkg, "ecosystem" => "Hex"}, "version" => version}) + + req = + {~c"https://api.osv.dev/v1/query", [{~c"user-agent", @ua}], ~c"application/json", + IO.iodata_to_binary(body)} + + case :httpc.request(:post, req, [ssl: ssl(), timeout: 30_000], body_format: :binary) do + {:ok, {{_, 200, _}, _h, resp}} -> + vulns = Map.get(:json.decode(resp), "vulns", []) + {:ok, MapSet.new(Enum.flat_map(vulns, &[&1["id"] | &1["aliases"] || []]))} + + other -> + {:error, "OSV query for #{pkg} #{version}: #{inspect(other) |> String.slice(0, 120)}"} + end + end + + defp github_headers do + base = [ + {~c"accept", ~c"application/vnd.github+json"}, + {~c"x-github-api-version", ~c"2022-11-28"} + ] + + case System.get_env("GITHUB_TOKEN") || System.get_env("GH_TOKEN") do + nil -> base + "" -> base + t -> [{~c"authorization", String.to_charlist("Bearer " <> t)} | base] + end + end + + defp get_json(url, headers \\ []) do + case http_get(url, headers) do + {:ok, 200, body} -> {:ok, :json.decode(body)} + {:ok, status, _} -> {:error, "#{url} answered #{status}"} + {:error, why} -> {:error, why} + end + end + + defp ssl do + [ + verify: :verify_peer, + cacerts: :public_key.cacerts_get(), + customize_hostname_check: [match_fun: :public_key.pkix_verify_hostname_match_fun(:https)] + ] + end + + defp http_get(url, headers) do + req = {String.to_charlist(url), [{~c"user-agent", @ua} | headers]} + + case :httpc.request(:get, req, [ssl: ssl(), timeout: 30_000], body_format: :binary) do + {:ok, {{_, status, _}, _h, body}} -> {:ok, status, body} + {:error, why} -> {:error, why} + end + end +end + +code = + case System.argv() do + ["--self-test"] -> + AdvisoryWatch.self_test() + + [] -> + AdvisoryWatch.run("mix.lock") + + [path] -> + AdvisoryWatch.run(path) + + _ -> + IO.puts("usage: elixir tools/advisory_watch.exs [--self-test | ]") + 2 + end + +System.halt(code)