diff --git a/dashboard/e2e/prs-overview-data.ts b/dashboard/e2e/prs-overview-data.ts index f07ec887..3d4ff6d9 100644 --- a/dashboard/e2e/prs-overview-data.ts +++ b/dashboard/e2e/prs-overview-data.ts @@ -546,6 +546,16 @@ export function overview(kind: Scenario = "normal", repo?: string): PrsOverview { group: "Renovate", merge_rate: null, superseded: null }, { group: "CoderHelm", merge_rate: chZero ? null : 0.92, superseded: chZero ? null : 0.04 }, ], + alerts: isEmpty + ? null + : { + open_without_pr: bad ? { critical: 1, high: 2, medium: 4, low: 0 } : { critical: 0, high: 0, medium: 2, low: 1 }, + past_sla_without_pr: bad ? 1 : 0, + oldest_secs: bad ? 12 * D : 3 * D, + dependabot: "on", + code_scanning: "needs_permission", + text: bad ? "7 open Dependabot alerts have no pull request; 1 is past its SLA." : "3 open Dependabot alerts have no pull request.", + }, }, events: isEmpty ? [] diff --git a/dashboard/e2e/prs-overview-mock.ts b/dashboard/e2e/prs-overview-mock.ts index 80146951..297cdfb5 100644 --- a/dashboard/e2e/prs-overview-mock.ts +++ b/dashboard/e2e/prs-overview-mock.ts @@ -1,18 +1,25 @@ import type { Page, Route } from "@playwright/test"; -import type { PrsOverview } from "../src/lib/api"; +import type { PrSettings, PrsOverview } from "../src/lib/api"; import { overview, type Scenario } from "./prs-overview-data"; import { detail, page as prsPage } from "./prs-data"; export interface OverviewBackend { calls: string[]; + /** The team's pull request settings as last saved (PUT /api/prs/settings). */ + settings: PrSettings; /** The answer to /api/prs/overview for its query; a number is an error status. Tests swap it mid-way. */ answer: (url: URL) => PrsOverview | number; } /** Answers every API call the overview and the list make, from the invented data. */ -export async function mockOverview(page: Page, scenario: Scenario | ((url: URL) => PrsOverview | number) = "normal"): Promise { +export async function mockOverview( + page: Page, + scenario: Scenario | ((url: URL) => PrsOverview | number) = "normal", + capabilities?: string[], +): Promise { const db: OverviewBackend = { calls: [], + settings: { sensitive: {}, sla: { critical: 7, high: 30, medium: 90, low: 180 }, digest: { enabled: false, channel: "", to: [] }, nudges: { enabled: false } }, answer: typeof scenario === "function" ? scenario : (url) => overview(scenario, url.searchParams.get("repo") ?? undefined), }; const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); @@ -21,7 +28,7 @@ export async function mockOverview(page: Page, scenario: Scenario | ((url: URL) const url = new URL(route.request().url()); const p = url.pathname; db.calls.push(`${route.request().method()} ${p}${url.search}`); - if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "octocat", email: "octocat@example.com", avatar_url: "", role: "member" }); + if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "octocat", email: "octocat@example.com", avatar_url: "", role: "member", ...(capabilities ? { capabilities } : {}) }); if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); if (p === "/api/banners") return json(route, { banners: [] }); if (p === "/api/security/overview") return json(route, { enabled: false, dry_run: true, counts: { open: 0, p0: 0, p1: 0 } }); @@ -34,6 +41,16 @@ export async function mockOverview(page: Page, scenario: Scenario | ((url: URL) if (typeof a === "number") return json(route, { error: "nope" }, a); return json(route, a); } + if (p === "/api/prs/settings") { + if (route.request().method() === "PUT") { + const body = JSON.parse(route.request().postData() ?? "{}") as PrSettings; + if (body.digest.enabled && body.digest.channel === "email" && body.digest.to.length === 0) { + return json(route, { error: "an email digest needs between 1 and 20 team members' addresses" }, 422); + } + db.settings = { ...body, updated_at: 1, updated_by: "octocat" }; + } + return json(route, db.settings); + } if (p === "/api/prs") return json(route, prsPage()); if (p === "/api/prs/detail") return json(route, detail()); return json(route, { error: "Not mocked" }, 404); diff --git a/dashboard/e2e/prs-overview.spec.ts b/dashboard/e2e/prs-overview.spec.ts index 7403a7f6..0e9ab8a2 100644 --- a/dashboard/e2e/prs-overview.spec.ts +++ b/dashboard/e2e/prs-overview.spec.ts @@ -235,3 +235,38 @@ for (const width of [320, 375]) { expect(wide).toBeLessThanOrEqual(0); }); } + +test("the Security panel counts open alerts with no pull request and says code scanning needs its permission", async ({ page }) => { + await open(page, "bad"); + const sec = page.getByTestId("panel-security"); + await expect(sec.getByTestId("security-alerts")).toHaveText("crit 1 · high 2 · medi 4 · low 0"); + await expect(sec.getByTestId("security-alerts-text")).toContainText("Code scanning alerts need the security events permission."); +}); + +test("settings: the digest and nudges start off, sensitive paths save per repo, and an email digest needs an address", async ({ page }) => { + const db = await mockOverview(page, "normal", ["view", "view_team", "agent_settings"]); + await page.goto("/prs/overview?org=acme"); + await page.getByTestId("overview-settings-link").click(); + await expect(page.getByTestId("prs-settings")).toBeVisible(); + await expect(page.getByTestId("prs-settings-digest")).toHaveAttribute("aria-checked", "false"); + await expect(page.getByTestId("prs-settings-nudges")).toHaveAttribute("aria-checked", "false"); + await page.getByTestId("prs-settings-sensitive").fill("acme/checkout: cart/rounding/**, *.pem"); + await page.getByTestId("prs-settings-digest").click(); + await page.getByRole("combobox", { name: "Send it to" }).click(); + await page.getByRole("option", { name: "Email" }).click(); + await page.getByRole("button", { name: "Save changes" }).click(); + await expect(page.getByTestId("save-bar")).toContainText("needs between 1 and 20"); + await page.getByTestId("prs-settings-digest-to").fill("octocat@example.com"); + await page.getByRole("button", { name: "Save changes" }).click(); + await expect.poll(() => db.settings.updated_by).toBe("octocat"); + expect(db.settings.sensitive).toEqual({ "acme/checkout": ["cart/rounding/**", "*.pem"] }); + expect(db.settings.digest).toEqual({ enabled: true, channel: "email", to: ["octocat@example.com"] }); + expect(db.settings.nudges.enabled).toBe(false); +}); + +test("settings: without agent settings they can be read but not changed", async ({ page }) => { + await mockOverview(page, "normal", ["view", "view_team"]); + await page.goto("/prs/overview/settings"); + await expect(page.getByTestId("prs-settings-sensitive")).toBeDisabled(); + await expect(page.getByTestId("prs-settings-nudges")).toBeDisabled(); +}); diff --git a/dashboard/e2e/wide-data/prs-overview.ts b/dashboard/e2e/wide-data/prs-overview.ts index 0a34d2d6..4154c5a6 100644 --- a/dashboard/e2e/wide-data/prs-overview.ts +++ b/dashboard/e2e/wide-data/prs-overview.ts @@ -21,11 +21,24 @@ function wide(): unknown { for (const e of o.events) e.text = `${e.text}: ${SENTENCE} ${TOKEN}`; o.summary.changed.parts.push({ t: ` ${SENTENCE} ${TOKEN}` }); o.failures.flaky = { count: 1, new: 1, top: [{ check: TOKEN, repo: REPO, retries: 12 }] }; + if (o.security.alerts) o.security.alerts.text = `${o.security.alerts.text} ${SENTENCE} ${TOKEN}`; return o; } +/** The settings with every repo list, pattern and address at its longest. */ +function settings(): unknown { + const pats = [`${TOKEN}/**/${TOKEN}/**`, `**/payments-${TOKEN}/**`, `*.${TOKEN}`]; + return { + sensitive: { [REPO]: pats, [`${REPO}-second-${TOKEN}`]: pats }, + sla: { critical: 7, high: 30, medium: 90, low: 180 }, + digest: { enabled: true, channel: "email", to: [`${LOGIN}-${TOKEN}@example.com`, `octocat-${TOKEN}@example.com`] }, + nudges: { enabled: true }, + }; +} + export const prsOverviewData: Handler = ({ method, path }) => { if (method !== "GET") return undefined; if (path === "/api/prs/overview") return wide(); + if (path === "/api/prs/settings") return settings(); return undefined; }; diff --git a/dashboard/src/app/prs/overview/page.tsx b/dashboard/src/app/prs/overview/page.tsx index d5cf4be8..7b7a9429 100644 --- a/dashboard/src/app/prs/overview/page.tsx +++ b/dashboard/src/app/prs/overview/page.tsx @@ -101,6 +101,11 @@ function Overview() { ? "One repo's open pull requests against its own history: where they wait, for whom, and whether that is usual here." : "Where your org's pull requests wait, for whom, and whether that is usual for this org." } + actions={ + + Settings + + } /> ); diff --git a/dashboard/src/app/prs/overview/panels.tsx b/dashboard/src/app/prs/overview/panels.tsx index 198e408e..05923540 100644 --- a/dashboard/src/app/prs/overview/panels.tsx +++ b/dashboard/src/app/prs/overview/panels.tsx @@ -387,6 +387,24 @@ export function SecurityPanel({ o, scope }: { o: PrsOverview; scope: Scope }) { Sensitive paths merged without an owner {s.sensitive_without_owner != null ? {s.sensitive_without_owner} : } +
+
+ Security alerts with no PR + {s.alerts ? ( + + {SEV.map((k) => `${k.slice(0, 4)} ${s.alerts!.open_without_pr[k]}`).join(" · ")} + + ) : ( + + )} +
+ {s.alerts && ( +

+ {s.alerts.text} + {s.alerts.code_scanning === "needs_permission" && " Code scanning alerts need the security events permission."} +

+ )} +
{s.dependency && (

Dependency PRs, 30 days: merged · superseded

diff --git a/dashboard/src/app/prs/overview/settings/page.tsx b/dashboard/src/app/prs/overview/settings/page.tsx new file mode 100644 index 00000000..d5463310 --- /dev/null +++ b/dashboard/src/app/prs/overview/settings/page.tsx @@ -0,0 +1,271 @@ +"use client"; + +// Pull requests settings: which paths are sensitive in each repo, the +// security deadlines the overview measures against, and the weekly digest and +// per-pull-request nudges. The digest and nudges are off until a team turns +// them on. Anyone can read these; changing them needs agent settings. + +import Link from "next/link"; +import { useCallback, useEffect, useState } from "react"; +import { api, ApiError, type PrSettings } from "@/lib/api"; +import { RoleGuard } from "@/components/role-guard"; +import { Page, PageHeader } from "@/components/page"; +import { Select } from "@/components/select"; +import { Skeleton } from "@/components/skeleton"; +import { useToast } from "@/components/toast"; +import { useCan } from "@/hooks/use-can"; +import { inputClass, linkButton } from "@/components/ui"; +import { SaveBar, SettingsRow, SettingsSection, Switch, useDirtyForm } from "@/components/settings"; + +const DEFAULT_SENSITIVE = ["**/auth/**", "**/payments/**", "**/secrets/**", "**/infra/**", "**/migrations/**"]; + +interface Form { + /** One repo a line: `owner/repo: pattern, pattern`. */ + sensitive: string; + critical: string; + high: string; + medium: string; + low: string; + digest: boolean; + channel: string; + to: string; + nudges: boolean; +} + +const EMPTY: Form = { + sensitive: "", + critical: "7", + high: "30", + medium: "90", + low: "180", + digest: false, + channel: "slack", + to: "", + nudges: false, +}; + +function toForm(s: PrSettings): Form { + return { + sensitive: Object.entries(s.sensitive ?? {}) + .map(([repo, pats]) => `${repo}: ${pats.join(", ")}`) + .join("\n"), + critical: String(s.sla?.critical ?? 7), + high: String(s.sla?.high ?? 30), + medium: String(s.sla?.medium ?? 90), + low: String(s.sla?.low ?? 180), + digest: !!s.digest?.enabled, + channel: s.digest?.channel || "slack", + to: (s.digest?.to ?? []).join("\n"), + nudges: !!s.nudges?.enabled, + }; +} + +/** Pure: the form as settings, or the first line that isn't `owner/repo: patterns`. */ +function fromForm(f: Form): PrSettings | string { + const sensitive: Record = {}; + for (const line of f.sensitive.split("\n").map((l) => l.trim()).filter(Boolean)) { + const at = line.indexOf(":"); + const repo = at > 0 ? line.slice(0, at).trim() : ""; + if (repo.split("/").length !== 2) return `"${line}" isn't owner/repo: patterns`; + sensitive[repo] = line + .slice(at + 1) + .split(",") + .map((p) => p.trim()) + .filter(Boolean); + } + const days = (v: string) => Number.parseInt(v, 10) || 0; + return { + sensitive, + sla: { critical: days(f.critical), high: days(f.high), medium: days(f.medium), low: days(f.low) }, + digest: { + enabled: f.digest, + channel: f.channel as PrSettings["digest"]["channel"], + to: f.channel === "email" ? f.to.split(/[\n,]/).map((a) => a.trim()).filter(Boolean) : [], + }, + nudges: { enabled: f.nudges }, + }; +} + +export default function PrSettingsGuarded() { + return ( + + + + ); +} + +function PrSettingsPage() { + const { toast } = useToast(); + const { ready, can } = useCan(); + const admin = ready && can("agent_settings"); + const [loaded, setLoaded] = useState(false); + const [loadFailed, setLoadFailed] = useState(null); + const [saving, setSaving] = useState(false); + const [problem, setProblem] = useState(null); + const form = useDirtyForm
(EMPTY, { disabled: !loaded }); + const { reset } = form; + + const load = useCallback(async () => { + try { + reset(toForm(await api.prsSettings())); + setLoaded(true); + setLoadFailed(null); + } catch (e) { + setLoadFailed(e instanceof ApiError && e.status === 404 ? "This install's CoderHelm doesn't have these settings yet." : "The settings couldn't be loaded."); + } + }, [reset]); + useEffect(() => { + load(); + }, [load]); + + const save = async () => { + const body = fromForm(form.values); + if (typeof body === "string") { + setProblem(body); + return; + } + setSaving(true); + setProblem(null); + try { + reset(toForm(await api.savePrSettings(body))); + toast("Pull requests settings saved"); + } catch (e) { + setProblem(e instanceof ApiError ? e.message : "The settings weren't saved. Try again."); + } finally { + setSaving(false); + } + }; + + const v = form.values; + const off = !admin; + return ( + + + Back to the overview + + } + /> + {loadFailed ? ( +

+ {loadFailed} +

+ ) : !loaded ? ( + + ) : ( +
+ {ready && !admin &&

You can read these. Changing them needs the agent settings permission.

} + + ( +