internal/deps/report.go

221 lines · 6782 bytes

  1package deps
  2
  3import (
  4	"fmt"
  5	"sort"
  6	"strings"
  7
  8	"gitbay.org/gitbay/internal/botissue"
  9	"gitbay.org/gitbay/internal/config"
 10	"gitbay.org/gitbay/internal/store"
 11)
 12
 13// IssueTitle is fixed so the issue this worker maintains is recognizable
 14// across sweeps, in listings, and to the maintainer.
 15const IssueTitle = "Dependency updates available"
 16
 17// AdvisoryTitle is the advisories issue's, fixed for the same reason.
 18const AdvisoryTitle = "Known vulnerabilities in dependencies"
 19
 20// ecosystemNames are how the four appear in the issue body.
 21var ecosystemNames = map[string]string{
 22	EcoGo:    "Go",
 23	EcoNPM:   "npm",
 24	EcoCargo: "Cargo",
 25	EcoPyPI:  "PyPI",
 26	EcoSwift: "Swift",
 27}
 28
 29// order is the sequence sections appear in.
 30var order = []string{EcoGo, EcoNPM, EcoCargo, EcoPyPI, EcoSwift}
 31
 32// Body renders the issue: one table per ecosystem, sorted, so a diff
 33// between sweeps reads as a diff of what is behind.
 34func Body(branch string, reports []store.DepReport) string {
 35	var b strings.Builder
 36	fmt.Fprintf(&b, "Dependencies declared on `%s` are behind their latest release. "+
 37		"This issue is kept up to date as that changes, and closed once nothing is behind.\n", branch)
 38	byEco := map[string][]store.DepReport{}
 39	for _, r := range reports {
 40		byEco[r.Ecosystem] = append(byEco[r.Ecosystem], r)
 41	}
 42	for _, eco := range order {
 43		rows := byEco[eco]
 44		if len(rows) == 0 {
 45			continue
 46		}
 47		sort.Slice(rows, func(i, j int) bool { return rows[i].Name < rows[j].Name })
 48		fmt.Fprintf(&b, "\n### %s\n\n", ecosystemNames[eco])
 49		cells := [][]string{{"Package", "Current", "Latest"}}
 50		for _, r := range rows {
 51			cells = append(cells, []string{"`" + r.Name + "`", r.Current, r.Latest})
 52		}
 53		b.WriteString(table(cells))
 54	}
 55	return b.String()
 56}
 57
 58// AdvisoryReport is what the advisories issue says: the advisories still
 59// open, how many were dismissed, and the Go ones set aside because no file
 60// imports the packages they name.
 61type AdvisoryReport struct {
 62	Repo, Branch string
 63	Open         []store.DepAdvisory
 64	Dismissed    int
 65	NotImported  []store.DepAdvisory
 66}
 67
 68// AdvisoryBody renders the advisories issue: a table per ecosystem, then
 69// each advisory's summary and link, which would make the table too wide to
 70// read as plain text, then what is not listed.
 71func AdvisoryBody(r AdvisoryReport) string {
 72	var b strings.Builder
 73	fmt.Fprintf(&b, "Dependencies resolved on `%s` match published advisories. "+
 74		"This issue is kept up to date as that changes, and closed once none are open.\n", r.Branch)
 75	byEco := map[string][]store.DepAdvisory{}
 76	for _, a := range r.Open {
 77		byEco[a.Ecosystem] = append(byEco[a.Ecosystem], a)
 78	}
 79	for _, eco := range order {
 80		rows := byEco[eco]
 81		if len(rows) == 0 {
 82			continue
 83		}
 84		fmt.Fprintf(&b, "\n### %s\n\n", ecosystemNames[eco])
 85		cells := [][]string{{"Package", "Version", "Advisory", "Severity", "Fixed in"}}
 86		for _, a := range rows {
 87			cells = append(cells, []string{"`" + a.Name + "`", a.Version, a.ID, a.Severity, a.Fixed})
 88		}
 89		b.WriteString(table(cells))
 90	}
 91	if len(r.Open) > 0 {
 92		b.WriteString("\n### Advisories\n\n")
 93		seen := map[string]bool{}
 94		for _, a := range r.Open {
 95			if seen[a.ID] {
 96				continue
 97			}
 98			seen[a.ID] = true
 99			fmt.Fprintf(&b, "- %s: %s https://osv.dev/vulnerability/%s\n", a.ID, a.Summary, a.ID)
100		}
101	}
102	var notListed []string
103	if r.Dismissed > 0 {
104		notListed = append(notListed, fmt.Sprintf("%d dismissed", r.Dismissed))
105	}
106	if len(r.NotImported) > 0 {
107		var ids []string
108		for _, a := range r.NotImported {
109			ids = append(ids, fmt.Sprintf("%s (`%s`)", a.ID, a.Name))
110		}
111		notListed = append(notListed, "for Go packages no file here imports: "+strings.Join(ids, ", "))
112	}
113	if len(notListed) > 0 {
114		fmt.Fprintf(&b, "\nNot listed: %s. Imports through another module are not seen here. `repo deps status %s` shows them.\n",
115			strings.Join(notListed, "; "), r.Repo)
116	}
117	if len(r.Open) > 0 {
118		fmt.Fprintf(&b, "\nTo dismiss one: `repo deps dismiss %s <advisory> --reason not-affected|wont-fix|dev-only`.\n", r.Repo)
119	}
120	return b.String()
121}
122
123// MaintainAdvisories brings the advisories issue in line with a matching
124// set: the open ones listed, the dismissed and not imported ones counted,
125// closed when none are open.
126func MaintainAdvisories(st *store.Store, cfg config.Config, repo store.Repo, matched []store.DepAdvisory,
127	changed bool, save func() error) error {
128	check, err := st.DepCheckFor(repo.ID)
129	if err != nil {
130		return err
131	}
132	dismissed, err := st.AdvisoryDismissals(repo.ID)
133	if err != nil {
134		return err
135	}
136	r := AdvisoryReport{Repo: repo.Path(), Branch: repo.DefaultBranch}
137	for _, a := range matched {
138		switch {
139		case a.NotImported:
140			r.NotImported = append(r.NotImported, a)
141		case dismissed[a.ID].ID != "":
142			r.Dismissed++
143		default:
144			r.Open = append(r.Open, a)
145		}
146	}
147	return botissue.Maintain(st, cfg, repo, botissue.Tracked{
148		Title:   AdvisoryTitle,
149		Number:  check.AdvisoryIssueNumber,
150		Record:  func(n int64) error { return st.SetDepAdvisoryIssue(repo.ID, n) },
151		Empty:   len(r.Open) == 0,
152		Changed: changed,
153		Save:    save,
154		Body:    func() string { return AdvisoryBody(r) },
155	})
156}
157
158// table pads every cell to its column, because the body is read twice: as
159// a rendered table on the web, where the padding is ignored, and as the
160// plain text of the notification mail, where it is the only thing keeping
161// the columns readable. Row 0 is the header.
162func table(cells [][]string) string {
163	w := make([]int, len(cells[0]))
164	for _, c := range cells {
165		for i := range w {
166			if n := len(c[i]); n > w[i] {
167				w[i] = n
168			}
169		}
170	}
171	var b strings.Builder
172	row := func(c []string) {
173		b.WriteString("|")
174		for i := range w {
175			fmt.Fprintf(&b, " %-*s |", w[i], c[i])
176		}
177		b.WriteString("\n")
178	}
179	row(cells[0])
180	rule := make([]string, len(w))
181	for i := range w {
182		rule[i] = strings.Repeat("-", w[i])
183	}
184	row(rule)
185	for _, c := range cells[1:] {
186		row(c)
187	}
188	return b.String()
189}
190
191// same reports whether two outdated sets are equal, which is what decides
192// between leaving the issue alone and rewriting it. Both sides arrive
193// sorted by (ecosystem, name).
194func same(a, b []store.DepReport) bool {
195	if len(a) != len(b) {
196		return false
197	}
198	for i := range a {
199		if a[i] != b[i] {
200			return false
201		}
202	}
203	return true
204}
205
206// sameAdvisories reports whether two matching sets name the same
207// advisories against the same versions. A summary or severity edited
208// upstream does not count as a change worth a notification.
209func sameAdvisories(a, b []store.DepAdvisory) bool {
210	if len(a) != len(b) {
211		return false
212	}
213	for i := range a {
214		if a[i].Ecosystem != b[i].Ecosystem || a[i].Name != b[i].Name ||
215			a[i].Version != b[i].Version || a[i].ID != b[i].ID || a[i].Fixed != b[i].Fixed ||
216			a[i].NotImported != b[i].NotImported {
217			return false
218		}
219	}
220	return true
221}