Public: anyone can read this; the crew can change it.
Pinned dependencies are matched against a local mirror of OSV advisories, and a vulnerable one is a finding #17082
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/17047-pinned-dependencies-are-matched-against → main 0 commits fork 4 threads · 4 unresolved
19 files
changed +679
−61
- docs/features/maintenance-dependencies.md
- src/maintenance/findings.ts
- src/maintenance/level.ts
- src/security/duty.ts
- src/security/forge_pins.ts
- src/security/mirror.ts
- src/security/osv.ts
- src/security/standing.ts
- src/tui/screens/maintenance.ts
- src/web/pages/maintenance.ts
- test/maintenance-calm.test.ts
- test/maintenance-finding-age.test.ts
- test/maintenance-json.test.ts
- test/maintenance-level.test.ts
- test/osv-findings.test.ts
- test/retention-events.test.ts
- test/runner-adopt.test.ts
- test/security-osv.test.ts
- test/signup-fresh.test.ts
docs/features/maintenance-dependencies.md added +54
| @@ -0,0 +1,54 @@ | ||
| 1 | --- | |
| 2 | topic: When something is wrong | |
| 3 | row: Vulnerable dependencies on the maintenance board | |
| 4 | --- | |
| 5 | # Vulnerable dependencies on the maintenance board (#17047) | |
| 6 | ||
| 7 | The forge matches every package its own lockfiles pin against its local mirror of OSV.dev | |
| 8 | advisories, and lists each pinned version an advisory affects on `/maintenance` (admin), one row | |
| 9 | each, naming the version that fixes it. | |
| 10 | ||
| 11 | - **One mirror.** The advisories come from the forge's one OSV mirror, `$FORGE_APP_DATA/osv/`, | |
| 12 | kept by the hourly `osv-mirror` refresh (`src/security/duty.ts`, `src/security/mirror.ts`), the | |
| 13 | same mirror the repository dependency report and fix issues read. The board adds no second | |
| 14 | fetcher and no second store. | |
| 15 | - **What is read.** `bun.lock` and `package-lock.json` at the forge's root, through the lockfile | |
| 16 | reader (`src/security/lockfile.ts`), matched locally (`src/security/forge_pins.ts`). These pins | |
| 17 | are never sent anywhere: what the refresh asks api.osv.dev about is unchanged, the pins of public | |
| 18 | repositories and of opted-in ones (`src/security/optin.ts`), and the forge's own repository is | |
| 19 | always opted in. A pin no asked-about repository holds has no advisory mirrored, so it is never | |
| 20 | a finding: set `FORGE_REPO` to the forge's own repository (`owner/name`) so its pins are asked about. | |
| 21 | - **Untrusted data.** An advisory is checked at the boundary (`toAdvisory` in | |
| 22 | `src/security/osv.ts`): its id must be safe as a file name, every list is bounded (200 packages, | |
| 23 | 50 ranges, 100 events, 5,000 listed versions), every string short, and only what matching reads | |
| 24 | is kept. A withdrawn or malformed advisory is not mirrored. An answer from api.osv.dev is read at | |
| 25 | most 4,000,000 bytes, counted as they arrive. Every line is escaped on the page. | |
| 26 | - **The match.** OSV's evaluation (https://ossf.github.io/osv-schema/#evaluation): events sorted by | |
| 27 | semver precedence (pre-releases by §11, so `rc.2` < `rc.10`), `introduced` turns it on at or | |
| 28 | above, `fixed` and `limit` turn it off at or above, `last_affected` turns it off above; an exact | |
| 29 | listed version also matches. A range whose events are not semver, a GIT range, or another | |
| 30 | ecosystem never matches. The fix named is the lowest `fixed` above the pin; "no fixed version is | |
| 31 | published yet" when none. | |
| 32 | - **When the fetch fails.** A failed read writes nothing, so the old mirror is kept and the match | |
| 33 | runs against it. The refresh's outcome is kept in `$FORGE_APP_DATA/osv-refresh.json` | |
| 34 | (`src/security/standing.ts`), and the board shows "OSV refresh failed at <time>: <why>; kept the | |
| 35 | mirror from <time> (N advisories)" until a refresh reads everything, in the gate's own words when | |
| 36 | the forge's gate refused the host ("refused by this forge: api.osv.dev is not in this app's | |
| 37 | forge.json egress"). | |
| 38 | ||
| 39 | ## On the web | |
| 40 | ||
| 41 | `/maintenance` shows a **Vulnerable dependencies** fold, open and in the "needs you" view while any | |
| 42 | pin is affected: a row labelled "lodash 4.17.20" reading "affected by GHSA-35jh-r3h4-6jhm; fixed in | |
| 43 | 4.17.21". The status line above counts them ("Needs you: 1 vulnerable dependency"). When nothing is | |
| 44 | affected and only the refresh failed, the fold sits in the "for information" view. `GET /maintenance.json` answers the same findings as | |
| 45 | `dependencies: [{name, version, id, fixedIn}]` beside `findings`. | |
| 46 | ||
| 47 | ## In the terminal | |
| 48 | ||
| 49 | The Maintenance screen (`src/tui/screens/maintenance.ts`, admins) ends with "Vulnerable | |
| 50 | dependencies (OSV.dev):" and one line per finding ("lodash 4.17.20 is affected by | |
| 51 | GHSA-35jh-r3h4-6jhm; fixed in 4.17.21"), from `dependencyLines` in `src/maintenance/findings.ts`. | |
| 52 | `l` splits the screen the way the page does, by the same rule (`dependencyLevel` in | |
| 53 | `src/maintenance/level.ts`): the lines are under "needs you" while a pin is affected, and under | |
| 54 | "for information" when only the refresh failed. |
src/maintenance/findings.ts +44 −2
| @@ -5,6 +5,8 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { Database } from "bun:sqlite"; |
| 8 | import { forgeFindings, type DependencyFinding } from "../security/forge_pins.ts"; | |
| 9 | import { readStanding, type Standing } from "../security/standing.ts"; | |
| 8 | 10 | |
| 9 | 11 | const DAY_MS = 86_400_000; |
| 10 | 12 | |
| @@ -153,9 +155,13 @@ export interface FindingJson { | ||
| 153 | 155 | readonly touchedAt: string | null; |
| 154 | 156 | } |
| 155 | 157 | |
| 156 | /** The same rows as `findingRows`, as the plain data `/maintenance.json` answers. */ | |
| 157 | export function findingsJson(db: Database): { findings: FindingJson[] } { | |
| 158 | /** | |
| 159 | * The same rows as `findingRows`, as the plain data `/maintenance.json` answers, and the vulnerable | |
| 160 | * dependencies the OSV mirror matched. | |
| 161 | */ | |
| 162 | export function findingsJson(db: Database, dataDir: string, root: string = process.cwd()): { findings: FindingJson[]; dependencies: DependencyFinding[] } { | |
| 158 | 163 | return { |
| 164 | dependencies: forgeFindings(dataDir, root), | |
| 159 | 165 | findings: oldestFirst(latestSpans(db, FINDING_ROWS).got).map((r) => ({ |
| 160 | 166 | duty: r.cause, |
| 161 | 167 | severity: r.closed_at === null && r.swept_at === null ? "degraded" : "cleared", |
| @@ -187,3 +193,39 @@ export function findingLines(db: Database, now: number = Date.now()): string[] { | ||
| 187 | 193 | ...(more > 0 ? [`And ${String(more)} more, older causes, not listed.`] : []), |
| 188 | 194 | ]; |
| 189 | 195 | } |
| 196 | ||
| 197 | /** | |
| 198 | * What an OSV advisory does to one pinned version (#17047): the advisory, and the version that | |
| 199 | * fixes it or that none is published yet. The board's row says it beside the package's label. | |
| 200 | */ | |
| 201 | export const dependencyFix = (f: DependencyFinding): string => | |
| 202 | `affected by ${f.id}; ${f.fixedIn === null ? "no fixed version is published yet" : `fixed in ${f.fixedIn}`}`; | |
| 203 | ||
| 204 | /** The same as one sentence, led by the package and version: the terminal's line. */ | |
| 205 | export const dependencyLine = (f: DependencyFinding): string => `${f.name} ${f.version} is ${dependencyFix(f)}`; | |
| 206 | ||
| 207 | /** | |
| 208 | * Where the OSV mirror stands, one line, only when its last refresh failed: the failure in its own | |
| 209 | * words and the mirror it kept. Undefined while it is current. | |
| 210 | */ | |
| 211 | export function mirrorLine(s: Standing): string | undefined { | |
| 212 | if (s.why === null || s.checkedAt === null) return undefined; | |
| 213 | const kept = s.okAt === null | |
| 214 | ? `kept the mirror as it was (${String(s.advisories)} advisories; no refresh has ever read everything it asked for)` | |
| 215 | : `kept the mirror from ${new Date(s.okAt).toISOString()} (${String(s.advisories)} advisories)`; | |
| 216 | return `OSV refresh failed at ${new Date(s.checkedAt).toISOString()}: ${s.why}; ${kept}`; | |
| 217 | } | |
| 218 | ||
| 219 | /** | |
| 220 | * The forge's own pinned versions the mirror says are vulnerable, and the mirror's line when its | |
| 221 | * last refresh failed. Read from the one OSV mirror (`src/security/`), never fetched here. | |
| 222 | */ | |
| 223 | export function dependencyFindings(dataDir: string, root: string = process.cwd()): { rows: DependencyFinding[]; mirror: string | undefined } { | |
| 224 | return { rows: forgeFindings(dataDir, root), mirror: mirrorLine(readStanding(dataDir)) }; | |
| 225 | } | |
| 226 | ||
| 227 | /** The same as terminal lines, led by a blank line; nothing when there is nothing to say. */ | |
| 228 | export function dependencyLines({ rows, mirror }: ReturnType<typeof dependencyFindings>): string[] { | |
| 229 | if (rows.length === 0 && mirror === undefined) return []; | |
| 230 | return ["", "Vulnerable dependencies (OSV.dev):", ...(mirror === undefined ? [] : [mirror]), ...rows.map(dependencyLine)]; | |
| 231 | } |
src/maintenance/level.ts +3 −1
| @@ -23,8 +23,10 @@ export function nextLevel(now: Level | undefined): Level | undefined { | ||
| 23 | 23 | /** |
| 24 | 24 | * Where each section of the board sits, written once for the page and the terminal so the two |
| 25 | 25 | * doors cannot drift: duties need you while one is overdue or paused, the maintenance state while |
| 26 | * maintenance is on, the last return when it failed a check. Everything else is fixed per section. | |
| 26 | * maintenance is on, the last return when it failed a check, the vulnerable dependencies while one | |
| 27 | * is affected (#17047). Everything else is fixed per section. | |
| 27 | 28 | */ |
| 28 | 29 | export const dutiesLevel = (overdue: number, paused: number): Level => (overdue + paused > 0 ? "needs-you" : "fyi"); |
| 29 | 30 | export const stateLevel = (phase: string): Level => (phase === "idle" ? "fyi" : "needs-you"); |
| 30 | 31 | export const returnLevel = (healthy: boolean | undefined): Level => (healthy === false ? "needs-you" : "fyi"); |
| 32 | export const dependencyLevel = (affected: number): Level => (affected > 0 ? "needs-you" : "fyi"); |
src/security/duty.ts +5 −1
| @@ -10,6 +10,7 @@ import { repoDir } from "../git/repos.ts"; | ||
| 10 | 10 | import { refreshMirror, type Fetch, type Refresh } from "./mirror.ts"; |
| 11 | 11 | import { mayAsk } from "./optin.ts"; |
| 12 | 12 | import { pinsOf } from "./scan.ts"; |
| 13 | import { recordStanding } from "./standing.ts"; | |
| 13 | 14 | import type { Pinned } from "./lockfile.ts"; |
| 14 | 15 | |
| 15 | 16 | const MAX_REPOS = 5000; |
| @@ -31,6 +32,9 @@ export async function refreshOsv(app: Pick<App, "db" | "reposRoot" | "config" | | ||
| 31 | 32 | } |
| 32 | 33 | } |
| 33 | 34 | const out = await refreshMirror(join(app.config.dataDir, "osv"), pins, fetcher); |
| 34 | app.log.info("osv mirror refreshed", { ...out }); | |
| 35 | // The outcome is kept for the board: a failure says why and that the old mirror was kept | |
| 36 | // (#17047). | |
| 37 | recordStanding(app.config.dataDir, out, Date.now()); | |
| 38 | app.log.info("osv mirror refreshed", { asked: out.asked, written: out.written, failed: out.failed, ...(out.why === null ? {} : { why: out.why }) }); | |
| 35 | 39 | return out; |
| 36 | 40 | } |
src/security/forge_pins.ts added +68
| @@ -0,0 +1,68 @@ | ||
| 1 | /** | |
| 2 | * The forge's own pinned dependencies matched against the OSV mirror (#17047): `bun.lock` and | |
| 3 | * `package-lock.json` at the forge's root, read from disk and matched locally. Nothing here touches | |
| 4 | * the network, so nothing here widens what is sent to api.osv.dev: the hourly refresh | |
| 5 | * (`security/duty.ts`) asks only about the pins of public or opted-in repositories | |
| 6 | * (`security/optin.ts`), the forge's own repository among them, and these pins are matched | |
| 7 | * against whatever that refresh mirrored. | |
| 8 | */ | |
| 9 | ||
| 10 | import { readFileSync, statSync } from "node:fs"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { LOCKFILES, parseLockfile, type Pinned } from "./lockfile.ts"; | |
| 13 | import { loadAdvisories, scanPinned } from "./osv.ts"; | |
| 14 | import { mirrorStamp } from "./report_cache.ts"; | |
| 15 | ||
| 16 | /** A pinned version an advisory affects, as the board and `/maintenance.json` carry it. */ | |
| 17 | export interface DependencyFinding { | |
| 18 | readonly name: string; | |
| 19 | readonly version: string; | |
| 20 | readonly id: string; | |
| 21 | readonly fixedIn: string | null; | |
| 22 | } | |
| 23 | ||
| 24 | const MAX_LOCKFILE_BYTES = 10_000_000; | |
| 25 | ||
| 26 | function stampOf(path: string): string { | |
| 27 | try { | |
| 28 | const s = statSync(path); | |
| 29 | return `${String(s.mtimeMs)}:${String(s.size)}`; | |
| 30 | } catch { | |
| 31 | return "none"; | |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | /** The packages the lockfiles at `root` pin; a missing or oversized lockfile pins nothing. */ | |
| 36 | export function rootPins(root: string): Pinned[] { | |
| 37 | const pins = new Map<string, Pinned>(); | |
| 38 | for (const name of LOCKFILES) { | |
| 39 | const path = join(root, name); | |
| 40 | try { | |
| 41 | if (statSync(path).size > MAX_LOCKFILE_BYTES) continue; | |
| 42 | for (const p of parseLockfile(name, readFileSync(path, "utf8"))) pins.set(`${p.name}@${p.version}`, p); | |
| 43 | } catch { | |
| 44 | // Not there: this root has no such lockfile. | |
| 45 | } | |
| 46 | } | |
| 47 | return [...pins.values()]; | |
| 48 | } | |
| 49 | ||
| 50 | /** The last answer, held by the mirror's stamp and each lockfile's: a page view is a lookup. */ | |
| 51 | let held: { key: string; rows: DependencyFinding[] } | undefined; | |
| 52 | ||
| 53 | /** | |
| 54 | * Every pinned version at `root` an advisory in the mirror affects, one per name, version and | |
| 55 | * advisory, sorted by name, version and id. | |
| 56 | */ | |
| 57 | export function forgeFindings(dataDir: string, root: string): DependencyFinding[] { | |
| 58 | const mirror = join(dataDir, "osv"); | |
| 59 | const key = [mirror, mirrorStamp(mirror), root, ...LOCKFILES.map((n) => stampOf(join(root, n)))].join("\0"); | |
| 60 | if (held?.key === key) return held.rows; | |
| 61 | const seen = new Map<string, DependencyFinding>(); | |
| 62 | for (const f of scanPinned(rootPins(root), loadAdvisories(mirror))) | |
| 63 | seen.set(`${f.package}@${f.version} ${f.advisory}`, { name: f.package, version: f.version, id: f.advisory, fixedIn: f.fixedIn }); | |
| 64 | const cmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0); | |
| 65 | const rows = [...seen.values()].sort((a, b) => cmp(a.name, b.name) || cmp(a.version, b.version) || cmp(a.id, b.id)); | |
| 66 | held = { key, rows }; | |
| 67 | return rows; | |
| 68 | } |
src/security/mirror.ts +40 −10
| @@ -8,6 +8,9 @@ | ||
| 8 | 8 | import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; |
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import { stringField } from "../kernel/json_string.ts"; |
| 11 | import { GateRefusedError } from "../kernel/outbound.ts"; | |
| 12 | import { refusedWords } from "../maintain/refused_once.ts"; | |
| 13 | import { readCapped } from "../spawn/bounded_read.ts"; | |
| 11 | 14 | import { toAdvisory } from "./osv.ts"; |
| 12 | 15 | import type { Pinned } from "./lockfile.ts"; |
| 13 | 16 | |
| @@ -15,15 +18,39 @@ export const OSV_HOST = "api.osv.dev"; | ||
| 15 | 18 | const BATCH = 500; |
| 16 | 19 | const MAX_FETCHED = 500; |
| 17 | 20 | const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; |
| 21 | /** The largest answer read, in bytes: an advisory is a few kB, a querybatch tens of kB (#17047). */ | |
| 22 | export const MAX_BODY = 4_000_000; | |
| 18 | 23 | |
| 19 | 24 | export interface Refresh { |
| 20 | 25 | readonly asked: number; |
| 21 | 26 | readonly written: number; |
| 22 | 27 | readonly failed: number; |
| 28 | /** The first read that failed, in words; null when none did. */ | |
| 29 | readonly why: string | null; | |
| 23 | 30 | } |
| 24 | 31 | |
| 25 | 32 | export type Fetch = (url: string, init?: RequestInit) => Promise<Response>; |
| 26 | 33 | |
| 34 | /** | |
| 35 | * An answer from api.osv.dev as JSON, read at most MAX_BODY bytes as they arrive, whatever | |
| 36 | * content-length says. Throws a sentence: the gate's own words when the forge's gate refused the | |
| 37 | * host (a 403 marked `x-forge-egress: refused`). | |
| 38 | */ | |
| 39 | async function answerOf(res: Response): Promise<unknown> { | |
| 40 | if (res.status === 403 && res.headers.get("x-forge-egress") === "refused") throw new Error(refusedWords(OSV_HOST)); | |
| 41 | if (!res.ok) throw new Error(`${OSV_HOST} answered HTTP ${String(res.status)}`); | |
| 42 | const body = await readCapped(res, MAX_BODY); | |
| 43 | if (body === undefined) throw new Error(`${OSV_HOST} answered more than ${String(MAX_BODY)} bytes, or broke off`); | |
| 44 | try { | |
| 45 | return JSON.parse(new TextDecoder().decode(body)); | |
| 46 | } catch { | |
| 47 | throw new Error(`${OSV_HOST} answered something that is not JSON`); | |
| 48 | } | |
| 49 | } | |
| 50 | ||
| 51 | const wordsOf = (error: unknown): string => | |
| 52 | error instanceof GateRefusedError ? refusedWords(OSV_HOST) : error instanceof Error ? error.message : String(error); | |
| 53 | ||
| 27 | 54 | function modifiedAt(file: string): string { |
| 28 | 55 | try { |
| 29 | 56 | return stringField(readFileSync(file, "utf8"), "modified"); |
| @@ -36,6 +63,11 @@ export async function refreshMirror(dir: string, pins: readonly Pinned[], fetche | ||
| 36 | 63 | const unique = [...new Map(pins.map((p) => [`${p.name}@${p.version}`, p])).values()]; |
| 37 | 64 | const wanted = new Map<string, string>(); |
| 38 | 65 | let failed = 0; |
| 66 | let why: string | null = null; | |
| 67 | const fail = (error: unknown): void => { | |
| 68 | failed++; | |
| 69 | why ??= wordsOf(error); | |
| 70 | }; | |
| 39 | 71 | for (let i = 0; i < unique.length; i += BATCH) { |
| 40 | 72 | const queries = unique.slice(i, i + BATCH).map((p) => ({ |
| 41 | 73 | package: { name: p.name, ecosystem: "npm" }, |
| @@ -47,13 +79,12 @@ export async function refreshMirror(dir: string, pins: readonly Pinned[], fetche | ||
| 47 | 79 | headers: { "content-type": "application/json" }, |
| 48 | 80 | body: JSON.stringify({ queries }), |
| 49 | 81 | }); |
| 50 | if (!res.ok) throw new Error(String(res.status)); | |
| 51 | const { results } = (await res.json()) as { results?: { vulns?: { id?: unknown; modified?: unknown }[] }[] }; | |
| 82 | const { results } = (await answerOf(res)) as { results?: { vulns?: { id?: unknown; modified?: unknown }[] }[] }; | |
| 52 | 83 | for (const r of results ?? []) |
| 53 | 84 | for (const v of r.vulns ?? []) |
| 54 | 85 | if (typeof v.id === "string" && ID.test(v.id)) wanted.set(v.id, typeof v.modified === "string" ? v.modified : ""); |
| 55 | } catch { | |
| 56 | failed++; | |
| 86 | } catch (error) { | |
| 87 | fail(error); | |
| 57 | 88 | } |
| 58 | 89 | } |
| 59 | 90 | mkdirSync(dir, { recursive: true }); |
| @@ -63,16 +94,15 @@ export async function refreshMirror(dir: string, pins: readonly Pinned[], fetche | ||
| 63 | 94 | if (modified !== "" && modifiedAt(file) >= modified) continue; |
| 64 | 95 | try { |
| 65 | 96 | const res = await fetcher(`https://${OSV_HOST}/v1/vulns/${encodeURIComponent(id)}`); |
| 66 | if (!res.ok) throw new Error(String(res.status)); | |
| 67 | const doc = await res.json(); | |
| 68 | if (!toAdvisory(doc)) throw new Error("not an advisory"); | |
| 97 | const doc = await answerOf(res); | |
| 98 | if (!toAdvisory(doc)) throw new Error(`${OSV_HOST} answered something that is not an OSV advisory for ${id}`); | |
| 69 | 99 | // Written whole then renamed: a scan never reads half an advisory. |
| 70 | 100 | writeFileSync(`${file}.tmp`, JSON.stringify(doc)); |
| 71 | 101 | renameSync(`${file}.tmp`, file); |
| 72 | 102 | written++; |
| 73 | } catch { | |
| 74 | failed++; | |
| 103 | } catch (error) { | |
| 104 | fail(error); | |
| 75 | 105 | } |
| 76 | 106 | } |
| 77 | return { asked: unique.length, written, failed }; | |
| 107 | return { asked: unique.length, written, failed, why }; | |
| 78 | 108 | } |
src/security/osv.ts +92 −27
| @@ -73,17 +73,66 @@ function severityOf(raw: unknown): Severity { | ||
| 73 | 73 | return "unknown"; |
| 74 | 74 | } |
| 75 | 75 | |
| 76 | /** A parsed OSV document, or undefined when it is not one. */ | |
| 76 | /** An OSV id, safe in a URL path and a file name: `GHSA-…`, `CVE-2024-1234`, `MAL-2024-1`. */ | |
| 77 | const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; | |
| 78 | const EVENTS = ["introduced", "fixed", "last_affected", "limit"] as const; | |
| 79 | /** Bounds on one advisory, so a hostile one cannot make the mirror or a match large (#17047). */ | |
| 80 | const MAX_AFFECTED = 200; | |
| 81 | const MAX_RANGES = 50; | |
| 82 | const MAX_EVENTS = 100; | |
| 83 | const MAX_VERSIONS = 5_000; | |
| 84 | const MAX_TEXT = 256; | |
| 85 | const MAX_SUMMARY = 1_000; | |
| 86 | ||
| 87 | const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v); | |
| 88 | const short = (v: unknown): v is string => typeof v === "string" && v.length > 0 && v.length <= MAX_TEXT; | |
| 89 | ||
| 90 | /** One `ranges` entry checked: a type and 1..MAX_EVENTS events, each exactly one kind. */ | |
| 91 | function toRange(raw: unknown): { type: string; events: Record<string, string>[] } | undefined { | |
| 92 | if (!isRecord(raw) || !short(raw.type) || !Array.isArray(raw.events)) return undefined; | |
| 93 | if (raw.events.length === 0 || raw.events.length > MAX_EVENTS) return undefined; | |
| 94 | const events: Record<string, string>[] = []; | |
| 95 | for (const e of raw.events) { | |
| 96 | if (!isRecord(e)) return undefined; | |
| 97 | const kinds = EVENTS.filter((k) => e[k] !== undefined); | |
| 98 | const kind = kinds[0]; | |
| 99 | if (kinds.length !== 1 || kind === undefined || !short(e[kind])) return undefined; | |
| 100 | events.push({ [kind]: e[kind] }); | |
| 101 | } | |
| 102 | return { type: raw.type, events }; | |
| 103 | } | |
| 104 | ||
| 105 | /** | |
| 106 | * A parsed OSV document, or undefined when it is not one. Advisory text is untrusted | |
| 107 | * (https://ossf.github.io/osv-schema): the id must be safe as a path, every list is bounded, every | |
| 108 | * string short, and only the fields matching reads are kept. A withdrawn advisory is none. | |
| 109 | */ | |
| 77 | 110 | export function toAdvisory(doc: unknown): Advisory | undefined { |
| 78 | if (typeof doc !== "object" || doc === null) return undefined; | |
| 79 | const d = doc as Record<string, unknown>; | |
| 80 | if (typeof d.id !== "string" || !Array.isArray(d.affected)) return undefined; | |
| 81 | const specific = d.database_specific as Record<string, unknown> | undefined; | |
| 111 | if (!isRecord(doc)) return undefined; | |
| 112 | if (typeof doc.id !== "string" || !ID.test(doc.id)) return undefined; | |
| 113 | if (doc.withdrawn !== undefined && doc.withdrawn !== null) return undefined; | |
| 114 | if (!Array.isArray(doc.affected) || doc.affected.length > MAX_AFFECTED) return undefined; | |
| 115 | const affected: Advisory["affected"][number][] = []; | |
| 116 | for (const a of doc.affected) { | |
| 117 | if (!isRecord(a) || !isRecord(a.package)) return undefined; | |
| 118 | const { ecosystem, name } = a.package; | |
| 119 | if (!short(ecosystem) || !short(name)) return undefined; | |
| 120 | if (a.ranges !== undefined && (!Array.isArray(a.ranges) || a.ranges.length > MAX_RANGES)) return undefined; | |
| 121 | if (a.versions !== undefined && (!Array.isArray(a.versions) || a.versions.length > MAX_VERSIONS || !a.versions.every(short))) return undefined; | |
| 122 | const ranges = ((a.ranges ?? []) as unknown[]).map(toRange); | |
| 123 | if (ranges.some((r) => r === undefined)) return undefined; | |
| 124 | affected.push({ | |
| 125 | package: { ecosystem, name }, | |
| 126 | ranges: ranges as { type: string; events: Record<string, string>[] }[], | |
| 127 | versions: (a.versions ?? []) as string[], | |
| 128 | }); | |
| 129 | } | |
| 130 | const specific = isRecord(doc.database_specific) ? doc.database_specific : undefined; | |
| 82 | 131 | return { |
| 83 | id: d.id, | |
| 84 | summary: typeof d.summary === "string" ? d.summary : "", | |
| 132 | id: doc.id, | |
| 133 | summary: typeof doc.summary === "string" ? doc.summary.slice(0, MAX_SUMMARY) : "", | |
| 85 | 134 | severity: severityOf(specific?.severity), |
| 86 | affected: d.affected as Advisory["affected"], | |
| 135 | affected, | |
| 87 | 136 | }; |
| 88 | 137 | } |
| 89 | 138 | |
| @@ -111,6 +160,37 @@ export function loadAdvisories(dir: string): Advisory[] { | ||
| 111 | 160 | return out; |
| 112 | 161 | } |
| 113 | 162 | |
| 163 | const SEMVER = /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; | |
| 164 | const eventVersion = (e: Record<string, string>): string => e.introduced ?? e.fixed ?? e.last_affected ?? e.limit ?? ""; | |
| 165 | /** `introduced: "0"` is below every version, pre-releases of 0.0.0 too. */ | |
| 166 | const atOrAbove = (v: string, e: string): number => (e === "0" ? 1 : compareVersions(v, e)); | |
| 167 | ||
| 168 | /** | |
| 169 | * Whether `version` falls in one range, by OSV's evaluation | |
| 170 | * (https://ossf.github.io/osv-schema/#evaluation): events sorted by version, `introduced` turns it | |
| 171 | * on at or above, `fixed` and `limit` turn it off at or above, `last_affected` turns it off above. | |
| 172 | * `fixedIn` is the first `fixed` above the version, null when none is published. Undefined when an | |
| 173 | * event's version is not semver: such a range is never matched. | |
| 174 | */ | |
| 175 | export function inRange(version: string, events: readonly Record<string, string>[]): { affected: boolean; fixedIn: string | null } | undefined { | |
| 176 | if (!events.every((e) => eventVersion(e) === "0" || SEMVER.test(eventVersion(e)))) return undefined; | |
| 177 | const sorted = [...events].sort((p, q) => { | |
| 178 | const a = eventVersion(p); | |
| 179 | const b = eventVersion(q); | |
| 180 | return a === "0" ? (b === "0" ? 0 : -1) : b === "0" ? 1 : compareVersions(a, b); | |
| 181 | }); | |
| 182 | let affected = false; | |
| 183 | for (const e of sorted) { | |
| 184 | const c = atOrAbove(version, eventVersion(e)); | |
| 185 | if (e.introduced !== undefined && c >= 0) affected = true; | |
| 186 | else if ((e.fixed !== undefined || e.limit !== undefined) && c >= 0) affected = false; | |
| 187 | else if (e.last_affected !== undefined && c > 0) affected = false; | |
| 188 | } | |
| 189 | if (!affected) return { affected, fixedIn: null }; | |
| 190 | const fix = sorted.find((e) => e.fixed !== undefined && compareVersions(e.fixed, version) > 0); | |
| 191 | return { affected, fixedIn: fix?.fixed ?? null }; | |
| 192 | } | |
| 193 | ||
| 114 | 194 | /** Findings for one package: which advisories cover its version, and the fix. */ |
| 115 | 195 | export function affectedBy(pkg: Pinned, advisories: readonly Advisory[]): Finding[] { |
| 116 | 196 | const out: Finding[] = []; |
| @@ -121,25 +201,10 @@ export function affectedBy(pkg: Pinned, advisories: readonly Advisory[]): Findin | ||
| 121 | 201 | let fixedIn: string | null = null; |
| 122 | 202 | for (const range of aff.ranges ?? []) { |
| 123 | 203 | if (range.type !== "SEMVER" && range.type !== "ECOSYSTEM") continue; |
| 124 | // Events walk in version order; the last one at or below the pin decides. | |
| 125 | const events = [...range.events].sort((p, q) => | |
| 126 | compareVersions(p.introduced ?? p.fixed ?? "0.0.0", q.introduced ?? q.fixed ?? "0.0.0"), | |
| 127 | ); | |
| 128 | let open = false; | |
| 129 | let fix: string | null = null; | |
| 130 | for (const ev of events) { | |
| 131 | if (ev.introduced !== undefined && compareVersions(pkg.version, ev.introduced === "0" ? "0.0.0" : ev.introduced) >= 0) { | |
| 132 | open = true; | |
| 133 | fix = null; | |
| 134 | } else if (ev.fixed !== undefined) { | |
| 135 | if (compareVersions(pkg.version, ev.fixed) >= 0) open = false; | |
| 136 | else if (open && fix === null) fix = ev.fixed; | |
| 137 | } | |
| 138 | } | |
| 139 | if (open) { | |
| 140 | hit = true; | |
| 141 | fixedIn = fix; | |
| 142 | } | |
| 204 | const r = inRange(pkg.version, range.events); | |
| 205 | if (r === undefined || !r.affected) continue; | |
| 206 | hit = true; | |
| 207 | if (r.fixedIn !== null && (fixedIn === null || compareVersions(r.fixedIn, fixedIn) < 0)) fixedIn = r.fixedIn; | |
| 143 | 208 | } |
| 144 | 209 | if (hit) |
| 145 | 210 | out.push({ |
src/security/standing.ts added +63
| @@ -0,0 +1,63 @@ | ||
| 1 | /** | |
| 2 | * Where the OSV mirror stands (#17047): when the last refresh ran, when one last read everything it | |
| 3 | * asked for, and why the last one failed. Kept beside the mirror, as | |
| 4 | * `$FORGE_APP_DATA/osv-refresh.json` (not inside `osv/`, so recording it does not change the | |
| 5 | * mirror's stamp). A failed refresh writes no advisory it could not read, so the old mirror is kept | |
| 6 | * as it was; this is how the board says so. | |
| 7 | */ | |
| 8 | ||
| 9 | import { readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import type { Refresh } from "./mirror.ts"; | |
| 12 | ||
| 13 | export interface Standing { | |
| 14 | /** When the last refresh finished, ms; null before the first. */ | |
| 15 | readonly checkedAt: number | null; | |
| 16 | /** When a refresh last read everything it asked for, ms; null when none ever has. */ | |
| 17 | readonly okAt: number | null; | |
| 18 | /** Why the last refresh failed; null when it did not. */ | |
| 19 | readonly why: string | null; | |
| 20 | /** Advisories the mirror holds. */ | |
| 21 | readonly advisories: number; | |
| 22 | } | |
| 23 | ||
| 24 | const fileOf = (dataDir: string): string => join(dataDir, "osv-refresh.json"); | |
| 25 | const when = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); | |
| 26 | ||
| 27 | function advisoryCount(dataDir: string): number { | |
| 28 | try { | |
| 29 | return readdirSync(join(dataDir, "osv")).filter((n) => n.endsWith(".json")).length; | |
| 30 | } catch { | |
| 31 | return 0; | |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | export function readStanding(dataDir: string): Standing { | |
| 36 | let doc: Record<string, unknown> = {}; | |
| 37 | try { | |
| 38 | const parsed: unknown = JSON.parse(readFileSync(fileOf(dataDir), "utf8")); | |
| 39 | if (typeof parsed === "object" && parsed !== null) doc = parsed as Record<string, unknown>; | |
| 40 | } catch { | |
| 41 | // No refresh has run yet, or the file is torn: nothing is known. | |
| 42 | } | |
| 43 | return { | |
| 44 | checkedAt: when(doc.checkedAt), | |
| 45 | okAt: when(doc.okAt), | |
| 46 | why: typeof doc.why === "string" ? doc.why.slice(0, 500) : null, | |
| 47 | advisories: advisoryCount(dataDir), | |
| 48 | }; | |
| 49 | } | |
| 50 | ||
| 51 | /** Record one refresh's outcome; a failure keeps the last success's time. */ | |
| 52 | export function recordStanding(dataDir: string, refresh: Refresh, now: number): void { | |
| 53 | const before = readStanding(dataDir); | |
| 54 | const failed = refresh.failed > 0; | |
| 55 | const doc = { | |
| 56 | checkedAt: now, | |
| 57 | okAt: failed ? before.okAt : now, | |
| 58 | why: failed ? (refresh.why ?? `${String(refresh.failed)} reads failed`) : null, | |
| 59 | }; | |
| 60 | const file = fileOf(dataDir); | |
| 61 | writeFileSync(`${file}.tmp`, JSON.stringify(doc)); | |
| 62 | renameSync(`${file}.tmp`, file); | |
| 63 | } |
src/tui/screens/maintenance.ts +9 −5
| @@ -11,9 +11,9 @@ import { effectWords, effectsOf, readRuns } from "../../maintain/effect.ts"; | ||
| 11 | 11 | import { diskLine, diskSentence } from "../../maintenance/disk_line.ts"; |
| 12 | 12 | import { readDisk } from "../../kernel/disk_reading.ts"; |
| 13 | 13 | import { filedText } from "../../maintenance/filed.ts"; |
| 14 | import { autoClosedCauses, findingLines, reopenFinding } from "../../maintenance/findings.ts"; | |
| 14 | import { autoClosedCauses, dependencyFindings, dependencyLines, findingLines, reopenFinding } from "../../maintenance/findings.ts"; | |
| 15 | 15 | import { secretPushLines } from "../../checks/pushed_secrets.ts"; |
| 16 | import { LEVEL_WORDS, nextLevel, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts"; | |
| 16 | import { LEVEL_WORDS, dependencyLevel, nextLevel, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts"; | |
| 17 | 17 | import { dutyStates } from "../../maintain/pause.ts"; |
| 18 | 18 | import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts"; |
| 19 | 19 | import { drillLine } from "../../maintenance/drill_line.ts"; |
| @@ -70,6 +70,10 @@ export function maintenanceLines(f: Session, standby?: Standby, level?: Level): | ||
| 70 | 70 | // Secret-shaped pushes (#17048), as on the page: each waits on a person to accept it. |
| 71 | 71 | const secrets = secretPushLines(f.app.db).flatMap((l) => wrap(l, INNER)); |
| 72 | 72 | const findings = findingLines(f.app.db).flatMap((l) => wrap(l, INNER)); |
| 73 | // Vulnerable dependencies (#17047), as on the page: they wait on a person while one is affected. | |
| 74 | const vulnerable = dependencyFindings(f.app.config.dataDir); | |
| 75 | const deps = dependencyLines(vulnerable).flatMap((l) => wrap(l, INNER)); | |
| 76 | const depsLevel = dependencyLevel(vulnerable.rows.length); | |
| 73 | 77 | // Findings quieted (#14557): numbered, so `b` can bring one back; when each is back. |
| 74 | 78 | const hidden = quieted(f.app.db).flatMap((q, i) => wrap(`${String(i + 1)}. quieted until ${when(q.until)}: ${q.label}`, INNER)); |
| 75 | 79 | const hiddenText = hidden.length === 0 ? [] : ["", ...hidden]; |
| @@ -82,15 +86,15 @@ export function maintenanceLines(f: Session, standby?: Standby, level?: Level): | ||
| 82 | 86 | // here. |
| 83 | 87 | const disk = diskLine((f.app.config.disk ?? readDisk)(f.app.config.dataDir)); |
| 84 | 88 | const diskText = disk === null ? [] : [...wrap(diskSentence(disk), INNER), ""]; |
| 85 | if (level === undefined) return [...diskText, ...stalled, ...drill, ...lead, "", ...facts, ...checks, "", ...dutyText(loud), ...paused, ...secrets, ...quietText, ...findings, ...hiddenText, ...effectText]; | |
| 89 | if (level === undefined) return [...diskText, ...stalled, ...drill, ...lead, "", ...facts, ...checks, "", ...dutyText(loud), ...paused, ...secrets, ...quietText, ...findings, ...deps, ...hiddenText, ...effectText]; | |
| 86 | 90 | // The same split as the page, by the same rule (maintenance/level.ts): what waits on a person, |
| 87 | 91 | // and what is only to read. |
| 88 | 92 | const needs = stateLevel(s.phase) === "needs-you" || returnLevel(last?.healthy) === "needs-you"; |
| 89 | 93 | const overdue = loud.filter((d) => d.overdue); |
| 90 | 94 | const out = |
| 91 | 95 | level === "needs-you" |
| 92 | ? [...(disk?.low === true ? diskText : []), ...stalled, ...drill, ...(needs ? [...lead, "", ...facts, ...checks, ""] : []), ...dutyText(overdue), ...paused, ...secrets] | |
| 93 | : [...(disk?.low === false ? diskText : []), ...(needs ? [] : [...lead, "", ...facts, ...checks, ""]), ...dutyText(loud.filter((d) => !d.overdue)), ...quietText, ...findings, ...hiddenText, ...effectText]; | |
| 96 | ? [...(disk?.low === true ? diskText : []), ...stalled, ...drill, ...(needs ? [...lead, "", ...facts, ...checks, ""] : []), ...dutyText(overdue), ...paused, ...secrets, ...(depsLevel === "needs-you" ? deps : [])] | |
| 97 | : [...(disk?.low === false ? diskText : []), ...(needs ? [] : [...lead, "", ...facts, ...checks, ""]), ...dutyText(loud.filter((d) => !d.overdue)), ...quietText, ...findings, ...(depsLevel === "fyi" ? deps : []), ...hiddenText, ...effectText]; | |
| 94 | 98 | return out.length === 0 ? [level === "needs-you" ? "Nothing here needs you." : "Nothing here to read."] : out; |
| 95 | 99 | } |
| 96 | 100 |
src/web/pages/maintenance.ts +21 −5
| @@ -10,8 +10,8 @@ import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | ||
| 10 | 10 | import { dutyStates, switchDuty } from "../../maintain/pause.ts"; |
| 11 | 11 | import { DISMISS_DAYS, REASON_MAX, dismiss, dismissals, dismissalWords } from "../../maintain/dismiss.ts"; |
| 12 | 12 | import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts"; |
| 13 | import { LEVELS, LEVEL_WORDS, dutiesLevel, levelOf, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts"; | |
| 14 | import { findingRows, findingsJson, reopenFinding, rowWords } from "../../maintenance/findings.ts"; | |
| 13 | import { LEVELS, LEVEL_WORDS, dependencyLevel, dutiesLevel, levelOf, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts"; | |
| 14 | import { dependencyFindings, dependencyFix, findingRows, findingsJson, reopenFinding, rowWords } from "../../maintenance/findings.ts"; | |
| 15 | 15 | import { NOTHING_FILED, filedPieces } from "../../maintenance/filed.ts"; |
| 16 | 16 | import { CLEAR_WORDS, forgeSecrets, secretLine } from "../../checks/pushed_secrets.ts"; |
| 17 | 17 | import { drillLine } from "../../maintenance/drill_line.ts"; |
| @@ -69,6 +69,19 @@ export function findingsFold(db: Parameters<typeof findingRows>[0], now: number | ||
| 69 | 69 | )}${more > 0 ? statusRow(`And ${String(more)} more`, html`<span class="muted">older causes, not listed</span>`) : html``}</dl>`); |
| 70 | 70 | } |
| 71 | 71 | |
| 72 | /** | |
| 73 | * The pinned dependencies an OSV advisory affects (#17047), one row each naming the fix version, | |
| 74 | * and the mirror's failure when its last refresh failed; nothing when neither. Open while any | |
| 75 | * dependency is affected: an upgrade waits on a person. | |
| 76 | */ | |
| 77 | export function dependenciesFold({ rows, mirror }: ReturnType<typeof dependencyFindings>): Html { | |
| 78 | if (rows.length === 0 && mirror === undefined) return html``; | |
| 79 | return fold("maintenance-dependencies", "Vulnerable dependencies", String(rows.length), rows.length > 0, | |
| 80 | html`<dl id="maintenance-dependencies-rows" class="status-rows">${mirror === undefined ? null : statusRow("OSV mirror", html`<span data-osv="failed">${mirror}</span>`)}${rows.map( | |
| 81 | (r) => statusRow(`${r.name} ${r.version}`, html`<span data-advisory="${r.id}">${dependencyFix(r)}</span>`), | |
| 82 | )}</dl>`); | |
| 83 | } | |
| 84 | ||
| 72 | 85 | /** |
| 73 | 86 | * The forge's open secret-shaped pushes (#17048), one row per finding with its repository and its |
| 74 | 87 | * masked line, each linked to the findings page that accepts it; nothing when none. Always open: |
| @@ -92,7 +105,7 @@ function foundWords(ctx: Ctx, d: { detail: string; found: string; lastRun: strin | ||
| 92 | 105 | } |
| 93 | 106 | |
| 94 | 107 | /** What waits on a person, in words; empty when nothing does. Plain data in, plain data out. */ |
| 95 | export function needsYou(o: { phase: string; healthy?: boolean; overdue: number; paused: number; stale: number; secrets?: number }): string[] { | |
| 108 | export function needsYou(o: { phase: string; healthy?: boolean; overdue: number; paused: number; stale: number; secrets?: number; vulnerable?: number }): string[] { | |
| 96 | 109 | const out: string[] = []; |
| 97 | 110 | if (o.phase !== "idle") out.push("maintenance is on"); |
| 98 | 111 | if (o.healthy === false) out.push("the last return failed a check"); |
| @@ -100,6 +113,7 @@ export function needsYou(o: { phase: string; healthy?: boolean; overdue: number; | ||
| 100 | 113 | if (o.paused > 0) out.push(plural(o.paused, "duty paused", "duties paused")); |
| 101 | 114 | if (o.stale > 0) out.push(plural(o.stale, "stale pull", "stale pulls")); |
| 102 | 115 | if ((o.secrets ?? 0) > 0) out.push(plural(o.secrets ?? 0, "secret-shaped push", "secret-shaped pushes")); |
| 116 | if ((o.vulnerable ?? 0) > 0) out.push(plural(o.vulnerable ?? 0, "vulnerable dependency", "vulnerable dependencies")); | |
| 103 | 117 | return out; |
| 104 | 118 | } |
| 105 | 119 | |
| @@ -119,7 +133,7 @@ function stalledCard(s: ReturnType<typeof stalledStep>, withAction: boolean): Ht | ||
| 119 | 133 | export function maintenanceJson(ctx: Ctx): Response { |
| 120 | 134 | const denied = admin(ctx); |
| 121 | 135 | if (denied) return denied; |
| 122 | return json(findingsJson(ctx.app.db), 200, { "cache-control": "no-store", vary: "accept" }); | |
| 136 | return json(findingsJson(ctx.app.db, ctx.app.config.dataDir), 200, { "cache-control": "no-store", vary: "accept" }); | |
| 123 | 137 | } |
| 124 | 138 | |
| 125 | 139 | /** |
| @@ -153,7 +167,8 @@ async function maintenanceAnswer(ctx: Ctx): Promise<Response> { | ||
| 153 | 167 | const dismissable = states.filter((d) => !d.paused && dismissed.get(d.name)?.active !== true).map((d) => d.name); |
| 154 | 168 | const paused = states.filter((d) => d.paused).length; |
| 155 | 169 | const secrets = forgeSecrets(ctx.app.db); |
| 156 | const waiting = needsYou({ phase: s.phase, ...(s.healthy === undefined ? {} : { healthy: s.healthy }), overdue, paused, stale, secrets: secrets.rows.length + secrets.more }); | |
| 170 | const vulnerable = dependencyFindings(ctx.app.config.dataDir); | |
| 171 | const waiting = needsYou({ phase: s.phase, ...(s.healthy === undefined ? {} : { healthy: s.healthy }), overdue, paused, stale, secrets: secrets.rows.length + secrets.more, vulnerable: vulnerable.rows.length }); | |
| 157 | 172 | const idle = s.phase === "idle"; |
| 158 | 173 | const drill = lastDrill(ctx.app.db); |
| 159 | 174 | const statusLine = waiting.length === 0 |
| @@ -184,6 +199,7 @@ async function maintenanceAnswer(ctx: Ctx): Promise<Response> { | ||
| 184 | 199 | ["fyi", fold("maintenance-budgets", "Budgets", String(states.length), false, html`<dl class="status-rows">${budgetRows(ctx.app, states.map((d) => d.name))}</dl>`)], |
| 185 | 200 | ["needs-you", secretsFold(secrets)], |
| 186 | 201 | ["fyi", findingsFold(ctx.app.db)], |
| 202 | [dependencyLevel(vulnerable.rows.length), dependenciesFold(vulnerable)], | |
| 187 | 203 | ["fyi", writePauseFold(ctx.app.db)], |
| 188 | 204 | ["needs-you", stale > 0 |
| 189 | 205 | ? fold("stale-pulls", `Pulls untouched for ${String(STALE_DAYS)} days`, String(stale), true, staleRows(ctx.auth.user!.kind !== "agent", stalePending)) |
test/maintenance-calm.test.ts +2
| @@ -59,6 +59,8 @@ test("a paused duty says needs you and opens the duties", async () => { | ||
| 59 | 59 | test("needsYou names each waiting thing", () => { |
| 60 | 60 | expect(needsYou({ phase: "idle", overdue: 0, paused: 0, stale: 0 })).toEqual([]); |
| 61 | 61 | expect(needsYou({ phase: "ready", healthy: false, overdue: 2, paused: 0, stale: 1 })).toEqual(["maintenance is on", "the last return failed a check", "2 duties overdue", "1 stale pull"]); |
| 62 | expect(needsYou({ phase: "idle", overdue: 0, paused: 0, stale: 0, vulnerable: 1 })).toEqual(["1 vulnerable dependency"]); | |
| 63 | expect(needsYou({ phase: "idle", overdue: 0, paused: 0, stale: 0, vulnerable: 3 })).toEqual(["3 vulnerable dependencies"]); | |
| 62 | 64 | }); |
| 63 | 65 | |
| 64 | 66 | test("every fold's summary carries a count", async () => { |
test/maintenance-finding-age.test.ts +8 −3
| @@ -2,9 +2,14 @@ | ||
| 2 | 2 | import { expect, test } from "bun:test"; |
| 3 | 3 | import { Database } from "bun:sqlite"; |
| 4 | 4 | import { findingsFold } from "../src/web/pages/maintenance.ts"; |
| 5 | import { mkdtempSync } from "node:fs"; | |
| 6 | import { tmpdir } from "node:os"; | |
| 7 | import { join } from "node:path"; | |
| 5 | 8 | import { findingLines, findingRows, findingsJson, openedWords, reopenFinding } from "../src/maintenance/findings.ts"; |
| 6 | 9 | |
| 7 | 10 | const DAY = 86_400_000; |
| 11 | /** A data directory with no OSV mirror in it: the findings here are the duties' own. */ | |
| 12 | const NO_MIRROR = mkdtempSync(join(tmpdir(), "finding-age-")); | |
| 8 | 13 | const NOW = Date.parse("2026-11-23T12:00:00.000Z"); |
| 9 | 14 | |
| 10 | 15 | function seed(): Database { |
| @@ -28,7 +33,7 @@ test("findings list oldest first, in the rows, the terminal and the JSON", () => | ||
| 28 | 33 | const db = seed(); |
| 29 | 34 | expect(findingRows(db).rows.map((r) => r.cause)).toEqual(["oldest", "middle", "newer"]); |
| 30 | 35 | expect(findingLines(db, NOW)[2]).toBe("oldest: x (opened 3 d ago; still open; untouched)"); |
| 31 | const json = findingsJson(db).findings; | |
| 36 | const json = findingsJson(db, NO_MIRROR).findings; | |
| 32 | 37 | expect(json.map((f) => f.duty)).toEqual(["oldest", "middle", "newer"]); |
| 33 | 38 | expect(json[0]?.openedAt).toBe(new Date(NOW - 3 * DAY).toISOString()); |
| 34 | 39 | }); |
| @@ -52,7 +57,7 @@ test("a cause that cleared and opened again keeps the age of its first kept span | ||
| 52 | 57 | const [row] = findingRows(db).rows; |
| 53 | 58 | expect(row?.openedAt).toBe(NOW - 5 * DAY); |
| 54 | 59 | expect(findingLines(db, NOW)[2]).toBe("disk: again (opened 5 d ago; still open; untouched)"); |
| 55 | expect(findingsJson(db).findings[0]?.openedAt).toBe(new Date(NOW - 5 * DAY).toISOString()); | |
| 60 | expect(findingsJson(db, NO_MIRROR).findings[0]?.openedAt).toBe(new Date(NOW - 5 * DAY).toISOString()); | |
| 56 | 61 | }); |
| 57 | 62 | |
| 58 | 63 | test("a row names who last touched it and when, or says untouched (#16187)", () => { |
| @@ -66,7 +71,7 @@ test("a row names who last touched it and when, or says untouched (#16187)", () | ||
| 66 | 71 | expect(lines.find((l) => l.startsWith("oldest:"))).toContain("last touched by ada 2 h ago"); |
| 67 | 72 | expect(lines.find((l) => l.startsWith("middle:"))).toContain("untouched"); |
| 68 | 73 | expect(String(findingsFold(db, NOW))).toContain("last touched by ada 2 h ago"); |
| 69 | const json = findingsJson(db).findings; | |
| 74 | const json = findingsJson(db, NO_MIRROR).findings; | |
| 70 | 75 | expect(json.find((f) => f.duty === "oldest")).toMatchObject({ touchedBy: "ada", touchedAt: new Date(NOW - 2 * 3_600_000).toISOString() }); |
| 71 | 76 | expect(json.find((f) => f.duty === "middle")).toMatchObject({ touchedBy: null, touchedAt: null }); |
| 72 | 77 | }); |
test/maintenance-json.test.ts +1 −1
| @@ -48,7 +48,7 @@ test("the JSON carries the findings the page lists, from the same module", async | ||
| 48 | 48 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); |
| 49 | 49 | expect(res.headers.get("referrer-policy")).toBeTruthy(); |
| 50 | 50 | expect(res.headers.get("content-security-policy")).toBeTruthy(); |
| 51 | expect(await res.json()).toEqual({ findings: want }); | |
| 51 | expect(await res.json()).toEqual({ findings: want, dependencies: [] }); | |
| 52 | 52 | } |
| 53 | 53 | const page = await (await fetch(`${servers.url}/maintenance`, { headers: { cookie } })).text(); |
| 54 | 54 | for (const r of findingRows(app.db).rows) expect(page).toContain(`data-finding="${r.cause}"`); |
test/maintenance-level.test.ts +30 −2
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | /** /maintenance?level= narrows the board to one severity; anything else shows all. */ |
| 2 | 2 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 3 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; | |
| 4 | 4 | import { tmpdir } from "node:os"; |
| 5 | 5 | import { join } from "node:path"; |
| 6 | 6 | import { createApp, type App } from "../src/app.ts"; |
| @@ -8,7 +8,7 @@ import { createRepo } from "../src/core/repos.ts"; | ||
| 8 | 8 | import { id } from "../src/kernel/id.ts"; |
| 9 | 9 | import { createUser } from "../src/core/users.ts"; |
| 10 | 10 | import { serve, type Servers } from "../src/http/server.ts"; |
| 11 | import { dutiesLevel, levelOf, nextLevel, returnLevel, stateLevel, type Level } from "../src/maintenance/level.ts"; | |
| 11 | import { dependencyLevel, dutiesLevel, levelOf, nextLevel, returnLevel, stateLevel, type Level } from "../src/maintenance/level.ts"; | |
| 12 | 12 | import { JOBS } from "../src/nightly/jobs.ts"; |
| 13 | 13 | import { writeLast } from "../src/nightly/stamps.ts"; |
| 14 | 14 | import { dutyStates, setPaused } from "../src/maintain/pause.ts"; |
| @@ -167,3 +167,31 @@ test("while maintenance is on, its sentence and End button stay off the calm vie | ||
| 167 | 167 | await fetch(`${servers.url}/maintenance/resume`, { method: "POST", redirect: "manual", headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, body: "" }); |
| 168 | 168 | } |
| 169 | 169 | }); |
| 170 | ||
| 171 | test("a vulnerable dependency needs you on both doors; a current mirror with none affected is fyi", async () => { | |
| 172 | expect(dependencyLevel(0)).toBe("fyi"); | |
| 173 | expect(dependencyLevel(2)).toBe("needs-you"); | |
| 174 | const { maintenanceLines } = await import("../src/tui/screens/maintenance.ts"); | |
| 175 | const { Session } = await import("../src/tui/session.ts"); | |
| 176 | const { getUserById } = await import("../src/core/users.ts"); | |
| 177 | const boss = app.db.query("SELECT id FROM user WHERE username = 'boss'").get() as { id: string }; | |
| 178 | const f = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: getUserById(app.db, boss.id) }); | |
| 179 | // The forge's own bun.lock pins typescript; an advisory over every version of it is one finding. | |
| 180 | const osv = join(dir, "osv"); | |
| 181 | await mkdir(osv, { recursive: true }); | |
| 182 | const advisory = { schema_version: "1.6.0", id: "GHSA-test-ts", modified: "2026-11-30T10:00:00Z", affected: [{ package: { ecosystem: "npm", name: "typescript" }, ranges: [{ type: "SEMVER", events: [{ introduced: "0" }] }] }] }; | |
| 183 | await writeFile(join(osv, "GHSA-test-ts.json"), JSON.stringify(advisory)); | |
| 184 | try { | |
| 185 | const needs = maintenanceLines(f, undefined, "needs-you").join("\n"); | |
| 186 | const fyi = maintenanceLines(f, undefined, "fyi").join("\n"); | |
| 187 | expect(needs).toContain("typescript 7.0.2 is affected by GHSA-test-ts"); | |
| 188 | expect(fyi).not.toContain("GHSA-test-ts"); | |
| 189 | // The page agrees, and its status line counts it rather than saying nothing needs you. | |
| 190 | const page = await get("?level=needs-you"); | |
| 191 | expect(page).toContain('id="maintenance-dependencies"'); | |
| 192 | expect(page).toMatch(/data-state="needs-you"[^\n]*vulnerable dependenc/); | |
| 193 | expect(await get("?level=fyi")).not.toContain('id="maintenance-dependencies"'); | |
| 194 | } finally { | |
| 195 | await rm(osv, { recursive: true, force: true }); | |
| 196 | } | |
| 197 | }); |
test/osv-findings.test.ts added +223
| @@ -0,0 +1,223 @@ | ||
| 1 | /** | |
| 2 | * The forge's pinned dependencies matched against the one OSV mirror (#17047), on main's | |
| 3 | * `src/security/`: OSV's range evaluation, the advisory checked at the boundary, the refresh that | |
| 4 | * keeps the old mirror and says why when a read fails, and the findings on /maintenance, one row | |
| 5 | * each naming the fix. No network: api.osv.dev is a stub handed in. | |
| 6 | */ | |
| 7 | import { expect, test } from "bun:test"; | |
| 8 | import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { GateRefusedError } from "../src/kernel/outbound.ts"; | |
| 12 | import type { Pinned } from "../src/security/lockfile.ts"; | |
| 13 | import { refreshMirror, type Fetch } from "../src/security/mirror.ts"; | |
| 14 | import { affectedBy, inRange, loadAdvisories, toAdvisory } from "../src/security/osv.ts"; | |
| 15 | import { forgeFindings } from "../src/security/forge_pins.ts"; | |
| 16 | import { readStanding, recordStanding } from "../src/security/standing.ts"; | |
| 17 | import { dependencyFindings, dependencyLine, dependencyLines, findingsJson } from "../src/maintenance/findings.ts"; | |
| 18 | import { dependenciesFold } from "../src/web/pages/maintenance.ts"; | |
| 19 | import { Database } from "bun:sqlite"; | |
| 20 | ||
| 21 | const npm = (name: string, version: string): Pinned => ({ ecosystem: "npm", name, version }); | |
| 22 | const tmp = (tag: string): string => mkdtempSync(join(tmpdir(), `osv-${tag}-`)); | |
| 23 | ||
| 24 | /** An advisory as OSV.dev serves it: GHSA-style, one npm package, one SEMVER range. */ | |
| 25 | function raw(id: string, name: string, events: Record<string, string>[], extra: Record<string, unknown> = {}): Record<string, unknown> { | |
| 26 | return { | |
| 27 | schema_version: "1.6.0", | |
| 28 | id, | |
| 29 | modified: "2026-11-30T10:00:00Z", | |
| 30 | summary: "<script>alert(1)</script>", | |
| 31 | affected: [{ package: { ecosystem: "npm", name }, ranges: [{ type: "SEMVER", events }] }], | |
| 32 | ...extra, | |
| 33 | }; | |
| 34 | } | |
| 35 | ||
| 36 | test("a range: affected from introduced, fixed at fixed, unaffected below and above", () => { | |
| 37 | const range = [{ introduced: "1.2.0" }, { fixed: "1.4.3" }]; | |
| 38 | expect(inRange("1.1.9", range)).toEqual({ affected: false, fixedIn: null }); | |
| 39 | expect(inRange("1.2.0", range)).toEqual({ affected: true, fixedIn: "1.4.3" }); | |
| 40 | expect(inRange("1.4.2", range)).toEqual({ affected: true, fixedIn: "1.4.3" }); | |
| 41 | expect(inRange("1.4.3", range)).toEqual({ affected: false, fixedIn: null }); | |
| 42 | expect(inRange("2.0.0", range)).toEqual({ affected: false, fixedIn: null }); | |
| 43 | // A pre-release of the fix precedes the fix, so it is still affected (semver §11). | |
| 44 | expect(inRange("1.4.3-rc.1", range)).toEqual({ affected: true, fixedIn: "1.4.3" }); | |
| 45 | }); | |
| 46 | ||
| 47 | test("introduced 0, two intervals, last_affected and limit, events in any order", () => { | |
| 48 | const two = [{ fixed: "2.1.0" }, { introduced: "0" }, { fixed: "1.0.5" }, { introduced: "2.0.0" }]; | |
| 49 | expect(inRange("0.0.1", two)).toEqual({ affected: true, fixedIn: "1.0.5" }); | |
| 50 | expect(inRange("0.0.0-alpha", two)?.affected).toBe(true); | |
| 51 | expect(inRange("1.5.0", two)?.affected).toBe(false); | |
| 52 | expect(inRange("2.0.9", two)).toEqual({ affected: true, fixedIn: "2.1.0" }); | |
| 53 | expect(inRange("2.1.0", two)?.affected).toBe(false); | |
| 54 | const last = [{ introduced: "3.0.0" }, { last_affected: "3.2.1" }]; | |
| 55 | expect(inRange("3.2.1", last)).toEqual({ affected: true, fixedIn: null }); | |
| 56 | expect(inRange("3.2.2", last)?.affected).toBe(false); | |
| 57 | const limit = [{ introduced: "0" }, { limit: "5.0.0" }]; | |
| 58 | expect(inRange("4.9.9", limit)?.affected).toBe(true); | |
| 59 | expect(inRange("5.0.0", limit)?.affected).toBe(false); | |
| 60 | // An event that is not semver: the range is never matched. | |
| 61 | expect(inRange("1.0.0", [{ introduced: "not a version" }])).toBeUndefined(); | |
| 62 | }); | |
| 63 | ||
| 64 | test("each affected pin names its advisory and its fix; listed versions match; unaffected pins do not", () => { | |
| 65 | const advisories = [ | |
| 66 | toAdvisory(raw("GHSA-aaaa-bbbb-cccc", "lodash", [{ introduced: "0" }, { fixed: "4.17.21" }]))!, | |
| 67 | toAdvisory(raw("GHSA-dddd-eeee-ffff", "@scope/pkg", [{ introduced: "2.0.0" }]))!, | |
| 68 | toAdvisory({ ...raw("GHSA-gggg-hhhh-iiii", "minimist", []), affected: [{ package: { ecosystem: "npm", name: "minimist" }, versions: ["1.2.5"] }] })!, | |
| 69 | ]; | |
| 70 | const hit = (p: Pinned) => affectedBy(p, advisories).map((f) => [f.package, f.version, f.advisory, f.fixedIn]); | |
| 71 | expect(hit(npm("lodash", "4.17.20"))).toEqual([["lodash", "4.17.20", "GHSA-aaaa-bbbb-cccc", "4.17.21"]]); | |
| 72 | expect(hit(npm("lodash", "4.17.21"))).toEqual([]); | |
| 73 | expect(hit(npm("@scope/pkg", "2.3.0"))).toEqual([["@scope/pkg", "2.3.0", "GHSA-dddd-eeee-ffff", null]]); | |
| 74 | expect(hit(npm("@scope/pkg", "1.9.0"))).toEqual([]); | |
| 75 | expect(hit(npm("minimist", "1.2.5"))).toEqual([["minimist", "1.2.5", "GHSA-gggg-hhhh-iiii", null]]); | |
| 76 | expect(hit(npm("minimist", "1.2.6"))).toEqual([]); | |
| 77 | }); | |
| 78 | ||
| 79 | test("where two ranges of one advisory hold a version, the lowest fix is named", () => { | |
| 80 | const adv = toAdvisory({ | |
| 81 | id: "GHSA-two", | |
| 82 | affected: [{ package: { ecosystem: "npm", name: "a" }, ranges: [ | |
| 83 | { type: "SEMVER", events: [{ introduced: "1.0.0" }, { fixed: "1.9.0" }] }, | |
| 84 | { type: "SEMVER", events: [{ introduced: "1.0.0" }, { fixed: "1.5.0" }] }, | |
| 85 | ] }], | |
| 86 | })!; | |
| 87 | expect(affectedBy(npm("a", "1.2.0"), [adv])[0]?.fixedIn).toBe("1.5.0"); | |
| 88 | }); | |
| 89 | ||
| 90 | test("an advisory is checked at the boundary: malformed and withdrawn are none; other ecosystems and git ranges never match", () => { | |
| 91 | expect(toAdvisory(null)).toBeUndefined(); | |
| 92 | expect(toAdvisory(raw("../../etc", "a", [{ introduced: "0" }]))).toBeUndefined(); | |
| 93 | expect(toAdvisory(raw("GHSA-x", "a", [{ introduced: "0", fixed: "1.0.0" }]))).toBeUndefined(); | |
| 94 | expect(toAdvisory(raw("GHSA-x", "a", []))).toBeUndefined(); | |
| 95 | expect(toAdvisory(raw("GHSA-x", "a", [{ introduced: "0" }], { withdrawn: "2026-01-01T00:00:00Z" }))).toBeUndefined(); | |
| 96 | expect(toAdvisory({ ...raw("GHSA-x", "a", []), affected: [{ package: { ecosystem: "npm", name: "a" }, versions: Array(5_001).fill("1.0.0") }] })).toBeUndefined(); | |
| 97 | expect(toAdvisory({ ...raw("GHSA-x", "a", []), affected: [{ package: "a" }] })).toBeUndefined(); | |
| 98 | expect(toAdvisory({ ...raw("GHSA-x", "a", []), affected: Array(201).fill({ package: { ecosystem: "npm", name: "a" } }) })).toBeUndefined(); | |
| 99 | const pypi = toAdvisory({ ...raw("GHSA-x", "a", []), affected: [{ package: { ecosystem: "PyPI", name: "a" }, ranges: [{ type: "ECOSYSTEM", events: [{ introduced: "0" }] }] }] })!; | |
| 100 | expect(affectedBy(npm("a", "1.0.0"), [pypi])).toEqual([]); | |
| 101 | const git = toAdvisory({ ...raw("GHSA-x", "a", []), affected: [{ package: { ecosystem: "npm", name: "a" }, ranges: [{ type: "GIT", repo: "x", events: [{ introduced: "abc" }] }] }] })!; | |
| 102 | expect(affectedBy(npm("a", "1.0.0"), [git])).toEqual([]); | |
| 103 | // Only what matching reads is kept: no `repo`, no stray keys on events. | |
| 104 | expect(toAdvisory({ ...raw("GHSA-x", "a", [{ introduced: "0", note: "x" }]) })?.affected[0]?.ranges?.[0]?.events).toEqual([{ introduced: "0" }]); | |
| 105 | }); | |
| 106 | ||
| 107 | /** | |
| 108 | * A stub of api.osv.dev: querybatch lists `vulns` per package, /v1/vulns/{id} answers the advisory. | |
| 109 | */ | |
| 110 | function osv(vulns: Record<string, Record<string, unknown>[]>): Fetch { | |
| 111 | return async (url, init) => { | |
| 112 | const u = new URL(url); | |
| 113 | if (u.host !== "api.osv.dev") throw new Error(`unexpected host ${u.host}`); | |
| 114 | if (u.pathname === "/v1/querybatch") { | |
| 115 | const asked = JSON.parse(String(init?.body)) as { queries: { package: { name: string } }[] }; | |
| 116 | return Response.json({ results: asked.queries.map((q) => ({ vulns: (vulns[q.package.name] ?? []).map((a) => ({ id: a["id"], modified: a["modified"] })) })) }); | |
| 117 | } | |
| 118 | const id = decodeURIComponent(u.pathname.slice("/v1/vulns/".length)); | |
| 119 | const found = Object.values(vulns).flat().find((a) => a["id"] === id); | |
| 120 | return found === undefined ? new Response("not found", { status: 404 }) : Response.json(found); | |
| 121 | }; | |
| 122 | } | |
| 123 | ||
| 124 | const T0 = Date.parse("2026-12-01T10:00:00.000Z"); | |
| 125 | const LODASH = raw("GHSA-35jh-r3h4-6jhm", "lodash", [{ introduced: "0" }, { fixed: "4.17.21" }]); | |
| 126 | ||
| 127 | test("an answer larger than the cap is abandoned while streaming; the mirror is kept", async () => { | |
| 128 | const dir = join(tmp("cap"), "osv"); | |
| 129 | await refreshMirror(dir, [npm("lodash", "4.17.20")], osv({ lodash: [LODASH] })); | |
| 130 | let pulled = 0; | |
| 131 | let cancelled = false; | |
| 132 | const MiB = new Uint8Array(1 << 20).fill(0x20); | |
| 133 | // An endless body with no content-length: only counting the bytes read can stop it. | |
| 134 | const flood: Fetch = async () => | |
| 135 | new Response( | |
| 136 | new ReadableStream<Uint8Array>({ | |
| 137 | pull(c) { | |
| 138 | pulled++; | |
| 139 | c.enqueue(MiB); | |
| 140 | }, | |
| 141 | cancel() { | |
| 142 | cancelled = true; | |
| 143 | }, | |
| 144 | }), | |
| 145 | { status: 200 }, | |
| 146 | ); | |
| 147 | expect(await refreshMirror(dir, [npm("lodash", "4.17.20")], flood)).toEqual({ asked: 1, written: 0, failed: 1, why: "api.osv.dev answered more than 4000000 bytes, or broke off" }); | |
| 148 | expect(cancelled).toBe(true); | |
| 149 | expect(pulled).toBeLessThanOrEqual(6); | |
| 150 | expect(loadAdvisories(dir).map((a) => a.id)).toEqual(["GHSA-35jh-r3h4-6jhm"]); | |
| 151 | }); | |
| 152 | ||
| 153 | test("a failed refresh keeps the old mirror and says why, in the gate's words when the gate refused", async () => { | |
| 154 | const dataDir = tmp("fail"); | |
| 155 | const dir = join(dataDir, "osv"); | |
| 156 | const pins = [npm("lodash", "4.17.20")]; | |
| 157 | recordStanding(dataDir, await refreshMirror(dir, pins, osv({ lodash: [LODASH] })), T0); | |
| 158 | expect(readStanding(dataDir)).toEqual({ checkedAt: T0, okAt: T0, why: null, advisories: 1 }); | |
| 159 | const down: Fetch = async () => new Response("busy", { status: 503 }); | |
| 160 | expect((await refreshMirror(dir, pins, down)).why).toBe("api.osv.dev answered HTTP 503"); | |
| 161 | const marked: Fetch = async () => new Response("no", { status: 403, headers: { "x-forge-egress": "refused" } }); | |
| 162 | const words = "refused by this forge: api.osv.dev is not in this app's forge.json egress"; | |
| 163 | expect((await refreshMirror(dir, pins, marked)).why).toBe(words); | |
| 164 | const thrown: Fetch = async () => { | |
| 165 | throw new GateRefusedError("api.osv.dev"); | |
| 166 | }; | |
| 167 | const refused = await refreshMirror(dir, pins, thrown); | |
| 168 | expect(refused.why).toBe(words); | |
| 169 | recordStanding(dataDir, refused, T0 + 3_600_000); | |
| 170 | expect(loadAdvisories(dir).map((a) => a.id)).toEqual(["GHSA-35jh-r3h4-6jhm"]); | |
| 171 | expect(readStanding(dataDir)).toEqual({ checkedAt: T0 + 3_600_000, okAt: T0, why: words, advisories: 1 }); | |
| 172 | const root = tmp("root"); | |
| 173 | expect(dependencyLines(dependencyFindings(dataDir, root))).toEqual(["", "Vulnerable dependencies (OSV.dev):", `OSV refresh failed at 2026-12-01T11:00:00.000Z: ${words}; kept the mirror from 2026-12-01T10:00:00.000Z (1 advisories)`]); | |
| 174 | // The next refresh that reads everything clears the line. | |
| 175 | recordStanding(dataDir, await refreshMirror(dir, pins, osv({ lodash: [LODASH] })), T0 + 7_200_000); | |
| 176 | expect(dependencyLines(dependencyFindings(dataDir, root))).toEqual([]); | |
| 177 | }); | |
| 178 | ||
| 179 | /** A data directory whose mirror holds `advisories`, and a root whose bun.lock pins `pins`. */ | |
| 180 | function forge(advisories: Record<string, unknown>[], pins: string[]): { dataDir: string; root: string } { | |
| 181 | const dataDir = tmp("data"); | |
| 182 | mkdirSync(join(dataDir, "osv")); | |
| 183 | for (const a of advisories) writeFileSync(join(dataDir, "osv", `${String(a["id"])}.json`), JSON.stringify(a)); | |
| 184 | const root = tmp("root"); | |
| 185 | const packages = Object.fromEntries(pins.map((p, i) => [`p${String(i)}`, [p, "", {}, "sha512-x"]])); | |
| 186 | writeFileSync(join(root, "bun.lock"), JSON.stringify({ lockfileVersion: 1, workspaces: { "": { name: "app" } }, packages })); | |
| 187 | return { dataDir, root }; | |
| 188 | } | |
| 189 | ||
| 190 | test("the forge's own root lockfile is matched against the mirror, locally, and a new advisory is seen at once", () => { | |
| 191 | const { dataDir, root } = forge([LODASH], ["[email protected]", "[email protected]"]); | |
| 192 | expect(forgeFindings(dataDir, root)).toEqual([{ name: "lodash", version: "4.17.20", id: "GHSA-35jh-r3h4-6jhm", fixedIn: "4.17.21" }]); | |
| 193 | const db = new Database(":memory:"); | |
| 194 | db.run("CREATE TABLE degraded_span (id INTEGER PRIMARY KEY AUTOINCREMENT, cause TEXT NOT NULL, sentence TEXT NOT NULL, href TEXT NOT NULL, opened_at INTEGER NOT NULL, closed_at INTEGER, swept_at INTEGER, clock_at INTEGER, touched_by TEXT, touched_at INTEGER)"); | |
| 195 | expect(findingsJson(db, dataDir, root)).toEqual({ findings: [], dependencies: forgeFindings(dataDir, root) }); | |
| 196 | writeFileSync(join(dataDir, "osv", "GHSA-ms.json"), JSON.stringify(raw("GHSA-ms", "ms", [{ introduced: "2.0.0" }, { fixed: "2.1.4" }]))); | |
| 197 | expect(forgeFindings(dataDir, root).map((f) => f.id)).toEqual(["GHSA-35jh-r3h4-6jhm", "GHSA-ms"]); | |
| 198 | }); | |
| 199 | ||
| 200 | test("on /maintenance each vulnerable dependency is one row: the label names the pin, the value the advisory and fix, escaped", () => { | |
| 201 | const { dataDir, root } = forge([LODASH, raw("GHSA-zz", "<b>x</b>", [{ introduced: "0" }])], ["[email protected]", "<b>x</b>@1.0.0"]); | |
| 202 | const out = String(dependenciesFold(dependencyFindings(dataDir, root))); | |
| 203 | expect(out).toContain("lodash 4.17.20"); | |
| 204 | expect(out).toContain("affected by GHSA-35jh-r3h4-6jhm; fixed in 4.17.21"); | |
| 205 | // Said once: the row's value does not repeat its label. | |
| 206 | expect(out).not.toContain("lodash 4.17.20 is affected"); | |
| 207 | expect(out).toContain("<b>x</b> 1.0.0"); | |
| 208 | expect(out).toContain("affected by GHSA-zz; no fixed version is published yet"); | |
| 209 | expect(out).not.toContain("<b>x</b>"); | |
| 210 | expect(out).toContain('id="maintenance-dependencies"'); | |
| 211 | expect(dependencyLines(dependencyFindings(dataDir, root)).slice(1)).toEqual([ | |
| 212 | "Vulnerable dependencies (OSV.dev):", | |
| 213 | "<b>x</b> 1.0.0 is affected by GHSA-zz; no fixed version is published yet", | |
| 214 | "lodash 4.17.20 is affected by GHSA-35jh-r3h4-6jhm; fixed in 4.17.21", | |
| 215 | ]); | |
| 216 | expect(dependencyLine({ name: "a", version: "1.0.0", id: "X-1", fixedIn: "1.0.1" })).toBe("a 1.0.0 is affected by X-1; fixed in 1.0.1"); | |
| 217 | }); | |
| 218 | ||
| 219 | test("nothing affected and a current mirror: no fold, no lines", () => { | |
| 220 | const { dataDir, root } = forge([LODASH], ["[email protected]"]); | |
| 221 | expect(String(dependenciesFold(dependencyFindings(dataDir, root)))).toBe(""); | |
| 222 | expect(dependencyLines(dependencyFindings(dataDir, root))).toEqual([]); | |
| 223 | }); |
test/retention-events.test.ts +3 −1
| @@ -294,8 +294,10 @@ describe("pruneLiveEvents: wake-ups live hours, not 30 days", () => { | ||
| 294 | 294 | })(); |
| 295 | 295 | pruneLiveEvents(db, NOW, 1); |
| 296 | 296 | let r = { deleted: 0, more: false }; |
| 297 | // No wall-clock budget: a loaded box past LIVE_SLICE_MS would end the slice early (#17047); | |
| 298 | // the count of statements, not the clock, is under test. | |
| 297 | 299 | const cost = await (await import("./helpers/statements.ts")).once(db, () => { |
| 298 | r = pruneLiveEvents(db, NOW); | |
| 300 | r = pruneLiveEvents(db, NOW, LIVE_SLICE_ROWS, LIVE_KEEP_MS, Number.POSITIVE_INFINITY); | |
| 299 | 301 | }); |
| 300 | 302 | expect(r.deleted).toBe(LIVE_SLICE_ROWS); |
| 301 | 303 | expect(r.more).toBe(true); |
test/runner-adopt.test.ts +3
| @@ -146,6 +146,9 @@ describe("a restart with a job on a runner", () => { | ||
| 146 | 146 | // this job at once instead of waiting for its own pull's: a race on how fast the lane offers. |
| 147 | 147 | for (const run of again) cancelRun(f.app.db, run.id); |
| 148 | 148 | f.checks = startChecks(f.app, options()); |
| 149 | // The check queued again settles before the next test's runner claims: left queued, that | |
| 150 | // claim would be handed this job and never wait (#17047: 4 s lost under load). | |
| 151 | await f.settled((r) => r.commitOid === c.oid && r.id !== c.runId, 30_000); | |
| 149 | 152 | }); |
| 150 | 153 | |
| 151 | 154 | test("a job a live forge still waits on is never taken back: only one its forge handed over", async () => { |
test/security-osv.test.ts +5 −1
| @@ -13,6 +13,7 @@ import { listIssues } from "../src/core/issues.ts"; | ||
| 13 | 13 | import { FORGE_SCOPE } from "../src/core/config.ts"; |
| 14 | 14 | import { reportAt, reportWait } from "../src/security/report_cache.ts"; |
| 15 | 15 | import { refreshOsv } from "../src/security/duty.ts"; |
| 16 | import { readStanding } from "../src/security/standing.ts"; | |
| 16 | 17 | import { findingRows } from "../src/tui/screens/dependencies.ts"; |
| 17 | 18 | import { seedAdmin } from "./helpers/admin.ts"; |
| 18 | 19 | |
| @@ -233,7 +234,7 @@ describe("mirror refresh", () => { | ||
| 233 | 234 | return url.endsWith("GHSA-aaaa-0001") ? Response.json(doc) : Response.json({ nope: 1 }); |
| 234 | 235 | }; |
| 235 | 236 | const pins = [{ ecosystem: "npm" as const, name: "lodash", version: "4.17.20" }]; |
| 236 | expect(await refreshMirror(dir, pins, fake)).toEqual({ asked: 1, written: 1, failed: 1 }); | |
| 237 | expect(await refreshMirror(dir, pins, fake)).toEqual({ asked: 1, written: 1, failed: 1, why: "api.osv.dev answered something that is not an OSV advisory for BAD-1" }); | |
| 237 | 238 | expect(loadAdvisories(dir).map((a) => a.id)).toEqual(["GHSA-aaaa-0001"]); |
| 238 | 239 | calls.length = 0; |
| 239 | 240 | expect((await refreshMirror(dir, pins, fake)).written).toBe(0); |
| @@ -276,6 +277,9 @@ describe("what leaves the forge", () => { | ||
| 276 | 277 | expect(all).toContain("left-pad"); |
| 277 | 278 | expect(all).toContain("opted-pkg"); |
| 278 | 279 | expect(all).not.toContain("secret-pkg"); |
| 280 | // The duty keeps its outcome for the board (#17047): a refresh that read everything. | |
| 281 | expect(readStanding(dataDir)).toMatchObject({ why: null }); | |
| 282 | expect(readStanding(dataDir).okAt).not.toBeNull(); | |
| 279 | 283 | } finally { |
| 280 | 284 | servers.stop(); |
| 281 | 285 | app.close(); |
test/signup-fresh.test.ts +5 −2
| @@ -77,8 +77,11 @@ describe("main.ts", () => { | ||
| 77 | 77 | stderr: "ignore", |
| 78 | 78 | }); |
| 79 | 79 | try { |
| 80 | // A wall-clock deadline, not a count of tries: a loaded check box has booted main.ts in | |
| 81 | // 11.8 s (the gate box's usual is 3.1 s), and what this asserts is the stored value. | |
| 82 | const deadline = Date.now() + 40_000; | |
| 80 | 83 | let value: string | undefined; |
| 81 | for (let i = 0; i < 100 && value === undefined; i++) { | |
| 84 | while (value === undefined && Date.now() < deadline) { | |
| 82 | 85 | await Bun.sleep(100); |
| 83 | 86 | try { |
| 84 | 87 | const db = new Database(join(dir, "forge.db"), { readonly: true }); |
| @@ -91,5 +94,5 @@ describe("main.ts", () => { | ||
| 91 | 94 | proc.kill(); |
| 92 | 95 | await proc.exited; |
| 93 | 96 | } |
| 94 | }); | |
| 97 | }, 60_000); | |
| 95 | 98 | }); |
new above
offline