Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

233 linesCodeBlameRaw
1import { RefreshCw, ShieldCheck } from "lucide-react";
2import { useFetcher, useSearchParams } from "react-router";
3
4import type { AlertState, DismissReason } from "@g1t/contracts";
5
6import type { Route } from "./+types/security";
7import { page } from "../../lib/meta";
8import {
9 type PullInfo,
10 ScanSummary,
11 SeverityCountsGrid,
12 StateFilter,
13 type UpgradeFix,
14 VulnerabilityList,
15} from "../../components/security";
16import { Button } from "../../components/ui/button";
17import { Card } from "../../components/ui/card";
18import { Hint } from "../../components/ui/hint";
19import { Switch } from "../../components/ui/switch";
20import { security, work } from "../../lib/services.server";
21import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
22import { refusal, requireInsider } from "../../lib/access.server";
23import { whyNot } from "../../lib/access";
24import { alertCapability, countByState, parseAlertState } from "../../lib/security-alerts";
25import { severityCounts } from "../../lib/security-suite";
26import { repoPages } from "../../lib/repo-live";
27import { useRepoLive } from "../../lib/use-repo-live";
28
29export function meta({ params, ...args }: Route.MetaArgs) {
30 return page(args, { title: `Vulnerabilities · ${params.owner}/${params.repo} · g1t` });
31}
32
33/** Upgrade issues and security update pull requests looked up per page, at most. */
34const MAX_FIXES = 30;
35
36export async function loader({ params, context, request }: Route.LoaderArgs) {
37 // Git's refusal links here; someone signed out signs in first.
38 const viewer = getViewer(context) ?? requireUser(context, request);
39 // Findings are for people who can push, public project or not: Write and up.
40 const { access } = await requireInsider(context, params, "security_alerts");
41 const repo = { namespace: params.owner, name: params.repo };
42 const overview = unwrap(await security.overview(repo, viewer));
43 const unique = (numbers: (number | null | undefined)[]) =>
44 [...new Set(numbers.filter((n): n is number => n != null))].slice(0, MAX_FIXES);
45 // Security updates' pull requests, for their live status.
46 const pullNumbers = unique(overview.vulnerabilities.map((vuln) => vuln.update?.pull));
47 // Older upgrade issues, from before g1t opened pull requests itself.
48 const issueNumbers = unique(overview.vulnerabilities.filter((vuln) => !vuln.update).map((vuln) => vuln.issue));
49 const [pullDetails, issueDetails] = await Promise.all([
50 Promise.all(pullNumbers.map((number) => work.getPull(repo, number, viewer).catch(() => null))),
51 Promise.all(issueNumbers.map((number) => work.getIssue(repo, number, viewer).catch(() => null))),
52 ]);
53 const pulls: Record<number, PullInfo> = {};
54 for (const found of pullDetails) {
55 if (!found?.ok) continue;
56 const { pull } = found.value;
57 pulls[pull.number] = { number: pull.number, status: pull.status, title: pull.title };
58 }
59 const fixes: Record<number, UpgradeFix> = {};
60 for (const found of issueDetails) {
61 if (!found?.ok) continue;
62 const { issue, pulls: issuePulls } = found.value;
63 const latest = issuePulls.at(-1) ?? null;
64 fixes[issue.number] = {
65 number: issue.number,
66 state: issue.state,
67 resolvedBy: issue.resolvedBy,
68 pull: latest ? { number: latest.number, status: latest.status, agent: latest.runtime === "hosted" ? latest.agent : null } : null,
69 };
70 }
71 return { overview, fixes, pulls, can: access.can };
72}
73
74const DISMISS_REASONS = new Set<string>([
75 "false_positive",
76 "used_in_tests",
77 "revoked",
78 "wont_fix",
79 "fix_started",
80 "no_bandwidth",
81 "tolerable_risk",
82 "inaccurate",
83 "not_used",
84]);
85
86export async function action({ params, context, request }: Route.ActionArgs) {
87 assertSameOrigin(request);
88 const user = requireUser(context, request);
89 const repo = { namespace: params.owner, name: params.repo };
90 const form = await request.formData();
91 const intent = String(form.get("intent") ?? "");
92 const id = String(form.get("id") ?? "");
93 // Scanning spends compute (Write); security updates are a setting
94 // (Maintain); an alert is dismissed or reopened with Write, or by a
95 // security manager of the workspace.
96 const capability =
97 intent === "rescan" ? "run" : intent === "upkeep" ? "manage_settings" : intent === "dismiss" || intent === "reopen" ? alertCapability(id) : null;
98 if (!capability) return { ok: false, error: "Unknown action." };
99 const refused = await refusal(context, params, capability);
100 if (refused) return { ok: false, error: refused };
101 if (intent === "dismiss") {
102 const reason = String(form.get("reason") ?? "");
103 if (!DISMISS_REASONS.has(reason)) return { ok: false, error: "Choose a reason." };
104 const comment = String(form.get("comment") ?? "").trim().slice(0, 500);
105 const dismissed = await security.dismiss(user, repo, id, reason as DismissReason, comment);
106 return dismissed.ok ? { ok: true } : { ok: false, error: dismissed.error.message };
107 }
108 if (intent === "reopen") {
109 const reopened = await security.reopen(user, repo, id);
110 return reopened.ok ? { ok: true } : { ok: false, error: reopened.error.message };
111 }
112 if (intent === "rescan") {
113 const scanned = await security.rescan(user, repo);
114 return scanned.ok ? { ok: true } : { ok: false, error: scanned.error.message };
115 }
116 const set = await security.setUpkeep(user, repo, form.get("enabled") === "true");
117 return set.ok ? { ok: true } : { ok: false, error: set.error.message };
118}
119
120export default function ProjectSecurity({ loaderData, params }: Route.ComponentProps) {
121 const { overview, fixes, pulls, can } = loaderData;
122 // Alerts opening, fixed and dismissed show as it happens.
123 useRepoLive({ match: repoPages.security() });
124 const base = `/${params.owner}/${params.repo}`;
125 const action = `${base}/security/vulnerabilities`;
126 const [search, setSearch] = useSearchParams();
127 const rescan = useFetcher<{ ok: boolean; error?: string }>();
128 const upkeep = useFetcher<{ ok: boolean; error?: string }>();
129 const upkeepOn = upkeep.formData ? upkeep.formData.get("enabled") === "true" : overview.upkeep;
130 const vulnCounts = countByState(overview.vulnerabilities);
131 // A link to one alert shows it wherever it stands.
132 const focus = search.get("finding");
133 const focused = focus ? overview.vulnerabilities.find((vuln) => vuln.id === focus) : undefined;
134 const state: AlertState = search.get("state") ? parseAlertState(search.get("state")) : (focused?.state ?? "open");
135 const navigate = (change: (next: URLSearchParams) => void) => {
136 const next = new URLSearchParams(search);
137 change(next);
138 next.delete("finding");
139 setSearch(next, { replace: true, preventScrollReset: true });
140 };
141 const setState = (value: AlertState) =>
142 navigate((next) => (value === "open" ? next.delete("state") : next.set("state", value)));
143 return (
144 <div className="max-w-5xl">
145 <div className="flex flex-wrap items-start justify-between gap-4">
146 <div>
147 <h2 className="flex items-center gap-2 text-xl font-semibold tracking-tight">
148 <ShieldCheck size={19} className="text-accent" />
149 Vulnerabilities
150 </h2>
151 <p className="mt-1.5 max-w-2xl text-sm text-muted">
152 Every package the lockfiles resolve is checked for known vulnerabilities, on every push to the default branch and
153 daily.{" "}
154 With security updates on, g1t opens a pull request to upgrade each one that has a fix.
155 </p>
156 </div>
157 {can.run && (
158 <rescan.Form method="post" action={action}>
159 <input type="hidden" name="intent" value="rescan" />
160 <Button
161 type="submit"
162 disabled={rescan.state !== "idle"}
163 variant="outline"
164 size="sm"
165 className="gap-2 px-3 text-sm font-normal"
166 >
167 <RefreshCw size={14} className={rescan.state !== "idle" ? "animate-spin" : ""} />
168 {rescan.state !== "idle" ? "Scanning…" : "Re-scan now"}
169 </Button>
170 {rescan.data?.error && <p className="mt-1.5 text-xs text-danger">{rescan.data.error}</p>}
171 </rescan.Form>
172 )}
173 </div>
174
175 <div className="mt-6">
176 <SeverityCountsGrid counts={severityCounts(overview.vulnerabilities)} />
177 <p className="mt-2 text-xs text-faint">Open vulnerability alerts by severity.</p>
178 </div>
179
180 <div className="mt-4">
181 <ScanSummary scan={overview.scan} />
182 </div>
183
184 <div className="mt-8">
185 <div>
186 <StateFilter counts={vulnCounts} value={state} onChange={setState} />
187 <div className="mt-3">
188 <VulnerabilityList
189 vulnerabilities={overview.vulnerabilities.filter((vuln) => vuln.state === state)}
190 state={state}
191 activity={overview.activity}
192 fixes={fixes}
193 pulls={pulls}
194 upkeep={overview.upkeep}
195 base={base}
196 action={action}
197 focus={focus}
198 canDismiss={can.push}
199 />
200 </div>
201 </div>
202 </div>
203
204 <section className="mt-10" aria-labelledby="security-settings">
205 <h3 id="security-settings" className="text-base font-semibold tracking-tight">
206 Settings
207 </h3>
208 <div className="mt-3 space-y-3">
209 <Card asChild className="flex cursor-pointer items-start justify-between gap-4 p-4 transition-colors hover:border-line-strong">
210 <label>
211 <span className="min-w-0">
212 <span className="block text-sm font-medium">Security updates</span>
213 <span className="mt-1 block text-sm text-muted">
214 Open a pull request to upgrade each vulnerable dependency that has a fix. It lands through your branch's
215 required checks.
216 </span>
217 {upkeep.data?.error && <span className="mt-1 block text-xs text-danger">{upkeep.data.error}</span>}
218 </span>
219 <Hint label={whyNot(can, "manage_settings")} disabled={!can.manage_settings}>
220 <Switch
221 className="mt-0.5"
222 checked={upkeepOn}
223 disabled={upkeep.state !== "idle" || !can.manage_settings}
224 onCheckedChange={(checked) => upkeep.submit({ intent: "upkeep", enabled: String(checked) }, { method: "post", action })}
225 />
226 </Hint>
227 </label>
228 </Card>
229 </div>
230 </section>
231 </div>
232 );
233}