Public: anyone can read this; the crew can change it.

Security against 24/7 agent swarms: OSV dependency scans with auto-fix pulls, secret scanning at push, code scanning in review, an exposure map with rate limits, a scheduled red team #16997

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/6004-security-against-24-7-agent-swarms-osv-d → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/6004-security-against-24-7-agent-swarms-osv-d was merged into main as e1014df.

Review

Sign in to review this change.
22 files changed +1096 −7
docs/features/security-osv.md added +17
@@ -0,0 +1,17 @@
1 ---
2 topic: Ship and undo
3 row: "Dependency scan: a repository's lockfile against OSV advisories"
4 ---
5 # Dependency scan (OSV)
6
7 `GET /api/v1/repos/:owner/:name/dependencies[?ref=]` reads a repository's `bun.lock` / `package-lock.json` at a ref and matches the pins against OSV advisories mirrored as `*.json` files under `$FORGE_APP_DATA/osv/`. Each finding names the advisory, severity and the smallest fixed version. No dependency added; the response also carries `fixes`: per vulnerable pin the smallest bump that clears every advisory, critical first. The mirror refreshes hourly from api.osv.dev (`security/mirror.ts`, only the advisories for pins the forge holds; the host is in `egress`). After each refresh the same hourly duty files one issue per fixable pin in the repository's own tracker (`security/fix_issues.ts`: "Bump lodash from 4.17.20 to 4.17.21 (critical advisory)"), critical first, at most 3 new per repository per pass, none when one with that title is open; the crew picks the issue up and opens the pull, with its own check and normal review.
8
9 **Terminal:** open a repository, then the palette entry "Dependencies" (`src/tui/screens/dependencies.ts`): one row per finding, `g` reads again. It shows what the API shows, to whoever can read the repository, through the same cache and rate limit.
10
11 **Load.** The report is held by commit oid and the mirror's stamp, so a repeat read costs a lookup; a client address may read 20 times a minute and the forge 300 (429 with `Retry-After` beyond), and one read takes at most 20 lockfiles and 30 MB.
12
13 **Who takes part.** The hourly duty touches the forge's own repository (`forgeRepo`) and the `owner/name` entries of the forge config key `osv.repos`; no other repository gets issues filed as its owner. The mirror refresh sends the names and versions of pinned packages (nothing else) to api.osv.dev for public repositories and those same entries; a private repository that has not opted in never has a pin leave the forge. A bump already filed as an issue, open or closed, is not filed again.
14
15 **Secrets.** A pushed secret is handled one way: code scanning (#9593) accepts the push and records the finding. This feature adds no push refusal.
16
17 Not built yet: queue priority for critical issues (the tracker has none), and the security tab (#6004).
forge.json +2 −1
@@ -19,7 +19,8 @@
1919 "login.microsoftonline.com",
2020 "management.azure.com",
2121 "api.typesafe.ai",
22 "graph.instagram.com"
22 "graph.instagram.com",
23 "api.osv.dev"
2324 ],
2425 "schedules": [
2526 { "name": "heartbeat", "cron": "5 7 * * *", "timezone": "UTC", "path": "/jobs/heartbeat", "timeout": 120, "retries": 3, "catchUp": "6h" }
src/contract/openapi/routes/getApiV1ReposOwnerNameDependencies.ts added +13
@@ -0,0 +1,13 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `${REPO}/dependencies`,
6 summary: "A repository's lockfile pins against the local OSV mirror",
7 detail: "Reads the lockfiles at `ref` (default: the default branch) and answers the report of vulnerable pins with `fixes`, the smallest bump per pin; never cached",
8 auth: false,

Non-blocking: "never cached" is stale. The client gets no-store, but the server holds the report by commit oid and mirror stamp. Reword it.

9 role: "anonymous",
10 query: { ref: "string" },
11 reply: { findings: "array", fixes: "array" },
12 refuses: [404],
13 };
src/contract/openapi/routes/index.ts +1
@@ -175,6 +175,7 @@ export { route as getApiV1ReposOwnerNameDataEnvFileRows } from "./getApiV1ReposO
175175 export { route as getApiV1ReposOwnerNameDataEnvFileTables } from "./getApiV1ReposOwnerNameDataEnvFileTables.ts";
176176 export { route as getApiV1ReposOwnerNameDataMove } from "./getApiV1ReposOwnerNameDataMove.ts";
177177 export { route as getApiV1ReposOwnerNameDecisions } from "./getApiV1ReposOwnerNameDecisions.ts";
178 export { route as getApiV1ReposOwnerNameDependencies } from "./getApiV1ReposOwnerNameDependencies.ts";
178179 export { route as getApiV1ReposOwnerNameDesk } from "./getApiV1ReposOwnerNameDesk.ts";
179180 export { route as getApiV1ReposOwnerNameDrop } from "./getApiV1ReposOwnerNameDrop.ts";
180181 export { route as getApiV1ReposOwnerNameDropFile } from "./getApiV1ReposOwnerNameDropFile.ts";
src/contract/tags.ts +1
@@ -114,6 +114,7 @@ const ALIAS: Readonly<Record<string, string>> = {
114114 deepsec: "reports",
115115 status: "reports",
116116 envelope: "apps",
117 dependencies: "repos",
117118 };
118119
119120 /** One line on each tag the document lists. */
src/engine/duties.ts +8
@@ -13,6 +13,8 @@
1313 * list back (`takeBack`): the forge is then one thread that serves and works.
1414 */
1515
16 import { refreshOsv } from "../security/duty.ts";
17 import { fileAllFixIssues } from "../security/fix_issues.ts";
1618 import { pruneCopies } from "../core/copies.ts";
1719 import type { App } from "../app.ts";
1820 import { runModelReview } from "../actions/model_review.ts";
@@ -76,6 +78,12 @@ export function startDuties(app: App, options: { onWorker: boolean }): () => voi
7678 // archived after a month (`actions/start_sweep.ts`, #10912): hourly, and on boot.
7779 timers.push(setInterval(() => during("starts", () => void sweepStarts(app), undefined, app), HOUR_MS));
7880 during("starts", () => void sweepStarts(app), undefined, app);
81 // The OSV mirror the dependency scan reads is refreshed hourly (`security/duty.ts`, #6004).
82 const osv = (): void =>
83 void refreshOsv(app)
84 .then(() => fileAllFixIssues(app))
85 .catch((error) => app.log.warn("osv refresh failed", { error: String(error) }));
86 timers.push(setInterval(() => during("osv-mirror", osv, undefined, app), HOUR_MS));
7987 // A token a brokered sign-in sealed is swept by a timer a minute later
8088 // (`spawn/origin_broker.ts`), and a timer dies with its process: what a restart left past its
8189 // minute goes here, on boot.
src/http/api.ts +15
@@ -95,6 +95,7 @@ import {
9595 deleteBranch as deleteBranchAction,
9696 } from "../actions/branches.ts";
9797 import { editFiles, type EditFile } from "../actions/contents.ts";
98 import { reportAt, reportWait } from "../security/report_cache.ts";
9899 import {
99100 contribute,
100101 type ContributeResult,
@@ -2168,6 +2169,20 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
21682169 rendering,
21692170 );
21702171 };
2172 // Lockfiles at a ref against the local OSV mirror (`security/`): the data
2173 // layer of the repository's security tab.
2174 router.add("GET", "/api/v1/repos/:owner/:name/dependencies", async (ctx) => {
2175 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
2176 const repo = loadRepo(ctx);
2177 if (!repo) return notFound();
2178 const ref = ctx.url.searchParams.get("ref") || repo.defaultBranch;
2179 if (!isSafeRef(ref)) return notFound();
2180 const wait = reportWait(ctx.app, clientAddress(ctx.request));
2181 if (wait !== undefined) return tryAgain("rate_limited", 429, "too many dependency reads; wait and ask again", wait);
2182 const report = await reportAt(ctx.app, ctx.app.config.dataDir, dirOf(ctx, repo), ref);
2183 if (!report) return notFound();
2184 return json(report, 200, { "cache-control": "no-store" });
2185 });
21712186 router.add("GET", "/api/v1/repos/:owner/:name/contents", contentsHandler);
outdated

Unauthenticated, uncached and unmetered: lockfile reads, parsing and a full advisory reload per request. Cache by oid + mirror mtime and rate-limit by socket address.

21722187 router.add(
21732188 "GET",
src/kernel/json_string.ts added +13
@@ -0,0 +1,13 @@
1 /**
2 * One string field of a JSON document, or "" when the text is not JSON, not an object, or the field
3 * is not a string.
4 */
5 export function stringField(raw: Uint8Array | string, key: string): string {
6 try {
7 const doc = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw)) as Record<string, unknown> | null;
8 const v = doc?.[key];
9 return typeof v === "string" ? v : "";
10 } catch {
11 return "";
12 }
13 }
src/security/duty.ts added +36
@@ -0,0 +1,36 @@
1 /**
2 * The hourly duty: gather the pins at the default branch of each repository that may be asked
3 * about (public, or opted in: `security/optin.ts`) and refresh the mirror. Private repositories
4 * that have not opted in never have a pin sent to api.osv.dev.
5 */
6
7 import { join } from "node:path";
8 import type { App } from "../app.ts";
9 import { repoDir } from "../git/repos.ts";
10 import { refreshMirror, type Fetch, type Refresh } from "./mirror.ts";
11 import { mayAsk } from "./optin.ts";
12 import { pinsOf } from "./scan.ts";
13 import type { Pinned } from "./lockfile.ts";
14
outdated

Pins of every repo, private included, go to api.osv.dev. Limit to public/opted-in repos or document it.

15 const MAX_REPOS = 5000;
16
17 export async function refreshOsv(app: Pick<App, "db" | "reposRoot" | "config" | "configs" | "log">, fetcher?: Fetch): Promise<Refresh> {
18 const rows = app.db
19 .query<{ owner: string; name: string; branch: string; visibility: "public" | "private" }, [number]>(
20 `SELECT user.username AS owner, repo.name AS name, repo.default_branch AS branch, repo.visibility AS visibility
21 FROM repo JOIN user ON user.id = repo.owner_id ORDER BY repo.id LIMIT ?1`,
22 )
23 .all(MAX_REPOS);
24 const pins: Pinned[] = [];
25 for (const r of rows) {
26 if (!mayAsk(app, r)) continue;
27 try {
28 pins.push(...(await pinsOf(repoDir(app.reposRoot, r.owner, r.name), r.branch)).pins);
29 } catch {
30 // A repository that cannot be read is skipped; the rest still refresh.
31 }
32 }
33 const out = await refreshMirror(join(app.config.dataDir, "osv"), pins, fetcher);
34 app.log.info("osv mirror refreshed", { ...out });
35 return out;
36 }
src/security/fix.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * The upgrade a fix pull would make: for each vulnerable pin, the smallest
3 * version that clears every advisory on it. Plain data in, plain data out;
4 * opening the pull is the crew's job and is not done here.
5 */
6
7 import { compareVersions, type Finding, type Severity } from "./osv.ts";
8
9 export interface Bump {
10 readonly package: string;
11 readonly from: string;
12 /** The highest `fixedIn` among the pin's advisories: clears all of them. */
13 readonly to: string;
14 readonly severity: Severity;
15 readonly advisories: readonly string[];
16 }
17
18 const RANK: Record<Severity, number> = { critical: 0, high: 1, moderate: 2, low: 3, unknown: 4 };
19
20 /** One bump per pin, critical first; pins whose advisories name no fix are left out. */
21 export function planFixes(findings: readonly Finding[]): Bump[] {
22 const byPin = new Map<string, Finding[]>();
23 for (const f of findings) {
24 const key = `${f.package}@${f.version}`;
25 byPin.set(key, [...(byPin.get(key) ?? []), f]);
26 }
27 const out: Bump[] = [];
28 for (const group of byPin.values()) {
29 // One advisory without a fix means no bump clears the pin: skip it whole.
30 if (group.some((f) => f.fixedIn === null)) continue;
31 const to = group.map((f) => f.fixedIn as string).reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b));
32 const worst = group.reduce((a, b) => (RANK[a.severity] <= RANK[b.severity] ? a : b));
33 out.push({
34 package: worst.package,
35 from: worst.version,
36 to,
37 severity: worst.severity,
38 advisories: group.map((f) => f.advisory),
39 });
40 }
41 return out.sort((a, b) => RANK[a.severity] - RANK[b.severity] || a.package.localeCompare(b.package));
42 }
src/security/fix_issues.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * Fix issues (#6004): for every repository, one issue per vulnerable pin that a bump clears, in
3 * the repository's own tracker where the crew picks it up and opens the pull (its own check,
4 * normal review). An issue for the same bump, open or closed, is not filed twice. Only the forge's
5 * own repository and those that opted in take part (`optin.ts`). Critical first, so a critical pin
6 * is filed before a low one when a pass runs out of its per-repository cap.
7 */
8
9 import { join } from "node:path";
10 import type { App } from "../app.ts";
11 import { openIssue } from "../actions/issues.ts";
12 import { listIssues } from "../core/issues.ts";
13 import { getRepo } from "../core/repos.ts";
14 import { getUserById } from "../core/users.ts";
15 import { repoDir } from "../git/repos.ts";
16 import { planFixes, type Bump } from "./fix.ts";
17 import { loadAdvisories, type Advisory } from "./osv.ts";
18 import { optedIn } from "./optin.ts";
19 import { scanRepo } from "./scan.ts";
20
21 /** At most this many new fix issues per repository per pass. */
22 export const PER_PASS = 3;
23 const MAX_REPOS = 5000;
24
25 export function fixTitle(b: Bump): string {
26 return `Bump ${b.package} from ${b.from} to ${b.to} (${b.severity} advisory)`;
27 }
28
29 export function fixBody(b: Bump): string {
30 return [
31 `\`${b.package}\` ${b.from} is affected by ${b.advisories.join(", ")} (OSV, ${b.severity}).`,
32 `Upgrade it to ${b.to}, the smallest version that clears every advisory on it, in each lockfile that pins ${b.from}.`,
33 "Change the lockfile (and the manifest range when it forbids the bump) and nothing else.",
34 ].join("\n\n");
35 }
36
37 /** One repository: file the bumps not already open as issues; returns how many were filed. */
38 export async function fileFixIssues(
39 app: Pick<App, "db" | "reposRoot">,
40 repoId: string,
41 advisories: readonly Advisory[],
42 ): Promise<number> {
43 const row = app.db
44 .query<{ owner: string; name: string; branch: string }, [string]>(
45 `SELECT user.username AS owner, repo.name AS name, repo.default_branch AS branch
46 FROM repo JOIN user ON user.id = repo.owner_id WHERE repo.id = ?1`,
47 )
48 .get(repoId);
49 if (!row) return 0;
50 const repo = getRepo(app.db, row.owner, row.name);
51 const actor = repo && getUserById(app.db, repo.ownerId);
52 if (!repo || !actor) return 0;
53 const report = await scanRepo(repoDir(app.reposRoot, row.owner, row.name), row.branch, advisories);
outdated

Only open titles are checked, so a closed or declined bump is filed again every hour. Dedupe against closed issues too.

54 let filed = 0;
55 for (const bump of planFixes(report.findings)) {
56 if (filed >= PER_PASS) break;
57 const title = fixTitle(bump);
58 // Open or closed: a bump the crew declined or already made is not asked for again.
59 const seen = listIssues(app.db, repo.id, { state: "all", kind: "issue", query: title, limit: 20 });
60 if (seen.some((i) => i.title === title)) continue;
61 if (openIssue(app as App, actor, repo, { title, body: fixBody(bump) }).ok) filed++;
62 }
63 return filed;
64 }
65
66 /**
67 * Every repository's default branch against the mirror; one bad repository does not stop the rest.
68 */
69 export async function fileAllFixIssues(app: App): Promise<number> {
70 const advisories = loadAdvisories(join(app.config.dataDir, "osv"));
71 if (advisories.length === 0) return 0;
72 const rows = app.db
73 .query<{ id: string; owner: string; name: string; visibility: "public" | "private" }, [number]>(
74 `SELECT repo.id AS id, user.username AS owner, repo.name AS name, repo.visibility AS visibility
75 FROM repo JOIN user ON user.id = repo.owner_id ORDER BY repo.id LIMIT ?1`,
76 )
77 .all(MAX_REPOS);
78 let filed = 0;
79 for (const { id, ...r } of rows) {
80 if (!optedIn(app, r)) continue;
81 try {
82 filed += await fileFixIssues(app, id, advisories);
83 } catch {
84 // Unreadable repository: skipped, the rest still run.
85 }
86 }
87 return filed;
88 }
src/security/lockfile.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * Lockfile text in, the packages it pins out. `bun.lock` (JSONC: trailing
3 * commas) and `package-lock.json` (v2/v3 `packages`) are read; any other file
4 * is not a lockfile this module knows, and yields nothing.
5 */
6
7 export interface Pinned {
8 readonly ecosystem: "npm";
9 readonly name: string;
10 readonly version: string;
11 }
12
13 /** Lockfile paths worth reading, by basename. */
14 export const LOCKFILES: readonly string[] = ["bun.lock", "package-lock.json"];
15
16 export function isLockfile(path: string): boolean {
17 return LOCKFILES.includes(path.slice(path.lastIndexOf("/") + 1));
18 }
19
20 /** Drop trailing commas outside strings, so JSONC parses as JSON. */
21 function stripTrailingCommas(text: string): string {
22 let out = "";
23 let inString = false;
24 for (let i = 0; i < text.length; i++) {
25 const c = text[i]!;
26 if (inString) {
27 out += c;
28 if (c === "\\") out += text[++i] ?? "";
29 else if (c === '"') inString = false;
30 } else if (c === '"') {
31 inString = true;
32 out += c;
33 } else if (c === ",") {
34 let j = i + 1;
35 while (j < text.length && /\s/.test(text[j]!)) j++;
36 if (text[j] !== "}" && text[j] !== "]") out += c;
37 } else out += c;
38 }
39 return out;
40 }
41
42 function parse(text: string): unknown {
43 try {
44 return JSON.parse(stripTrailingCommas(text));
45 } catch {
46 return undefined;
47 }
48 }
49
50 const isRecord = (v: unknown): v is Record<string, unknown> =>
51 typeof v === "object" && v !== null && !Array.isArray(v);
52
53 /** `[email protected]` → its parts; an alias (`npm:x@1`) or a git/file spec is skipped. */
54 function splitSpec(spec: string): Pinned | undefined {
55 const at = spec.lastIndexOf("@");
56 if (at <= 0 || spec.includes("@npm:")) return undefined;
57 const name = spec.slice(0, at);
58 const version = spec.slice(at + 1);
59 if (!/^\d+\.\d+\.\d+([-+][0-9A-Za-z.+-]*)?$/.test(version)) return undefined;
60 return { ecosystem: "npm", name, version };
61 }
62
63 export function parseLockfile(path: string, text: string): Pinned[] {
64 const base = path.slice(path.lastIndexOf("/") + 1);
65 const doc = parse(text);
66 if (!isRecord(doc)) return [];
67 const found = new Map<string, Pinned>();
68 const add = (p: Pinned | undefined) => {
69 if (p) found.set(`${p.name}@${p.version}`, p);
70 };
71 if (base === "bun.lock" && isRecord(doc.packages)) {
72 for (const entry of Object.values(doc.packages)) {
73 if (Array.isArray(entry) && typeof entry[0] === "string") add(splitSpec(entry[0]));
74 }
75 } else if (base === "package-lock.json" && isRecord(doc.packages)) {
76 for (const [key, entry] of Object.entries(doc.packages)) {
77 const at = key.lastIndexOf("node_modules/");
78 if (at < 0 || !isRecord(entry) || typeof entry.version !== "string") continue;
79 add(splitSpec(`${key.slice(at + "node_modules/".length)}@${entry.version}`));
80 }
81 }
82 return [...found.values()];
83 }
src/security/mirror.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * Keep the local OSV mirror (`$FORGE_APP_DATA/osv/*.json`) current: ask api.osv.dev
3 * which advisories touch the pins the forge's repositories hold, and write the ones
4 * that are new or changed. Only the advisories that matter are mirrored, so there is
5 * no archive to unpack. The only network use in `security/`; `fetch` is passed in.
6 */
7
8 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9 import { join } from "node:path";
10 import { stringField } from "../kernel/json_string.ts";
11 import { toAdvisory } from "./osv.ts";
12 import type { Pinned } from "./lockfile.ts";
13
14 export const OSV_HOST = "api.osv.dev";
15 const BATCH = 500;
16 const MAX_FETCHED = 500;
17 const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
18
19 export interface Refresh {
20 readonly asked: number;
21 readonly written: number;
22 readonly failed: number;
23 }
24
25 export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
26
27 function modifiedAt(file: string): string {
28 try {
29 return stringField(readFileSync(file, "utf8"), "modified");
30 } catch {
31 return "";
32 }
33 }
34
35 export async function refreshMirror(dir: string, pins: readonly Pinned[], fetcher: Fetch = fetch): Promise<Refresh> {
36 const unique = [...new Map(pins.map((p) => [`${p.name}@${p.version}`, p])).values()];
37 const wanted = new Map<string, string>();
38 let failed = 0;
39 for (let i = 0; i < unique.length; i += BATCH) {
40 const queries = unique.slice(i, i + BATCH).map((p) => ({
41 package: { name: p.name, ecosystem: "npm" },
42 version: p.version,
43 }));
44 try {
45 const res = await fetcher(`https://${OSV_HOST}/v1/querybatch`, {
46 method: "POST",
47 headers: { "content-type": "application/json" },
48 body: JSON.stringify({ queries }),
49 });
50 if (!res.ok) throw new Error(String(res.status));
51 const { results } = (await res.json()) as { results?: { vulns?: { id?: unknown; modified?: unknown }[] }[] };
52 for (const r of results ?? [])
53 for (const v of r.vulns ?? [])
54 if (typeof v.id === "string" && ID.test(v.id)) wanted.set(v.id, typeof v.modified === "string" ? v.modified : "");
55 } catch {
56 failed++;
57 }
58 }
59 mkdirSync(dir, { recursive: true });
60 let written = 0;
61 for (const [id, modified] of [...wanted].slice(0, MAX_FETCHED)) {
62 const file = join(dir, `${id}.json`);
63 if (modified !== "" && modifiedAt(file) >= modified) continue;
64 try {
65 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");
69 // Written whole then renamed: a scan never reads half an advisory.
70 writeFileSync(`${file}.tmp`, JSON.stringify(doc));
71 renameSync(`${file}.tmp`, file);
72 written++;
73 } catch {
74 failed++;
75 }
76 }
77 return { asked: unique.length, written, failed };
78 }
src/security/optin.ts added +27
@@ -0,0 +1,27 @@
1 /**
2 * Which repositories the security duty may touch (#6004). Filing issues acts as a repository's
3 * owner, and the mirror refresh sends pinned package names and versions to api.osv.dev, so
4 * neither is done to a repository that has not said yes: the forge's own repository
5 * (`forgeRepo`) and the `owner/name` entries of the forge config key `osv.repos` take part in
6 * both; a public repository also takes part in the refresh, and never in the issues.
7 */
8
9 import type { App } from "../app.ts";
10 import { FORGE_SCOPE } from "../core/config.ts";
11
12 export interface Candidate {
13 readonly owner: string;
14 readonly name: string;
15 readonly visibility: "public" | "private";
16 }
17
18 export function optedIn(app: Pick<App, "configs" | "config">, r: Candidate): boolean {
19 const slug = `${r.owner}/${r.name}`;
20 if (app.config.forgeRepo === slug) return true;
21 const listed = app.configs.get(FORGE_SCOPE, "osv.repos");
22 return Array.isArray(listed) && listed.includes(slug);
23 }
24
25 /** May this repository's pins leave the forge for api.osv.dev? */
26 export const mayAsk = (app: Pick<App, "configs" | "config">, r: Candidate): boolean =>
27 r.visibility === "public" || optedIn(app, r);
src/security/osv.ts added +164
@@ -0,0 +1,164 @@
1 /**
2 * OSV advisories (https://ossf.github.io/osv-schema) matched against pinned
3 * packages. Plain data in, plain data out: the mirror on disk is read by
4 * `loadAdvisories`, the match is `affectedBy`, neither touches the network.
5 */
6
7 import { readdirSync, readFileSync, statSync } from "node:fs";
8 import { join } from "node:path";
9 import type { Pinned } from "./lockfile.ts";
10
11 export type Severity = "critical" | "high" | "moderate" | "low" | "unknown";
12
13 export interface Advisory {
14 readonly id: string;
15 readonly summary: string;
16 readonly severity: Severity;
17 readonly affected: readonly {
18 readonly package: { readonly ecosystem: string; readonly name: string };
19 readonly ranges?: readonly {
20 readonly type: string;
21 readonly events: readonly Record<string, string>[];
22 }[];
23 readonly versions?: readonly string[];
24 }[];
25 }
26
27 export interface Finding {
28 readonly advisory: string;
29 readonly summary: string;
30 readonly severity: Severity;
31 readonly package: string;
32 readonly version: string;
33 /** The smallest version that fixes it, when the advisory names one. */
34 readonly fixedIn: string | null;
35 }
36
37 /** [major, minor, patch] and the prerelease identifiers after a dash (none for a release). */
38 function parts(v: string): [number, number, number, string[]] {
39 const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(v);
40 return m ? [+m[1]!, +m[2]!, +m[3]!, m[4] ? m[4].split(".") : []] : [0, 0, 0, []];
41 }
42
43 /**
44 * SemVer precedence: a release outranks its prereleases; identifiers compare one by one, numbers as
45 * numbers.
46 */
47 function comparePre(a: string[], b: string[]): number {
48 if (a.length === 0 || b.length === 0) return a.length === b.length ? 0 : a.length === 0 ? 1 : -1;
49 for (let i = 0; i < Math.min(a.length, b.length); i++) {
50 const p = a[i]!;
51 const q = b[i]!;
52 if (p === q) continue;
53 const pn = /^\d+$/.test(p);
54 const qn = /^\d+$/.test(q);
55 if (pn && qn) return Number(p) < Number(q) ? -1 : 1;
56 if (pn !== qn) return pn ? -1 : 1;
57 return p < q ? -1 : 1;
58 }
59 return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
60 }
61
62 export function compareVersions(a: string, b: string): number {
63 const x = parts(a);
64 const y = parts(b);
65 for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return (x[i] as number) < (y[i] as number) ? -1 : 1;
66 return comparePre(x[3], y[3]);
67 }
68
69 function severityOf(raw: unknown): Severity {
70 const s = String(raw ?? "").toLowerCase();
71 if (s === "critical" || s === "high" || s === "low") return s;
72 if (s === "moderate" || s === "medium") return "moderate";
73 return "unknown";
74 }
75
76 /** A parsed OSV document, or undefined when it is not one. */
77 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;
82 return {
83 id: d.id,
84 summary: typeof d.summary === "string" ? d.summary : "",
85 severity: severityOf(specific?.severity),
86 affected: d.affected as Advisory["affected"],
87 };
88 }
89
90 /** Every `*.json` in the mirror directory; a missing directory is an empty mirror. */
91 export function loadAdvisories(dir: string): Advisory[] {
92 let names: string[];
93 try {
94 if (!statSync(dir).isDirectory()) return [];
95 names = readdirSync(dir).filter((n) => n.endsWith(".json"));
96 } catch {
97 return [];
98 }
99 const out: Advisory[] = [];
100 for (const name of names) {
101 try {
102 const doc = JSON.parse(readFileSync(join(dir, name), "utf8"));
103 for (const item of Array.isArray(doc) ? doc : [doc]) {
104 const a = toAdvisory(item);
105 if (a) out.push(a);
106 }
107 } catch {
108 // A torn or foreign file in the mirror is skipped, not fatal.
109 }
110 }
111 return out;
112 }
113
114 /** Findings for one package: which advisories cover its version, and the fix. */
115 export function affectedBy(pkg: Pinned, advisories: readonly Advisory[]): Finding[] {
116 const out: Finding[] = [];
117 for (const adv of advisories) {
118 for (const aff of adv.affected) {
119 if (aff.package.ecosystem.toLowerCase() !== pkg.ecosystem || aff.package.name !== pkg.name) continue;
120 let hit = aff.versions?.includes(pkg.version) ?? false;
121 let fixedIn: string | null = null;
122 for (const range of aff.ranges ?? []) {
123 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 }
143 }
144 if (hit)
145 out.push({
146 advisory: adv.id,
147 summary: adv.summary,
148 severity: adv.severity,
149 package: pkg.name,
150 version: pkg.version,
151 fixedIn,
152 });
153 }
154 }
155 return out;
156 }
157
158 const RANK: Record<Severity, number> = { critical: 0, high: 1, moderate: 2, low: 3, unknown: 4 };
159
160 export function scanPinned(pins: readonly Pinned[], advisories: readonly Advisory[]): Finding[] {
161 return pins
162 .flatMap((p) => affectedBy(p, advisories))
163 .sort((a, b) => RANK[a.severity] - RANK[b.severity] || a.package.localeCompare(b.package));
164 }
src/security/report_cache.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * The dependency report, held by what it was computed from: the commit oid and the advisory
3 * mirror's stamp. A request for the same pair is a map lookup (and one in flight is shared), so a
4 * reader of a public repository cannot make the forge re-read lockfiles and advisories each time
5 * (#6004). A per-client window and a whole-forge window bound the misses.
6 */
7
8 import { readdirSync, statSync } from "node:fs";
9 import { join } from "node:path";
10 import { resolveOid } from "../git/merge.ts";
11 import { planFixes, type Bump } from "./fix.ts";
12 import { loadAdvisories } from "./osv.ts";
13 import { scanRepo, type ScanReport } from "./scan.ts";
14
15 export interface Report extends ScanReport {
16 readonly fixes: readonly Bump[];
17 }
18
19 const MAX_HELD = 200;
20 const heldBy = new WeakMap<object, Map<string, Promise<Report>>>();
21
22 function heldOf(owner: object): Map<string, Promise<Report>> {
23 let m = heldBy.get(owner);
24 if (m === undefined) heldBy.set(owner, (m = new Map()));
25 return m;
26 }
27
28 /** Changes when the mirror gains or changes an advisory (a file is renamed in). */
29 export function mirrorStamp(dir: string): string {
30 try {
31 return `${statSync(dir).mtimeMs}:${readdirSync(dir).length}`;
32 } catch {
33 return "none";
34 }
35 }
36
37 /** The report at a ref, or undefined when the ref names no commit. */
38 export async function reportAt(owner: object, dataDir: string, repoPath: string, ref: string): Promise<Report | undefined> {
39 const oid = await resolveOid(repoPath, ref);
40 if (oid === undefined) return undefined;
41 const mirror = join(dataDir, "osv");
42 const key = `${repoPath}\0${oid}\0${mirrorStamp(mirror)}`;
43 const held = heldOf(owner);
44 let report = held.get(key);
45 if (report === undefined) {
46 report = scanRepo(repoPath, oid, loadAdvisories(mirror)).then((r) => ({ ...r, ref, fixes: planFixes(r.findings) }));
47 if (held.size >= MAX_HELD) held.delete(held.keys().next().value as string);
48 held.set(key, report);
49 report.catch(() => held.delete(key));
50 }
51 return report;
52 }
53
54
55 const WINDOW_MS = 60_000;
56 const PER_CLIENT = 20;
57 const FORGE_WIDE = 300;
58 const MAX_CLIENTS = 10_000;
59 const windowsBy = new WeakMap<object, Map<string, { start: number; n: number }>>();
60
61 /**
62 * Seconds to wait when this client (or the forge as a whole) has asked too often; else undefined.
63 */
64 export function reportWait(owner: object, client: string, now = Date.now()): number | undefined {
65 let windows = windowsBy.get(owner);
66 if (windows === undefined) windowsBy.set(owner, (windows = new Map()));
67 if (windows.size > MAX_CLIENTS) windows.clear();
68 for (const [key, cap] of [[client, PER_CLIENT], ["*", FORGE_WIDE]] as const) {
69 let w = windows.get(key);
70 if (w === undefined || now - w.start >= WINDOW_MS) {
71 w = { start: now, n: 0 };
72 windows.set(key, w);
73 }
74 if (w.n >= cap) return Math.max(1, Math.ceil((w.start + WINDOW_MS - now) / 1000));
75 w.n++;
76 }
77 return undefined;
78 }
79
src/security/scan.ts added +43
@@ -0,0 +1,43 @@
1 /** One repository at one ref: read its lockfiles from git, match them to the mirror. */
2
3 import { blobForRender, listPaths } from "../git/read.ts";
4 import { isLockfile, parseLockfile, type Pinned } from "./lockfile.ts";
5 import { scanPinned, type Advisory, type Finding } from "./osv.ts";
6
7 const MAX_LOCKFILE_BYTES = 10_000_000;
8 const MAX_LOCKFILES = 20;
9 /** All lockfiles of one read together: a repository of many large ones is read in part. */
10 const MAX_TOTAL_BYTES = 30_000_000;
11
12 export interface ScanReport {
13 readonly ref: string;
14 readonly lockfiles: readonly string[];
15 readonly packages: number;
16 readonly findings: readonly Finding[];
17 }
18
19 /** Every pinned package in a repository's lockfiles at a ref, and the lockfile paths read. */
20 export async function pinsOf(dir: string, ref: string): Promise<{ paths: string[]; pins: Pinned[] }> {
21 const listing = await listPaths(dir, ref);
22 const paths = listing.ok ? listing.value.paths.filter(isLockfile).slice(0, MAX_LOCKFILES) : [];
23 const pins = new Map<string, Pinned>();
24 let total = 0;
25 for (const path of paths) {
26 if (total >= MAX_TOTAL_BYTES) break;
27 const blob = await blobForRender(dir, ref, path, MAX_LOCKFILE_BYTES);
28 if (blob.kind !== "text") continue;
29 total += blob.body.length;
30 for (const p of parseLockfile(path, new TextDecoder().decode(blob.body)))
31 pins.set(`${p.name}@${p.version}`, p);
32 }
33 return { paths, pins: [...pins.values()] };
34 }
35
36 export async function scanRepo(
37 dir: string,
38 ref: string,
39 advisories: readonly Advisory[],
40 ): Promise<ScanReport> {
41 const { paths, pins } = await pinsOf(dir, ref);
42 return { ref, lockfiles: paths, packages: pins.length, findings: scanPinned(pins, advisories) };
43 }
src/spawn/model_door.ts +2 −6
@@ -12,6 +12,7 @@
1212 * spend can pass the cap by no more than what those calls cost.
1313 */
1414
15 import { stringField } from "../kernel/json_string.ts";
1516 import type { App } from "../app.ts";
1617 import { addSpend, creditOfToken, leftUsd, readCredit, spentWords, type Credit } from "./credit.ts";
1718 import { listPriceUsd, NO_USAGE, type Usage } from "./list_price.ts";
@@ -127,12 +128,7 @@ class Tally {
127128
128129 /** The model a request names, or "" (priced as the dearest). */
129130 function modelOf(raw: Uint8Array): string {
130 try {
131 const m = (JSON.parse(new TextDecoder().decode(raw)) as { model?: unknown }).model;
132 return typeof m === "string" ? m : "";
133 } catch {
134 return "";
135 }
131 return stringField(raw, "model");
136132 }
137133
138134 /** Counts a reply as it passes and gives the call's place back when it ends, however it ends. */
src/tui/screens/dependencies.ts added +81
@@ -0,0 +1,81 @@
1 /**
2 * A repository's dependency findings, in the terminal (#6004): the report behind
3 * `GET /api/v1/repos/:owner/:name/dependencies` (`security/report_cache.ts`, so the API and this
4 * screen share one cached read and one rate limit), gated the same way — anyone who can read the
5 * repository sees it. `g` reads again.
6 */
7
8 import { requireReader } from "../../actions/access.ts";
9 import type { Repo } from "../../core/repos.ts";
10 import { repoDir } from "../../git/repos.ts";
11 import { reportAt, reportWait, type Report } from "../../security/report_cache.ts";
12 import type { Ctx, Screen } from "../app/app.ts";
13 import type { Command } from "../app/palette.ts";
14 import { binding } from "../app/keys.ts";
15 import { style } from "../term/style.ts";
16 import { truncate } from "../term/width.ts";
17 import type { Session } from "../session.ts";
18 import { fill, len, split } from "../ui/layout.ts";
19 import { ListState, drawList, type ListRow } from "./common.ts";
20
21 /** One line per finding; pure. */
22 export function findingRows(report: Report): ListRow[] {
23 return report.findings.map((f) => ({
24 title: `${f.package} ${f.version}: ${f.advisory}`,
25 secondary: f.severity,
26 meta: f.fixedIn ? `fix ${f.fixedIn}` : "no fix named",
27 ...(f.summary ? { note: f.summary } : {}),
28 }));
29 }
30
31 export function dependenciesScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
32 const state = new ListState();
33 let report: Report | undefined;
34 let note = "Reading the lockfiles…";
35 const read = async (): Promise<void> => {
36 if (!requireReader(f.app, f.user, repo).ok) {
37 note = "No such repository.";
38 return;
39 }
40 const wait = reportWait(f.app, `tui:${f.user?.id ?? "anon"}`);
41 if (wait !== undefined) {
42 note = `Too many reads; try again in ${wait}s.`;
43 return;
44 }
45 report = await reportAt(f.app, f.app.config.dataDir, repoDir(f.app.reposRoot, repo.ownerName, repo.name), repo.defaultBranch);
46 note = report === undefined ? "No such branch." : report.findings.length === 0 ? `No known advisory in ${report.packages} pinned packages.` : `${report.findings.length} findings in ${report.packages} pinned packages.`;
47 };
48 const again = (): void => void read().catch(() => (note = "The lockfiles could not be read.")).finally(() => ctx.invalidate());
49 return {
50 title: `${repo.ownerName}/${repo.name} — Dependencies`,
51 keys: [binding(["j", "k"], "move cursor"), binding(["g"], "read again")],
52 async load() {
53 again();
54 },
55 render(area, s) {
56 const c = ctx.theme.c;
57 const [head, list] = split(area, "v", [len(1), fill(1)]);
58 s.text(head!.x, head!.y, truncate(note, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
59 drawList(s, list!, c, state, report ? findingRows(report) : []);
60 },
61 key(e) {
62 if (state.key(e, report?.findings.length ?? 0)) return true;
63 if (e.ctrl || e.alt || e.key !== "g") return false;
64 again();
65 return true;
66 },
67 };
68 }
69
70 /** The palette's command while a repository is open. */
71 export function dependenciesCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
72 if (repo === undefined || !requireReader(f.app, f.user, repo).ok) return [];
73 return [
74 {
75 id: "dependencies-app",
76 title: `${repo.ownerName}/${repo.name} — Dependencies`,
77 hint: "known advisories against this repository's lockfiles",
78 run: () => ctx.push(dependenciesScreen(f, ctx, repo)),
79 },
80 ];
81 }
src/tui/screens/workspace.ts +2
@@ -230,6 +230,7 @@ import { settingHistoryCommands } from "./settinghistory.ts";
230230 import { templateCommands } from "./template.ts";
231231 import { buildCacheCommands } from "./buildcache.ts";
232232 import { schedulesCommands } from "./schedules.ts";
233 import { dependenciesCommands } from "./dependencies.ts";
233234 import { demoCommands } from "./demo.ts";
234235 import { appReleasesCommands } from "./appreleases.ts";
235236 import { largeFilesCommands } from "./largefiles.ts";
@@ -2457,6 +2458,7 @@ export function workspaceScreen(
24572458 ...autonomyCommands(f, ctx, repo),
24582459 ...trafficCommands(f, ctx, repo),
24592460 ...schedulesCommands(f, ctx, repo),
2461 ...dependenciesCommands(f, ctx, repo),
24602462 ...demoCommands(f, ctx, repo),
24612463 ...appReleasesCommands(f, ctx, repo),
24622464 ...largeFilesCommands(f, ctx, repo),
test/job-slices.test.ts +1
@@ -266,6 +266,7 @@ function jobs(): Record<string, () => unknown> {
266266 * on.
267267 */
268268 const UNTIMED: Record<string, string> = {
269 "osv-mirror": "hourly: fetches advisories for the pins the forge holds from api.osv.dev, then files fix issues; network and git reads off the loop (security/duty.ts, fix_issues.ts); security-osv.test.ts drives both",
269270 "config-poll": "a short timer that re-reads one small row per scope and fires listeners only when another process changed it (core/config.ts start/refresh); config-store.test.ts drives a change from a second handle",
270271 "allocation": "one settle pass hourly over repositories with a wallet (core/allocation.ts settleAll): indexed reads and a write only when a week turned; allocation tests drive settleAll directly",
271272 "copies-prune": "two DELETEs on indexed time columns (core/copies.ts pruneCopies), hourly on the outsider prune's own timer; copies-elsewhere.test.ts drives both fades",
test/security-osv.test.ts added +300
@@ -0,0 +1,300 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { serve, type Servers } from "../src/http/server.ts";
7 import { parseLockfile } from "../src/security/lockfile.ts";
8 import { planFixes } from "../src/security/fix.ts";
9 import { compareVersions, loadAdvisories, scanPinned, toAdvisory } from "../src/security/osv.ts";
10 import { fileAllFixIssues } from "../src/security/fix_issues.ts";
11 import { getRepo } from "../src/core/repos.ts";
12 import { listIssues } from "../src/core/issues.ts";
13 import { FORGE_SCOPE } from "../src/core/config.ts";
14 import { reportAt, reportWait } from "../src/security/report_cache.ts";
15 import { refreshOsv } from "../src/security/duty.ts";
16 import { findingRows } from "../src/tui/screens/dependencies.ts";
17 import { seedAdmin } from "./helpers/admin.ts";
18
19 const owner = {};
20
21 const advisory = toAdvisory({
22 id: "GHSA-test-0001",
23 summary: "prototype pollution",
24 database_specific: { severity: "HIGH" },
25 affected: [
26 {
27 package: { ecosystem: "npm", name: "lodash" },
28 ranges: [{ type: "SEMVER", events: [{ introduced: "0" }, { fixed: "4.17.21" }] }],
29 },
30 ],
31 })!;
32
33 describe("lockfiles", () => {
34 test("bun.lock with trailing commas and a string holding a comma-brace", () => {
35 const text = `{ "packages": { "a": ["[email protected]", "", {},], "b": ["@x/[email protected]", "", {"note": ",}"},], "c": ["foo@npm:[email protected]", ""] },}`;
36 expect(parseLockfile("bun.lock", text).map((p) => `${p.name}@${p.version}`)).toEqual([
37 "[email protected]",
38 "@x/[email protected]",
39 ]);
40 });
41 test("package-lock.json reads nested node_modules", () => {
42 const text = JSON.stringify({ packages: { "": {}, "node_modules/a/node_modules/lodash": { version: "4.17.0" } } });
43 expect(parseLockfile("web/package-lock.json", text)).toEqual([
44 { ecosystem: "npm", name: "lodash", version: "4.17.0" },
45 ]);
46 });
47 test("garbage is nothing", () => {
48 expect(parseLockfile("bun.lock", "not json")).toEqual([]);
49 });
50 });
51
52 describe("matching", () => {
53 test("versions order, prereleases before releases", () => {
54 expect(compareVersions("1.0.0-rc.1", "1.0.0")).toBe(-1);
55 expect(compareVersions("1.10.0", "1.9.9")).toBe(1);
56 });
57 test("prerelease tags order among themselves: rc.1 < rc.2 < rc.10, numbers before words", () => {
58 expect(compareVersions("1.0.0-rc.1", "1.0.0-rc.2")).toBe(-1);
59 expect(compareVersions("1.0.0-rc.10", "1.0.0-rc.2")).toBe(1);
60 expect(compareVersions("1.0.0-alpha", "1.0.0-beta")).toBe(-1);
61 expect(compareVersions("1.0.0-1", "1.0.0-alpha")).toBe(-1);
62 expect(compareVersions("1.0.0-rc", "1.0.0-rc.1")).toBe(-1);
63 expect(compareVersions("1.0.0-rc.2", "1.0.0-rc.2")).toBe(0);
64 });
65 test("a vulnerable pin names its fix; a fixed pin is clean", () => {
66 const pins = [
67 { ecosystem: "npm" as const, name: "lodash", version: "4.17.20" },
68 { ecosystem: "npm" as const, name: "lodash", version: "4.17.21" },
69 { ecosystem: "npm" as const, name: "other", version: "1.0.0" },
70 ];
71 const found = scanPinned(pins, [advisory]);
72 expect(found).toHaveLength(1);
73 expect(found[0]).toMatchObject({ version: "4.17.20", fixedIn: "4.17.21", severity: "high" });
74 });
75 });
76
77 describe("fix plan", () => {
78 const f = (advisory: string, severity: "high" | "low", fixedIn: string | null, version = "1.0.0") =>
79 ({ advisory, summary: "", severity, package: "p", version, fixedIn }) as const;
80 test("the highest fix clears every advisory, the worst severity leads", () => {
81 expect(planFixes([f("A", "low", "1.2.0"), f("B", "high", "1.10.0")])).toEqual([
82 { package: "p", from: "1.0.0", to: "1.10.0", severity: "high", advisories: ["A", "B"] },
83 ]);
84 });
85 test("a pin with an unfixable advisory gets no bump", () => {
86 expect(planFixes([f("A", "high", "1.2.0"), f("B", "high", null)])).toEqual([]);
87 });
88 });
89
90 describe("GET /api/v1/repos/:o/:n/dependencies", () => {
91 let dataDir: string;
92 let app: App;
93 let servers: Servers;
94
95 beforeAll(async () => {
96 dataDir = await mkdtemp(join(tmpdir(), "forge-osv-"));
97 await mkdir(join(dataDir, "osv"));
98 await writeFile(
99 join(dataDir, "osv", "a.json"),
100 JSON.stringify({
101 id: "GHSA-test-0001",
102 database_specific: { severity: "CRITICAL" },
103 affected: [
104 {
105 package: { ecosystem: "npm", name: "lodash" },
106 ranges: [{ type: "SEMVER", events: [{ introduced: "0" }, { fixed: "4.17.21" }] }],
107 },
108 ],
109 }),
110 );
111 app = createApp({ dataDir, port: 0 });
112 servers = await serve(app);
113 await seedAdmin(app, { username: "mira", email: "[email protected]", password: "osv-pass-1234" });
114 });
115 afterAll(async () => {
116 servers.stop();
117 app.close();
118 await rm(dataDir, { recursive: true, force: true });
119 });
120
121 test("scans the default branch's lockfile; unknown repo is 404", async () => {
122 const base = servers.url;
123 const token = await fetch(`${base}/api/v1/tokens`, {
124 method: "POST",
125 headers: { "content-type": "application/json" },
126 body: JSON.stringify({ adminConfirm: true, username: "mira", password: "osv-pass-1234", name: "t", scope: "rw" }),
127 })
128 .then((r) => r.json())
129 .then((j) => (j as { token: string }).token);
130 const h = { authorization: `Bearer ${token}`, "content-type": "application/json" };
131 await fetch(`${base}/api/v1/repos`, { method: "POST", headers: h, body: JSON.stringify({ name: "app", visibility: "public" }) });
132 await fetch(`${base}/api/v1/repos/mira/app/contents`, {
133 method: "POST",
134 headers: h,
135 body: JSON.stringify({
136 message: "lock",
137 files: [{ path: "bun.lock", content: `{"packages":{"l":["[email protected]","",{}],}}` }],
138 }),
139 });
140 const res = await fetch(`${base}/api/v1/repos/mira/app/dependencies`, { headers: h });
141 expect(res.status).toBe(200);
142 const body = (await res.json()) as { lockfiles: string[]; findings: { advisory: string; fixedIn: string; severity: string }[] };
143 expect(body.lockfiles).toEqual(["bun.lock"]);
144 expect(body.findings).toMatchObject([{ advisory: "GHSA-test-0001", fixedIn: "4.17.21", severity: "critical" }]);
145 expect((body as unknown as { fixes: unknown }).fixes).toEqual([
146 { package: "lodash", from: "4.17.20", to: "4.17.21", severity: "critical", advisories: ["GHSA-test-0001"] },
147 ]);
148 expect((await fetch(`${base}/api/v1/repos/mira/nope/dependencies`, { headers: h })).status).toBe(404);
149 // The same commit and mirror answer from the held report: one object, not a second read.
150 const dir = join(app.reposRoot, "mira", "app.git");
151 const first = await reportAt(owner, dataDir, dir, "main");
152 expect(first?.findings.length).toBe(1);
153 expect(await reportAt(owner, dataDir, dir, "main")).toBe(first);
154 expect(await reportAt(owner, dataDir, dir, "no-such-branch")).toBeUndefined();
155 // A new advisory in the mirror changes its stamp, so the report is made again.
156 await writeFile(join(dataDir, "osv", "b.json"), JSON.stringify({ id: "GHSA-test-0009", affected: [] }));
157 expect(await reportAt(owner, dataDir, dir, "main")).not.toBe(first);
158 // A client that asks too often is told to wait.
159 let last = 200;
160 for (let i = 0; i < 25; i++) last = (await fetch(`${base}/api/v1/repos/mira/app/dependencies`, { headers: h })).status;
161 expect(last).toBe(429);
162 });
163 });
164
165 describe("fix issues", () => {
166 test("a vulnerable pin is filed once as an issue naming the bump; a second pass files nothing", async () => {
167 const dataDir = await mkdtemp(join(tmpdir(), "forge-osv-fix-"));
168 await mkdir(join(dataDir, "osv"));
169 await writeFile(
170 join(dataDir, "osv", "a.json"),
171 JSON.stringify({
172 id: "GHSA-test-0002",
173 database_specific: { severity: "CRITICAL" },
174 affected: [
175 {
176 package: { ecosystem: "npm", name: "lodash" },
177 ranges: [{ type: "SEMVER", events: [{ introduced: "0" }, { fixed: "4.17.21" }] }],
178 },
179 ],
180 }),
181 );
182 const app = createApp({ dataDir, port: 0 });
183 const servers = await serve(app);
184 try {
185 await seedAdmin(app, { username: "mira", email: "[email protected]", password: "osv-pass-1234" });
186 const token = await fetch(`${servers.url}/api/v1/tokens`, {
187 method: "POST",
188 headers: { "content-type": "application/json" },
189 body: JSON.stringify({ adminConfirm: true, username: "mira", password: "osv-pass-1234", name: "t", scope: "rw" }),
190 })
191 .then((r) => r.json())
192 .then((j) => (j as { token: string }).token);
193 const h = { authorization: `Bearer ${token}`, "content-type": "application/json" };
194 await fetch(`${servers.url}/api/v1/repos`, { method: "POST", headers: h, body: JSON.stringify({ name: "app", visibility: "public" }) });
195 await fetch(`${servers.url}/api/v1/repos/mira/app/contents`, {
196 method: "POST",
197 headers: h,
198 body: JSON.stringify({ message: "lock", files: [{ path: "bun.lock", content: `{"packages":{"l":["[email protected]","",{}],}}` }] }),
199 });
200 // A repository that has not opted in is not touched, public or not.
201 expect(await fileAllFixIssues(app)).toBe(0);
202 app.configs.set(FORGE_SCOPE, { "osv.repos": ["mira/app"] }, "test", "opt in");
203 expect(await fileAllFixIssues(app)).toBe(1);
204 expect(await fileAllFixIssues(app)).toBe(0);
205 const repo = getRepo(app.db, "mira", "app")!;
206 // A closed bump is not asked for again.
207 app.db.query(`UPDATE issue SET state = 'closed' WHERE repo_id = ?1`).run(repo.id);
208 expect(await fileAllFixIssues(app)).toBe(0);
209 app.db.query(`UPDATE issue SET state = 'open' WHERE repo_id = ?1`).run(repo.id);
210 const issues = listIssues(app.db, repo.id, { state: "open", kind: "issue" });
211 expect(issues.map((i) => i.title)).toEqual(["Bump lodash from 4.17.20 to 4.17.21 (critical advisory)"]);
212 expect(issues[0]!.body).toContain("GHSA-test-0002");
213 } finally {
214 servers.stop();
215 app.close();
216 await rm(dataDir, { recursive: true, force: true });
217 }
218 });
219 });
220
221 describe("mirror refresh", () => {
222 test("writes new advisories, skips current ones, refuses odd ids and non-advisories", async () => {
223 const { refreshMirror } = await import("../src/security/mirror.ts");
224 const dir = await mkdtemp(join(tmpdir(), "forge-mirror-"));
225 const doc = { id: "GHSA-aaaa-0001", modified: "2026-01-01T00:00:00Z", affected: [] };
226 const calls: string[] = [];
227 const fake = async (url: string) => {
228 calls.push(url);
229 if (url.endsWith("/v1/querybatch"))
230 return Response.json({
231 results: [{ vulns: [{ id: "GHSA-aaaa-0001", modified: doc.modified }, { id: "../evil", modified: "x" }, { id: "BAD-1", modified: "x" }] }],
232 });
233 return url.endsWith("GHSA-aaaa-0001") ? Response.json(doc) : Response.json({ nope: 1 });
234 };
235 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(loadAdvisories(dir).map((a) => a.id)).toEqual(["GHSA-aaaa-0001"]);
238 calls.length = 0;
239 expect((await refreshMirror(dir, pins, fake)).written).toBe(0);
240 expect(calls.some((c) => c.includes("GHSA-aaaa-0001"))).toBe(false);
241 await rm(dir, { recursive: true, force: true });
242 });
243 });
244
245 describe("what leaves the forge", () => {
246 test("only public or opted-in repositories have their pins sent to the OSV host", async () => {
247 const dataDir = await mkdtemp(join(tmpdir(), "forge-osv-out-"));
248 const app = createApp({ dataDir, port: 0 });
249 const servers = await serve(app);
250 try {
251 await seedAdmin(app, { username: "mira", email: "[email protected]", password: "osv-pass-1234" });
252 const token = await fetch(`${servers.url}/api/v1/tokens`, {
253 method: "POST",
254 headers: { "content-type": "application/json" },
255 body: JSON.stringify({ adminConfirm: true, username: "mira", password: "osv-pass-1234", name: "t", scope: "rw" }),
256 })
257 .then((r) => r.json())
258 .then((j) => (j as { token: string }).token);
259 const h = { authorization: `Bearer ${token}`, "content-type": "application/json" };
260 for (const [name, visibility, pkg] of [["pub", "public", "left-pad"], ["priv", "private", "secret-pkg"], ["yes", "private", "opted-pkg"]] as const) {
261 await fetch(`${servers.url}/api/v1/repos`, { method: "POST", headers: h, body: JSON.stringify({ name, visibility }) });
262 await fetch(`${servers.url}/api/v1/repos/mira/${name}/contents`, {
263 method: "POST",
264 headers: h,
265 body: JSON.stringify({ message: "lock", files: [{ path: "bun.lock", content: `{"packages":{"l":["${pkg}@1.0.0","",{}],}}` }] }),
266 });
267 }
268 app.configs.set(FORGE_SCOPE, { "osv.repos": ["mira/yes"] }, "test", "opt in");
269 const sent: string[] = [];
270 const fake = async (_url: string, init?: RequestInit) => {
271 sent.push(String(init?.body ?? ""));
272 return Response.json({ results: [] });
273 };
274 await refreshOsv(app, fake);
275 const all = sent.join("");
276 expect(all).toContain("left-pad");
277 expect(all).toContain("opted-pkg");
278 expect(all).not.toContain("secret-pkg");
279 } finally {
280 servers.stop();
281 app.close();
282 await rm(dataDir, { recursive: true, force: true });
283 }
284 });
285 test("the terminal's rows name the package, advisory, severity and fix", () => {
286 const rows = findingRows({
287 ref: "main",
288 lockfiles: ["bun.lock"],
289 packages: 1,
290 findings: [{ advisory: "GHSA-x", summary: "bad", severity: "high", package: "lodash", version: "4.17.20", fixedIn: "4.17.21" }],
291 fixes: [],
292 });
293 expect(rows).toEqual([{ title: "lodash 4.17.20: GHSA-x", secondary: "high", meta: "fix 4.17.21", note: "bad" }]);
294 });
295 test("the per-client window refuses the 21st read and opens again a minute later", () => {
296 for (let i = 0; i < 20; i++) expect(reportWait(owner, "a", 1000)).toBeUndefined();
297 expect(reportWait(owner, "a", 1000)).toBe(60);
298 expect(reportWait(owner, "a", 61_000)).toBeUndefined();
299 });
300 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs