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

Fix pulls and accept-risk actions for an advisory #17221

opened this

Merged 37h 12m ago, live in production

scout/forge:scout/17143-fix-pulls-and-accept-risk-actions-for-an → main 0 commits fork

  • Merged. scout/17143-fix-pulls-and-accept-risk-actions-for-an was merged into main as 13bda2f.

Review

Sign in to review this change.
15 files changed +555 −26
docs/features/security-osv.md +3 −1
@@ -6,9 +6,11 @@ row: "Dependency scan: a repository's lockfile against OSV advisories"
66
77 `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.
88
9 **Fix and accept the risk (#17143).** A person with write access answers a finding two ways, with an `rw` token. `POST /api/v1/repos/:owner/:name/dependencies/fix` with `{package, version}` files that pin's bump as an issue now (the title and body the hourly pass uses, so one is never filed twice: 201 `{filed: true}`, 200 `{filed: false}` when it exists, 404 when no open advisory on that pin has a fix); the crew opens the pull. `POST …/dependencies/accept` with `{package, version, advisory, reason}` (3 to 500 characters) records that the version may stay affected: a person only, never an agent, and only for an advisory the report names. The report then lists it under `accepted` (who, why, when) instead of `findings`, plans no bump for it, and the hourly pass files no issue for it.
10
911 **More feeds (#17141).** The same refresh also reads GHSA (`api.github.com/advisories`, reviewed npm advisories for the pins the forge holds, written into the mirror as OSV documents; an id OSV already supplied is kept) and rates any mirrored advisory that has a CVE id and no severity from NVD (`services.nvd.nist.gov`), then CVE.org (`cveawg.mitre.org`), by CVSS. NVD and CVE.org rate; they do not find, as they name no npm versions. Each CVE is asked about once, and at most 10 per pass. Both hosts are in `egress`; a gate refusal is reported in the gate's words. Anyone who can read the dependency scan (API or terminal) sees these findings; there is no separate page. **EPSS (#17142).** The same refresh asks api.first.org (in `egress`) for the EPSS probability of each mirrored advisory with a CVE id, up to 300 a pass in batches of 100, again after a day. A finding carries `epss` (0..1) when FIRST has a score; within one severity the likelier-exploited finding comes first, and the terminal row reads "high, EPSS 4.30%". **Exploited (#17144).** The same refresh reads CISA's known-exploited catalogue (`www.cisa.gov`, in `egress`, one request a pass, only while a mirrored advisory has a CVE id) and stamps a matching advisory once. A finding carries `exploited: true`, the terminal row reads "high, exploited, EPSS 4.30%", and the hourly duty files one issue per exploited advisory and pin, ahead of the bumps and under the same per-pass cap of 3 ("Exploited: GHSA-… in lodash 4.17.20 (CISA KEV)"), in the same opted-in repositories; the issue is the notice. Not built: a GitHub token for a higher rate, paging past 100 GHSA hits per 25 pins.
1012
11 **Terminal:** open a repository, then the palette entry "Dependencies" (`src/tui/screens/dependencies.ts`): one row per finding, `R` reads again. It shows what the API shows, to whoever can read the repository, through the same cache and rate limit.
13 **Terminal:** open a repository, then the palette entry "Dependencies" (`src/tui/screens/dependencies.ts`): one row per finding, `R` reads again, `a` accepts the selected finding's risk (asks why), `f` files its fix as an issue; accepted ones close the list. It shows what the API shows, to whoever can read the repository, through the same cache and rate limit.
1214
1315 **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.
1416
src/contract/openapi/routes/index.ts +2
@@ -419,6 +419,8 @@ export { route as postApiV1ReposOwnerNameDataEnvFileQuery } from "./postApiV1Rep
419419 export { route as postApiV1ReposOwnerNameDataImport } from "./postApiV1ReposOwnerNameDataImport.ts";
420420 export { route as postApiV1ReposOwnerNameDataMove } from "./postApiV1ReposOwnerNameDataMove.ts";
421421 export { route as postApiV1ReposOwnerNameDeepsec } from "./postApiV1ReposOwnerNameDeepsec.ts";
422 export { route as postApiV1ReposOwnerNameDependenciesAccept } from "./postApiV1ReposOwnerNameDependenciesAccept.ts";
423 export { route as postApiV1ReposOwnerNameDependenciesFix } from "./postApiV1ReposOwnerNameDependenciesFix.ts";
422424 export { route as postApiV1ReposOwnerNameDesk } from "./postApiV1ReposOwnerNameDesk.ts";
423425 export { route as postApiV1ReposOwnerNameDrop } from "./postApiV1ReposOwnerNameDrop.ts";
424426 export { route as postApiV1ReposOwnerNameEdits } from "./postApiV1ReposOwnerNameEdits.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameDependenciesAccept.ts added +19
@@ -0,0 +1,19 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/dependencies/accept`,
6 summary: "Accept the risk of one advisory on a lockfile pin",
7 detail: "Records a person's acceptance of `advisory` on `package`@`version`, with a `reason`, against the default branch's report (rw scope; a person who writes); answers `{accepted: true}`",
8 auth: true,
9 role: "member",
10 body: { package: "string", version: "string", advisory: "string", reason: "string" },
11 reply: { accepted: "boolean" },
12 refusals: {
13 forbidden: "not a person who writes to the repository (403)",
14 not_found: "no such repository, pin or advisory (404)",
15 conflict: "already accepted (409)",
16 invalid: "a field is missing or malformed (400)",
17 },
18 refuses: [401, 404],
19 };
src/contract/openapi/routes/postApiV1ReposOwnerNameDependenciesFix.ts added +18
@@ -0,0 +1,18 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/dependencies/fix`,
6 summary: "Open the issue that bumps a vulnerable lockfile pin",
7 detail: "Files the issue for the smallest bump of `package`@`version` that clears its open advisories (rw scope; a person who writes); answers 201 when filed, 200 when one is already open",
8 auth: true,
9 role: "member",
10 body: { package: "string", version: "string" },
11 reply: { filed: "boolean" },
12 refusals: {
13 forbidden: "not a person who writes to the repository (403)",
14 no_fix: "no open advisory on that pin has a fix that clears it (404)",
15 refused: "the issue could not be opened (422)",
16 },
17 refuses: [401, 404],
18 };
src/core/account_purge.ts +4
@@ -61,6 +61,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
6161 "crew_device.added_by": FORMER,
6262 "crew_device.granted_by": FORMER,
6363 "degraded_span.touched_by": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" },
64 "dep_accept.by_name": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" },
6465 "repo_review.by": FORMER,
6566 "review_request.requested_by": FORMER,
6667 "review_request.reviewer_id": FORMER,
@@ -373,6 +374,9 @@ export function purgeAccount(db: Database, userId: string, now: Date): PurgeOutc
373374 // `degraded_span.touched_by` holds a username (or the tick's name): the finding keeps the
374375 // touch, as the placeholder's.
375376 if (name !== "") kept += db.query("UPDATE degraded_span SET touched_by = ?2 WHERE touched_by = ?1").run(name, FORMER_NAME).changes;
377 // `dep_accept.by_name` holds a username: an accepted advisory keeps its reason, as the
378 // placeholder's.
379 if (name !== "") kept += db.query("UPDATE dep_accept SET by_name = ?2 WHERE by_name = ?1").run(name, FORMER_NAME).changes;
376380 // `entitlement.payer` is an address, not an id: an ended plan forgets who paid.
377381 const email = db.query<{ email: string }, [string]>("SELECT email FROM user WHERE id = ?1").get(userId)?.email ?? "";
378382 if (email !== "") kept += db.query("UPDATE entitlement SET payer = '' WHERE payer = ?1 COLLATE NOCASE").run(email).changes;
src/core/migration-pins/20261201190200-dep-accept.pin added +1
@@ -0,0 +1,1 @@
1 d9180b595665b6c4c8a55fdf9314adb43c07ae4c6af6e3e47aa8b29b0a2e7a4b
src/core/migrations/20261201190200-dep-accept.ts added +16
@@ -0,0 +1,16 @@
1 // An accepted dependency advisory (#17143): a person with write access says why a pinned version
2 // may stay affected by an OSV advisory; who, why and when are kept. One row per
3 // repository, package, version and advisory. New table only. Additive.
4 export default `
5 CREATE TABLE dep_accept (
6 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
7 package TEXT NOT NULL,
8 version TEXT NOT NULL,
9 advisory TEXT NOT NULL,
10 by_id TEXT REFERENCES user(id) ON DELETE SET NULL,
11 by_name TEXT NOT NULL,
12 reason TEXT NOT NULL,
13 at TEXT NOT NULL,
14 PRIMARY KEY (repo_id, package, version, advisory)
15 );
16 `;
src/generated/migrations.ts +6 −4
@@ -457,8 +457,9 @@ import m452 from "../core/migrations/20261201150000-pinned-firewall.ts";
457457 import m453 from "../core/migrations/20261201170000-managed-database.ts";
458458 import m454 from "../core/migrations/20261201180000-game-box-diag.ts";
459459 import m455 from "../core/migrations/20261201190000-working-edit.ts";
460 import m456 from "../core/migrations/20261201190500-runner-machine.ts";
461 import m457 from "../core/migrations/20261201200000-cloud-projects.ts";
460 import m456 from "../core/migrations/20261201190200-dep-accept.ts";
461 import m457 from "../core/migrations/20261201190500-runner-machine.ts";
462 import m458 from "../core/migrations/20261201200000-cloud-projects.ts";
462463
463464 /** Each migration file's name and its default export, in name order. */
464465 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -918,6 +919,7 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
918919 ["20261201170000-managed-database.ts", m453],
919920 ["20261201180000-game-box-diag.ts", m454],
920921 ["20261201190000-working-edit.ts", m455],
921 ["20261201190500-runner-machine.ts", m456],
922 ["20261201200000-cloud-projects.ts", m457],
922 ["20261201190200-dep-accept.ts", m456],
923 ["20261201190500-runner-machine.ts", m457],
924 ["20261201200000-cloud-projects.ts", m458],
923925 ];
src/http/api.ts +26 −1
@@ -90,6 +90,7 @@ import {
9090 } from "../actions/branches.ts";
9191 import { editFiles, type EditFile } from "../actions/contents.ts";
9292 import { reportAt, reportWait } from "../security/report_cache.ts";
93 import { acceptAdvisory, mayAct, REFUSAL_CODE, requestFix, withAcceptances } from "../security/accept.ts";
9394 import {
9495 contribute,
9596 type ContributeResult,
@@ -2177,8 +2178,32 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
21772178 if (wait !== undefined) return tryAgain("rate_limited", 429, "too many dependency reads; wait and ask again", wait);
21782179 const report = await reportAt(ctx.app, ctx.app.config.dataDir, dirOf(ctx, repo), ref);
21792180 if (!report) return notFound();
2180 return json(report, 200, { "cache-control": "no-store" });
2181 return json(withAcceptances(ctx.app.db, repo.id, report), 200, { "cache-control": "no-store", vary: "authorization, cookie" });
21812182 });
2183 // Accept the risk of one advisory on a pin (#17143), or ask for its fix: a person's call.
2184 const depAction = (what: "accept" | "fix") => async (ctx: Ctx): Promise<Response> => {
2185 const denied = requireScope(ctx, "rw");
2186 if (denied) return denied;
2187 const repo = loadRepo(ctx);
2188 if (!repo) return notFound();
2189 const user = ctx.auth.user;
2190 if (!mayAct(ctx.app, repo, user)) return apiError("forbidden", 403, "write access to this repository is needed");
2191 const input = await body(ctx.request);
2192 const wait = reportWait(ctx.app, clientAddress(ctx.request));
2193 if (wait !== undefined) return tryAgain("rate_limited", 429, "too many dependency reads; wait and ask again", wait);
2194 const report = await reportAt(ctx.app, ctx.app.config.dataDir, dirOf(ctx, repo), repo.defaultBranch);
2195 if (!report) return notFound();
2196 const pin = { package: str(input.package), version: str(input.version) };
2197 if (what === "accept") {
2198 const done = acceptAdvisory(ctx.app, repo, user, report, { ...pin, advisory: str(input.advisory), reason: str(input.reason) });
2199 return done.ok ? json({ accepted: true }) : apiError(REFUSAL_CODE[done.status], done.status, done.why);
2200 }
2201 const done = requestFix(ctx.app, repo, user, report, pin);
2202 if (!done.ok) return apiError(done.status === 404 ? "no_fix" : REFUSAL_CODE[done.status], done.status, done.why);
2203 return json({ filed: done.result === "filed" }, done.result === "filed" ? 201 : 200);
2204 };
2205 router.add("POST", "/api/v1/repos/:owner/:name/dependencies/accept", depAction("accept"));
2206 router.add("POST", "/api/v1/repos/:owner/:name/dependencies/fix", depAction("fix"));
21822207 router.add("GET", "/api/v1/repos/:owner/:name/contents", contentsHandler);
21832208 router.add(
21842209 "GET",
src/http/lazy_lists.ts +2
@@ -1324,6 +1324,8 @@ export const API_ROUTES = [
13241324 ["GET", "/api/v1/repos/:owner/:name/commits/:oid"],
13251325 ["GET", "/api/v1/repos/:owner/:name/commits/:oid/check"],
13261326 ["GET", "/api/v1/repos/:owner/:name/dependencies"],
1327 ["POST", "/api/v1/repos/:owner/:name/dependencies/accept"],
1328 ["POST", "/api/v1/repos/:owner/:name/dependencies/fix"],
13271329 ["GET", "/api/v1/repos/:owner/:name/contents"],
13281330 ["GET", "/api/v1/repos/:owner/:name/contents/*path"],
13291331 ["POST", "/api/v1/repos/:owner/:name/contents"],
src/security/accept.ts added +125
@@ -0,0 +1,125 @@
1 /**
2 * Accept the risk of a dependency advisory (#17143): a person with write access says why a pinned
3 * version may stay affected. The report then lists it apart, and no fix is planned or filed for it.
4 * Plain rows in, plain rows out; the API and the terminal call `acceptAdvisory`.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import type { App } from "../app.ts";
9 import { canWrite, type Repo } from "../core/repos.ts";
10 import { isActive, type User } from "../core/users.ts";
11 import type { Finding } from "./osv.ts";
12 import { planFixes } from "./fix.ts";
13 import { fileBump } from "./fix_issues.ts";
14 import type { Report } from "./report_cache.ts";
15
16 const REASON_MIN = 3;
17 const REASON_MAX = 500;
18 const NAME_MAX = 214;
19
20 export interface Acceptance {
21 readonly package: string;
22 readonly version: string;
23 readonly advisory: string;
24 readonly by: string;
25 readonly reason: string;
26 readonly at: string;
27 }
28
29 type Refused = { ok: false; status: 400 | 403 | 404 | 409 | 422; why: string };
30 type Accepted = { ok: true } | Refused;
31
32 /** The API's error code for each refusal status. */
33 export const REFUSAL_CODE = { 400: "invalid", 403: "forbidden", 404: "not_found", 409: "conflict", 422: "refused" } as const;
34
35 /**
36 * C0 and C1 control characters (ESC among them): typed by one person, drawn in another's terminal.
37 */
38 const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
39
40 /**
41 * Whether this user may change the report's standing: write access, shared by the API and the
42 * terminal.
43 */
44 export function mayAct(app: App, repo: Repo, user: User | undefined): user is User {
45 return user !== undefined && isActive(user) && canWrite(app.db, repo, user);
46 }
47
48 const key = (f: { package: string; version: string; advisory: string }): string =>
49 `${f.package}\0${f.version}\0${f.advisory}`;
50
51 export function listAcceptances(db: Database, repoId: string): Acceptance[] {
52 return db
53 .query<Acceptance, [string]>(
54 `SELECT package, version, advisory, by_name AS by, reason, at FROM dep_accept
55 WHERE repo_id = ?1 ORDER BY package, version, advisory`,
56 )
57 .all(repoId);
58 }
59
60 /** Findings still open, the ones accepted, and the bumps that clear the open ones. Pure. */
61 function split(report: Report, accepted: readonly Acceptance[]): ReportWithAccepted {
62 const held = new Map(accepted.map((a) => [key(a), a]));
63 const open: Finding[] = [];
64 const stood: Array<Finding & { accepted: Acceptance }> = [];
65 for (const f of report.findings) {
66 const a = held.get(key(f));
67 if (a) stood.push({ ...f, accepted: a });
68 else open.push(f);
69 }
70 return { ...report, findings: open, fixes: planFixes(open), accepted: stood };
71 }
72
73 export interface ReportWithAccepted extends Report {
74 readonly accepted: ReadonlyArray<Finding & { accepted: Acceptance }>;
75 }
76
77 export function withAcceptances(db: Database, repoId: string, report: Report): ReportWithAccepted {
78 return split(report, listAcceptances(db, repoId));
79 }
80
81 /**
82 * Only a person (never an agent) with write access lifts an advisory; the pin must be one the
83 * report names.
84 */
85 export function acceptAdvisory(
86 app: App,
87 repo: Repo,
88 user: User | undefined,
89 report: Report,
90 input: { package: string; version: string; advisory: string; reason: string },
91 ): Accepted {
92 if (!mayAct(app, repo, user) || user.kind !== "user")
93 return { ok: false, status: 403, why: "Only a person with write access accepts an advisory." };
94 if ([input.package, input.version, input.advisory].some((s) => s.length === 0 || s.length > NAME_MAX))
95 return { ok: false, status: 400, why: "Name the package, its version and the advisory." };
96 const reason = input.reason.replace(CONTROL, " ").replace(/\s+/g, " ").trim();
97 if (reason.length < REASON_MIN || reason.length > REASON_MAX)
98 return { ok: false, status: 400, why: `Say why it may stand, in ${REASON_MIN} to ${REASON_MAX} characters.` };
99 if (!report.findings.some((f) => key(f) === key(input)))
100 return { ok: false, status: 404, why: "No such open advisory on a pinned version." };
101 const done = app.db
102 .query(
103 `INSERT OR IGNORE INTO dep_accept (repo_id, package, version, advisory, by_id, by_name, reason, at)
104 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`,
105 )
106 .run(repo.id, input.package, input.version, input.advisory, user.id, user.username, reason, new Date().toISOString());
107 if (done.changes === 0) return { ok: false, status: 409, why: "That advisory is already accepted." };
108 app.log.info("advisory accepted", { repo: `${repo.ownerName}/${repo.name}`, advisory: input.advisory, by: user.username });
109 return { ok: true };
110 }
111
112 /** Ask for the fix of one pin as an issue: "filed" now, "seen" when one exists, else a refusal. */
113 export function requestFix(
114 app: App,
115 repo: Repo,
116 user: User | undefined,
117 report: Report,
118 pin: { package: string; version: string },
119 ): { ok: true; result: "filed" | "seen" } | Refused {
120 if (!mayAct(app, repo, user)) return { ok: false, status: 403, why: "Write access to this repository is needed." };
121 const bump = withAcceptances(app.db, repo.id, report).fixes.find((b) => b.package === pin.package && b.from === pin.version);
122 if (!bump) return { ok: false, status: 404, why: "No open advisory on that pin has a fix that clears it." };
123 const result = fileBump(app, user, repo, bump);
124 return result === "refused" ? { ok: false, status: 422, why: "The issue could not be opened." } : { ok: true, result };
125 }
src/security/fix_issues.ts +20 −10
@@ -10,13 +10,14 @@ import { join } from "node:path";
1010 import type { App } from "../app.ts";
1111 import { openIssue } from "../actions/issues.ts";
1212 import { listIssues } from "../core/issues.ts";
13 import { getRepo } from "../core/repos.ts";
14 import { getUserById } from "../core/users.ts";
13 import { getRepo, type Repo } from "../core/repos.ts";
14 import { getUserById, type User } from "../core/users.ts";
1515 import { repoDir } from "../git/repos.ts";
16 import { planFixes, type Bump } from "./fix.ts";
16 import { type Bump } from "./fix.ts";
1717 import { loadAdvisories, type Advisory, type Finding } from "./osv.ts";
1818 import { optedIn } from "./optin.ts";
1919 import { scanRepo } from "./scan.ts";
20 import { withAcceptances } from "./accept.ts";
2021
2122 /** At most this many new fix issues per repository per pass. */
2223 export const PER_PASS = 3;
@@ -59,7 +60,9 @@ export async function fileFixIssues(
5960 const repo = getRepo(app.db, row.owner, row.name);
6061 const actor = repo && getUserById(app.db, repo.ownerId);
6162 if (!repo || !actor) return 0;
62 const report = await scanRepo(repoDir(app.reposRoot, row.owner, row.name), row.branch, advisories);
63 const scanned = await scanRepo(repoDir(app.reposRoot, row.owner, row.name), row.branch, advisories);
64 // An advisory a person accepted (#17143) is not asked for again.
65 const report = withAcceptances(app.db, repo.id, { ...scanned, fixes: [] });
6366 let filed = 0;
6467 // A pin hit by an exploited advisory is told first, before any bump, once per advisory and pin.
6568 for (const f of report.findings) {
@@ -69,17 +72,24 @@ export async function fileFixIssues(
6972 if (seen.some((i) => i.title === title)) continue;
7073 if (openIssue(app as App, actor, repo, { title, body: exploitedBody(f) }).ok) filed++;
7174 }
72 for (const bump of planFixes(report.findings)) {
75 for (const bump of report.fixes) {
7376 if (filed >= PER_PASS) break;
74 const title = fixTitle(bump);
75 // Open or closed: a bump the crew declined or already made is not asked for again.
76 const seen = listIssues(app.db, repo.id, { state: "all", kind: "issue", query: title, limit: 20 });
77 if (seen.some((i) => i.title === title)) continue;
78 if (openIssue(app as App, actor, repo, { title, body: fixBody(bump) }).ok) filed++;
77 if (fileBump(app, actor, repo, bump) === "filed") filed++;
7978 }
8079 return filed;
8180 }
8281
82 /**
83 * One bump as an issue in the repository's tracker. "seen" when an issue with that title exists,
84 * open or closed: a bump the crew declined or already made is not asked for again.
85 */
86 export function fileBump(app: Pick<App, "db">, actor: User, repo: Repo, bump: Bump): "filed" | "seen" | "refused" {
87 const title = fixTitle(bump);
88 const seen = listIssues(app.db, repo.id, { state: "all", kind: "issue", query: title, limit: 20 });
89 if (seen.some((i) => i.title === title)) return "seen";
90 return openIssue(app as App, actor, repo, { title, body: fixBody(bump) }).ok ? "filed" : "refused";
91 }
92
8393 /**
8494 * Every repository's default branch against the mirror; one bad repository does not stop the rest.
8595 */
src/tui/screens/dependencies.ts +47 −10
@@ -10,6 +10,7 @@ import { requireReader } from "../../actions/access.ts";
1010 import type { Repo } from "../../core/repos.ts";
1111 import { repoDir } from "../../git/repos.ts";
1212 import { reportAt, reportWait, type Report } from "../../security/report_cache.ts";
13 import { acceptAdvisory, requestFix, withAcceptances, type ReportWithAccepted } from "../../security/accept.ts";
1314 import type { Ctx, Screen } from "../app/app.ts";
1415 import type { Command } from "../app/palette.ts";
1516 import { binding } from "../app/keys.ts";
@@ -17,21 +18,29 @@ import { style } from "../term/style.ts";
1718 import { truncate } from "../term/width.ts";
1819 import type { Session } from "../session.ts";
1920 import { fill, len, split } from "../ui/layout.ts";
20 import { ListState, drawList, type ListRow } from "./common.ts";
21 import { ListState, drawList, later, promptScreen, type ListRow } from "./common.ts";
2122
2223 /** One line per finding; pure. */
23 export function findingRows(report: Report): ListRow[] {
24 return report.findings.map((f) => ({
24 export function findingRows(report: Report & { accepted?: ReportWithAccepted["accepted"] }): ListRow[] {
25 const open: ListRow[] = report.findings.map((f) => ({
2526 title: `${f.package} ${f.version}: ${f.advisory}`,
2627 secondary: [f.severity, ...(f.exploited ? ["exploited"] : []), ...(f.epss === undefined ? [] : [`EPSS ${(f.epss * 100).toFixed(f.epss < 0.1 ? 2 : 1)}%`])].join(", "),
2728 meta: f.fixedIn ? `fix ${f.fixedIn}` : "no fix named",
2829 ...(f.summary ? { note: f.summary } : {}),
2930 }));
31 // Accepted ones close the list, with who said why.
32 const stood: ListRow[] = (report.accepted ?? []).map((f) => ({
33 title: `${f.package} ${f.version}: ${f.advisory}`,
34 secondary: "accepted",
35 meta: f.accepted.by,
36 note: f.accepted.reason,
37 }));
38 return [...open, ...stood];
3039 }
3140
3241 export function dependenciesScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3342 const state = new ListState();
34 let report: Report | undefined;
43 let report: ReportWithAccepted | undefined;
3544 let note = "Reading the lockfiles…";
3645 const read = async (): Promise<void> => {
3746 if (!requireReader(f.app, f.user, repo).ok) {
@@ -43,13 +52,14 @@ export function dependenciesScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4352 note = `Too many reads; try again in ${wait}s.`;
4453 return;
4554 }
46 report = await reportAt(f.app, f.app.config.dataDir, repoDir(f.app.reposRoot, repo.ownerName, repo.name), repo.defaultBranch);
55 const fresh = await reportAt(f.app, f.app.config.dataDir, repoDir(f.app.reposRoot, repo.ownerName, repo.name), repo.defaultBranch);
56 report = fresh && withAcceptances(f.app.db, repo.id, fresh);
4757 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.`;
4858 };
4959 const again = (): void => void read().catch(() => (note = "The lockfiles could not be read.")).finally(() => ctx.invalidate());
50 return {
60 const screen: Screen = {
5161 title: `${repo.ownerName}/${repo.name} — Dependencies`,
52 keys: [binding(["j", "k"], "move cursor"), binding([keyOf("reread")], "read again")],
62 keys: [binding(["j", "k"], "move cursor"), binding([keyOf("reread")], "read again"), binding(["a"], "accept the risk"), binding(["f"], "file the fix")],
5363 async load() {
5464 again();
5565 },
@@ -61,11 +71,38 @@ export function dependenciesScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6171 },
6272 key(e) {
6373 if (state.key(e, report?.findings.length ?? 0)) return true;
64 if (e.ctrl || e.alt || e.key !== keyOf("reread")) return false;
65 again();
66 return true;
74 if (e.ctrl || e.alt) return false;
75 if (e.key === keyOf("reread")) {
76 again();
77 return true;
78 }
79 const row = report?.findings[state.index];
80 if (e.key === "a" || e.key === "f") {
81 if (!report || !row) return true;
82 if (e.key === "f") {
83 const done = requestFix(f.app, repo, f.user, report, { package: row.package, version: row.version });
84 if (!done.ok) ctx.toast(done.why, "danger");
85 else ctx.toast(done.result === "filed" ? "fix filed as an issue" : "a fix issue already exists", "default");
86 return true;
87 }
88 const held = report;
89 later(ctx, () =>
90 promptScreen(ctx, screen, {
91 title: `Accept ${row.advisory} on ${row.package} ${row.version}`,
92 label: "Why may it stand?",
93 onSubmit: (reason) => {
94 const done = acceptAdvisory(f.app, repo, f.user, held, { package: row.package, version: row.version, advisory: row.advisory, reason });
95 if (!done.ok) return done.why;
96 return Promise.resolve().then(() => again());
97 },
98 }),
99 );
100 return true;
101 }
102 return false;
67103 },
68104 };
105 return screen;
69106 }
70107
71108 /** The palette's command while a repository is open. */
test/account-purge.test.ts +15
@@ -230,6 +230,21 @@ describe("a finding's toucher", () => {
230230 });
231231 });
232232
233 describe("an accepted advisory's acceptor", () => {
234 test("a purged person's name on an accepted advisory becomes the placeholder's", async () => {
235 const dana = await make("dana");
236 const owner = await make("hollis");
237 const host = await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "keep", visibility: "public" });
238 if (!host.ok) throw new Error("repo");
239 app.db.run("INSERT INTO dep_accept (repo_id, package, version, advisory, by_id, by_name, reason, at) VALUES (?1, 'p', '1.0.0', 'GHSA-x', ?2, 'dana', 'ok', 't'), (?1, 'p', '1.0.0', 'GHSA-y', NULL, 'danae', 'ok', 't')", [host.value.id, dana.id]);
240 requestClose(app.db, dana.id, T0);
241 await purgeDue(app, at(7));
242 const by = (a: string) => app.db.query<{ n: string }, [string]>("SELECT by_name AS n FROM dep_accept WHERE advisory = ?1").get(a)?.n;
243 expect(by("GHSA-x")).toBe(FORMER_NAME);
244 expect(by("GHSA-y")).toBe("danae");
245 });
246 });
247
233248 describe("every column that names a user is covered", () => {
234249 test("by its cascade or by a row of COVERED", () => {
235250 // A new table that holds a user id with no ON DELETE CASCADE / SET NULL
test/dependencies-accept.test.ts added +251
@@ -0,0 +1,251 @@
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 { FORGE_SCOPE } from "../src/core/config.ts";
7 import { listIssues } from "../src/core/issues.ts";
8 import { getRepo } from "../src/core/repos.ts";
9 import { createUser, getUserByName } from "../src/core/users.ts";
10 import { acceptAdvisory } from "../src/security/accept.ts";
11 import { reportAt } from "../src/security/report_cache.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { dependenciesScreen, findingRows } from "../src/tui/screens/dependencies.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { settleApp } from "./helpers/tui.ts";
16 import { repoDir } from "../src/git/repos.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { fileAllFixIssues } from "../src/security/fix_issues.ts";
19 import { seedAdmin } from "./helpers/admin.ts";
20
21 // Accepting the risk of an advisory, and asking for its fix (#17143).
22 describe("dependency fix and accept-risk actions", () => {
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let h: Record<string, string>;
27 const api = (path: string, body?: unknown) =>
28 fetch(`${servers.url}/api/v1/repos/mira/app/dependencies${path}`, {
29 method: body === undefined ? "GET" : "POST",
30 headers: h,
31 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
32 });
33 const pin = { package: "lodash", version: "4.17.20" };
34
35 beforeAll(async () => {
36 dataDir = await mkdtemp(join(tmpdir(), "forge-dep-accept-"));
37 await mkdir(join(dataDir, "osv"));
38 await writeFile(
39 join(dataDir, "osv", "a.json"),
40 JSON.stringify({
41 id: "GHSA-test-0001",
42 database_specific: { severity: "CRITICAL" },
43 affected: [{ package: { ecosystem: "npm", name: "lodash" }, ranges: [{ type: "SEMVER", events: [{ introduced: "0" }, { fixed: "4.17.21" }] }] }],
44 }),
45 );
46 app = createApp({ dataDir, port: 0 });
47 servers = await serve(app);
48 await seedAdmin(app, { username: "mira", email: "[email protected]", password: "osv-pass-1234" });
49 const token = await fetch(`${servers.url}/api/v1/tokens`, {
50 method: "POST",
51 headers: { "content-type": "application/json" },
52 body: JSON.stringify({ adminConfirm: true, username: "mira", password: "osv-pass-1234", name: "t", scope: "rw" }),
53 })
54 .then((r) => r.json())
55 .then((j) => (j as { token: string }).token);
56 h = { authorization: `Bearer ${token}`, "content-type": "application/json" };
57 await fetch(`${servers.url}/api/v1/repos`, { method: "POST", headers: h, body: JSON.stringify({ name: "app", visibility: "public" }) });
58 await fetch(`${servers.url}/api/v1/repos/mira/app/contents`, {
59 method: "POST",
60 headers: h,
61 body: JSON.stringify({ message: "lock", files: [{ path: "bun.lock", content: `{"packages":{"l":["[email protected]","",{}],}}` }] }),
62 });
63 });
64 afterAll(async () => {
65 servers.stop();
66 app.close();
67 await rm(dataDir, { recursive: true, force: true });
68 });
69
70 test("fix files the bump as an issue once; asking again files nothing", async () => {
71 const first = await api("/fix", pin);
72 expect(first.status).toBe(201);
73 expect(await first.json()).toEqual({ filed: true });
74 const again = await api("/fix", pin);
75 expect(again.status).toBe(200);
76 expect(await again.json()).toEqual({ filed: false });
77 const repo = getRepo(app.db, "mira", "app")!;
78 expect(listIssues(app.db, repo.id, { state: "all", kind: "issue", limit: 20 }).map((i) => i.title)).toEqual([
79 "Bump lodash from 4.17.20 to 4.17.21 (critical advisory)",
80 ]);
81 expect((await api("/fix", { package: "nope", version: "1.0.0" })).status).toBe(404);
82 });
83
84 test("accept needs a reason and a real advisory on a pinned version", async () => {
85 expect((await api("/accept", { ...pin, advisory: "GHSA-test-0001", reason: "" })).status).toBe(400);
86 expect((await api("/accept", { ...pin, advisory: "GHSA-other", reason: "dev only" })).status).toBe(404);
87 expect((await api("/accept", { ...pin, version: "9.9.9", advisory: "GHSA-test-0001", reason: "dev only" })).status).toBe(404);
88 });
89
90 test("an accepted advisory leaves the open findings and the fixes, and is listed with who and why", async () => {
91 const done = await api("/accept", { ...pin, advisory: "GHSA-test-0001", reason: " only used in a build script " });
92 expect(done.status).toBe(200);
93 const body = (await (await api("")).json()) as { findings: unknown[]; fixes: unknown[]; accepted: { accepted: { by: string; reason: string } }[] };
94 expect(body.findings).toEqual([]);
95 expect(body.fixes).toEqual([]);
96 expect(body.accepted).toMatchObject([{ package: "lodash", accepted: { by: "mira", reason: "only used in a build script" } }]);
97 expect((await api("/accept", { ...pin, advisory: "GHSA-test-0001", reason: "again" })).status).toBe(409);
98 expect((await api("/fix", pin)).status).toBe(404);
99 });
100
101 test("a stranger without write access is refused", async () => {
102 const res = await fetch(`${servers.url}/api/v1/repos/mira/app/dependencies/accept`, {
103 method: "POST",
104 headers: { "content-type": "application/json" },
105 body: JSON.stringify({ ...pin, advisory: "GHSA-test-0001", reason: "because" }),
106 });
107 expect([401, 403]).toContain(res.status);
108 });
109
110 test("a signed-in user without write access gets 403 on accept and fix, an agent on accept", async () => {
111 await createUser(app.db, { origin: "seed", trusted: true, username: "omar", email: "[email protected]", password: "other-pass-1234" });
112 const token = await fetch(`${servers.url}/api/v1/tokens`, {
113 method: "POST",
114 headers: { "content-type": "application/json" },
115 body: JSON.stringify({ username: "omar", password: "other-pass-1234", name: "t", scope: "rw" }),
116 })
117 .then((r) => r.json())
118 .then((j) => (j as { token: string }).token);
119 const as = { authorization: `Bearer ${token}`, "content-type": "application/json" };
120 for (const [path, body] of [["accept", { ...pin, advisory: "GHSA-test-0001", reason: "because" }], ["fix", pin]] as const) {
121 const res = await fetch(`${servers.url}/api/v1/repos/mira/app/dependencies/${path}`, { method: "POST", headers: as, body: JSON.stringify(body) });
122 expect(res.status).toBe(403);
123 }
124 // An agent that could write is still refused: only a person accepts a risk.
125 const repo = getRepo(app.db, "mira", "app")!;
126 const report = (await reportAt(app, dataDir, repoDir(app.reposRoot, "mira", "app"), "main"))!;
127 const mira = getUserByName(app.db, "mira")!;
128 const input = { ...pin, advisory: "GHSA-test-0001", reason: "because" };
129 expect(acceptAdvisory(app, repo, { ...mira, kind: "agent" }, report, input)).toMatchObject({ ok: false, status: 403 });
130 });
131
132 test("control characters in a reason are removed before it is kept", async () => {
133 await fetch(`${servers.url}/api/v1/repos`, { method: "POST", headers: h, body: JSON.stringify({ name: "ctl", visibility: "public" }) });
134 await fetch(`${servers.url}/api/v1/repos/mira/ctl/contents`, {
135 method: "POST",
136 headers: h,
137 body: JSON.stringify({ message: "lock", files: [{ path: "bun.lock", content: `{"packages":{"l":["[email protected]","",{}],}}` }] }),
138 });
139 const repo = getRepo(app.db, "mira", "ctl")!;
140 const report = (await reportAt(app, dataDir, repoDir(app.reposRoot, "mira", "ctl"), "main"))!;
141 const mira = getUserByName(app.db, "mira")!;
142 const input = { ...pin, advisory: "GHSA-test-0001" };
143 expect(acceptAdvisory(app, repo, mira, report, { ...input, reason: "\u0007\u009b\u001b" })).toMatchObject({ ok: false, status: 400 });
144 expect(acceptAdvisory(app, repo, mira, report, { ...input, reason: "dev\u001b[2Jonly\u0007\u009bhere" })).toEqual({ ok: true });
145 const kept = app.db.query<{ reason: string }, [string]>("SELECT reason FROM dep_accept WHERE repo_id = ?1").get(repo.id)!.reason;
146 expect(kept).toBe("dev [2Jonly here");
147 expect(kept).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/);
148 });
149
150 test("the terminal lists an accepted advisory after the open ones", () => {
151 const rows = findingRows({
152 ref: "main",
153 lockfiles: [],
154 packages: 1,
155 findings: [],
156 fixes: [],
157 accepted: [{ advisory: "GHSA-x", summary: "", severity: "high", package: "lodash", version: "4.17.20", fixedIn: null, accepted: { package: "lodash", version: "4.17.20", advisory: "GHSA-x", by: "mira", reason: "dev only", at: "2026-12-01T00:00:00.000Z" } }],
158 });
159 expect(rows).toEqual([{ title: "lodash 4.17.20: GHSA-x", secondary: "accepted", meta: "mira", note: "dev only" }]);
160 });
161
162 test("the terminal keys a and f accept a risk and file the fix, and report what happened", async () => {
163 await fetch(`${servers.url}/api/v1/repos`, { method: "POST", headers: h, body: JSON.stringify({ name: "term", visibility: "public" }) });
164 await fetch(`${servers.url}/api/v1/repos/mira/term/contents`, {
165 method: "POST",
166 headers: h,
167 body: JSON.stringify({ message: "lock", files: [{ path: "bun.lock", content: `{"packages":{"l":["[email protected]","",{}],}}` }] }),
168 });
169 const repo = getRepo(app.db, "mira", "term")!;
170 const open = async (username: string) => {
171 const user = getUserByName(app.db, username)!;
172 const { app: tui, session } = createForgeApp(
173 app,
174 { sshUsername: username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user },
175 { terminal: headlessTerminal(160, 44), exitHooks: false },
176 );
177 tui.start();
178 tui.ctx.push(dependenciesScreen(session, tui.ctx, repo));
179 await settleApp(tui);
180 const press = async (key: string) => {
181 tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
182 await settleApp(tui);
183 };
184 return { tui, press, text: () => tui.screen.toText() };
185 };
186 const stranger = await open("omar");
187 try {
188 await stranger.press("f");
189 expect(stranger.text()).toContain("Write access to this repository is needed");
190 } finally {
191 stranger.tui.stop();
192 }
193 const s = await open("mira");
194 try {
195 await s.press("f");
196 expect(s.text()).toContain("fix filed as an issue");
197 await s.press("f");
198 expect(s.text()).toContain("a fix issue already exists");
199 await s.press("a");
200 expect(s.text()).toContain("Accept GHSA-test-0001 on lodash 4.17.20");
201 for (const ch of "dev only") await s.press(ch);
202 await s.press("enter");
203 expect(s.text()).toContain("accepted");
204 expect(s.text()).toContain("dev only");
205 } finally {
206 s.tui.stop();
207 }
208 }, 60_000);
209 });
210
211 describe("the hourly pass leaves an accepted advisory alone", () => {
212 test("no fix issue is filed for it", async () => {
213 const dataDir = await mkdtemp(join(tmpdir(), "forge-dep-accept2-"));
214 await mkdir(join(dataDir, "osv"));
215 await writeFile(
216 join(dataDir, "osv", "a.json"),
217 JSON.stringify({ id: "GHSA-test-0001", affected: [{ package: { ecosystem: "npm", name: "lodash" }, ranges: [{ type: "SEMVER", events: [{ introduced: "0" }, { fixed: "4.17.21" }] }] }] }),
218 );
219 const app = createApp({ dataDir, port: 0 });
220 const servers = await serve(app);
221 try {
222 await seedAdmin(app, { username: "mira", email: "[email protected]", password: "osv-pass-1234" });
223 const token = await fetch(`${servers.url}/api/v1/tokens`, {
224 method: "POST",
225 headers: { "content-type": "application/json" },
226 body: JSON.stringify({ adminConfirm: true, username: "mira", password: "osv-pass-1234", name: "t", scope: "rw" }),
227 })
228 .then((r) => r.json())
229 .then((j) => (j as { token: string }).token);
230 const h = { authorization: `Bearer ${token}`, "content-type": "application/json" };
231 await fetch(`${servers.url}/api/v1/repos`, { method: "POST", headers: h, body: JSON.stringify({ name: "app", visibility: "private" }) });
232 await fetch(`${servers.url}/api/v1/repos/mira/app/contents`, {
233 method: "POST",
234 headers: h,
235 body: JSON.stringify({ message: "lock", files: [{ path: "bun.lock", content: `{"packages":{"l":["[email protected]","",{}],}}` }] }),
236 });
237 app.configs.set(FORGE_SCOPE, { "osv.repos": ["mira/app"] }, "test", "opt in");
238 const accept = await fetch(`${servers.url}/api/v1/repos/mira/app/dependencies/accept`, {
239 method: "POST",
240 headers: h,
241 body: JSON.stringify({ package: "lodash", version: "4.17.20", advisory: "GHSA-test-0001", reason: "dev only" }),
242 });
243 expect(accept.status).toBe(200);
244 expect(await fileAllFixIssues(app)).toBe(0);
245 } finally {
246 servers.stop();
247 app.close();
248 await rm(dataDir, { recursive: true, force: true });
249 }
250 });
251 });

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

Keyboard shortcuts

Docs