internal/control/deps.go

343 lines · 12222 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"slices"
  8	"strconv"
  9	"strings"
 10
 11	"gitbay.org/gitbay/internal/deps"
 12	"gitbay.org/gitbay/internal/policy"
 13	"gitbay.org/gitbay/internal/protocol"
 14	"gitbay.org/gitbay/internal/store"
 15)
 16
 17func init() {
 18	// Dependency update and advisory checks. Opt-in per repository: the
 19	// check tells a public registry and OSV what the repository depends on,
 20	// which is the owner's disclosure to make, not the instance's.
 21	register(Command{Path: []string{"repo", "deps", "enable"},
 22		Summary:  "check dependencies for updates and advisories",
 23		Usage:    "repo deps enable <owner/name>",
 24		Examples: []string{"repo deps enable krz/gitbay"},
 25		Run:      runDepsEnable})
 26	register(Command{Path: []string{"repo", "deps", "disable"},
 27		Summary:  "stop checking dependencies",
 28		Usage:    "repo deps disable <owner/name>",
 29		Examples: []string{"repo deps disable krz/gitbay"},
 30		Run:      runDepsDisable})
 31	register(Command{Path: []string{"repo", "deps", "status"},
 32		Summary:  "show dependency check state",
 33		Usage:    "repo deps status <owner/name>",
 34		Examples: []string{"repo deps status krz/gitbay"},
 35		ReadOnly: true, Run: runDepsStatus})
 36	register(Command{Path: []string{"repo", "deps", "dismiss"},
 37		Summary: "dismiss dependency advisories, which then stay out of the issue",
 38		Usage:   "repo deps dismiss <owner/name> <advisory>... --reason not-affected|wont-fix|dev-only",
 39		Flags: []Flag{
 40			{"--reason", "not-affected|wont-fix|dev-only", "why: does not apply, accepted, or only in development", ""},
 41		},
 42		Examples: []string{"repo deps dismiss krz/gitbay GO-2026-5932 --reason not-affected"},
 43		Run:      runDepsDismiss})
 44	register(Command{Path: []string{"repo", "deps", "reopen"},
 45		Summary:  "take back dismissals of dependency advisories",
 46		Usage:    "repo deps reopen <owner/name> <advisory>...",
 47		Examples: []string{"repo deps reopen krz/gitbay GO-2026-5932"},
 48		Run:      runDepsReopen})
 49}
 50
 51// Reasons an advisory is dismissed for.
 52var advisoryReasons = []string{"not-affected", "wont-fix", "dev-only"}
 53
 54// DepsOut is what `repo deps status` emits: the check's state and what
 55// the last run found behind or matching an advisory. Named so the web
 56// decodes the same struct the command writes.
 57type DepsOut struct {
 58	Enabled             bool          `json:"enabled"`
 59	LastCheck           string        `json:"last_check,omitempty"`
 60	LastError           string        `json:"last_error,omitempty"`
 61	IssueNumber         int64         `json:"issue_number,omitempty"`
 62	AdvisoryIssueNumber int64         `json:"advisory_issue_number,omitempty"`
 63	Behind              []DepBehind   `json:"behind"`
 64	Advisories          []DepAdvisory `json:"advisories"`
 65	// Dismissed and NotImported are matching advisories left out of the
 66	// issue: dismissed by a writer, or Go advisories for packages no file
 67	// imports.
 68	Dismissed   []DepAdvisory `json:"dismissed"`
 69	NotImported []DepAdvisory `json:"not_imported"`
 70}
 71
 72// DepBehind is one dependency with a newer release than the manifest pins.
 73type DepBehind struct {
 74	Ecosystem string `json:"ecosystem"`
 75	Name      string `json:"name"`
 76	Current   string `json:"current"`
 77	Latest    string `json:"latest"`
 78}
 79
 80// DepAdvisory is one published advisory matching a resolved dependency.
 81type DepAdvisory struct {
 82	Ecosystem string `json:"ecosystem"`
 83	Name      string `json:"name"`
 84	Version   string `json:"version"`
 85	ID        string `json:"id"`
 86	Summary   string `json:"summary"`
 87	Severity  string `json:"severity,omitempty"`
 88	Fixed     string `json:"fixed,omitempty"`
 89	Reason    string `json:"reason,omitempty"`
 90	By        string `json:"dismissed_by,omitempty"`
 91}
 92
 93func runDepsEnable(c *Ctx, args []string) int {
 94	if len(args) != 1 {
 95		return c.usage()
 96	}
 97	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 98	if code >= 0 {
 99		return code
100	}
101	if err := c.Store.EnableDepCheck(repo.ID); err != nil {
102		return c.fail(protocol.ExitFailure, "%v", err)
103	}
104	return c.emit(map[string]any{"enabled": true}, func(w io.Writer) {
105		fmt.Fprintf(w, "dependency checks enabled on %s\n", repo.Path())
106	})
107}
108
109func runDepsDisable(c *Ctx, args []string) int {
110	if len(args) != 1 {
111		return c.usage()
112	}
113	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
114	if code >= 0 {
115		return code
116	}
117	if err := c.Store.DisableDepCheck(repo.ID); err != nil {
118		return c.fail(protocol.ExitFailure, "%v", err)
119	}
120	return c.emit(map[string]any{"enabled": false}, func(w io.Writer) {
121		fmt.Fprintf(w, "dependency checks disabled on %s\n", repo.Path())
122	})
123}
124
125func runDepsStatus(c *Ctx, args []string) int {
126	if len(args) != 1 {
127		return c.usage()
128	}
129	repo, code := resolveRepo(c, args[0], policy.CanRead)
130	if code >= 0 {
131		return code
132	}
133	check, err := c.Store.DepCheckFor(repo.ID)
134	if errors.Is(err, store.ErrNotFound) {
135		return c.emitView(map[string]any{"enabled": false}, func(w io.Writer) {
136			v := c.view(w)
137			v.fields("checks", fmt.Sprintf("off (repo deps enable %s)", repo.Path()))
138		}, func() screen {
139			return screen{
140				fields:  []field{{"Checks", []cell{cText("off")}}},
141				actions: []action{{"Deps", []string{"repo", "deps", "enable", repo.Path()}}},
142			}
143		})
144	}
145	if err != nil {
146		return c.fail(protocol.ExitFailure, "%v", err)
147	}
148	reports, err := c.Store.ReportedDeps(repo.ID)
149	if err != nil {
150		return c.fail(protocol.ExitFailure, "%v", err)
151	}
152	advisories, err := c.Store.ReportedAdvisories(repo.ID)
153	if err != nil {
154		return c.fail(protocol.ExitFailure, "%v", err)
155	}
156	dismissed, err := c.Store.AdvisoryDismissals(repo.ID)
157	if err != nil {
158		return c.fail(protocol.ExitFailure, "%v", err)
159	}
160	out := DepsOut{Enabled: true, LastCheck: check.LastCheck, LastError: check.LastError,
161		IssueNumber: check.IssueNumber, AdvisoryIssueNumber: check.AdvisoryIssueNumber,
162		Behind: []DepBehind{}, Advisories: []DepAdvisory{}, Dismissed: []DepAdvisory{}, NotImported: []DepAdvisory{}}
163	for _, r := range reports {
164		out.Behind = append(out.Behind, DepBehind{r.Ecosystem, r.Name, r.Current, r.Latest})
165	}
166	for _, a := range advisories {
167		o := DepAdvisory{Ecosystem: a.Ecosystem, Name: a.Name, Version: a.Version, ID: a.ID,
168			Summary: a.Summary, Severity: a.Severity, Fixed: a.Fixed}
169		switch d, ok := dismissed[a.ID]; {
170		case a.NotImported:
171			out.NotImported = append(out.NotImported, o)
172		case ok:
173			o.Reason, o.By = d.Reason, d.By
174			out.Dismissed = append(out.Dismissed, o)
175		default:
176			out.Advisories = append(out.Advisories, o)
177		}
178	}
179	return c.emitView(out, func(w io.Writer) {
180		tracked, advised := "", ""
181		if check.IssueNumber != 0 {
182			tracked = fmt.Sprintf("#%d", check.IssueNumber)
183		}
184		if check.AdvisoryIssueNumber != 0 {
185			advised = fmt.Sprintf("#%d", check.AdvisoryIssueNumber)
186		}
187		v := c.view(w)
188		v.fields(
189			"checks", "on",
190			"last check", c.when(check.LastCheck),
191			"last error", check.LastError,
192			"tracked in", tracked,
193			"advisories in", advised,
194		)
195		if len(out.Behind) > 0 {
196			v.section("behind")
197			tb := c.table(w, "ECOSYSTEM", "NAME", "CURRENT", "LATEST")
198			for _, b := range out.Behind {
199				tb.row(cText(b.Ecosystem), cRef(b.Name), cText(b.Current), cText(b.Latest))
200			}
201			tb.flush()
202		}
203		if len(out.Advisories) > 0 {
204			v.section("advisories")
205			tb := c.table(w, "ECOSYSTEM", "NAME", "VERSION", "ADVISORY", "FIXED")
206			for _, a := range out.Advisories {
207				tb.row(cText(a.Ecosystem), cRef(a.Name), cText(a.Version), cText(a.ID), cText(a.Fixed))
208			}
209			tb.flush()
210		}
211		if len(out.Dismissed) > 0 {
212			v.section("dismissed")
213			tb := c.table(w, "ADVISORY", "NAME", "REASON", "BY")
214			for _, a := range out.Dismissed {
215				tb.row(cText(a.ID), cRef(a.Name), cText(a.Reason), cText(a.By))
216			}
217			tb.flush()
218		}
219		if len(out.NotImported) > 0 {
220			v.section("not imported")
221			tb := c.table(w, "ADVISORY", "NAME", "VERSION")
222			for _, a := range out.NotImported {
223				tb.row(cText(a.ID), cRef(a.Name), cText(a.Version))
224			}
225			tb.flush()
226		}
227	}, func() screen {
228		state := []cell{cGlyph("ok"), cText("on")}
229		if check.LastError != "" {
230			state = []cell{cGlyph("failed"), cText("on")}
231		}
232		s := screen{fields: []field{
233			{"Checks", state},
234			{"Last check", []cell{cAge(check.LastCheck)}},
235			{"Error", []cell{cMark(check.LastError, sgrRed)}},
236		}}
237		if check.IssueNumber != 0 {
238			n := strconv.FormatInt(check.IssueNumber, 10)
239			s.fields = append(s.fields, field{"Tracked in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}})
240		}
241		if check.AdvisoryIssueNumber != 0 {
242			n := strconv.FormatInt(check.AdvisoryIssueNumber, 10)
243			s.fields = append(s.fields, field{"Advisories in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}})
244		}
245		behind := section{title: "Behind", n: len(out.Behind)}
246		for _, b := range out.Behind {
247			behind.rows = append(behind.rows, rowOf(cRef(b.Name), cText(b.Ecosystem), cMeta(b.Current+" → "+b.Latest)))
248		}
249		advised := section{title: "Advisories", n: len(out.Advisories)}
250		for _, a := range out.Advisories {
251			fix := a.Version
252			if a.Fixed != "" {
253				fix += " → " + a.Fixed
254			}
255			advised.rows = append(advised.rows, rowOf(cRef(a.Name), cMark(a.ID, sgrRed), cMeta(fix)))
256		}
257		s.sections = []section{behind, advised}
258		if len(out.Dismissed) > 0 {
259			gone := section{title: "Dismissed", n: len(out.Dismissed)}
260			for _, a := range out.Dismissed {
261				gone.rows = append(gone.rows, rowOf(cRef(a.Name), cText(a.ID), cState(a.Reason)))
262			}
263			s.sections = append(s.sections, gone)
264		}
265		if len(out.NotImported) > 0 {
266			aside := section{title: "Not imported", n: len(out.NotImported)}
267			for _, a := range out.NotImported {
268				aside.rows = append(aside.rows, rowOf(cRef(a.Name), cText(a.ID), cMeta(a.Version)))
269			}
270			s.sections = append(s.sections, aside)
271		}
272		s.actions = []action{{"Deps", []string{"repo", "deps", "disable", repo.Path()}}}
273		if len(out.Advisories) > 0 {
274			s.actions = append(s.actions, action{"Deps", []string{"repo", "deps", "dismiss", repo.Path(), "<id>", "--reason", "<why>"}})
275		}
276		return s
277	})
278}
279
280func runDepsDismiss(c *Ctx, args []string) int {
281	f, err := c.parseArgs(args, flagSpec{Values: []string{"--reason"}, MaxPos: -1, Usage: c.Cmd.Usage})
282	if err != nil {
283		return c.fail(protocol.ExitUsage, "%v", err)
284	}
285	if len(f.Pos) < 2 {
286		return c.usage()
287	}
288	reason := f.Value("--reason")
289	if !slices.Contains(advisoryReasons, reason) {
290		return c.fail(protocol.ExitUsage, "--reason is one of %s", strings.Join(advisoryReasons, ", "))
291	}
292	return changeAdvisoryDismissals(c, f.Pos[0], f.Pos[1:], func(repoID int64, ids []string) error {
293		return c.Store.DismissAdvisories(repoID, c.User.ID, ids, reason)
294	}, "dismissed")
295}
296
297func runDepsReopen(c *Ctx, args []string) int {
298	if len(args) < 2 {
299		return c.usage()
300	}
301	return changeAdvisoryDismissals(c, args[0], args[1:], c.Store.ReopenAdvisories, "reopened")
302}
303
304// changeAdvisoryDismissals checks advisory ids against the last check's
305// matches, applies change, and rewrites the issue to match. Writers may do
306// it, as for code scanning.
307func changeAdvisoryDismissals(c *Ctx, name string, ids []string, change func(int64, []string) error, verb string) int {
308	repo, code := resolveRepo(c, name, policy.CanWrite)
309	if code >= 0 {
310		return code
311	}
312	if _, err := c.Store.DepCheckFor(repo.ID); errors.Is(err, store.ErrNotFound) {
313		return c.fail(protocol.ExitFailure, "dependency checks are off on %s (repo deps enable %s)", repo.Path(), repo.Path())
314	} else if err != nil {
315		return c.fail(protocol.ExitFailure, "%v", err)
316	}
317	matched, err := c.Store.ReportedAdvisories(repo.ID)
318	if err != nil {
319		return c.fail(protocol.ExitFailure, "%v", err)
320	}
321	var known []string
322	for _, a := range matched {
323		known = append(known, a.ID)
324	}
325	var unique []string
326	for _, id := range ids {
327		if !slices.Contains(known, id) {
328			return c.fail(protocol.ExitNotFound, "no advisory %q in the last check", id)
329		}
330		if !slices.Contains(unique, id) {
331			unique = append(unique, id)
332		}
333	}
334	if err := change(repo.ID, unique); err != nil {
335		return c.fail(protocol.ExitFailure, "%v", err)
336	}
337	if err := deps.MaintainAdvisories(c.Store, c.Cfg, repo, matched, true, func() error { return nil }); err != nil {
338		return c.fail(protocol.ExitFailure, "%v", err)
339	}
340	return c.emit(map[string]any{verb: unique}, func(w io.Writer) {
341		fmt.Fprintf(w, "%s %d on %s\n", verb, len(unique), repo.Path())
342	})
343}