diff --git a/docs/dashboard-spec.md b/docs/dashboard-spec.md index 4bcc3ce1..27611145 100644 --- a/docs/dashboard-spec.md +++ b/docs/dashboard-spec.md @@ -164,7 +164,7 @@ The Pipeline page also shows the Claude accounts panel (see Agents). ### Deep scans (`/security/scans`, `/security/scans/`) -Operators and maintainers only (other readers get 404). The list shows every scan of the repos the reader can see, newest first, filterable by repo (`?repo=`): state badge, repo, spent of cap, areas done, findings, who started it and when. A scan page shows the scan header (state, progress bar, spent, estimate, cap; Stop for operators while the scan is active), the threat model (summary, entry points, areas with risk, state and cost), the model calls in order (kind, area or finding, state, time, cost, a progress line for the running one; each opens to the run's prompt and output and links to its Agents page) and the findings, each linking to its finding page. Both follow the live topics, with no refresh. The nav lists "Deep scans" under Insight for staff; the repo page's Security part links to the list for its repo. +Operators and maintainers only (other readers get 404). The list shows every scan of the repos the reader can see, newest first, filterable by repo (`?repo=`): state badge, repo, spent of cap, areas done, findings, who started it and when. A scan page shows the scan header (state, progress bar, spent, estimate, cap; Stop for whoever may stop it while the scan is active), the threat model (summary, entry points, areas with risk, state and cost), the model calls in order (kind, area or finding, state, time, cost, a progress line for the running one; each opens to the run's prompt and output and links to its Agents page) and the findings, each linking to its finding page. Both follow the live topics, with no refresh. The nav lists "Deep scans" under Insight for staff; the repo page's Security part links to the list for its repo. ### Agents (`/agents`, `/agents/`) @@ -236,8 +236,8 @@ The pipeline runs Claude agents under the operator's own Claude account on the o | Access list, sessions, access-management audit rows | operator | | Repo settings and the audit log (without access rows), read-only | operator or maintainer | | Turn the pipeline on or off, change limits, start a job, cancel a job without a repo | operator; everyone signed in sees the Pipeline page | -| Per repo (the rule is `mayRunRepo`: an operator, or a maintainer with GitHub write permission on the repo, read live): approve labels, merging, CI runs, comments, pushes, issue fixes and red-main fixes; add or remove optional checks; switch the pipeline; cancel a job or build task of the repo; select its nightly checks; set up its screenshots; stop a deep scan and act on its findings (dismiss, backlog, fix, land, advisory) | operator or maintainer with write on the repo; others get 403 (a viewer gets 404 on security routes). The API returns `canManage`, `canSwitch`, `canAct`, `canCancel`, `canSelect` and `manageable` per repo or row, and the web reads them | -| Start or continue a deep scan (spends money) | operator | +| Per repo (the rule is `mayRunRepo`: an operator, or a maintainer with GitHub write permission on the repo, read live): approve labels, merging, CI runs, comments, pushes, issue fixes and red-main fixes; add or remove optional checks; switch the pipeline; cancel a job or build task of the repo; select its nightly checks; set up its screenshots; start or continue a deep scan with a spend cap (any positive amount), stop a deep scan and act on its findings (dismiss, backlog, fix, land, advisory) | operator or maintainer with write on the repo; others get 403 (a viewer gets 404 on security routes). The API returns `canManage`, `canSwitch`, `canAct`, `canStart` (security overview), `canContinue` (scan), `canCancel`, `canSelect` and `manageable` per repo or row, and the web reads them | +| Start or continue a deep scan without a spend cap | operator | | Feedback rate limit | operators and maintainers with write on the decision's repo are exempt | | Per repo and per item, on a repo the person runs: snooze or wake a decision, prepare it again, include a maintainer post for Opus, edit a fix-up's instructions, review, verify, fix or batch an item again, stop a fix, cancel or retry a pre-approval, hold or release a merge, remove a PR from a batch, stop a batch, fast track and its weight (also the MCP tools `set_weight` and `cancel_queued`), release one held outside item, edit an area list, start area steps, accept or dismiss area proposals, put a repo's open decisions on the Backlog in bulk | operator, or maintainer with GitHub write permission on the repo (read live; a batch or decision spanning repos needs write on each). `mayRunRepo` in `src/dash/repo-access.ts`; `GET /api/me` lists the repos in `runRepos`, and the interface reads it instead of the role | | Backlog in bulk without a repo, release all items held for an outside author | operator | diff --git a/docs/pipeline.md b/docs/pipeline.md index 96ffd6c5..02a1365a 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -4,7 +4,7 @@ The pipeline sorts the craft apps' open issues and PRs (about 21,000), reviews a ## The flow -Each column is an actor. Rows run top to bottom in pipeline order. The heavy line is the automatic path: nothing on it waits for a person. Thin lines are side branches, and dashed lines are branches that wait for the operator (Decide, Duplicate?, Close this PR?, Merge?, Hold) or are rare. Cards in the GitHub writes column name the approval they need for that repo (Repos page) and stay within their daily limit. The security deep scan is not drawn: an operator starts each scan, and it runs outside the daily pipeline (see Security deep scan). +Each column is an actor. Rows run top to bottom in pipeline order. The heavy line is the automatic path: nothing on it waits for a person. Thin lines are side branches, and dashed lines are branches that wait for the operator (Decide, Duplicate?, Close this PR?, Merge?, Hold) or are rare. Cards in the GitHub writes column name the approval they need for that repo (Repos page) and stay within their daily limit. The security deep scan is not drawn: an operator, or a maintainer with write access who sets a spend cap, starts each scan, and it runs outside the daily pipeline (see Security deep scan). ```swimlane pipeline @@ -461,14 +461,14 @@ A second Opus review of every PR the pipeline merged, to catch what the first re ## Security deep scan -Audits the default branch of one repo for vulnerabilities an outsider can reach, then fixes confirmed findings privately and lands each fix as a pull request that does not say what it protects against. It is not part of the daily pipeline: an operator starts each scan, the private fix of each confirmed finding starts on its own, and an operator starts every other step on a finding (Land, Advisory, Publish). The pipeline's on/off switch and daily limits do not apply. Its steps (`security-scan`, `security-fix`, `security-land`, `security-advisory`, `security-publish`) are jobs with no registry entry, so they get the default step time limit. The only model is Opus at high effort, with tools `Read`, `Grep` and `Glob` on a read-only checkout (no shell, no web tool). +Audits the default branch of one repo for vulnerabilities an outsider can reach, then fixes confirmed findings privately and lands each fix as a pull request that does not say what it protects against. It is not part of the daily pipeline: an operator, or a maintainer with write access who sets a spend cap, starts each scan, the private fix of each confirmed finding starts on its own, and an operator starts every other step on a finding (Land, Advisory, Publish). The pipeline's on/off switch and daily limits do not apply. Its steps (`security-scan`, `security-fix`, `security-land`, `security-advisory`, `security-publish`) are jobs with no registry entry, so they get the default step time limit. The only model is Opus at high effort, with tools `Read`, `Grep` and `Glob` on a read-only checkout (no shell, no web tool). -- **Starting a scan.** Only an operator, from the repo page or, on a test repo, with `autocraft-server security scan REPO --as LOGIN (--cap USD | --no-cap)`. The spend cap is a dollar amount above 0 and up to 100,000, or none. A repo has at most one active scan (modeling, scanning or verifying); a second start is refused with 409. The scan pins the default branch's head commit; every call, and any later fix, works on that commit. The scan's job and agent runs are recorded under the pseudo repo `(security):`, so job and run listings that hide untracked repos hide them. Stopping a scan cancels its job; the scan ends `stopped` before its next call. A scan whose job ended without finishing is closed as `stopped` (job cancelled) or `failed`, and one that was never queued fails after a minute. Scan states: `modeling`, `scanning`, `verifying`, `done`, `stopped`, `capped`, `failed`. +- **Starting a scan.** An operator (with any cap or none) or a maintainer with GitHub write permission on the repo (with a positive cap; without one the API answers 403), from the repo page or, on a test repo, with `autocraft-server security scan REPO --as LOGIN (--cap USD | --no-cap)`. The spend cap is a dollar amount above 0 and up to 100,000, or none. A repo has at most one active scan (modeling, scanning or verifying); a second start is refused with 409. The scan pins the default branch's head commit; every call, and any later fix, works on that commit. The scan's job and agent runs are recorded under the pseudo repo `(security):`, so job and run listings that hide untracked repos hide them. Stopping a scan cancels its job; the scan ends `stopped` before its next call. A scan whose job ended without finishing is closed as `stopped` (job cancelled) or `failed`, and one that was never queued fails after a minute. Scan states: `modeling`, `scanning`, `verifying`, `done`, `stopped`, `capped`, `failed`. - **Threat model.** `security.model` (Opus, high, 60 turns) lists entry points (kind from a fixed list, else `other`) and splits the code into areas, each with paths, entry points, a risk from 1 to 5 and a reason. Areas are sorted by risk, highest first (ties keep the reply's order), at most 60; an area whose paths are not in the checkout is skipped. A reply with no valid area is asked once more, then the scan fails. - **Area calls.** One `security.area` call per area, in risk order (Opus, high, 60 turns). A finding is kept only with confidence of at least 0.8, a title, severity (`critical`, `high`, `medium`, `low`), reach and impact, and at least one ref with a path and line (at most 8 refs, at most 12 findings per area). The first ref is the sink; a finding whose sink is not a real line of a file in the checkout is dropped, other refs that are not real lines are dropped. The model sets `urgent` only for a flaw that is easy to exploit against current users and needs an immediate release; it only marks the finding, the operator picks the route. A reply that cannot be read is asked once more; after that the area is `failed` and the scan goes on. - **Verify.** One `security.verify` call per new finding (Opus, high, 40 turns) tries to disprove it. The finding stays only with verdict `confirmed` and a score of at least 8 of 10; otherwise it is `disproved`. The model may propose a test; the scan stores it and does not run it. When the call gives no readable answer after two tries, the finding stays listed as not verified. A finding still unchecked when the scan ends is listed with the same note. - **Spend cap.** Before every call (and again before the repeat of an unreadable one) the scan stops as `capped` when the cost so far plus the call's expected cost would pass the cap. The expected cost is $2 for the threat model; for an area, the mean cost of the area calls so far, or before the first one $1 plus the area files' size in bytes divided by 200,000, at most $6; for a verify, the mean cost of the verify calls so far, or $0.60 before the first. A call that answered without reporting its cost counts as its expected cost. Money spent is added to the scan and to the area, and a call that stopped the scan is never started, so the cap is not passed by more than the error of an estimate. With no cap the check is skipped. -- **Continuing a scan.** An operator can continue a scan in state `capped` (`POST /api/security/scans//continue` with `{"cap": number|null}`, the Continue button on the scan header, or on a test repo `autocraft-server security continue REPO SCAN_ID --as LOGIN (--cap USD | --no-cap)`; audit action `security-scan-continue`). The new cap must be above what the scan has spent, or none; the repo must have no other active scan (409), and a scan in any other state is refused with 409 (a `stopped` scan was ended by an operator and may have no threat model, so it is not continued). The scan keeps its id, pinned commit, threat model, areas, findings and cost, takes the repo's active-scan slot again and queues a new `security-scan` job. Its state is `verifying` when the cap left findings unchecked, `modeling` when the cap stopped it before the threat model existed, else `scanning`. The runner checks out the pinned commit (the scan fails if the checkout is another commit), skips the threat model and every area already `done` or `failed`, first verifies the findings the cap left unchecked (they return to `unverified`; findings an operator already acted on stay as they are), and goes on in risk order. An area the cap stopped between its call and its verifies is not scanned again. The cap check uses the new cap against the total cost, and the estimates start from the mean cost of the calls the scan already made. +- **Continuing a scan.** An operator, or a maintainer with write access on the repo and a positive new cap, can continue a scan in state `capped` (`POST /api/security/scans//continue` with `{"cap": number|null}`, the Continue button on the scan header, or on a test repo `autocraft-server security continue REPO SCAN_ID --as LOGIN (--cap USD | --no-cap)`; audit action `security-scan-continue`). The new cap must be above what the scan has spent, or none; the repo must have no other active scan (409), and a scan in any other state is refused with 409 (a `stopped` scan was ended by an operator and may have no threat model, so it is not continued). The scan keeps its id, pinned commit, threat model, areas, findings and cost, takes the repo's active-scan slot again and queues a new `security-scan` job. Its state is `verifying` when the cap left findings unchecked, `modeling` when the cap stopped it before the threat model existed, else `scanning`. The runner checks out the pinned commit (the scan fails if the checkout is another commit), skips the threat model and every area already `done` or `failed`, first verifies the findings the cap left unchecked (they return to `unverified`; findings an operator already acted on stay as they are), and goes on in risk order. An area the cap stopped between its call and its verifies is not scanned again. The cap check uses the new cap against the total cost, and the estimates start from the mean cost of the calls the scan already made. - **Estimate.** After the threat model the estimate is the cost so far plus the sum of the area guesses. After each area it is the cost so far plus the remaining area count times the mean cost per started area, which includes that area's verify calls. - **Dedupe.** A new finding repeats an earlier finding of the same repo (any scan) when its fingerprint (first ref's path and line, plus the title reduced to lower-case words) is exactly the same, or when, for an earlier finding that is neither `disproved` nor a repeat, the sink file is the same, the sink line is within 3 lines and the category is the same or the titles share at least half of their words longer than 2 characters. A repeat is stored hidden, pointing at the earlier finding, which shows it in its timeline, and is not verified again. A disproved finding suppresses only an exact fingerprint match, so a reworded report of the same line can be raised again. - **Findings and states.** Verify and dedupe states (`unverified`, `disproved`, repeats) are never listed. Listed states: `new`, `dismissed`, `backlog`, `fixing`, `ready`, `landing`, `awaiting-admin`, `landed`, `advisory`, `published`. Operator actions: Dismiss (needs a reason; from `new`, `backlog`, `ready`, `awaiting-admin`), Backlog (from `new`, `dismissed`), Reopen (from `dismissed`, `backlog`, to `new`), Fix (from `new`, `backlog`; needs a verification), Land and Advisory (from `ready`, `awaiting-admin`), Publish (from `landed`, `advisory`). A step moves the finding to its working state when queued and a second press while it works is refused; a finding left in `fixing`, or in `landing` with no pull request, after its job ended goes back to `new` or `ready` with a note. diff --git a/src/dash/api/security.ts b/src/dash/api/security.ts index 81aab81a..13d6d821 100644 --- a/src/dash/api/security.ts +++ b/src/dash/api/security.ts @@ -16,9 +16,12 @@ function needStaff(req: Req): void { if (!canSeeInternals(req)) throw new HttpError(404, NOT_FOUND); } -function needOperator(req: Req): void { +/** Starting or continuing a scan: an operator with any cap or none, or a maintainer with write access to the repo with a positive cap. */ +async function needStartScan(req: Req, repo: string, cap: unknown): Promise { needStaff(req); - if (req.user.role !== "operator") throw new HttpError(403, "only operators start or continue scans"); + if (req.user.role === "operator") return; + if (!await mayRunRepo(req.user, repo)) throw new HttpError(403, "only an operator, or a maintainer with write access to the repo, starts or continues scans"); + if (typeof cap !== "number" || !(cap > 0)) throw new HttpError(403, "a spend cap is required: only operators run scans without one"); } /** Stopping a scan and deciding findings: an operator, or a maintainer with write access to the repo. */ @@ -45,7 +48,8 @@ function number(v: string | undefined, what: string): number { /** Marks whether the caller may stop or continue the scan and decide its findings. */ async function withAct(req: Req, s: T): Promise { - return { ...s, canAct: await mayRunRepo(req.user, s.repo) }; + const may = await mayRunRepo(req.user, s.repo); + return { ...s, canAct: may, canContinue: may }; } export async function security(db: Db, req: Req): Promise { @@ -53,7 +57,7 @@ export async function security(db: Db, req: Req): Promise { const repo = req.params.repo!; await needVisible(db, req, repo); const o = await overview(db, repo); - return { ...o, scans: await mapSeq(o.scans, async (s) => await withAct(req, s)) }; + return { ...o, canStart: await mayRunRepo(req.user, repo), scans: await mapSeq(o.scans, async (s) => await withAct(req, s)) }; } /** Runs a security action and gives its refusals the HTTP status they carry. */ @@ -67,10 +71,11 @@ async function asHttp(run: () => Promise | T>): Promise { } export async function startScan(db: Db, req: Req): Promise { - needOperator(req); + needStaff(req); const repo = req.params.repo!; await needVisible(db, req, repo); const b = body(req); + await needStartScan(req, repo, b.capUsd); return await withAct(req, await asHttp(async () => startScanAs(db, repo, req.user.login, b.capUsd))); } @@ -85,12 +90,13 @@ export async function stopScan(db: Db, req: Req): Promise { } export async function continueScan(db: Db, req: Req): Promise { - needOperator(req); + needStaff(req); const id = number(req.params.id, "scan"); const scan = await scanRow(db, id); if (!scan) throw new HttpError(404, NOT_FOUND); await needVisible(db, req, scan.repo); const cap = body(req).cap; + await needStartScan(req, scan.repo, cap); return await withAct(req, await asHttp(async () => continueScanAs(db, id, req.user.login, cap))); } diff --git a/src/security/store.ts b/src/security/store.ts index 78d677f9..8d6a8c07 100644 --- a/src/security/store.ts +++ b/src/security/store.ts @@ -28,7 +28,7 @@ export async function toScan(db: Db, r: ScanRow): Promise { const n = (await db.get(db.k.selectFrom("security_findings").select((eb) => eb.fn.countAll().as("n")).where("scan_id", "=", r.id).where("state", "not in", INTERNAL_FINDING_STATES)))!.n; return { id: r.id, repo: r.repo, commit: r.commit_sha, state: r.state, capUsd: r.cap_usd, costUsd: r.cost_usd, estimateUsd: r.estimate_usd, - areasTotal: r.areas_total, areasDone: r.areas_done, findingCount: n, startedBy: r.started_by, startedAt: r.started_at, endedAt: r.ended_at, error: r.error, canAct: false, + areasTotal: r.areas_total, areasDone: r.areas_done, findingCount: n, startedBy: r.started_by, startedAt: r.started_at, endedAt: r.ended_at, error: r.error, canAct: false, canContinue: false, }; } @@ -138,7 +138,7 @@ export async function overview(db: Db, repo: string): Promise await reconcileFindings(db, repo); const scanList = await mapSeq(await db.all(scans(db).where("repo", "=", repo).orderBy("id", "desc").limit(20)), async (r) => await toScan(db, r)); const listed = (await db.all(findings(db).where("repo", "=", repo).where("state", "not in", INTERNAL_FINDING_STATES).orderBy(severityOrder).orderBy("number").limit(500))).map(summary); - return { scans: scanList, findings: await withScanTests(db, listed) }; + return { canStart: false, scans: scanList, findings: await withScanTests(db, listed) }; } export const findingRow = async (db: Db, repo: string, n: number): Promise => diff --git a/test/maintainer-repo-actions.test.ts b/test/maintainer-repo-actions.test.ts index df79ec67..5923a579 100644 --- a/test/maintainer-repo-actions.test.ts +++ b/test/maintainer-repo-actions.test.ts @@ -12,7 +12,7 @@ const as = (login: string, role: "viewer" | "maintainer" | "operator", json: unk user: { login, role, canWrite: async (repo: string) => repo === "alpha", canRead: async () => true }, csrf: "", nonce: "", }); -test("a maintainer with write runs their repo's approvals, findings and jobs; others are refused; scans and repo-less jobs stay operator", async () => { +test("a maintainer with write runs their repo's approvals, findings and jobs; others are refused; scans need a cap, repo-less jobs stay operator", async () => { const db = await connectDb(":memory:"); for (const name of ["alpha", "beta"]) { await db.run(db.k.insertInto("tracked_repos").values({ name })); @@ -40,14 +40,23 @@ test("a maintainer with write runs their repo's approvals, findings and jobs; ot // Advisory and publish open or publish an advisory: operator only. for (const action of ["advisory", "publish"]) await assert.rejects(dismiss(as("maint", "maintainer", { action }, { repo: "alpha", n: "1" })), { status: 403 }); - // Continuing a capped scan spends more: operator only, whatever the cap. + // Scans spend money: a maintainer with write on the repo starts or continues one only with a cap; others are refused. await db.run(db.k.insertInto("security_scans").values({ id: 1, repo: "alpha", state: "capped", cap_usd: 10, cost_usd: 5, started_by: "op", started_at: at })); - const cont = (cap: number | null) => continueScan(db, as("maint", "maintainer", { cap }, { id: "1" })); - await assert.rejects(cont(null), { status: 403 }); - await assert.rejects(cont(8), { status: 403 }); - - // Starting a scan spends money: operator only. - await assert.rejects(startScan(db, as("maint", "maintainer", {}, { repo: "alpha" })), { status: 403 }); + const cont = (who: Req["user"]["role"], cap: number | null) => continueScan(db, as("maint", who, { cap }, { id: "1" })); + const start = (login: string, role: "viewer" | "maintainer" | "operator", repo: string, capUsd?: number | null) => startScan(db, as(login, role, capUsd === undefined ? {} : { capUsd }, { repo })); + const refused = (e: { status: number }) => e.status === 403 || e.status === 404; + await assert.rejects(cont("maintainer", null), { status: 403 }); + await assert.rejects(start("maint", "maintainer", "alpha"), { status: 403 }); + await assert.rejects(start("maint", "maintainer", "alpha", 0), { status: 403 }); + await assert.rejects(start("maint", "maintainer", "beta", 5), { status: 403 }); + await assert.rejects(start("view", "viewer", "alpha", 5), refused); + await assert.rejects(cont("viewer", 8), refused); + assert.equal((await cont("maintainer", 8)).capUsd, 8); + await db.run(db.k.updateTable("security_scans").set({ state: "stopped" }).where("id", "=", 1)); + const started = await start("maint", "maintainer", "alpha", 3); + assert.equal(started.capUsd, 3); + await db.run(db.k.updateTable("security_scans").set({ state: "stopped" }).where("id", "=", started.id)); + assert.equal((await start("op", "operator", "alpha")).capUsd, null); // Jobs: the maintainer cancels a job of their repo, not another repo's, not a repo-less one. const own = await job("alpha"); diff --git a/web/src/api/mock/securityMock.ts b/web/src/api/mock/securityMock.ts index bc2d5fed..f09ae71a 100644 --- a/web/src/api/mock/securityMock.ts +++ b/web/src/api/mock/securityMock.ts @@ -13,10 +13,10 @@ const call = (kind: FindingCall["kind"], minAgo: number, costUsd: number | null, function scans(me: { role: string }): ScanView[] { const base = { startedBy: "kiri-n", error: null, endedAt: null }; return [ - { ...base, id: 3, repo: "designcraft", canAct: mayRunMock(me, "designcraft"), commit: "a41f9c02d7e8", findingCount: 1, state: "scanning", capUsd: 15, costUsd: 4.18, estimateUsd: 11.6, areasTotal: 6, areasDone: 2, startedAt: iso(38) }, - { ...base, id: 2, repo: "designcraft", canAct: mayRunMock(me, "designcraft"), commit: "9c7e41b0a3d5", findingCount: 2, state: "capped", capUsd: 5, costUsd: 5.03, estimateUsd: 13.2, areasTotal: 9, areasDone: 3, startedAt: iso(3 * 1440), endedAt: iso(3 * 1440 - 41) }, - { ...base, id: 1, repo: "designcraft", canAct: mayRunMock(me, "designcraft"), commit: SHA.slice(0, 12), findingCount: 8, state: "done", capUsd: null, costUsd: 11.87, estimateUsd: 12.4, areasTotal: 8, areasDone: 8, startedAt: iso(9 * 1440), endedAt: iso(9 * 1440 - 74) }, - { ...base, id: 4, repo: "pdfcraft", canAct: mayRunMock(me, "pdfcraft"), commit: "5be20d41c9a7", findingCount: 1, state: "capped", capUsd: 6, costUsd: 5.41, estimateUsd: 12.8, areasTotal: 6, areasDone: 2, startedAt: iso(26 * 60), endedAt: iso(25 * 60) }, + { ...base, id: 3, repo: "designcraft", canAct: mayRunMock(me, "designcraft"), canContinue: mayRunMock(me, "designcraft"), commit: "a41f9c02d7e8", findingCount: 1, state: "scanning", capUsd: 15, costUsd: 4.18, estimateUsd: 11.6, areasTotal: 6, areasDone: 2, startedAt: iso(38) }, + { ...base, id: 2, repo: "designcraft", canAct: mayRunMock(me, "designcraft"), canContinue: mayRunMock(me, "designcraft"), commit: "9c7e41b0a3d5", findingCount: 2, state: "capped", capUsd: 5, costUsd: 5.03, estimateUsd: 13.2, areasTotal: 9, areasDone: 3, startedAt: iso(3 * 1440), endedAt: iso(3 * 1440 - 41) }, + { ...base, id: 1, repo: "designcraft", canAct: mayRunMock(me, "designcraft"), canContinue: mayRunMock(me, "designcraft"), commit: SHA.slice(0, 12), findingCount: 8, state: "done", capUsd: null, costUsd: 11.87, estimateUsd: 12.4, areasTotal: 8, areasDone: 8, startedAt: iso(9 * 1440), endedAt: iso(9 * 1440 - 74) }, + { ...base, id: 4, repo: "pdfcraft", canAct: mayRunMock(me, "pdfcraft"), canContinue: mayRunMock(me, "pdfcraft"), commit: "5be20d41c9a7", findingCount: 1, state: "capped", capUsd: 6, costUsd: 5.41, estimateUsd: 12.8, areasTotal: 6, areasDone: 2, startedAt: iso(26 * 60), endedAt: iso(25 * 60) }, ]; } @@ -124,6 +124,10 @@ export function createSecurityMock(me: User, changed: () => void): Pick { if (!mayRunMock(me, repo)) throw new Error("only an operator, or a maintainer with write access to the repo, stops scans and decides findings"); }; + const mayStart = (repo: string, cap: number | null) => { + if (!mayRunMock(me, repo)) throw new Error("only an operator, or a maintainer with write access to the repo, starts or continues scans"); + if (me.role !== "operator" && !(cap !== null && cap > 0)) throw new Error("a spend cap is required: only operators run scans without one"); + }; const sc = scans(me); const fs = findings(); const summary = (f: FindingView): FindingSummary => ({ repo: f.repo, number: f.number, key: f.key, scanId: f.scanId, title: f.title, severity: f.severity, urgent: f.urgent, area: f.area, state: f.state, createdAt: f.createdAt, updatedAt: f.updatedAt, ...(f.scanTest && { scanTest: f.scanTest }) }); @@ -136,7 +140,7 @@ export function createSecurityMock(me: User, changed: () => void): Pick { forbidden(); - return wait({ scans: sc.filter((s) => s.repo === repo).sort((a, b) => b.id - a.id), findings: fs.filter((f) => f.repo === repo).map(summary) }); + return wait({ canStart: mayRunMock(me, repo), scans: sc.filter((s) => s.repo === repo).sort((a, b) => b.id - a.id), findings: fs.filter((f) => f.repo === repo).map(summary) }); }, scans: async (repo) => { forbidden(); @@ -149,9 +153,9 @@ export function createSecurityMock(me: User, changed: () => void): Pick { - operator(); + mayStart(repo, capUsd); if (sc.some((s) => s.repo === repo && ["modeling", "scanning", "verifying"].includes(s.state))) throw new Error("A scan is already running for this repo"); - const s: ScanView = { canAct: mayRunMock(me, repo), id: Math.max(...sc.map((x) => x.id)) + 1, repo, commit: SHA.slice(0, 12), findingCount: 0, state: "modeling", capUsd, costUsd: 0, estimateUsd: null, areasTotal: 0, areasDone: 0, startedBy: me.login, startedAt: new Date(NOW).toISOString(), endedAt: null, error: null }; + const s: ScanView = { canAct: mayRunMock(me, repo), canContinue: mayRunMock(me, repo), id: Math.max(...sc.map((x) => x.id)) + 1, repo, commit: SHA.slice(0, 12), findingCount: 0, state: "modeling", capUsd, costUsd: 0, estimateUsd: null, areasTotal: 0, areasDone: 0, startedBy: me.login, startedAt: new Date(NOW).toISOString(), endedAt: null, error: null }; sc.push(s); changed(); return wait(s); @@ -165,9 +169,9 @@ export function createSecurityMock(me: User, changed: () => void): Pick { - operator(); const s = sc.find((x) => x.id === id); if (!s) throw new Error("Not found"); + mayStart(s.repo, capUsd); if (s.state !== "capped") throw new Error("only a scan that stopped at its cap can be continued"); if (capUsd !== null && capUsd <= s.costUsd) throw new Error("the new cap must be above what the scan has spent"); Object.assign(s, { state: "scanning", capUsd, endedAt: null }); diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 43ad1efb..c343f32d 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -2499,6 +2499,8 @@ export type FindingAction = "fix" | "dismiss" | "backlog" | "reopen" | "land" | export interface ScanView { /** The caller may stop the scan and decide its findings (continuing stays with operators); the server sets it per request. */ canAct: boolean; + /** The caller may continue a capped scan with a new cap (same rule as starting one). */ + canContinue: boolean; id: number; repo: string; /** The pinned commit of the default branch; null before the scan has fetched it. */ @@ -2570,7 +2572,12 @@ export interface FindingView extends FindingSummary { timeline: FindingCall[]; } -export interface SecurityOverview { scans: ScanView[]; findings: FindingSummary[] } +export interface SecurityOverview { + /** The caller may start a scan on this repo (maintainers need a spend cap). */ + canStart: boolean; + scans: ScanView[]; + findings: FindingSummary[]; +} export type ScanAreaState = "pending" | "running" | "done" | "failed"; export interface ScanArea { idx: number; name: string; risk: number; why: string | null; paths: string[]; state: ScanAreaState; costUsd: number } diff --git a/web/src/modules/admin/securityParts.tsx b/web/src/modules/admin/securityParts.tsx index f4b67cc2..75aafb50 100644 --- a/web/src/modules/admin/securityParts.tsx +++ b/web/src/modules/admin/securityParts.tsx @@ -22,12 +22,12 @@ import { Segmented } from "../../ui/molecules/Segmented"; const usd = (v: number) => formatCost(v) ?? "$0.00"; /** The spend-cap form of starting and continuing a scan. */ -function CapDialog({ title, submit, initial, above, open, onClose, send }: { title: string; submit: string; initial: number; above: number; open: boolean; onClose: () => void; send: (cap: number | null) => Promise }) { +function CapDialog({ title, submit, initial, above, uncapped, open, onClose, send }: { title: string; submit: string; initial: number; above: number; uncapped: boolean; open: boolean; onClose: () => void; send: (cap: number | null) => Promise }) { const write = useWrite(); const [mode, setMode] = useState<"amount" | "none">("amount"); const [amount, setAmount] = useState(String(initial)); const cap = mode === "none" ? null : Number(amount); - const valid = cap === null || (Number.isFinite(cap) && cap > above); + const valid = cap === null ? uncapped : Number.isFinite(cap) && cap > above; return (
Spend cap - + {uncapped && } {mode === "amount" && (
)} > - {operator && setOpen(false)} />} + {data?.canStart && setOpen(false)} />} {scan && } {data && data.findings.length > 0 ? (