Public: anyone can read this; the crew can change it.
Security: one page per repository lists its sealed security reports by severity, and each can be given to the crew, dismissed or reopened from its row #14825
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14791-security-one-page-per-repository-lists-i → main 8 commits fork 5 threads · 5 unresolved
docs/features/security.md +30
| @@ -18,3 +18,33 @@ closes. Both read `src/view/security.ts`. | ||
| 18 | 18 | Every claim names its source and its proof, and `test/security-page.test.ts` fails when a source |
| 19 | 19 | no longer says what the claim leans on or the proof is gone. Machines read |
| 20 | 20 | `/.well-known/security.txt`; the admin's side is `/settings/security`. |
| 21 | ||
| 22 | ## Where sealed security reports go | |
| 23 | ||
| 24 | A repository's sealed issues labelled `security` have one page: | |
| 25 | `/<owner>/<name>/security` (`src/web/pages/reports.ts`, rows from | |
| 26 | `src/core/security_reports.ts`). Only people who may see sealed issues — the | |
| 27 | repository's writers and its crew — reach it; everyone else gets 404, from the | |
| 28 | page and from `GET /api/v1/repos/<owner>/<name>/security` alike, and sees no count. | |
| 29 | ||
| 30 | - **Rows.** Grouped by severity from the `sev:critical`, `sev:high`, | |
| 31 | `sev:medium` and `sev:bug` labels (critical first): title, state, age and | |
| 32 | the first repository path its words name. | |
| 33 | - **States.** `open`; `building` (a pull closing it is open, or merged and not | |
| 34 | yet live); `fixed` only when that pull's merge is in a production deploy | |
| 35 | (`deploy_landed`, the ask-to-live rule); `dismissed` (closed as dropped); | |
| 36 | `closed`. | |
| 37 | - **Filters** are one segmented control per axis: `?severity=`, `?state=`, | |
| 38 | and `?path=` (a path prefix; click the file on a row). | |
| 39 | - **Actions** are the issue's own routes, so the page keeps no state: *Give it | |
| 40 | to the crew* links the report under the Trust pillar's umbrella (or the | |
| 41 | first pillar) so it is ready; *Dismiss* opens a note field on that row only | |
| 42 | (`?dismiss=N`) and closes it as dropped — the close is refused without the | |
| 43 | one-sentence reason, at every door; *Reopen* opens it again. | |
| 44 | - **Count.** Writers see "N open security reports, M critical" on the | |
| 45 | repository's Issues list. | |
| 46 | ||
| 47 | In the terminal, a repository's `:` palette offers **Security (N)** (`src/tui/screens/reports.ts`) | |
| 48 | while N > 0: every report, critical first, read again on each draw; `j`/`k` | |
| 49 | scroll, `c` gives the one under the cursor to the crew, `d` asks why and | |
| 50 | dismisses it, `o` reopens it — the same issue actions the page posts to. |
src/actions/issues.ts +5 −2
| @@ -518,7 +518,8 @@ export function setIssueState( | ||
| 518 | 518 | ? (alreadyDone(app.db, [issue.id]).get(issue.id) ?? []) |
| 519 | 519 | : []; |
| 520 | 520 | // A bug closed with no fix behind it (no commit on main, no split) says |
| 521 | // why; the crew's own live triage and stale sweeps note it themselves. | |
| 521 | // why, and so does a security report dismissed (#14791); the crew's own | |
| 522 | // live triage and stale sweeps note it themselves. | |
| 522 | 523 | if (closing.note !== undefined && typeof closing.note !== "string") return err("invalid_note"); |
| 523 | 524 | const note = (closing.note ?? "").trim(); |
| 524 | 525 | if (note.length > MAX_NOTE) return err("invalid_note"); |
| @@ -531,7 +532,9 @@ export function setIssueState( | ||
| 531 | 532 | !closing.triage && |
| 532 | 533 | !closing.stale && |
| 533 | 534 | !closing.system && |
| 534 | labelsFor(app.db, issue.id).some((l) => l.name === "bug") | |
| 535 | labelsFor(app.db, issue.id).some( | |
| 536 | (l) => l.name === "bug" || (reason === "dropped" && l.name === "security"), | |
| 537 | ) | |
| 535 | 538 | ) |
| 536 | 539 | return err("reason_required"); |
| 537 | 540 | const changed = app.db.transaction(() => { |
src/contract/openapi/routes/getApiV1ReposOwnerNameSecurity.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import { REPO, type Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: `${REPO}/security`, | |
| 6 | summary: "List the repository's sealed security reports, critical first", | |
| 7 | detail: | |
| 8 | "List the repository's sealed security reports (issues labelled security), critical first, for a writer or its crew; anyone else gets 404. Filters: severity (critical, high, medium, bug, unrated), state (open, building, fixed, dismissed, closed), path (a path prefix the report names). Answers { items: [{ number, title, severity, files, state, pull, pillar, createdAt }], open, critical }; state is fixed only when the closing pull's merge is in a production deploy", | |
| 9 | auth: true, | |
| 10 | role: "member", | |
| 11 | refuses: [404], | |
| 12 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -203,6 +203,7 @@ export { route as getApiV1ReposOwnerNameRuns } from "./getApiV1ReposOwnerNameRun | ||
| 203 | 203 | export { route as getApiV1ReposOwnerNameRunsId } from "./getApiV1ReposOwnerNameRunsId.ts"; |
| 204 | 204 | export { route as getApiV1ReposOwnerNameRunsIdLog } from "./getApiV1ReposOwnerNameRunsIdLog.ts"; |
| 205 | 205 | export { route as getApiV1ReposOwnerNameSchedules } from "./getApiV1ReposOwnerNameSchedules.ts"; |
| 206 | export { route as getApiV1ReposOwnerNameSecurity } from "./getApiV1ReposOwnerNameSecurity.ts"; | |
| 206 | 207 | export { route as getApiV1ReposOwnerNameStatement } from "./getApiV1ReposOwnerNameStatement.ts"; |
| 207 | 208 | export { route as getApiV1ReposOwnerNameTags } from "./getApiV1ReposOwnerNameTags.ts"; |
| 208 | 209 | export { route as getApiV1ReposOwnerNameUpstream } from "./getApiV1ReposOwnerNameUpstream.ts"; |
src/contract/tags.ts +1
| @@ -96,6 +96,7 @@ const ALIAS: Readonly<Record<string, string>> = { | ||
| 96 | 96 | "data-import": "apps", |
| 97 | 97 | "data-move": "apps", |
| 98 | 98 | drop: "apps", |
| 99 | security: "reports", | |
| 99 | 100 | }; |
| 100 | 101 | |
| 101 | 102 | /** One line on each tag the document lists. */ |
src/core/security_reports.ts added +237
| @@ -0,0 +1,237 @@ | ||
| 1 | /** | |
| 2 | * A repository's security reports (#14791): its sealed issues labelled | |
| 3 | * `security`, as rows the Security page, its API and its count all read. | |
| 4 | * Nothing is stored here; every action on a row is the issue's own (close | |
| 5 | * with a reason, reopen, link under a pillar), so the issue is the state. | |
| 6 | * | |
| 7 | * Only someone who may see sealed issues (`canSeeSealed`) gets rows: the | |
| 8 | * caller asks `mayReadSecurity` first and answers 404 otherwise, and | |
| 9 | * `securityReports` asks again, so a caller that forgets gets nothing. | |
| 10 | * | |
| 11 | * A report reads `fixed` only when a pull that closes it has gone live: a | |
| 12 | * production deploy carrying its merge (`deploy_landed`, the ask-to-live | |
| 13 | * rule). Merged but not yet live, or open, is `building`. | |
| 14 | */ | |
| 15 | ||
| 16 | import type { Database } from "bun:sqlite"; | |
| 17 | import { listIssues, labelsForIssues, type Issue } from "./issues.ts"; | |
| 18 | import { pillarsOf, servedBy, type Pillar } from "./pillars.ts"; | |
| 19 | import { closesFromBody } from "./pulls.ts"; | |
| 20 | import type { Repo } from "./repos.ts"; | |
| 21 | import { canSeeSealed } from "./sealed.ts"; | |
| 22 | import type { User } from "./users.ts"; | |
| 23 | ||
| 24 | export const SECURITY_LABEL = "security"; | |
| 25 | export const SEVERITIES = ["critical", "high", "medium", "bug"] as const; | |
| 26 | export type Severity = (typeof SEVERITIES)[number] | "unrated"; | |
| 27 | export const REPORT_STATES = ["open", "building", "fixed", "dismissed", "closed"] as const; | |
| 28 | export type ReportState = (typeof REPORT_STATES)[number]; | |
| 29 | ||
| 30 | export interface SecurityRow { | |
| 31 | readonly number: number; | |
| 32 | readonly title: string; | |
| 33 | readonly severity: Severity; | |
| 34 | readonly files: readonly string[]; | |
| 35 | readonly state: ReportState; | |
| 36 | /** The pull fixing it, when one is building or live. */ | |
| 37 | readonly pull: number | null; | |
| 38 | /** The pillar it serves: given to the crew. */ | |
| 39 | readonly pillar: string | null; | |
| 40 | readonly createdAt: string; | |
| 41 | } | |
| 42 | ||
| 43 | export interface SecurityFilter { | |
| 44 | readonly severity?: Severity; | |
| 45 | readonly state?: ReportState; | |
| 46 | /** Rows naming a file under this path. */ | |
| 47 | readonly path?: string; | |
| 48 | } | |
| 49 | ||
| 50 | /** Whether `user` may read the Security page of `repo` at all. */ | |
| 51 | export function mayReadSecurity(db: Database, repo: Repo, user: User | undefined): boolean { | |
| 52 | return canSeeSealed(db, repo, user); | |
| 53 | } | |
| 54 | ||
| 55 | /** A filter from query parameters; anything not one of the known values is left out. */ | |
| 56 | export function securityFilter(params: URLSearchParams): SecurityFilter { | |
| 57 | const severity = params.get("severity") ?? ""; | |
| 58 | const state = params.get("state") ?? ""; | |
| 59 | const path = (params.get("path") ?? "").trim(); | |
| 60 | return { | |
| 61 | ...((SEVERITIES as readonly string[]).includes(severity) || severity === "unrated" | |
| 62 | ? { severity: severity as Severity } | |
| 63 | : {}), | |
| 64 | ...((REPORT_STATES as readonly string[]).includes(state) ? { state: state as ReportState } : {}), | |
| 65 | ...(/^[\w./-]{1,200}$/.test(path) ? { path } : {}), | |
| 66 | }; | |
| 67 | } | |
| 68 | ||
| 69 | /** The page's address with this filter, one key changed. */ | |
| 70 | export function securityHref(base: string, f: SecurityFilter, key?: keyof SecurityFilter, value?: string): string { | |
| 71 | const q = new URLSearchParams(); | |
| 72 | const next = key === undefined ? f : { ...f, [key]: value }; | |
| 73 | for (const k of ["severity", "state", "path"] as const) { | |
| 74 | const v = next[k]; | |
| 75 | if (v !== undefined) q.set(k, v); | |
| 76 | } | |
| 77 | const s = q.toString(); | |
| 78 | return `${base}/security${s === "" ? "" : `?${s}`}`; | |
| 79 | } | |
| 80 | ||
| 81 | /** The number in `?dismiss=N`: the one row showing its note field. */ | |
| 82 | export function dismissing(params: URLSearchParams): number | undefined { | |
| 83 | const v = params.get("dismiss") ?? ""; | |
| 84 | return /^[1-9]\d{0,8}$/.test(v) ? Number(v) : undefined; | |
| 85 | } | |
| 86 | ||
| 87 | const FILE = /(?:^|[\s`'"(])((?:src|test|scripts|docs|bench|templates)\/[\w./-]*\w)/g; | |
| 88 | ||
| 89 | /** The repository paths a report's words name, first five, each once. */ | |
| 90 | export function filesNamed(body: string): string[] { | |
| 91 | const out: string[] = []; | |
| 92 | for (const m of body.matchAll(FILE)) { | |
| 93 | const path = m[1]!; | |
| 94 | if (!out.includes(path)) out.push(path); | |
| 95 | if (out.length === 5) break; | |
| 96 | } | |
| 97 | return out; | |
| 98 | } | |
| 99 | ||
| 100 | function severityOf(labels: readonly string[]): Severity { | |
| 101 | for (const s of SEVERITIES) if (labels.includes(`sev:${s}`)) return s; | |
| 102 | return "unrated"; | |
| 103 | } | |
| 104 | ||
| 105 | const RANK: Record<Severity, number> = { critical: 0, high: 1, medium: 2, bug: 3, unrated: 4 }; | |
| 106 | ||
| 107 | /** | |
| 108 | * The pull that closes each report, and whether it went live: one read of the pulls whose | |
| 109 | * description names one of the reports' numbers, however old the pull. | |
| 110 | */ | |
| 111 | function fixesFor( | |
| 112 | db: Database, | |
| 113 | repoId: string, | |
| 114 | numbers: readonly number[], | |
| 115 | ): Map<number, { pull: number; live: boolean }> { | |
| 116 | const out = new Map<number, { pull: number; live: boolean }>(); | |
| 117 | if (numbers.length === 0) return out; | |
| 118 | const pulls = db | |
| 119 | .query<{ number: number; body: string; merged_at: string | null; landed: string | null }, [string, number, string]>( | |
| 120 | FIXES_SQL, | |
| 121 | ) | |
| 122 | .all(repoId, Math.min(...numbers), JSON.stringify(numbers)); | |
| 123 | return fixesFrom(pulls, new Set(numbers), out); | |
| 124 | } | |
| 125 | ||
| 126 | /** | |
| 127 | * The pulls that name a report: numbered after the oldest (`issue_repo_kind_number`), open or | |
| 128 | * merged, whose body says `#n` for one of the numbers in `?3` (a JSON array). No cap by recency: | |
| 129 | * an old pull that fixed a report still reads as its fix. `fixesFrom` keeps only real `Closes #n`. | |
| 130 | */ | |
| 131 | export const FIXES_SQL = `SELECT issue.number, issue.body, pull.merged_at, deploy_landed.at AS landed | |
| 132 | FROM issue JOIN pull ON pull.issue_id = issue.id | |
| 133 | LEFT JOIN deploy_landed ON deploy_landed.issue_id = issue.id | |
| 134 | WHERE issue.repo_id = ?1 AND issue.kind = 'pull' AND issue.number > ?2 | |
| 135 | AND (issue.state = 'open' OR pull.merged_at IS NOT NULL) | |
| 136 | AND EXISTS (SELECT 1 FROM json_each(?3) AS n WHERE instr(issue.body, '#' || n.value) > 0)`; | |
| 137 | ||
| 138 | export function fixesFrom( | |
| 139 | pulls: readonly { number: number; body: string; merged_at: string | null; landed: string | null }[], | |
| 140 | wanted: ReadonlySet<number>, | |
| 141 | out: Map<number, { pull: number; live: boolean }>, | |
| 142 | ): Map<number, { pull: number; live: boolean }> { | |
| 143 | for (const p of pulls) { | |
| 144 | const live = p.merged_at !== null && p.landed !== null && p.landed >= p.merged_at; | |
| 145 | for (const n of closesFromBody(p.body)) { | |
| 146 | if (!wanted.has(n)) continue; | |
| 147 | const seen = out.get(n); | |
| 148 | if (seen === undefined || (live && !seen.live)) out.set(n, { pull: p.number, live }); | |
| 149 | } | |
| 150 | } | |
| 151 | return out; | |
| 152 | } | |
| 153 | ||
| 154 | function stateOf(issue: Issue, fix: { live: boolean } | undefined): ReportState { | |
| 155 | if (fix?.live === true) return "fixed"; | |
| 156 | if (issue.state === "open") return fix === undefined ? "open" : "building"; | |
| 157 | if (issue.closeReason === "dropped") return "dismissed"; | |
| 158 | return fix === undefined ? "closed" : "building"; | |
| 159 | } | |
| 160 | ||
| 161 | /** The security reports `user` may see, critical first then oldest first; empty for anyone else. */ | |
| 162 | export function securityReports( | |
| 163 | db: Database, | |
| 164 | repo: Repo, | |
| 165 | user: User | undefined, | |
| 166 | filter: SecurityFilter = {}, | |
| 167 | ): SecurityRow[] { | |
| 168 | if (!mayReadSecurity(db, repo, user)) return []; | |
| 169 | const issues = listIssues(db, repo.id, { | |
| 170 | kind: "issue", | |
| 171 | state: "all", | |
| 172 | label: SECURITY_LABEL, | |
| 173 | sealed: true, | |
| 174 | limit: 1000, | |
| 175 | }).filter((i) => i.sealed); | |
| 176 | const labels = labelsForIssues(db, issues.map((i) => i.id)); | |
| 177 | const fixes = fixesFor(db, repo.id, issues.map((i) => i.number)); | |
| 178 | const served = servedBy(db, pillarsOf(db, repo)); | |
| 179 | const rows = issues.map((issue): SecurityRow => { | |
| 180 | const fix = fixes.get(issue.number); | |
| 181 | return { | |
| 182 | number: issue.number, | |
| 183 | title: issue.title, | |
| 184 | severity: severityOf((labels.get(issue.id) ?? []).map((l) => l.name.toLowerCase())), | |
| 185 | files: filesNamed(issue.body), | |
| 186 | state: stateOf(issue, fix), | |
| 187 | pull: fix?.pull ?? null, | |
| 188 | pillar: served.get(issue.id) ?? null, | |
| 189 | createdAt: issue.createdAt, | |
| 190 | }; | |
| 191 | }); | |
| 192 | const path = filter.path; | |
| 193 | return rows | |
| 194 | .filter( | |
| 195 | (r) => | |
| 196 | (filter.severity === undefined || r.severity === filter.severity) && | |
| 197 | (filter.state === undefined || r.state === filter.state) && | |
| 198 | (path === undefined || r.files.some((f) => f.startsWith(path))), | |
| 199 | ) | |
| 200 | .sort((a, b) => RANK[a.severity] - RANK[b.severity] || a.number - b.number); | |
| 201 | } | |
| 202 | ||
| 203 | /** Open (and building) reports and how many of them are critical, for the repository page. */ | |
| 204 | export function securityCount(rows: readonly SecurityRow[]): { open: number; critical: number } { | |
| 205 | const open = rows.filter((r) => r.state === "open" || r.state === "building"); | |
| 206 | return { open: open.length, critical: open.filter((r) => r.severity === "critical").length }; | |
| 207 | } | |
| 208 | ||
| 209 | /** The pillar a report is given to the crew under: the Trust pillar, else the first. */ | |
| 210 | export function crewPillar(db: Database, repo: Repo): Pillar | undefined { | |
| 211 | const { pillars } = pillarsOf(db, repo); | |
| 212 | return pillars.find((p) => /trust|secur/i.test(p.name)) ?? pillars[0]; | |
| 213 | } | |
| 214 | ||
| 215 | /** | |
| 216 | * The repository page's count without the pulls read: open reports and how | |
| 217 | * many are critical, for whoever may read them; zero for anyone else. | |
| 218 | */ | |
| 219 | export function openSecurityCount( | |
| 220 | db: Database, | |
| 221 | repo: Repo, | |
| 222 | user: User | undefined, | |
| 223 | ): { open: number; critical: number } { | |
| 224 | if (!mayReadSecurity(db, repo, user)) return { open: 0, critical: 0 }; | |
| 225 | const open = listIssues(db, repo.id, { | |
| 226 | kind: "issue", | |
| 227 | state: "open", | |
| 228 | label: SECURITY_LABEL, | |
| 229 | sealed: true, | |
| 230 | limit: 1000, | |
| 231 | }).filter((i) => i.sealed); | |
| 232 | const labels = labelsForIssues(db, open.map((i) => i.id)); | |
| 233 | const critical = open.filter((i) => | |
| 234 | (labels.get(i.id) ?? []).some((l) => l.name.toLowerCase() === "sev:critical"), | |
| 235 | ).length; | |
| 236 | return { open: open.length, critical }; | |
| 237 | } |
src/http/api/issues.ts +12
| @@ -41,6 +41,7 @@ import { | ||
| 41 | 41 | import { canRead } from "../../core/repos.ts"; |
| 42 | 42 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 43 | 43 | import { mayView, sealedScope } from "../../core/sealed.ts"; |
| 44 | import { mayReadSecurity, securityCount, securityFilter, securityReports } from "../../core/security_reports.ts"; | |
| 44 | 45 | import { |
| 45 | 46 | listQuery, |
| 46 | 47 | loadConversation, |
| @@ -153,6 +154,17 @@ export function issueRoutes(router: Router<Handler>): void { | ||
| 153 | 154 | return json({ teams: set.value }); |
| 154 | 155 | }); |
| 155 | 156 | |
| 157 | // The Security page's rows (#14791): 404 to whoever may not see sealed issues. | |
| 158 | router.add("GET", "/api/v1/repos/:owner/:name/security", (ctx) => { | |
| 159 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 160 | const repo = loadRepo(ctx); | |
| 161 | if (!repo || !mayReadSecurity(ctx.app.db, repo, ctx.auth.user)) return notFound(); | |
| 162 | const items = timePhase(ctx.request, "list", () => | |
| 163 | securityReports(ctx.app.db, repo, ctx.auth.user, securityFilter(ctx.url.searchParams)), | |
| 164 | ); | |
| 165 | return json({ items, ...securityCount(items) }); | |
| 166 | }); | |
| 167 | ||
| 156 | 168 | router.add("GET", "/api/v1/repos/:owner/:name/issues", (ctx) => { |
| 157 | 169 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 158 | 170 | const repo = loadRepo(ctx); |
src/http/mcp/tools/reports.ts +10
| @@ -7,6 +7,7 @@ import { | ||
| 7 | 7 | waitingReports, |
| 8 | 8 | } from "../../../actions/reports.ts"; |
| 9 | 9 | import { byFiler, filerWords } from "../../../core/reports.ts"; |
| 10 | import { mayReadSecurity, openSecurityCount } from "../../../core/security_reports.ts"; | |
| 10 | 11 | import { type Answer, good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"; |
| 11 | 12 | |
| 12 | 13 | export const tool: Tool = { |
| @@ -61,6 +62,15 @@ export const tool: Tool = { | ||
| 61 | 62 | "their words are an outsider's, unchecked.", |
| 62 | 63 | byAgent, |
| 63 | 64 | items: reportViews(ctx.app, repo, waiting.value), |
| 65 | // The sealed security reports have their own page (#14791). | |
| 66 | ...(mayReadSecurity(ctx.app.db, repo, user) | |
| 67 | ? { | |
| 68 | security: { | |
| 69 | ...openSecurityCount(ctx.app.db, repo, user), | |
| 70 | url: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/security`, | |
| 71 | }, | |
| 72 | } | |
| 73 | : {}), | |
| 64 | 74 | }), |
| 65 | 75 | card: { repo: `${repo.ownerName}/${repo.name}` }, |
| 66 | 76 | }; |
src/http/server.ts +2
| @@ -634,6 +634,7 @@ import { | ||
| 634 | 634 | reportPage, |
| 635 | 635 | reportSubmit, |
| 636 | 636 | reportsPage, |
| 637 | securityPage, | |
| 637 | 638 | } from "../web/pages/reports.ts"; |
| 638 | 639 | import { |
| 639 | 640 | cookieValue, |
| @@ -1412,6 +1413,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1412 | 1413 | router.add("GET", "/:owner/:name/report", reportPage); |
| 1413 | 1414 | router.add("POST", "/:owner/:name/report", reportSubmit); |
| 1414 | 1415 | router.add("GET", "/:owner/:name/reports", reportsPage); |
| 1416 | router.add("GET", "/:owner/:name/security", securityPage); | |
| 1415 | 1417 | router.add("POST", "/:owner/:name/reports/:id/accept", reportAcceptSubmit); |
| 1416 | 1418 | router.add("POST", "/:owner/:name/reports/:id/dismiss", reportDismissSubmit); |
| 1417 | 1419 | router.add("GET", "/:owner/:name/issues/new", newIssuePage); |
src/tui/screens/reports.ts +112 −2
| @@ -12,6 +12,10 @@ import { REPORT_ALREADY_DECIDED } from "../../actions/origin_app_words.ts"; | ||
| 12 | 12 | import { acceptReport, dismissReport, waitingCount, waitingReports } from "../../actions/reports.ts"; |
| 13 | 13 | import { byFiler, filerWords, isOverdue, type Report } from "../../core/reports.ts"; |
| 14 | 14 | import type { Repo } from "../../core/repos.ts"; |
| 15 | import { linkIssue } from "../../actions/dependencies.ts"; | |
| 16 | import { setIssueStateThrough } from "../../actions/issues.ts"; | |
| 17 | import { getIssue } from "../../core/issues.ts"; | |
| 18 | import { crewPillar, openSecurityCount, securityReports, type SecurityRow } from "../../core/security_reports.ts"; | |
| 15 | 19 | import type { Ctx, Screen } from "../app/app.ts"; |
| 16 | 20 | import { binding } from "../app/keys.ts"; |
| 17 | 21 | import type { Command } from "../app/palette.ts"; |
| @@ -19,14 +23,15 @@ import { style } from "../term/style.ts"; | ||
| 19 | 23 | import { truncate, wrap } from "../term/width.ts"; |
| 20 | 24 | import type { Session } from "../session.ts"; |
| 21 | 25 | import { beside, fill, len, pct, split } from "../ui/layout.ts"; |
| 22 | import { ListState, ago, confirmScreen, drawList, errorText, runAsync, type ListRow } from "./common.ts"; | |
| 26 | import { ListState, ago, confirmScreen, drawList, errorText, promptScreen, runAsync, type ListRow } from "./common.ts"; | |
| 23 | 27 | |
| 24 | 28 | /** The palette row for `repo`: only while reports wait, only to a decider. */ |
| 25 | 29 | export function reportsCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] { |
| 26 | 30 | if (repo === undefined || f.user === undefined) return []; |
| 27 | 31 | const n = waitingCount(f.app, f.user, repo); |
| 28 | if (n === 0) return []; | |
| 32 | if (n === 0) return securityCommands(f, ctx, repo); | |
| 29 | 33 | return [ |
| 34 | ...securityCommands(f, ctx, repo), | |
| 30 | 35 | { |
| 31 | 36 | id: "reports", |
| 32 | 37 | title: `${repo.ownerName}/${repo.name} — Reports (${n})`, |
| @@ -36,6 +41,111 @@ export function reportsCommands(f: Session, ctx: Ctx, repo: Repo | undefined): C | ||
| 36 | 41 | ]; |
| 37 | 42 | } |
| 38 | 43 | |
| 44 | /** | |
| 45 | * The repository's sealed security reports (#14791, `web/pages/reports.ts`): "Security (N)" | |
| 46 | * while N are open. | |
| 47 | */ | |
| 48 | function securityCommands(f: Session, ctx: Ctx, repo: Repo): Command[] { | |
| 49 | const { open } = openSecurityCount(f.app.db, repo, f.user); | |
| 50 | if (open === 0) return []; | |
| 51 | return [ | |
| 52 | { | |
| 53 | id: "security", | |
| 54 | title: `${repo.ownerName}/${repo.name} — Security (${open})`, | |
| 55 | hint: "open sealed security reports, critical first", | |
| 56 | run: () => ctx.push(securityScreen(f, ctx, repo)), | |
| 57 | }, | |
| 58 | ]; | |
| 59 | } | |
| 60 | ||
| 61 | export const NO_SECURITY = "No security reports."; | |
| 62 | ||
| 63 | /** One list row per report: `#n title`, then its severity and state. */ | |
| 64 | export function securityRows(rows: readonly SecurityRow[]): ListRow[] { | |
| 65 | return rows.map((r) => ({ | |
| 66 | title: `#${String(r.number)} ${r.title}`, | |
| 67 | state: r.state === "open" || r.state === "building" ? "open" : "closed", | |
| 68 | secondary: r.severity, | |
| 69 | meta: `${r.state}${r.pull === null ? "" : ` #${String(r.pull)}`}${r.pillar === null ? "" : ` · ${r.pillar}`}`, | |
| 70 | })); | |
| 71 | } | |
| 72 | ||
| 73 | /** | |
| 74 | * Every report, open or not, read again on each draw. `c` gives the one under the cursor to the | |
| 75 | * crew (it joins the Trust pillar's umbrella), `d` dismisses it with a note, `o` reopens it: | |
| 76 | * the same issue actions the page's row forms post to, with their own rules. | |
| 77 | */ | |
| 78 | export function securityScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 79 | const state = new ListState(); | |
| 80 | let note = ""; | |
| 81 | let shown: SecurityRow[] = []; | |
| 82 | const issueOf = (r: SecurityRow) => getIssue(f.app.db, repo.id, r.number); | |
| 83 | const screen: Screen = { | |
| 84 | title: `Security · ${repo.ownerName}/${repo.name}`, | |
| 85 | keys: [ | |
| 86 | binding(["j", "k"], "move cursor"), | |
| 87 | binding(["c"], "give to the crew"), | |
| 88 | binding(["d"], "dismiss"), | |
| 89 | binding(["o"], "reopen"), | |
| 90 | ], | |
| 91 | render(area, s) { | |
| 92 | const c = ctx.theme.c; | |
| 93 | shown = securityReports(f.app.db, repo, f.user); | |
| 94 | const [head, body] = split(area, "v", [len(1), fill(1)]); | |
| 95 | const status = shown.length === 0 ? NO_SECURITY : note === "" ? "Critical first. c gives to the crew, d dismisses, o reopens." : note; | |
| 96 | s.text(head!.x, head!.y, truncate(status, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 97 | drawList(s, body!, c, state, securityRows(shown)); | |
| 98 | }, | |
| 99 | key(e) { | |
| 100 | if (state.key(e, shown.length)) return true; | |
| 101 | if (e.ctrl || e.alt) return false; | |
| 102 | const picked = shown[state.index]; | |
| 103 | if (picked === undefined || !["c", "d", "o"].includes(e.key)) return false; | |
| 104 | const issue = issueOf(picked); | |
| 105 | if (issue === undefined) return false; | |
| 106 | if (e.key === "c") { | |
| 107 | const pillar = crewPillar(f.app.db, repo); | |
| 108 | const umbrella = pillar === undefined ? undefined : getIssue(f.app.db, repo.id, pillar.umbrella.number); | |
| 109 | if (umbrella === undefined) note = "This repository has no pillar to give it to."; | |
| 110 | else if (picked.pillar !== null) note = `Already with the crew under ${picked.pillar}.`; | |
| 111 | else { | |
| 112 | const done = linkIssue(f.app, f.user, repo, umbrella, issue); | |
| 113 | note = done.ok ? `Given to the crew under ${pillar!.name}.` : errorText(done.error); | |
| 114 | } | |
| 115 | ctx.invalidate(); | |
| 116 | return true; | |
| 117 | } | |
| 118 | if (e.key === "o") { | |
| 119 | runAsync(ctx, async () => { | |
| 120 | const done = await setIssueStateThrough(f.app, f.user, repo, issue, "open"); | |
| 121 | note = done.ok ? `Reopened #${String(picked.number)}.` : errorText(done.error); | |
| 122 | ctx.invalidate(); | |
| 123 | }); | |
| 124 | return true; | |
| 125 | } | |
| 126 | ctx.push( | |
| 127 | promptScreen(ctx, screen, { | |
| 128 | title: `Dismiss #${String(picked.number)}`, | |
| 129 | label: "Why it is not a hole", | |
| 130 | onSubmit: (why) => { | |
| 131 | const text = why.trim(); | |
| 132 | if (text === "") return "Say why in one sentence."; | |
| 133 | if (text.length > 300) return "One sentence of at most 300 characters."; | |
| 134 | runAsync(ctx, async () => { | |
| 135 | const done = await setIssueStateThrough(f.app, f.user, repo, issue, "closed", { reason: "dropped", note: text }); | |
| 136 | note = done.ok ? `Dismissed #${String(picked.number)}.` : errorText(done.error); | |
| 137 | ctx.invalidate(); | |
| 138 | }); | |
| 139 | return undefined; | |
| 140 | }, | |
| 141 | }), | |
| 142 | ); | |
| 143 | return true; | |
| 144 | }, | |
| 145 | }; | |
| 146 | return screen; | |
| 147 | } | |
| 148 | ||
| 39 | 149 | /** A refusal from the action, in the words every other door uses. */ |
| 40 | 150 | function refusal(code: string): string { |
| 41 | 151 | return code === "decided" ? REPORT_ALREADY_DECIDED : errorText(code); |
src/web/pages/reports.ts +145 −1
| @@ -3,6 +3,10 @@ | ||
| 3 | 3 | * anyone fills on a public repository, and the queue its writers read. A |
| 4 | 4 | * report shows as plain text in a box that says where it came from — never |
| 5 | 5 | * markdown, so no link or image of a stranger's renders. |
| 6 | * | |
| 7 | * And the sealed security reports (#14791), at `/:owner/:name/security`, | |
| 8 | * acting through the issue's own routes; anyone who may not see sealed issues | |
| 9 | * gets the usual 404. | |
| 6 | 10 | */ |
| 7 | 11 | |
| 8 | 12 | import { |
| @@ -33,6 +37,20 @@ import { | ||
| 33 | 37 | type Report, |
| 34 | 38 | } from "../../core/reports.ts"; |
| 35 | 39 | import { canRead, type Repo } from "../../core/repos.ts"; |
| 40 | import type { Pillar } from "../../core/pillars.ts"; | |
| 41 | import { | |
| 42 | REPORT_STATES, | |
| 43 | SEVERITIES, | |
| 44 | crewPillar, | |
| 45 | dismissing, | |
| 46 | mayReadSecurity, | |
| 47 | openSecurityCount, | |
| 48 | securityFilter, | |
| 49 | securityHref, | |
| 50 | securityReports, | |
| 51 | type SecurityFilter, | |
| 52 | type SecurityRow, | |
| 53 | } from "../../core/security_reports.ts"; | |
| 36 | 54 | import { scopeAllows } from "../../core/tokens.ts"; |
| 37 | 55 | import type { Ctx } from "../../http/context.ts"; |
| 38 | 56 | import { |
| @@ -55,7 +73,7 @@ import { field, readForm } from "../form.ts"; | ||
| 55 | 73 | import { pageAddress } from "../studio/toolbar.ts"; |
| 56 | 74 | import { html, when, type Html } from "../html.ts"; |
| 57 | 75 | import { flashTo, page } from "../layout.ts"; |
| 58 | import { btn, field as formField, messageText, row, time } from "../ui.ts"; | |
| 76 | import { btn, field as formField, messageText, row, seg, time } from "../ui.ts"; | |
| 59 | 77 | |
| 60 | 78 | /** The repository, when it takes reports: public, and so seen by anyone. */ |
| 61 | 79 | function publicRepo(ctx: Ctx): Repo | undefined { |
| @@ -442,3 +460,129 @@ export async function reportDismissSubmit(ctx: Ctx): Promise<Response> { | ||
| 442 | 460 | message: "Dismissed.", |
| 443 | 461 | }); |
| 444 | 462 | } |
| 463 | ||
| 464 | // ---- security reports (#14791) ---- | |
| 465 | ||
| 466 | /** Each state in the words a row says it. */ | |
| 467 | export const REPORT_STATE_WORDS: Record<SecurityRow["state"], string> = { | |
| 468 | open: "open", | |
| 469 | building: "a fix is building", | |
| 470 | fixed: "fixed and live", | |
| 471 | dismissed: "dismissed", | |
| 472 | closed: "closed, no fix live", | |
| 473 | }; | |
| 474 | ||
| 475 | /** One segmented control per axis, and the path filter when one is set. */ | |
| 476 | function filterBar(base: string, f: SecurityFilter): Html { | |
| 477 | const axis = (key: "severity" | "state", values: readonly string[], any: string, words: (v: string) => string) => | |
| 478 | seg([ | |
| 479 | { label: any, href: securityHref(base, f, key, undefined), current: f[key] === undefined }, | |
| 480 | ...values.map((v) => ({ label: words(v), href: securityHref(base, f, key, v), current: f[key] === v })), | |
| 481 | ]); | |
| 482 | return html`${axis("severity", [...SEVERITIES, "unrated"], "Any severity", (v) => v)} | |
| 483 | ${axis("state", REPORT_STATES, "Any state", (v) => REPORT_STATE_WORDS[v as SecurityRow["state"]])} | |
| 484 | ${when(f.path, (p) => html`<p class="small">Under <code>${p}</code> · <a href="${securityHref(base, f, "path", undefined)}">any path</a></p>`)}`; | |
| 485 | } | |
| 486 | ||
| 487 | function rowActions(base: string, back: string, r: SecurityRow, pillar: Pillar | undefined, open: boolean): Html { | |
| 488 | const issue = `${base}/issues/${r.number}`; | |
| 489 | if (r.state === "dismissed" || r.state === "closed" || r.state === "fixed") | |
| 490 | return html`<form method="post" action="${issue}/state"> | |
| 491 | <input type="hidden" name="state" value="open" /> | |
| 492 | <input type="hidden" name="back" value="${back}" /> | |
| 493 | ${btn("Reopen", { size: "sm", variant: "ghost" })} | |
| 494 | </form>`; | |
| 495 | const give = when( | |
| 496 | pillar !== undefined && r.pillar === null, | |
| 497 | () => html`<form method="post" action="${base}/issues/${pillar!.umbrella.number}/dependencies"> | |
| 498 | <input type="hidden" name="blockedBy" value="${String(r.number)}" /> | |
outdated
Principle 5: a primary (accent) button on every row means many accents on one page. Make it ghost like the others, or give the page one primary action. |
||
| 499 | <input type="hidden" name="back" value="${back}" /> | |
| 500 | ${btn("Give it to the crew", { size: "sm", variant: "ghost" })} | |
| 501 | </form>`, | |
| 502 | ); | |
| 503 | if (!open) | |
| 504 | return html`${give}${btn("Dismiss", { | |
| 505 | href: `${back}${back.includes("?") ? "&" : "?"}dismiss=${String(r.number)}-${String(r.number)}`, | |
| 506 | size: "sm", | |
outdated
Principles 3 and 7: a text input plus a button inside every row is a form under every row, not a row. Put Dismiss behind the report's own page, or show the note field only for the row being dismissed (e.g. |
||
| 507 | variant: "ghost", | |
| 508 | })}`; | |
| 509 | return html`${give}<form method="post" action="${issue}/state"> | |
| 510 | <input type="hidden" name="state" value="closed" /> | |
| 511 | <input type="hidden" name="reason" value="dropped" /> | |
| 512 | <input type="hidden" name="back" value="${back}" /> | |
| 513 | <label class="sr-only" for="why-${String(r.number)}">Why dismiss #${String(r.number)}</label> | |
| 514 | <input id="why-${String(r.number)}" name="note" required maxlength="300" placeholder="Why it is not a hole" autofocus /> | |
| 515 | ${btn("Dismiss", { size: "sm", variant: "ghost" })} | |
| 516 | </form>`; | |
| 517 | } | |
| 518 | ||
| 519 | function securityRow(base: string, back: string, r: SecurityRow, f: SecurityFilter, pillar: Pillar | undefined, open: boolean): Html { | |
outdated
Principle 7/8: the meta line packs severity pill, state, pull, pillar, age and up to five file links into one run. The severity is already the section heading, so the pill repeats it (principle 1). Drop the pill and keep the files to one. |
||
| 520 | const file = r.files[0]; | |
| 521 | return row({ | |
| 522 | href: `${base}/issues/${r.number}`, | |
| 523 | title: `#${r.number} ${r.title}`, | |
| 524 | nav: true, | |
| 525 | id: `report-${r.number}`, | |
| 526 | data: { severity: r.severity, state: r.state }, | |
| 527 | state: r.state === "open" || r.state === "building" ? "open" : "closed", | |
| 528 | meta: html`${REPORT_STATE_WORDS[r.state]}${when(r.pull, (n) => html` (#${String(n)})`)}${when( | |
| 529 | r.pillar, | |
| 530 | (p) => html` · with the crew under ${p}`, | |
| 531 | )} · ${time(r.createdAt)}${when( | |
| 532 | file, | |
| 533 | (path) => html` · <a href="${securityHref(base, f, "path", path)}"><code>${path}</code></a>`, | |
| 534 | )}`, | |
| 535 | after: rowActions(base, back, r, pillar, open), | |
| 536 | }); | |
| 537 | } | |
| 538 | ||
| 539 | /** | |
| 540 | * "N open security reports, M critical", linked, for whoever may read them; nothing for anyone | |
| 541 | * else. | |
| 542 | */ | |
| 543 | export function securityLine(ctx: Ctx, repo: Repo): Html | undefined { | |
| 544 | const { open, critical } = openSecurityCount(ctx.app.db, repo, ctx.auth.user); | |
| 545 | if (open === 0) return undefined; | |
| 546 | return btn(`${String(open)} open security report${open === 1 ? "" : "s"}, ${String(critical)} critical`, { | |
| 547 | href: `${repoBase(repo)}/security`, | |
| 548 | size: "sm", | |
| 549 | variant: "ghost", | |
| 550 | }); | |
| 551 | } | |
| 552 | ||
| 553 | // GET /:owner/:name/security | |
| 554 | export function securityPage(ctx: Ctx): Response { | |
| 555 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 556 | const repo = timePhase(ctx.request, "repo", () => loadRepo(ctx)); | |
| 557 | if (!repo || !mayReadSecurity(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx); | |
| 558 | const filter = securityFilter(ctx.url.searchParams); | |
| 559 | const rows = timePhase(ctx.request, "reports", () => securityReports(ctx.app.db, repo, ctx.auth.user, filter)); | |
| 560 | const base = repoBase(repo); | |
| 561 | const back = securityHref(base, filter); | |
| 562 | const open = dismissing(ctx.url.searchParams); | |
| 563 | const pillar = crewPillar(ctx.app.db, repo); | |
| 564 | const groups = (["critical", "high", "medium", "bug", "unrated"] as const) | |
outdated
Principle 1: the hint says two things and the second (when it reads fixed) explains itself again. One confident sentence: what the page is for. The state wording on each row already says 'fixed and live'. |
||
| 565 | .map((s) => ({ s, items: rows.filter((r) => r.severity === s) })) | |
| 566 | .filter((g) => g.items.length > 0); | |
| 567 | const rendering = performance.now(); | |
| 568 | const response = page({ | |
| 569 | ctx, | |
| 570 | title: `Security · ${repo.ownerName}/${repo.name}`, | |
| 571 | crumbs: crumbsFor(repo), | |
| 572 | palette: repoPalette(ctx, repo), | |
| 573 | body: html`${repoHeader(ctx, repo, "issues", { compact: true, ownTitle: true })} | |
| 574 | <h1 class="mt">Security</h1> | |
| 575 | <p class="hint">The sealed reports labelled <code>security</code>, worst first, to fix or dismiss.</p> | |
| 576 | ${filterBar(base, filter)} | |
| 577 | ${groups.length === 0 | |
| 578 | ? html`<p class="muted small mt">No security reports match.</p>` | |
| 579 | : groups.map( | |
| 580 | (g) => html`<section class="settings-block"> | |
| 581 | <h2>${g.s} · ${String(g.items.length)}</h2> | |
| 582 | <ul class="list">${g.items.map((r) => securityRow(base, back, r, filter, pillar, r.number === open))}</ul> | |
| 583 | </section>`, | |
| 584 | )}`, | |
| 585 | }); | |
| 586 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 587 | return response; | |
| 588 | } |
src/web/pages/thread.ts +2 −2
| @@ -1042,7 +1042,7 @@ export async function stateSubmit( | ||
| 1042 | 1042 | ? "A merged change cannot be reopened." |
| 1043 | 1043 | : "A merged pull request cannot be reopened."; |
| 1044 | 1044 | const refusals: Record<string, string> = { |
| 1045 | reason_required: "A bug closed without a fix says why: add a sentence.", | |
| 1045 | reason_required: "A bug closed without a fix, or a security report dismissed, says why: add a sentence.", | |
| 1046 | 1046 | invalid_note: "A reason is one sentence of at most 300 characters.", |
| 1047 | 1047 | already_merged: merged, |
| 1048 | 1048 | forbidden: "Only the author or someone with write access can do that.", |
| @@ -1304,7 +1304,7 @@ export async function dependencySubmit(ctx: Ctx): Promise<Response> { | ||
| 1304 | 1304 | if (!ctx.auth.user) return signInFirst(ctx); |
| 1305 | 1305 | const form = await readForm(ctx, "rw"); |
| 1306 | 1306 | if (form instanceof Response) return form; |
| 1307 | const dest = `${repoBase(found.repo)}/issues/${found.issue.number}`; | |
| 1307 | const dest = backTo(form, `${repoBase(found.repo)}/issues/${found.issue.number}`); | |
| 1308 | 1308 | const unlink = field(form, "unlink").trim(); |
| 1309 | 1309 | const confirm = field(form, "confirm").trim(); |
| 1310 | 1310 | const raw = |
src/web/studio/lists.ts +3 −1
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | * `/pulls`. |
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | import { securityLine } from "../pages/reports.ts"; | |
| 12 | 13 | import { sealedScope } from "../../core/sealed.ts"; |
| 13 | 14 | import { appsRuntime } from "../../apps/runtime.ts"; |
| 14 | 15 | import { getAppByRepo } from "../../core/apps.ts"; |
| @@ -537,6 +538,7 @@ export async function tellsList(ctx: Ctx): Promise<Response> { | ||
| 537 | 538 | variant: "ghost", |
| 538 | 539 | }) |
| 539 | 540 | : undefined; |
| 541 | const security = securityLine(ctx, repo); | |
| 540 | 542 | const waiting = waitingCount(ctx.app, ctx.auth.user, repo); |
| 541 | 543 | const reports = |
| 542 | 544 | waiting > 0 |
| @@ -558,7 +560,7 @@ export async function tellsList(ctx: Ctx): Promise<Response> { | ||
| 558 | 560 | const verbs = |
| 559 | 561 | ctx.auth.user === undefined && outside === undefined |
| 560 | 562 | ? undefined |
| 561 | : html`${reports ?? null} ${compose} ${outside ?? null} ${signIn}`; | |
| 563 | : html`${security ?? null} ${reports ?? null} ${compose} ${outside ?? null} ${signIn}`; | |
| 562 | 564 | |
| 563 | 565 | const body = html`${repoHeader(ctx, repo, "issues")} |
| 564 | 566 | <div class="mt" data-tells> |
test/security-reports.test.ts added +315
| @@ -0,0 +1,315 @@ | ||
| 1 | /** | |
| 2 | * The Security page (#14791): a repository's sealed `security` reports, | |
| 3 | * critical first, for writers and the crew only; a stranger gets 404 for | |
| 4 | * the page and its API and sees no count. Each row's actions are the | |
| 5 | * issue's own routes and come back to the page. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createLabel, getIssue, setIssueLabels } from "../src/core/issues.ts"; | |
| 14 | import type { Repo } from "../src/core/repos.ts"; | |
| 15 | import { FIXES_SQL, filesNamed, fixesFrom, securityFilter, securityReports } from "../src/core/security_reports.ts"; | |
| 16 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | import { securityScreen } from "../src/tui/screens/reports.ts"; | |
| 20 | import type { Ctx, Screen } from "../src/tui/app/app.ts"; | |
| 21 | import type { Session } from "../src/tui/session.ts"; | |
| 22 | import type { KeyEvent } from "../src/tui/term/input.ts"; | |
| 23 | import { Screen as Surface } from "../src/tui/term/screen.ts"; | |
| 24 | import { theme } from "../src/tui/ui/theme.ts"; | |
| 25 | import { quietLogs } from "./helpers/globals.ts"; | |
| 26 | ||
| 27 | quietLogs(); | |
| 28 | ||
| 29 | let dataDir: string; | |
| 30 | let app: App; | |
| 31 | let servers: Servers; | |
| 32 | let alice: User; | |
| 33 | let mallory: User; | |
| 34 | let repo: Repo; | |
| 35 | const token: Record<string, string> = {}; | |
| 36 | const n: Record<string, number> = {}; | |
| 37 | const label: Record<string, string> = {}; | |
| 38 | ||
| 39 | const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => { | |
| 40 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 41 | return r.value; | |
| 42 | }; | |
| 43 | ||
| 44 | async function call(path: string, who?: string, form?: Record<string, string>) { | |
| 45 | const headers: Record<string, string> = who === undefined ? {} : { authorization: `Bearer ${token[who]}` }; | |
| 46 | const res = await fetch(`${servers.url}${path}`, { | |
| 47 | method: form === undefined ? "GET" : "POST", | |
| 48 | headers: form === undefined ? headers : { ...headers, "content-type": "application/x-www-form-urlencoded", origin: servers.url }, | |
| 49 | ...(form === undefined ? {} : { body: new URLSearchParams(form).toString() }), | |
| 50 | redirect: "manual", | |
| 51 | }); | |
| 52 | return { status: res.status, text: await res.text(), location: res.headers.get("location") ?? "" }; | |
| 53 | } | |
| 54 | ||
| 55 | async function open(title: string, body: string, labels: string[], sealed = true): Promise<number> { | |
| 56 | const res = await fetch(`${servers.url}/api/v1/repos/alice/square/issues`, { | |
| 57 | method: "POST", | |
| 58 | headers: { authorization: `Bearer ${token.alice}`, "content-type": "application/json" }, | |
| 59 | body: JSON.stringify({ title, body, labels, sealed }), | |
| 60 | }); | |
| 61 | expect(res.status).toBe(201); | |
| 62 | const number = ((await res.json()) as { number: number }).number; | |
| 63 | setIssueLabels(app.db, getIssue(app.db, repo.id, number)!.id, labels.map((l) => label[l]!)); | |
| 64 | return number; | |
| 65 | } | |
| 66 | ||
| 67 | beforeAll(async () => { | |
| 68 | dataDir = await mkdtemp(join(tmpdir(), "forge-security-")); | |
| 69 | app = createApp({ dataDir, port: 0 }); | |
| 70 | servers = await serve(app); | |
| 71 | const user = async (username: string, adminIfFirst = false) => | |
| 72 | ok( | |
| 73 | await createUser(app.db, { | |
| 74 | origin: "seed", | |
| 75 | trusted: true, | |
| 76 | username, | |
| 77 | email: `${username}@forge.local`, | |
| 78 | password: "a-good-passphrase", | |
| 79 | adminIfFirst, | |
| 80 | }), | |
| 81 | ); | |
| 82 | alice = await user("alice", true); | |
| 83 | mallory = await user("mallory"); | |
| 84 | repo = ok(await createRepo(app, alice, { name: "square", visibility: "public" })); | |
| 85 | ok(await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# square\n" }] })); | |
| 86 | for (const l of ["security", "sev:critical", "sev:high", "sev:medium"]) label[l] = ok(createLabel(app.db, repo.id, l, "cc3333")).id; | |
| 87 | token.alice = createToken(app.db, alice.id, "t", "rw").token; | |
| 88 | token.mallory = createToken(app.db, mallory.id, "t", "rw").token; | |
| 89 | n.umbrella = await open("P0 Trust: nothing leaks", "The pillar.", [], false); | |
| 90 | n.medium = await open("Z7MEDIUM header missing", "In `src/http/respond.ts`.", ["security", "sev:medium"]); | |
| 91 | n.critical = await open("Z7CRIT token bypass", "The check in src/auth/token.ts is skipped.", ["security", "sev:critical"]); | |
| 92 | n.high = await open("Z7HIGH path traversal", "See `src/web/pages/raw.ts`.", ["security", "sev:high"]); | |
| 93 | n.plain = await open("Z7PLAIN sealed but not security", "", [], true); | |
| 94 | }); | |
| 95 | ||
| 96 | afterAll(async () => { | |
| 97 | servers.stop(); | |
| 98 | app.close?.(); | |
| 99 | await rm(dataDir, { recursive: true, force: true }); | |
| 100 | }); | |
| 101 | ||
| 102 | test("the owner reads every sealed security report, critical first, and nothing else", async () => { | |
| 103 | const page = await call("/alice/square/security", "alice"); | |
| 104 | expect(page.status).toBe(200); | |
| 105 | const at = (s: string) => page.text.indexOf(s); | |
| 106 | expect(at("Z7CRIT")).toBeGreaterThan(-1); | |
| 107 | expect(at("Z7CRIT")).toBeLessThan(at("Z7HIGH")); | |
| 108 | expect(at("Z7HIGH")).toBeLessThan(at("Z7MEDIUM")); | |
| 109 | expect(page.text).not.toContain("Z7PLAIN"); | |
| 110 | const api = await call("/api/v1/repos/alice/square/security", "alice"); | |
| 111 | const body = JSON.parse(api.text) as { items: { number: number; severity: string }[]; open: number; critical: number }; | |
| 112 | expect(body.items.map((r) => r.number)).toEqual([n.critical!, n.high!, n.medium!]); | |
| 113 | expect(body.open).toBe(3); | |
| 114 | expect(body.critical).toBe(1); | |
| 115 | const list = await call("/alice/square/issues", "alice"); | |
| 116 | expect(list.text).toContain("3 open security reports, 1 critical"); | |
| 117 | }); | |
| 118 | ||
| 119 | test("a stranger and a signed-in reader get 404 for the page and its API, and no count", async () => { | |
| 120 | for (const who of [undefined, "mallory"]) { | |
| 121 | const page = await call("/alice/square/security", who); | |
| 122 | expect(page.status).toBe(404); | |
| 123 | expect(page.text).not.toContain("Z7"); | |
| 124 | const api = await call("/api/v1/repos/alice/square/security", who); | |
| 125 | expect(api.status).toBe(404); | |
| 126 | expect(api.text).not.toContain("Z7"); | |
| 127 | const list = await call("/alice/square/issues", who); | |
| 128 | expect(list.text).not.toContain("security report"); | |
| 129 | } | |
| 130 | expect(securityReports(app.db, repo, mallory)).toEqual([]); | |
| 131 | expect(securityReports(app.db, repo, undefined)).toEqual([]); | |
| 132 | }); | |
| 133 | ||
| 134 | test("filters are plain query words, and anything else is left out", async () => { | |
| 135 | expect(securityFilter(new URLSearchParams("severity=high&state=open&path=src/web"))).toEqual({ | |
| 136 | severity: "high", | |
| 137 | state: "open", | |
| 138 | path: "src/web", | |
| 139 | }); | |
| 140 | expect(securityFilter(new URLSearchParams("severity=x&state=y&path=<script>"))).toEqual({}); | |
| 141 | expect(filesNamed("in `src/a.ts` and src/b/c.ts, and src/a.ts again")).toEqual(["src/a.ts", "src/b/c.ts"]); | |
| 142 | const rows = securityReports(app.db, repo, alice, { path: "src/web" }); | |
| 143 | expect(rows.map((r) => r.number)).toEqual([n.high!]); | |
| 144 | }); | |
| 145 | ||
| 146 | test("give it to the crew, dismiss with a reason, and reopen, each from its row and back", async () => { | |
| 147 | const back = "/alice/square/security"; | |
| 148 | const give = await call(`/alice/square/issues/${n.umbrella}/dependencies`, "alice", { | |
| 149 | blockedBy: String(n.high), | |
| 150 | back, | |
| 151 | }); | |
| 152 | expect(give.status).toBe(303); | |
| 153 | expect(give.location).toContain(back); | |
| 154 | expect(securityReports(app.db, repo, alice).find((r) => r.number === n.high)?.pillar).toBe("P0 Trust"); | |
| 155 | ||
| 156 | const refused = await call(`/alice/square/issues/${n.medium}/state`, "alice", { state: "closed", reason: "nope", back }); | |
| 157 | expect(getIssue(app.db, repo.id, n.medium!)?.state).toBe("open"); | |
| 158 | expect(refused.status).toBe(303); | |
| 159 | // The note is the route's rule, not only the field's `required`. | |
| 160 | for (const note of [undefined, " "]) { | |
| 161 | const bare = await call(`/alice/square/issues/${n.medium}/state`, "alice", { | |
| 162 | state: "closed", | |
| 163 | reason: "dropped", | |
| 164 | ...(note === undefined ? {} : { note }), | |
| 165 | back, | |
| 166 | }); | |
| 167 | expect(bare.status).toBe(303); | |
| 168 | expect(bare.location).toContain(back); | |
| 169 | expect(getIssue(app.db, repo.id, n.medium!)?.state).toBe("open"); | |
| 170 | } | |
| 171 | ||
| 172 | const dismiss = await call(`/alice/square/issues/${n.medium}/state`, "alice", { | |
| 173 | state: "closed", | |
| 174 | reason: "dropped", | |
| 175 | note: "Only reachable by the owner.", | |
| 176 | back, | |
| 177 | }); | |
| 178 | expect(dismiss.location).toContain(back); | |
| 179 | expect(securityReports(app.db, repo, alice).find((r) => r.number === n.medium)?.state).toBe("dismissed"); | |
| 180 | const page = await call("/alice/square/security?state=dismissed", "alice"); | |
| 181 | expect(page.text).toContain("Z7MEDIUM"); | |
| 182 | expect(page.text).not.toContain("Z7CRIT"); | |
| 183 | ||
| 184 | await call(`/alice/square/issues/${n.medium}/state`, "alice", { state: "open", back }); | |
| 185 | expect(securityReports(app.db, repo, alice).find((r) => r.number === n.medium)?.state).toBe("open"); | |
| 186 | }); | |
| 187 | ||
| 188 | test("the terminal screen lists every report, live, and gives, dismisses and reopens from its row", async () => { | |
| 189 | const press = (key: string): KeyEvent => ({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 190 | const pushed: Screen[] = []; | |
| 191 | const tracked: Promise<unknown>[] = []; | |
| 192 | const ctx = { | |
| 193 | theme: theme("dark"), | |
| 194 | invalidate() {}, | |
| 195 | toast() {}, | |
| 196 | push: (s: Screen) => pushed.push(s), | |
| 197 | pop: () => pushed.pop(), | |
| 198 | track: (p: Promise<unknown>) => (tracked.push(p), p), | |
| 199 | copy() {}, | |
| 200 | hit() {}, | |
| 201 | setCursor() {}, | |
| 202 | } as unknown as Ctx; | |
| 203 | const screen = securityScreen({ app, db: app.db, user: alice } as unknown as Session, ctx, repo); | |
| 204 | const text = () => { | |
| 205 | const s = new Surface(120, 30); | |
| 206 | screen.render({ x: 0, y: 0, w: 120, h: 30 }, s); | |
| 207 | return s.toText(); | |
| 208 | }; | |
| 209 | const settle = async () => { | |
| 210 | await Promise.all(tracked.splice(0)); | |
| 211 | }; | |
| 212 | const report = (k: string) => securityReports(app.db, repo, alice).find((r) => r.number === n[k]); | |
| 213 | expect(text()).toContain("Z7CRIT"); | |
| 214 | ||
| 215 | // The cursor starts on the critical report: give it to the crew. | |
| 216 | expect(screen.key(press("c"))).toBe(true); | |
| 217 | expect(report("critical")?.pillar).toBe("P0 Trust"); | |
| 218 | expect(text()).toContain("Given to the crew"); | |
| 219 | ||
| 220 | // Dismiss asks why, refuses an empty reason, and closes with the note. | |
| 221 | expect(screen.key(press("d"))).toBe(true); | |
| 222 | const prompt = pushed.at(-1)!; | |
| 223 | prompt.key(press("enter")); | |
| 224 | expect(report("critical")?.state).toBe("open"); | |
| 225 | for (const ch of "Not reachable") prompt.key(press(ch)); | |
| 226 | prompt.key(press("enter")); | |
| 227 | await settle(); | |
| 228 | expect(report("critical")?.state).toBe("dismissed"); | |
| 229 | // Still listed (the screen reads every state, again on each draw), and reopened from its row. | |
| 230 | expect(text()).toContain("dismissed"); | |
| 231 | const at = securityReports(app.db, repo, alice).findIndex((r) => r.number === n.critical); | |
| 232 | for (let i = 0; i < at; i++) screen.key(press("j")); | |
| 233 | expect(screen.key(press("o"))).toBe(true); | |
| 234 | await settle(); | |
| 235 | expect(report("critical")?.state).toBe("open"); | |
| 236 | }); | |
| 237 | ||
| 238 | test("the terminal screen shows a stranger nothing", () => { | |
| 239 | const ctx = { theme: theme("dark"), invalidate() {}, toast() {}, push() {}, pop() {} } as unknown as Ctx; | |
| 240 | const screen = securityScreen({ app, db: app.db, user: mallory } as unknown as Session, ctx, repo); | |
| 241 | const s = new Surface(120, 10); | |
| 242 | screen.render({ x: 0, y: 0, w: 120, h: 10 }, s); | |
| 243 | expect(s.toText()).not.toContain("Z7"); | |
| 244 | }); | |
| 245 | ||
| 246 | test("a report fixed by an old pull reads fixed however many pulls came after", () => { | |
| 247 | const db = app.db; | |
| 248 | const author = alice.id; | |
| 249 | const pullAt = (number: number, body: string, merged: string | null) => { | |
| 250 | const id = `p${String(number)}`; | |
| 251 | db.query( | |
| 252 | `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at) | |
| 253 | VALUES (?1, ?2, ?3, 'pull', 't', ?4, ?5, ?6, '2026-11-20T00:00:00Z')`, | |
| 254 | ).run(id, repo.id, number, body, author, merged === null ? "open" : "closed"); | |
| 255 | db.query( | |
| 256 | `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at, merged_oid) | |
| 257 | VALUES (?1, 'main', ?2, 'a', 'b', ?3, ?4)`, | |
| 258 | ).run(id, `b${String(number)}`, merged, merged === null ? null : "c"); | |
| 259 | return id; | |
| 260 | }; | |
| 261 | const fix = pullAt(900, `Closes #${String(n.high)}`, "2026-11-20T10:00:00Z"); | |
| 262 | for (let i = 901; i < 930; i++) pullAt(i, `Closes #${String(n.umbrella)} and #${String(n.high)}0`, null); | |
| 263 | expect(securityReports(db, repo, alice).find((r) => r.number === n.high)).toMatchObject({ state: "building", pull: 900 }); | |
| 264 | db.query("INSERT INTO run (id, repo_id, kind, env, state) VALUES ('r900', ?1, 'deploy', 'production', 'ok')").run(repo.id); | |
| 265 | db.query("INSERT INTO deploy_landed (issue_id, run_id, pull_number, at) VALUES (?1, 'r900', 900, '2026-11-20T11:00:00Z')").run(fix); | |
| 266 | expect(securityReports(db, repo, alice).find((r) => r.number === n.high)).toMatchObject({ state: "fixed", pull: 900 }); | |
| 267 | expect(FIXES_SQL).not.toContain("LIMIT"); | |
| 268 | }); | |
| 269 | ||
| 270 | test("the MCP reports answer links the Security page for a writer, and not for a stranger", async () => { | |
| 271 | const ask = async (who: string) => { | |
| 272 | const res = await fetch(`${servers.url}/mcp`, { | |
| 273 | method: "POST", | |
| 274 | headers: { | |
| 275 | "content-type": "application/json", | |
| 276 | accept: "application/json, text/event-stream", | |
| 277 | authorization: `Bearer ${token[who]}`, | |
| 278 | }, | |
| 279 | body: JSON.stringify({ | |
| 280 | jsonrpc: "2.0", | |
| 281 | id: 1, | |
| 282 | method: "tools/call", | |
| 283 | params: { name: "reports", arguments: { repo: "alice/square" } }, | |
| 284 | }), | |
| 285 | }); | |
| 286 | return JSON.stringify(await res.json()); | |
| 287 | }; | |
| 288 | expect(await ask("alice")).toContain("/alice/square/security"); | |
| 289 | expect(await ask("mallory")).not.toContain("/security"); | |
| 290 | }); | |
| 291 | ||
| 292 | test("fixed means live: a merged pull counts only once a production deploy carried its merge", () => { | |
| 293 | const pull = (number: number, merged_at: string | null, landed: string | null) => ({ | |
| 294 | number, | |
| 295 | body: "Closes #7", | |
| 296 | merged_at, | |
| 297 | landed, | |
| 298 | }); | |
| 299 | const live = (p: ReturnType<typeof pull>) => fixesFrom([p], new Set([7]), new Map()).get(7); | |
| 300 | expect(live(pull(9, null, null))).toEqual({ pull: 9, live: false }); | |
| 301 | expect(live(pull(9, "2026-11-20T10:00:00Z", null))).toEqual({ pull: 9, live: false }); | |
| 302 | expect(live(pull(9, "2026-11-20T10:00:00Z", "2026-11-20T09:00:00Z"))).toEqual({ pull: 9, live: false }); | |
| 303 | expect(live(pull(9, "2026-11-20T10:00:00Z", "2026-11-20T11:00:00Z"))).toEqual({ pull: 9, live: true }); | |
| 304 | }); | |
| 305 | ||
| 306 | test("the fixes read walks issue_repo_kind_number and reaches the rest by key", () => { | |
| 307 | const plan = app.db | |
| 308 | .query<{ detail: string }, [string, number, string]>(`EXPLAIN QUERY PLAN ${FIXES_SQL}`) | |
| 309 | .all(repo.id, 1, "[1]") | |
| 310 | .map((r) => r.detail) | |
| 311 | .join("\n"); | |
| 312 | expect(plan).toContain("issue_repo_kind_number"); | |
| 313 | // The one scan is of the reports' own numbers (`json_each`), never of a table. | |
| 314 | expect(plan.replace(/SCAN n (EXISTS )?VIRTUAL TABLE[^\n]*/g, "")).not.toMatch(/SCAN|TEMP B-TREE/); | |
| 315 | }); |
Principles 3 and 6: two nav lines of ' · ' separated links is heavy chrome above the rows. Use the design system's filter/tab component if one exists, with one control per axis.