Commit a30ca59fb3

a30ca59fb34da7180bb533d546b6a0de237ed718

parent: 71f104fd43

Verified · cmc ci/build: success ci/quality: success ci/test: success

cmc <hello@cleberg.net> · 2026-10-31 06:23 UTC

deps: report known vulnerabilities from OSV

The dependency sweep now also sends each opted-in repository's resolved
set to OSV's querybatch and maintains a second issue, "Known
vulnerabilities in dependencies", with the same lifecycle as the updates
issue. The resolved set comes from lockfiles (go.mod including indirect
requirements, package-lock.json, Cargo.lock, uv.lock, poetry.lock,
Package.resolved at the root and inside Xcode bundles), or from exact
pins in manifests when there is no lockfile. SwiftPM is covered for
advisories only.

Migration 0080 adds dep_checks.advisory_issue_number and dep_advisories.
repo deps status and the settings page list the matches.

Closes #338

Layout: unified · split

.gitbay/wiki/Architecture/01-System-Context.org +1
@@ -39,6 +39,7 @@ do not reimplement logic (=internal/httpd/control.go=,
3939| Webhook endpoints | out | event delivery, user-configured | =internal/webhook/webhook.go= |
4040| Mirror remotes | out / in | push and pull mirrors, user-configured | =internal/mirror/mirror.go= |
4141| Package registries | out | dependency update checks (opt-in per repo)| =internal/deps/registry.go= |
42| OSV | out | dependency advisory checks (same opt-in) | =internal/deps/osv.go= |
4243| Offsite object storage | out | restic backups (host timer, not gitbayd) | documented: Admin wiki |
4344
4445gitbayd makes no other outbound connection: no telemetry or update
.gitbay/wiki/Architecture/03-Deployment.org +1
@@ -66,6 +66,7 @@ a database check.
6666| Webhook URLs | recorded events | yes when https; certificate verified | private, shared, loopback, link-local and multicast targets refused at save and again at connect time; no redirects (=internal/webhook/webhook.go=) |
6767| Mirror URLs | mirror schedule | per URL | address check at save and before each sync; git pinned to the checked addresses, no redirects (=internal/mirror/mirror.go=) |
6868| Package registries | dependency checks | yes | fixed hosts; only the package name varies (=internal/deps/registry.go=) |
69| OSV (=api.osv.dev=) | dependency checks | yes | fixed host; sent ecosystem, package name and version (=internal/deps/osv.go=) |
6970
7071* Host firewall
7172
.gitbay/wiki/Architecture/06-Data-and-Cryptography.org +1 −1
@@ -19,7 +19,7 @@ content (as confidential as the repository), *O* operational.
1919| Notifications | =notifications= (mail queue), =inbox=, =push_devices= (APNs token), =push_queue=, =mail_replies= (Message-IDs of posted replies) | P | device tokens sealed; looked up by SHA-256 |
2020| Signatures | =commit_signatures=, =settings.key_epoch= | O | verification cache |
2121| Audit and feed | =audit_log=, =events= | O, P | actor ids, pruned argv, fingerprints and IPs in some audit rows, a hash chain (=prev_hash=, =hash=) |
22| Dependencies | =dep_checks=, =dep_reports= | O | |
22| Dependencies | =dep_checks=, =dep_reports=, =dep_advisories= | O | |
2323
2424Outside the database:
2525
.gitbay/wiki/Architecture/07-CI-and-Supply-Chain.org +1 −1
@@ -78,7 +78,7 @@ Who may do what:
7878|-------------+----------------------+--------------------------------------------------------------------------------|
7979| Webhooks | recorded events | SSRF checks at save and connect time, no redirects, HMAC-SHA256 signature, 5 attempts with exponential backoff, response body capped at 4 KiB (=internal/webhook/webhook.go=) |
8080| Mirrors | schedule | address check at save and before each sync, git pinned to the checked addresses, no redirects; token via =GIT_ASKPASS= script (0700); heads and tags only; 10-minute timeout (=internal/mirror/mirror.go=) |
81| Dependency checks | schedule, opt-in | fixed registry hosts; package names restricted (=internal/deps/registry.go=) |
81| Dependency checks | schedule, opt-in | fixed registry hosts and OSV; package names restricted (=internal/deps/registry.go=, =internal/deps/osv.go=) |
8282
8383* The project's own supply chain
8484
.gitbay/wiki/Parity.org +6 −5
@@ -280,11 +280,12 @@ The web's watch and pin controls dispatch =repo pin=/=repo unpin= and
280280muted.
281281
282282Dependency checks are off until a repository's admin turns them on: the
283check tells a public registry what the repository depends on. =repo deps
284status= lists what is behind; the repository's settings page renders the
285same report under the toggle — last check, last error, the tracking
286issue, and the rows. The issue the worker opens, rewrites and closes is
287still the copy every other surface reads.
283check tells a public registry and OSV what the repository depends on.
284=repo deps status= lists what is behind and which advisories match the
285resolved set; the repository's settings page renders the same report
286under the toggle — last check, last error, the two tracking issues, and
287the rows. The issues the worker opens, rewrites and closes are still the
288copies every other surface reads.
288289
289290The wiki row covers reading. A wiki lives at =.gitbay/wiki/= on the
290291default branch, so editing one is editing a file in the repository —
cmd/gitbay/summaries_gen.go +1 −1
@@ -166,7 +166,7 @@ var summaries = map[string]string{
166166 "repo deploy-key list": "list deploy keys",
167167 "repo deploy-key remove": "remove a deploy key",
168168 "repo deps disable": "stop checking dependencies",
169 "repo deps enable": "check dependencies for updates",
169 "repo deps enable": "check dependencies for updates and advisories",
170170 "repo deps status": "show dependency check state",
171171 "repo diff": "the patch between two refs, from their merge base",
172172 "repo domain add": "claim a custom pages domain (verify with a DNS TXT record)",
internal/control/deps.go +60 −14
@@ -12,11 +12,11 @@ import (
1212)
1313
1414func init() {
15 // Dependency update checks. Opt-in per repository: the check tells a
16 // public registry what the repository depends on, which is the owner's
17 // disclosure to make, not the instance's.
15 // Dependency update and advisory checks. Opt-in per repository: the
16 // check tells a public registry and OSV what the repository depends on,
17 // which is the owner's disclosure to make, not the instance's.
1818 register(Command{Path: []string{"repo", "deps", "enable"},
19 Summary: "check dependencies for updates",
19 Summary: "check dependencies for updates and advisories",
2020 Usage: "repo deps enable <owner/name>",
2121 Examples: []string{"repo deps enable krz/gitbay"},
2222 Run: runDepsEnable})
@@ -33,14 +33,16 @@ func init() {
3333}
3434
3535// DepsOut is what `repo deps status` emits: the check's state and what
36// the last run found behind. Named so the web decodes the same struct
37// the command writes.
36// the last run found behind or matching an advisory. Named so the web
37// decodes the same struct the command writes.
3838type DepsOut struct {
39 Enabled bool `json:"enabled"`
40 LastCheck string `json:"last_check,omitempty"`
41 LastError string `json:"last_error,omitempty"`
42 IssueNumber int64 `json:"issue_number,omitempty"`
43 Behind []DepBehind `json:"behind"`
39 Enabled bool `json:"enabled"`
40 LastCheck string `json:"last_check,omitempty"`
41 LastError string `json:"last_error,omitempty"`
42 IssueNumber int64 `json:"issue_number,omitempty"`
43 AdvisoryIssueNumber int64 `json:"advisory_issue_number,omitempty"`
44 Behind []DepBehind `json:"behind"`
45 Advisories []DepAdvisory `json:"advisories"`
4446}
4547
4648// DepBehind is one dependency with a newer release than the manifest pins.
@@ -51,6 +53,17 @@ type DepBehind struct {
5153 Latest string `json:"latest"`
5254}
5355
56// DepAdvisory is one published advisory matching a resolved dependency.
57type DepAdvisory struct {
58 Ecosystem string `json:"ecosystem"`
59 Name string `json:"name"`
60 Version string `json:"version"`
61 ID string `json:"id"`
62 Summary string `json:"summary"`
63 Severity string `json:"severity,omitempty"`
64 Fixed string `json:"fixed,omitempty"`
65}
66
5467func runDepsEnable(c *Ctx, args []string) int {
5568 if len(args) != 1 {
5669 return c.usage()
@@ -110,22 +123,35 @@ func runDepsStatus(c *Ctx, args []string) int {
110123 if err != nil {
111124 return c.fail(protocol.ExitFailure, "%v", err)
112125 }
126 advisories, err := c.Store.ReportedAdvisories(repo.ID)
127 if err != nil {
128 return c.fail(protocol.ExitFailure, "%v", err)
129 }
113130 out := DepsOut{Enabled: true, LastCheck: check.LastCheck, LastError: check.LastError,
114 IssueNumber: check.IssueNumber, Behind: []DepBehind{}}
131 IssueNumber: check.IssueNumber, AdvisoryIssueNumber: check.AdvisoryIssueNumber,
132 Behind: []DepBehind{}, Advisories: []DepAdvisory{}}
115133 for _, r := range reports {
116134 out.Behind = append(out.Behind, DepBehind{r.Ecosystem, r.Name, r.Current, r.Latest})
117135 }
136 for _, a := range advisories {
137 out.Advisories = append(out.Advisories,
138 DepAdvisory{a.Ecosystem, a.Name, a.Version, a.ID, a.Summary, a.Severity, a.Fixed})
139 }
118140 return c.emitView(out, func(w io.Writer) {
119 tracked := ""
141 tracked, advised := "", ""
120142 if check.IssueNumber != 0 {
121143 tracked = fmt.Sprintf("#%d", check.IssueNumber)
122144 }
145 if check.AdvisoryIssueNumber != 0 {
146 advised = fmt.Sprintf("#%d", check.AdvisoryIssueNumber)
147 }
123148 v := c.view(w)
124149 v.fields(
125150 "checks", "on",
126151 "last check", c.when(check.LastCheck),
127152 "last error", check.LastError,
128153 "tracked in", tracked,
154 "advisories in", advised,
129155 )
130156 if len(out.Behind) > 0 {
131157 v.section("behind")
@@ -135,6 +161,14 @@ func runDepsStatus(c *Ctx, args []string) int {
135161 }
136162 tb.flush()
137163 }
164 if len(out.Advisories) > 0 {
165 v.section("advisories")
166 tb := c.table(w, "ECOSYSTEM", "NAME", "VERSION", "ADVISORY", "FIXED")
167 for _, a := range out.Advisories {
168 tb.row(cText(a.Ecosystem), cRef(a.Name), cText(a.Version), cText(a.ID), cText(a.Fixed))
169 }
170 tb.flush()
171 }
138172 }, func() screen {
139173 state := []cell{cGlyph("ok"), cText("on")}
140174 if check.LastError != "" {
@@ -149,11 +183,23 @@ func runDepsStatus(c *Ctx, args []string) int {
149183 n := strconv.FormatInt(check.IssueNumber, 10)
150184 s.fields = append(s.fields, field{"Tracked in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}})
151185 }
186 if check.AdvisoryIssueNumber != 0 {
187 n := strconv.FormatInt(check.AdvisoryIssueNumber, 10)
188 s.fields = append(s.fields, field{"Advisories in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}})
189 }
152190 behind := section{title: "Behind", n: len(out.Behind)}
153191 for _, b := range out.Behind {
154192 behind.rows = append(behind.rows, rowOf(cRef(b.Name), cText(b.Ecosystem), cMeta(b.Current+" → "+b.Latest)))
155193 }
156 s.sections = []section{behind}
194 advised := section{title: "Advisories", n: len(out.Advisories)}
195 for _, a := range out.Advisories {
196 fix := a.Version
197 if a.Fixed != "" {
198 fix += " → " + a.Fixed
199 }
200 advised.rows = append(advised.rows, rowOf(cRef(a.Name), cMark(a.ID, sgrRed), cMeta(fix)))
201 }
202 s.sections = []section{behind, advised}
157203 s.actions = []action{{"Deps", []string{"repo", "deps", "disable", repo.Path()}}}
158204 return s
159205 })
internal/control/stage3repo_test.go +32
@@ -3,6 +3,7 @@ package control
33import (
44 "bytes"
55 "crypto/ed25519"
6 "encoding/json"
67 "os"
78 "os/exec"
89 "path/filepath"
@@ -318,3 +319,34 @@ func TestRepoScreensFitSixtyColumns(t *testing.T) {
318319 }
319320 }
320321}
322
323func TestRepoDepsStatusAdvisories(t *testing.T) {
324 st, repo, u, root := browseFixture(t)
325 p := repo.Path()
326 dispatchIn(t, st, u, root, "", "repo", "deps", "enable", p)
327 if err := st.ReplaceDepAdvisories(repo.ID, []store.DepAdvisory{{Ecosystem: "go", Name: "golang.org/x/net",
328 Version: "v0.1.0", ID: "GO-2026-1", Summary: "reset flood", Severity: "high", Fixed: "0.7.0"}}); err != nil {
329 t.Fatal(err)
330 }
331 if err := st.SetDepAdvisoryIssue(repo.ID, 7); err != nil {
332 t.Fatal(err)
333 }
334 var got struct {
335 Data DepsOut `json:"data"`
336 }
337 if err := json.Unmarshal([]byte(dispatchIn(t, st, u, root, "", "repo", "deps", "status", p, "--json")), &got); err != nil {
338 t.Fatal(err)
339 }
340 if got.Data.AdvisoryIssueNumber != 7 || len(got.Data.Advisories) != 1 || got.Data.Advisories[0].ID != "GO-2026-1" {
341 t.Errorf("status = %+v", got.Data)
342 }
343 plain := dispatchIn(t, st, u, root, "", "repo", "deps", "status", p)
344 if !strings.Contains(plain, "advisories in #7") || !strings.Contains(plain, "GO-2026-1") {
345 t.Errorf("plain:\n%s", plain)
346 }
347 out := atTerminalIn(t, st, u, root, "repo", "deps", "status", p)
348 if !strings.Contains(out, "Advisories (1)") || !strings.Contains(out, "v0.1.0 → 0.7.0") {
349 t.Errorf("screen:\n%s", out)
350 }
351 checkLegend(t, out)
352}
internal/deps/gomod.go +7 −2
@@ -6,7 +6,12 @@ import "strings"
66// requirements are the module graph's business rather than the maintainer's,
77// and a replaced module does not come from the proxy at all, so both are
88// skipped.
9func parseGoMod(read ReadFile) []Dep {
9func parseGoMod(read ReadFile) []Dep { return goRequires(read, false) }
10
11// goRequires reads go.mod's requirements, the indirect ones too when asked.
12// Since Go 1.17 go.mod lists every module the build selects, so with them it
13// is the resolved set.
14func goRequires(read ReadFile, withIndirect bool) []Dep {
1015 raw, err := read("go.mod")
1116 if err != nil {
1217 return nil
@@ -41,7 +46,7 @@ func parseGoMod(read ReadFile) []Dep {
4146 }
4247 fields := strings.Fields(line)
4348 switch {
44 case directive == "require" && !indirect && len(fields) >= 2:
49 case directive == "require" && (withIndirect || !indirect) && len(fields) >= 2:
4550 reqs = append(reqs, [2]string{fields[0], fields[1]})
4651 case directive == "replace" && len(fields) >= 1:
4752 replaced[fields[0]] = true
internal/deps/osv.go added +302
@@ -0,0 +1,302 @@
1package deps
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "sort"
12 "strings"
13 "sync"
14
15 "gitbay.org/gitbay/internal/store"
16)
17
18// osvAPI is OSV's public API, a fixed host like the registries. What it is
19// sent is the resolved set: ecosystem, package name and version.
20const osvAPI = "https://api.osv.dev"
21
22// osvEcosystems are OSV's names for the ecosystems read here.
23var osvEcosystems = map[string]string{
24 EcoGo: "Go",
25 EcoNPM: "npm",
26 EcoCargo: "crates.io",
27 EcoPyPI: "PyPI",
28 EcoSwift: "SwiftURL",
29}
30
31// osvBatch is the most queries one querybatch request may carry.
32const osvBatch = 1000
33
34// osvPages bounds how far a query with more matches than one response holds
35// is followed. A package with that many advisories is reported in part.
36const osvPages = 5
37
38// maxAdvisories bounds the advisory records fetched for one repository.
39const maxAdvisories = 300
40
41type osvQuery struct {
42 Package struct {
43 Ecosystem string `json:"ecosystem"`
44 Name string `json:"name"`
45 } `json:"package"`
46 Version string `json:"version"`
47 PageToken string `json:"page_token,omitempty"`
48}
49
50// osvVuln is the part of an OSV record the issue reports.
51type osvVuln struct {
52 ID string `json:"id"`
53 Summary string `json:"summary"`
54 Details string `json:"details"`
55 Aliases []string `json:"aliases"`
56 Withdrawn string `json:"withdrawn"`
57 Affected []struct {
58 Package struct {
59 Ecosystem string `json:"ecosystem"`
60 Name string `json:"name"`
61 } `json:"package"`
62 Ranges []struct {
63 Events []struct {
64 Fixed string `json:"fixed"`
65 } `json:"events"`
66 } `json:"ranges"`
67 } `json:"affected"`
68 DatabaseSpecific struct {
69 Severity string `json:"severity"`
70 } `json:"database_specific"`
71}
72
73// Advisories returns the published advisories matching the resolved set.
74// One record often appears under several IDs (a GHSA and a PYSEC for the
75// same flaw); each is reported once per dependency, under whichever ID
76// sorts first. Withdrawn advisories are left out.
77func (c *Client) Advisories(ctx context.Context, found []Dep) ([]store.DepAdvisory, error) {
78 ids, err := c.matches(ctx, found)
79 if err != nil {
80 return nil, err
81 }
82 records, err := c.records(ctx, ids)
83 if err != nil {
84 return nil, err
85 }
86 var out []store.DepAdvisory
87 for i, d := range found {
88 seen := map[string]bool{}
89 for _, id := range ids[i] {
90 v, ok := records[id]
91 if !ok || seen[id] || v.Withdrawn != "" {
92 continue
93 }
94 seen[id] = true
95 for _, alias := range v.Aliases {
96 seen[alias] = true
97 }
98 out = append(out, store.DepAdvisory{
99 Ecosystem: d.Ecosystem, Name: d.Name, Version: d.Current, ID: v.ID,
100 Summary: summarize(v), Severity: strings.ToLower(v.DatabaseSpecific.Severity),
101 Fixed: fixedAfter(v, osvEcosystems[d.Ecosystem], d.Name, d.Current),
102 })
103 }
104 }
105 return out, nil
106}
107
108// matches asks OSV which advisory IDs affect each dependency, returning
109// them sorted, indexed like found.
110func (c *Client) matches(ctx context.Context, found []Dep) ([][]string, error) {
111 ids := make([][]string, len(found))
112 var pending []int
113 queries := make([]osvQuery, len(found))
114 for i, d := range found {
115 queries[i].Package.Ecosystem = osvEcosystems[d.Ecosystem]
116 queries[i].Package.Name = d.Name
117 queries[i].Version = d.Current
118 pending = append(pending, i)
119 }
120 for page := 0; len(pending) > 0 && page < osvPages; page++ {
121 var next []int
122 for start := 0; start < len(pending); start += osvBatch {
123 chunk := pending[start:min(start+osvBatch, len(pending))]
124 batch := make([]osvQuery, len(chunk))
125 for j, i := range chunk {
126 batch[j] = queries[i]
127 }
128 results, err := c.queryBatch(ctx, batch)
129 if err != nil {
130 return nil, err
131 }
132 for j, i := range chunk {
133 if j >= len(results) {
134 break
135 }
136 for _, v := range results[j].Vulns {
137 ids[i] = append(ids[i], v.ID)
138 }
139 if results[j].NextPageToken != "" {
140 queries[i].PageToken = results[j].NextPageToken
141 next = append(next, i)
142 }
143 }
144 }
145 pending = next
146 }
147 for i := range ids {
148 sort.Strings(ids[i])
149 }
150 return ids, nil
151}
152
153type osvResult struct {
154 Vulns []struct {
155 ID string `json:"id"`
156 } `json:"vulns"`
157 NextPageToken string `json:"next_page_token"`
158}
159
160func (c *Client) queryBatch(ctx context.Context, batch []osvQuery) ([]osvResult, error) {
161 payload, err := json.Marshal(map[string]any{"queries": batch})
162 if err != nil {
163 return nil, err
164 }
165 req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.osv()+"/v1/querybatch", bytes.NewReader(payload))
166 if err != nil {
167 return nil, err
168 }
169 req.Header.Set("Content-Type", "application/json")
170 body, err := c.do(req)
171 if err != nil {
172 return nil, err
173 }
174 var doc struct {
175 Results []osvResult `json:"results"`
176 }
177 if err := json.Unmarshal(body, &doc); err != nil {
178 return nil, fmt.Errorf("osv querybatch: %w", err)
179 }
180 return doc.Results, nil
181}
182
183// records fetches each distinct advisory once. One that fails to fetch is
184// dropped from this sweep, as a failed registry lookup is; all of them
185// failing is an error.
186func (c *Client) records(ctx context.Context, ids [][]string) (map[string]osvVuln, error) {
187 var distinct []string
188 seen := map[string]bool{}
189 for _, list := range ids {
190 for _, id := range list {
191 if !seen[id] && len(distinct) < maxAdvisories {
192 seen[id] = true
193 distinct = append(distinct, id)
194 }
195 }
196 }
197 var (
198 mu sync.Mutex
199 out = map[string]osvVuln{}
200 failed []error
201 wg sync.WaitGroup
202 tickets = make(chan struct{}, lookups)
203 )
204 for _, id := range distinct {
205 wg.Add(1)
206 go func(id string) {
207 defer wg.Done()
208 tickets <- struct{}{}
209 defer func() { <-tickets }()
210 v, err := c.record(ctx, id)
211 mu.Lock()
212 defer mu.Unlock()
213 if err != nil {
214 failed = append(failed, err)
215 return
216 }
217 out[id] = v
218 }(id)
219 }
220 wg.Wait()
221 if ctx.Err() != nil {
222 return nil, ctx.Err()
223 }
224 if len(failed) > 0 && len(failed) == len(distinct) {
225 return nil, failed[0]
226 }
227 return out, nil
228}
229
230func (c *Client) record(ctx context.Context, id string) (osvVuln, error) {
231 var v osvVuln
232 req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.osv()+"/v1/vulns/"+url.PathEscape(id), nil)
233 if err != nil {
234 return v, err
235 }
236 body, err := c.do(req)
237 if err != nil {
238 return v, err
239 }
240 if err := json.Unmarshal(body, &v); err != nil {
241 return v, fmt.Errorf("osv %s: %w", id, err)
242 }
243 return v, nil
244}
245
246func (c *Client) osv() string {
247 if c.OSV != "" {
248 return c.OSV
249 }
250 return osvAPI
251}
252
253func (c *Client) do(req *http.Request) ([]byte, error) {
254 req.Header.Set("User-Agent", "gitbay/"+c.Version+" (+https://gitbay.org)")
255 resp, err := c.HTTP.Do(req)
256 if err != nil {
257 return nil, err
258 }
259 defer resp.Body.Close()
260 if resp.StatusCode != http.StatusOK {
261 return nil, fmt.Errorf("%s: %s", req.URL, resp.Status)
262 }
263 return io.ReadAll(io.LimitReader(resp.Body, maxBody))
264}
265
266// summarize is the record's summary, or the first line of its details when
267// it has none, cut to fit a table cell.
268func summarize(v osvVuln) string {
269 s := strings.TrimSpace(v.Summary)
270 if s == "" {
271 s, _, _ = strings.Cut(strings.TrimSpace(v.Details), "\n")
272 }
273 s = strings.Join(strings.Fields(s), " ")
274 if r := []rune(s); len(r) > 120 {
275 s = string(r[:119]) + "…"
276 }
277 return s
278}
279
280// fixedAfter is the lowest fixed release above current among the record's
281// ranges for this package, or "" when no fix is published. A record can
282// carry one range per maintained branch, so the lowest one past current is
283// the nearest upgrade that clears it.
284func fixedAfter(v osvVuln, ecosystem, name, current string) string {
285 best := ""
286 for _, a := range v.Affected {
287 if a.Package.Ecosystem != ecosystem || a.Package.Name != name {
288 continue
289 }
290 for _, r := range a.Ranges {
291 for _, e := range r.Events {
292 if e.Fixed == "" || !Newer(current, e.Fixed) {
293 continue
294 }
295 if best == "" || Newer(e.Fixed, best) {
296 best = e.Fixed
297 }
298 }
299 }
300 }
301 return best
302}
internal/deps/osv_test.go added +99
@@ -0,0 +1,99 @@
1package deps
2
3import (
4 "context"
5 "encoding/json"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10)
11
12// fakeOSV answers querybatch from matches, keyed "ecosystem name version",
13// and serves records by ID.
14func fakeOSV(t *testing.T, matches map[string][]string, records map[string]string) *httptest.Server {
15 t.Helper()
16 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17 if r.URL.Path == "/v1/querybatch" {
18 var req struct {
19 Queries []osvQuery `json:"queries"`
20 }
21 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
22 http.Error(w, err.Error(), 400)
23 return
24 }
25 var results []map[string]any
26 for _, q := range req.Queries {
27 var vulns []map[string]string
28 for _, id := range matches[q.Package.Ecosystem+" "+q.Package.Name+" "+q.Version] {
29 vulns = append(vulns, map[string]string{"id": id})
30 }
31 results = append(results, map[string]any{"vulns": vulns})
32 }
33 json.NewEncoder(w).Encode(map[string]any{"results": results})
34 return
35 }
36 body, ok := records[strings.TrimPrefix(r.URL.Path, "/v1/vulns/")]
37 if !ok {
38 http.NotFound(w, r)
39 return
40 }
41 w.Write([]byte(body))
42 }))
43 t.Cleanup(srv.Close)
44 return srv
45}
46
47func TestAdvisories(t *testing.T) {
48 srv := fakeOSV(t, map[string][]string{
49 "PyPI flask 2.0.0": {"GHSA-aaaa", "PYSEC-1"},
50 "Go golang.org/x/net v0.1.0": {"GO-2", "GO-withdrawn"},
51 "SwiftURL github.com/vapor/vapor 4.0.0": {"GHSA-vapor"},
52 }, map[string]string{
53 "GHSA-aaaa": `{"id":"GHSA-aaaa","summary":"Session cookie\nleak","aliases":["PYSEC-1"],
54 "database_specific":{"severity":"HIGH"},
55 "affected":[{"package":{"ecosystem":"PyPI","name":"flask"},
56 "ranges":[{"events":[{"introduced":"0"},{"fixed":"1.9.0"}]},{"events":[{"introduced":"2.0.0"},{"fixed":"2.3.2"}]},{"events":[{"introduced":"2.0.0"},{"fixed":"2.2.5"}]}]}]}`,
57 "PYSEC-1": `{"id":"PYSEC-1","summary":"duplicate","aliases":["GHSA-aaaa"]}`,
58 "GO-2": `{"id":"GO-2","details":"First line.\nSecond line.","affected":[{"package":{"ecosystem":"Go","name":"golang.org/x/net"},"ranges":[{"events":[{"fixed":"0.7.0"}]}]}]}`,
59 "GO-withdrawn": `{"id":"GO-withdrawn","withdrawn":"2026-01-01T00:00:00Z"}`,
60 "GHSA-vapor": `{"id":"GHSA-vapor","summary":"no fix"}`,
61 })
62 c := NewClient("test")
63 c.OSV = srv.URL
64 got, err := c.Advisories(context.Background(), []Dep{
65 {Ecosystem: EcoGo, Name: "golang.org/x/net", Current: "v0.1.0"},
66 {Ecosystem: EcoPyPI, Name: "flask", Current: "2.0.0"},
67 {Ecosystem: EcoPyPI, Name: "clean", Current: "1.0.0"},
68 {Ecosystem: EcoSwift, Name: "github.com/vapor/vapor", Current: "4.0.0"},
69 })
70 if err != nil {
71 t.Fatal(err)
72 }
73 if len(got) != 3 {
74 t.Fatalf("advisories = %+v, want GO-2, GHSA-aaaa once, GHSA-vapor", got)
75 }
76 if a := got[0]; a.ID != "GO-2" || a.Summary != "First line." || a.Fixed != "0.7.0" || a.Severity != "" {
77 t.Errorf("go advisory = %+v", a)
78 }
79 // The alias is folded in, the summary's whitespace collapsed, and the
80 // nearest fix past 2.0.0 chosen over the branch fixes either side.
81 if a := got[1]; a.ID != "GHSA-aaaa" || a.Summary != "Session cookie leak" || a.Severity != "high" || a.Fixed != "2.2.5" {
82 t.Errorf("pypi advisory = %+v", a)
83 }
84 if a := got[2]; a.ID != "GHSA-vapor" || a.Fixed != "" {
85 t.Errorf("swift advisory = %+v", a)
86 }
87}
88
89func TestAdvisoriesFailWhenOSVIsDown(t *testing.T) {
90 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
91 http.Error(w, "down", http.StatusServiceUnavailable)
92 }))
93 t.Cleanup(srv.Close)
94 c := NewClient("test")
95 c.OSV = srv.URL
96 if _, err := c.Advisories(context.Background(), []Dep{{Ecosystem: EcoGo, Name: "x", Current: "v1.0.0"}}); err == nil {
97 t.Fatal("an unreachable OSV read as no advisories")
98 }
99}
internal/deps/python.go +5 −2
@@ -10,7 +10,10 @@ import (
1010// that name one release are reported: a bare `requests` or a `>=2,<3` range
1111// says the project accepts whatever is current, so there is nothing to tell
1212// its maintainer.
13func parsePython(read ReadFile) []Dep {
13func parsePython(read ReadFile) []Dep { return pythonDeps(read, pin) }
14
15// pythonDeps reads both files, reducing each requirement with pinned.
16func pythonDeps(read ReadFile, pinned func(string) string) []Dep {
1417 seen := map[string]bool{}
1518 var out []Dep
1619 add := func(name, version string) {
@@ -18,7 +21,7 @@ func parsePython(read ReadFile) []Dep {
1821 if name == "" || name == "python" || seen[name] {
1922 return
2023 }
21 if v := pin(version); v != "" {
24 if v := pinned(version); v != "" {
2225 seen[name] = true
2326 out = append(out, Dep{Ecosystem: EcoPyPI, Name: name, Current: v})
2427 }
internal/deps/registry.go +1
@@ -34,6 +34,7 @@ var safeName = regexp.MustCompile(`^@?[A-Za-z0-9][A-Za-z0-9._/@+-]*$`)
3434type Client struct {
3535 HTTP *http.Client
3636 Hosts map[string]string // overridden in tests
37 OSV string // osvAPI unless overridden in tests
3738 Version string // reported in User-Agent
3839}
3940
internal/deps/report.go +71 −8
@@ -12,16 +12,20 @@ import (
1212// across sweeps, in listings, and to the maintainer.
1313const IssueTitle = "Dependency updates available"
1414
15// AdvisoryTitle is the advisories issue's, fixed for the same reason.
16const AdvisoryTitle = "Known vulnerabilities in dependencies"
17
1518// ecosystemNames are how the four appear in the issue body.
1619var ecosystemNames = map[string]string{
1720 EcoGo: "Go",
1821 EcoNPM: "npm",
1922 EcoCargo: "Cargo",
2023 EcoPyPI: "PyPI",
24 EcoSwift: "Swift",
2125}
2226
2327// order is the sequence sections appear in.
24var order = []string{EcoGo, EcoNPM, EcoCargo, EcoPyPI}
28var order = []string{EcoGo, EcoNPM, EcoCargo, EcoPyPI, EcoSwift}
2529
2630// Body renders the issue: one table per ecosystem, sorted, so a diff
2731// between sweeps reads as a diff of what is behind.
@@ -40,21 +44,56 @@ func Body(branch string, reports []store.DepReport) string {
4044 }
4145 sort.Slice(rows, func(i, j int) bool { return rows[i].Name < rows[j].Name })
4246 fmt.Fprintf(&b, "\n### %s\n\n", ecosystemNames[eco])
43 cells := [][3]string{{"Package", "Current", "Latest"}}
47 cells := [][]string{{"Package", "Current", "Latest"}}
4448 for _, r := range rows {
45 cells = append(cells, [3]string{"`" + r.Name + "`", r.Current, r.Latest})
49 cells = append(cells, []string{"`" + r.Name + "`", r.Current, r.Latest})
4650 }
4751 b.WriteString(table(cells))
4852 }
4953 return b.String()
5054}
5155
56// AdvisoryBody renders the advisories issue: a table per ecosystem, then
57// each advisory's summary and link, which would make the table too wide to
58// read as plain text.
59func AdvisoryBody(branch string, matched []store.DepAdvisory) string {
60 var b strings.Builder
61 fmt.Fprintf(&b, "Dependencies resolved on `%s` match published advisories. "+
62 "This issue is kept up to date as that changes, and closed once none match.\n", branch)
63 byEco := map[string][]store.DepAdvisory{}
64 for _, a := range matched {
65 byEco[a.Ecosystem] = append(byEco[a.Ecosystem], a)
66 }
67 for _, eco := range order {
68 rows := byEco[eco]
69 if len(rows) == 0 {
70 continue
71 }
72 fmt.Fprintf(&b, "\n### %s\n\n", ecosystemNames[eco])
73 cells := [][]string{{"Package", "Version", "Advisory", "Severity", "Fixed in"}}
74 for _, a := range rows {
75 cells = append(cells, []string{"`" + a.Name + "`", a.Version, a.ID, a.Severity, a.Fixed})
76 }
77 b.WriteString(table(cells))
78 }
79 b.WriteString("\n### Advisories\n\n")
80 seen := map[string]bool{}
81 for _, a := range matched {
82 if seen[a.ID] {
83 continue
84 }
85 seen[a.ID] = true
86 fmt.Fprintf(&b, "- %s: %s https://osv.dev/vulnerability/%s\n", a.ID, a.Summary, a.ID)
87 }
88 return b.String()
89}
90
5291// table pads every cell to its column, because the body is read twice: as
5392// a rendered table on the web, where the padding is ignored, and as the
5493// plain text of the notification mail, where it is the only thing keeping
5594// the columns readable. Row 0 is the header.
56func table(cells [][3]string) string {
57 var w [3]int
95func table(cells [][]string) string {
96 w := make([]int, len(cells[0]))
5897 for _, c := range cells {
5998 for i := range w {
6099 if n := len(c[i]); n > w[i] {
@@ -63,11 +102,19 @@ func table(cells [][3]string) string {
63102 }
64103 }
65104 var b strings.Builder
66 row := func(c [3]string) {
67 fmt.Fprintf(&b, "| %-*s | %-*s | %-*s |\n", w[0], c[0], w[1], c[1], w[2], c[2])
105 row := func(c []string) {
106 b.WriteString("|")
107 for i := range w {
108 fmt.Fprintf(&b, " %-*s |", w[i], c[i])
109 }
110 b.WriteString("\n")
68111 }
69112 row(cells[0])
70 row([3]string{strings.Repeat("-", w[0]), strings.Repeat("-", w[1]), strings.Repeat("-", w[2])})
113 rule := make([]string, len(w))
114 for i := range w {
115 rule[i] = strings.Repeat("-", w[i])
116 }
117 row(rule)
71118 for _, c := range cells[1:] {
72119 row(c)
73120 }
@@ -88,3 +135,19 @@ func same(a, b []store.DepReport) bool {
88135 }
89136 return true
90137}
138
139// sameAdvisories reports whether two matching sets name the same
140// advisories against the same versions. A summary or severity edited
141// upstream does not count as a change worth a notification.
142func sameAdvisories(a, b []store.DepAdvisory) bool {
143 if len(a) != len(b) {
144 return false
145 }
146 for i := range a {
147 if a[i].Ecosystem != b[i].Ecosystem || a[i].Name != b[i].Name ||
148 a[i].Version != b[i].Version || a[i].ID != b[i].ID || a[i].Fixed != b[i].Fixed {
149 return false
150 }
151 }
152 return true
153}
internal/deps/report_test.go +16
@@ -41,3 +41,19 @@ func TestBodyAlignsColumns(t *testing.T) {
4141 t.Errorf("row not padded to its column:\n%s", body)
4242 }
4343}
44
45func TestAdvisoryBody(t *testing.T) {
46 body := AdvisoryBody("main", []store.DepAdvisory{
47 {Ecosystem: EcoGo, Name: "golang.org/x/net", Version: "v0.1.0", ID: "GO-2", Summary: "HTTP/2 reset", Severity: "", Fixed: "0.7.0"},
48 {Ecosystem: EcoPyPI, Name: "flask", Version: "2.0.0", ID: "GHSA-aaaa", Summary: "cookie leak", Severity: "high", Fixed: "2.2.5"},
49 })
50 for _, want := range []string{
51 "| `golang.org/x/net` | v0.1.0 | GO-2 | | 0.7.0 |",
52 "- GHSA-aaaa: cookie leak https://osv.dev/vulnerability/GHSA-aaaa",
53 "### PyPI",
54 } {
55 if !strings.Contains(body, want) {
56 t.Errorf("body missing %q:\n%s", want, body)
57 }
58 }
59}
internal/deps/resolved.go added +300
@@ -0,0 +1,300 @@
1package deps
2
3import (
4 "encoding/json"
5 "sort"
6 "strings"
7
8 "github.com/BurntSushi/toml"
9)
10
11// EcoSwift is reported for advisories only. Scan has no Swift reader: a
12// SwiftPM dependency is a git URL on any host, and finding its latest
13// release would mean listing tags on hosts the repository names.
14const EcoSwift = "swift"
15
16// MaxResolved bounds the resolved set one repository sends for advisory
17// matching. A lockfile lists the whole graph, so it is larger than MaxDeps.
18const MaxResolved = 3000
19
20// swiftResolvedDirs are where Xcode keeps Package.resolved inside a project
21// or workspace bundle at the repository root.
22var swiftResolvedDirs = map[string]string{
23 ".xcodeproj": "/project.xcworkspace/xcshareddata/swiftpm/Package.resolved",
24 ".xcworkspace": "/xcshareddata/swiftpm/Package.resolved",
25}
26
27// Resolved returns every dependency whose exact version is known, for
28// advisory matching: lockfiles where they exist, exact pins in manifests
29// where they do not. A range is left out rather than reduced to its floor,
30// since the floor is rarely what is installed and would match advisories
31// the build does not have. root lists the names at the top of the tree,
32// which is where Xcode bundles are looked for.
33func Resolved(read ReadFile, root []string) []Dep {
34 var out []Dep
35 out = append(out, goRequires(read, true)...)
36 out = append(out, npmResolved(read)...)
37 out = append(out, cargoResolved(read)...)
38 out = append(out, pythonResolved(read)...)
39 out = append(out, swiftResolved(read, root)...)
40 sort.Slice(out, func(i, j int) bool {
41 if out[i].Ecosystem != out[j].Ecosystem {
42 return out[i].Ecosystem < out[j].Ecosystem
43 }
44 if out[i].Name != out[j].Name {
45 return out[i].Name < out[j].Name
46 }
47 return out[i].Current < out[j].Current
48 })
49 out = dedupe(out)
50 if len(out) > MaxResolved {
51 out = out[:MaxResolved]
52 }
53 return out
54}
55
56func dedupe(sorted []Dep) []Dep {
57 var out []Dep
58 for i, d := range sorted {
59 if i > 0 && d == sorted[i-1] {
60 continue
61 }
62 out = append(out, d)
63 }
64 return out
65}
66
67// exact is pin restricted to a requirement that names one release: bare,
68// or after `==` or `=`. `^1.2` is a range in npm and Cargo, and so is a bare
69// `1.2` in Cargo, which is why Cargo callers check for `=` themselves.
70func exact(spec string) string {
71 s := strings.TrimSpace(spec)
72 s = strings.TrimPrefix(s, "==")
73 s = strings.TrimPrefix(s, "=")
74 if s == "" || strings.ContainsAny(s[:1], "^~<>!") {
75 return ""
76 }
77 return pin(s)
78}
79
80// npmResolved reads every install in package-lock.json, nested copies
81// included, or the exact pins in package.json when there is no lockfile.
82func npmResolved(read ReadFile) []Dep {
83 if raw, err := read("package-lock.json"); err == nil {
84 var lock struct {
85 Packages map[string]struct {
86 Version string `json:"version"`
87 Link bool `json:"link"`
88 } `json:"packages"`
89 }
90 if json.Unmarshal(raw, &lock) != nil {
91 return nil
92 }
93 var out []Dep
94 for path, entry := range lock.Packages {
95 i := strings.LastIndex(path, "node_modules/")
96 if i < 0 || entry.Link {
97 continue
98 }
99 if v := pin(entry.Version); v != "" {
100 out = append(out, Dep{Ecosystem: EcoNPM, Name: path[i+len("node_modules/"):], Current: v})
101 }
102 }
103 return out
104 }
105 raw, err := read("package.json")
106 if err != nil {
107 return nil
108 }
109 var pkg struct {
110 Dependencies map[string]string `json:"dependencies"`
111 DevDependencies map[string]string `json:"devDependencies"`
112 }
113 if json.Unmarshal(raw, &pkg) != nil {
114 return nil
115 }
116 var out []Dep
117 for _, set := range []map[string]string{pkg.Dependencies, pkg.DevDependencies} {
118 for name, spec := range set {
119 if v := exact(spec); v != "" {
120 out = append(out, Dep{Ecosystem: EcoNPM, Name: name, Current: v})
121 }
122 }
123 }
124 return out
125}
126
127// cargoResolved reads the crates.io packages in Cargo.lock, or the `=`
128// pins in Cargo.toml when there is no lockfile.
129func cargoResolved(read ReadFile) []Dep {
130 if raw, err := read("Cargo.lock"); err == nil {
131 var lock struct {
132 Package []struct {
133 Name string `toml:"name"`
134 Version string `toml:"version"`
135 Source string `toml:"source"`
136 } `toml:"package"`
137 }
138 if toml.Unmarshal(raw, &lock) != nil {
139 return nil
140 }
141 var out []Dep
142 for _, p := range lock.Package {
143 // No source is a workspace member; a git source is not on
144 // crates.io.
145 if !strings.HasPrefix(p.Source, "registry+") && !strings.HasPrefix(p.Source, "sparse+") {
146 continue
147 }
148 if v := pin(p.Version); v != "" {
149 out = append(out, Dep{Ecosystem: EcoCargo, Name: p.Name, Current: v})
150 }
151 }
152 return out
153 }
154 raw, err := read("Cargo.toml")
155 if err != nil {
156 return nil
157 }
158 var manifest struct {
159 Dependencies map[string]any `toml:"dependencies"`
160 DevDependencies map[string]any `toml:"dev-dependencies"`
161 BuildDependencies map[string]any `toml:"build-dependencies"`
162 }
163 if toml.Unmarshal(raw, &manifest) != nil {
164 return nil
165 }
166 var out []Dep
167 for _, set := range []map[string]any{manifest.Dependencies, manifest.DevDependencies, manifest.BuildDependencies} {
168 for name, spec := range set {
169 req, ok := cargoRequirement(spec)
170 if !ok || !strings.HasPrefix(strings.TrimSpace(req), "=") {
171 continue
172 }
173 if v := exact(req); v != "" {
174 out = append(out, Dep{Ecosystem: EcoCargo, Name: name, Current: v})
175 }
176 }
177 }
178 return out
179}
180
181// pythonResolved reads uv.lock or poetry.lock, or the `==` pins in
182// requirements.txt and pyproject.toml when there is neither.
183func pythonResolved(read ReadFile) []Dep {
184 for _, lockfile := range []string{"uv.lock", "poetry.lock"} {
185 raw, err := read(lockfile)
186 if err != nil {
187 continue
188 }
189 var lock struct {
190 Package []struct {
191 Name string `toml:"name"`
192 Version string `toml:"version"`
193 Source map[string]any `toml:"source"`
194 } `toml:"package"`
195 }
196 if toml.Unmarshal(raw, &lock) != nil {
197 return nil
198 }
199 var out []Dep
200 for _, p := range lock.Package {
201 if !fromPyPI(p.Source) {
202 continue
203 }
204 if v := pin(p.Version); v != "" {
205 out = append(out, Dep{Ecosystem: EcoPyPI, Name: normalizePyPI(p.Name), Current: v})
206 }
207 }
208 return out
209 }
210 return pythonDeps(read, exact)
211}
212
213// fromPyPI reads a lockfile package's source. uv records
214// `source = { registry = "..." }` for an index and `editable`, `virtual`,
215// `path`, `directory` or `git` otherwise; poetry records no source for PyPI
216// and a typed one otherwise.
217func fromPyPI(source map[string]any) bool {
218 if len(source) == 0 {
219 return true
220 }
221 if _, ok := source["registry"]; ok {
222 return true
223 }
224 typ, _ := source["type"].(string)
225 return typ == "legacy"
226}
227
228// swiftResolved reads Package.resolved at the root and inside any Xcode
229// project or workspace at the root. Version 1 files nest the pins under
230// `object` and name the URL `repositoryURL`; versions 2 and 3 use `pins`
231// and `location`. A pin to a branch or a revision has no version and is
232// left out.
233func swiftResolved(read ReadFile, root []string) []Dep {
234 paths := []string{"Package.resolved"}
235 for _, name := range root {
236 for suffix, inside := range swiftResolvedDirs {
237 if strings.HasSuffix(name, suffix) {
238 paths = append(paths, name+inside)
239 }
240 }
241 }
242 sort.Strings(paths[1:])
243 var out []Dep
244 for _, path := range paths {
245 raw, err := read(path)
246 if err != nil {
247 continue
248 }
249 type pinned struct {
250 Location string `json:"location"`
251 RepositoryURL string `json:"repositoryURL"`
252 State struct {
253 Version string `json:"version"`
254 } `json:"state"`
255 }
256 var doc struct {
257 Pins []pinned `json:"pins"`
258 Object struct {
259 Pins []pinned `json:"pins"`
260 } `json:"object"`
261 }
262 if json.Unmarshal(raw, &doc) != nil {
263 continue
264 }
265 for _, p := range append(doc.Pins, doc.Object.Pins...) {
266 url := p.Location
267 if url == "" {
268 url = p.RepositoryURL
269 }
270 name := swiftURLName(url)
271 if v := pin(p.State.Version); v != "" && name != "" {
272 out = append(out, Dep{Ecosystem: EcoSwift, Name: name, Current: v})
273 }
274 }
275 }
276 return out
277}
278
279// swiftURLName reduces a package URL to the form OSV's SwiftURL ecosystem
280// keys on: host and path, no scheme, user or .git suffix.
281// `https://github.com/vapor/vapor.git` and `git@github.com:vapor/vapor`
282// both become `github.com/vapor/vapor`. A local path has no name.
283func swiftURLName(url string) string {
284 u := strings.TrimSpace(url)
285 if i := strings.Index(u, "://"); i >= 0 {
286 u = u[i+3:]
287 } else if at := strings.Index(u, "@"); at >= 0 && strings.Contains(u[at:], ":") {
288 u = strings.Replace(u[at+1:], ":", "/", 1)
289 } else {
290 return ""
291 }
292 if at := strings.Index(u, "@"); at >= 0 && at < strings.Index(u+"/", "/") {
293 u = u[at+1:]
294 }
295 u = strings.TrimSuffix(strings.TrimSuffix(u, "/"), ".git")
296 if !strings.Contains(u, "/") || strings.HasPrefix(u, "/") {
297 return ""
298 }
299 return u
300}
internal/deps/resolved_test.go added +112
@@ -0,0 +1,112 @@
1package deps
2
3import "testing"
4
5func TestResolvedReadsLockfiles(t *testing.T) {
6 got := found(t, Resolved(tree(map[string]string{
7 "go.mod": `module x
8
9require (
10 github.com/a/direct v1.0.0
11 github.com/a/indirect v0.2.0 // indirect
12 github.com/a/replaced v1.0.0
13)
14
15replace github.com/a/replaced => ../replaced
16`,
17 "package-lock.json": `{"packages":{
18 "": {"name":"app"},
19 "node_modules/left-pad": {"version":"1.3.0"},
20 "node_modules/a/node_modules/nested": {"version":"2.0.0"},
21 "node_modules/linked": {"link": true}
22 }}`,
23 "package.json": `{"dependencies":{"ignored-when-locked":"1.0.0"}}`,
24 "Cargo.lock": `
25[[package]]
26name = "serde"
27version = "1.0.197"
28source = "registry+https://github.com/rust-lang/crates.io-index"
29
30[[package]]
31name = "member"
32version = "0.1.0"
33
34[[package]]
35name = "from-git"
36version = "0.3.0"
37source = "git+https://example.com/x.git#abc"
38`,
39 "uv.lock": `
40[[package]]
41name = "Requests"
42version = "2.31.0"
43source = { registry = "https://pypi.org/simple" }
44
45[[package]]
46name = "app"
47version = "0.1.0"
48source = { editable = "." }
49`,
50 "Package.resolved": `{"pins":[
51 {"identity":"vapor","location":"https://github.com/vapor/vapor.git","state":{"version":"4.0.0"}},
52 {"identity":"branchy","location":"https://github.com/x/branchy","state":{"branch":"main","revision":"abc"}}
53 ],"version":2}`,
54 "App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved": `{"object":{"pins":[
55 {"package":"Sparkle","repositoryURL":"git@github.com:sparkle-project/Sparkle.git","state":{"version":"2.6.0"}}
56 ]},"version":1}`,
57 }), []string{"go.mod", "App.xcodeproj", "Sources"}))
58
59 want := map[string]string{
60 "go:github.com/a/direct": "v1.0.0",
61 "go:github.com/a/indirect": "v0.2.0",
62 "npm:left-pad": "1.3.0",
63 "npm:nested": "2.0.0",
64 "cargo:serde": "1.0.197",
65 "pypi:requests": "2.31.0",
66 "swift:github.com/vapor/vapor": "4.0.0",
67 "swift:github.com/sparkle-project/Sparkle": "2.6.0",
68 }
69 for k, v := range want {
70 if got[k] != v {
71 t.Errorf("%s = %q, want %q", k, got[k], v)
72 }
73 }
74 if len(got) != len(want) {
75 t.Errorf("resolved %v, want exactly %v", got, want)
76 }
77}
78
79// Without a lockfile only exact pins are sent: a range's floor is rarely
80// what is installed, and would match advisories the build does not have.
81func TestResolvedWithoutLockfilesKeepsExactPins(t *testing.T) {
82 got := found(t, Resolved(tree(map[string]string{
83 "package.json": `{"dependencies":{"exact":"1.2.3","caret":"^1.2.3","tilde":"~1.2.3"}}`,
84 "Cargo.toml": "[dependencies]\npinned = \"=1.0.0\"\ncaret = \"1.0\"\n",
85 "requirements.txt": "flask==3.0.0\nrequests>=2.31\nbare\n",
86 }), nil))
87 want := map[string]string{"npm:exact": "1.2.3", "cargo:pinned": "1.0.0", "pypi:flask": "3.0.0"}
88 for k, v := range want {
89 if got[k] != v {
90 t.Errorf("%s = %q, want %q", k, got[k], v)
91 }
92 }
93 if len(got) != len(want) {
94 t.Errorf("resolved %v, want exactly %v", got, want)
95 }
96}
97
98func TestSwiftURLName(t *testing.T) {
99 for in, want := range map[string]string{
100 "https://github.com/vapor/vapor.git": "github.com/vapor/vapor",
101 "https://github.com/vapor/vapor": "github.com/vapor/vapor",
102 "git@github.com:vapor/vapor.git": "github.com/vapor/vapor",
103 "ssh://git@gitbay.org/krz/org-swift": "gitbay.org/krz/org-swift",
104 "https://user@example.com/a/b.git/": "example.com/a/b",
105 "/Users/me/local-package": "",
106 "../sibling": "",
107 } {
108 if got := swiftURLName(in); got != want {
109 t.Errorf("swiftURLName(%q) = %q, want %q", in, got, want)
110 }
111 }
112}
internal/deps/worker.go +95 −22
@@ -23,7 +23,8 @@ const manifestLimit = 1 << 20
2323const lookups = 4
2424
2525// Worker sweeps repositories that have opted in, comparing their manifests
26// against the registries and maintaining one issue per repository.
26// against the registries and OSV and maintaining up to two issues per
27// repository: one for updates, one for advisories.
2728type Worker struct {
2829 St *store.Store
2930 Cfg config.Config
@@ -83,17 +84,32 @@ func (w *Worker) Sweep(ctx context.Context) {
8384 }
8485}
8586
86// check compares one repository against the registries and reconciles its
87// issue with the result.
87// check compares one repository against the registries and OSV, and
88// reconciles its two issues with the result. A failure on one side leaves
89// the other reconciled, and leaves its own issue as it was rather than
90// closing it on an answer that never came.
8891func (w *Worker) check(ctx context.Context, repo store.Repo) error {
8992 dir := w.RepoDir(repo.OwnerName, repo.Name)
9093 sha, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch)
9194 if err != nil {
9295 return nil // empty repo, or no default branch yet
9396 }
94 found := Scan(func(path string) ([]byte, error) {
97 read := func(path string) ([]byte, error) {
9598 return gitutil.ReadBlob(dir, sha, path, manifestLimit)
96 })
99 }
100 var root []string
101 if entries, err := gitutil.ListTree(dir, sha, ""); err == nil {
102 for _, e := range entries {
103 root = append(root, e.Name)
104 }
105 }
106 return errors.Join(
107 w.checkUpdates(ctx, repo, Scan(read)),
108 w.checkAdvisories(ctx, repo, Resolved(read, root)),
109 )
110}
111
112func (w *Worker) checkUpdates(ctx context.Context, repo store.Repo, found []Dep) error {
97113 if len(found) == 0 {
98114 return w.reconcile(repo, nil)
99115 }
@@ -104,6 +120,17 @@ func (w *Worker) check(ctx context.Context, repo store.Repo) error {
104120 return w.reconcile(repo, behind)
105121}
106122
123func (w *Worker) checkAdvisories(ctx context.Context, repo store.Repo, resolved []Dep) error {
124 if len(resolved) == 0 {
125 return w.reconcileAdvisories(repo, nil)
126 }
127 matched, err := w.Client.Advisories(ctx, resolved)
128 if err != nil {
129 return fmt.Errorf("advisories: %w", err)
130 }
131 return w.reconcileAdvisories(repo, matched)
132}
133
107134// behind queries the registries and keeps the dependencies whose latest
108135// release is greater than what the manifest declares. A lookup that fails
109136// is dropped rather than failing the sweep: one unreachable package should
@@ -152,9 +179,7 @@ func (w *Worker) behind(ctx context.Context, found []Dep) ([]store.DepReport, er
152179 return out, nil
153180}
154181
155// reconcile brings the repository's issue in line with what is behind:
156// opened when something first falls behind, rewritten when the set changes,
157// closed when nothing is behind any more.
182// reconcile brings the updates issue in line with what is behind.
158183func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error {
159184 check, err := w.St.DepCheckFor(repo.ID)
160185 if err != nil {
@@ -164,32 +189,80 @@ func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error {
164189 if err != nil {
165190 return err
166191 }
167 issue, hasIssue := w.openIssue(repo, check.IssueNumber)
168 if len(behind) == 0 {
192 return w.maintain(repo, tracked{
193 title: IssueTitle,
194 number: check.IssueNumber,
195 record: func(n int64) error { return w.St.SetDepIssue(repo.ID, n) },
196 empty: len(behind) == 0,
197 changed: !same(previous, behind),
198 save: func() error { return w.St.ReplaceDepReports(repo.ID, behind) },
199 body: func() string { return Body(repo.DefaultBranch, behind) },
200 })
201}
202
203// reconcileAdvisories brings the advisories issue in line with what
204// matches.
205func (w *Worker) reconcileAdvisories(repo store.Repo, matched []store.DepAdvisory) error {
206 check, err := w.St.DepCheckFor(repo.ID)
207 if err != nil {
208 return err
209 }
210 previous, err := w.St.ReportedAdvisories(repo.ID)
211 if err != nil {
212 return err
213 }
214 return w.maintain(repo, tracked{
215 title: AdvisoryTitle,
216 number: check.AdvisoryIssueNumber,
217 record: func(n int64) error { return w.St.SetDepAdvisoryIssue(repo.ID, n) },
218 empty: len(matched) == 0,
219 changed: !sameAdvisories(previous, matched),
220 save: func() error { return w.St.ReplaceDepAdvisories(repo.ID, matched) },
221 body: func() string { return AdvisoryBody(repo.DefaultBranch, matched) },
222 })
223}
224
225// tracked is one issue the worker maintains for a repository and the set
226// it reports.
227type tracked struct {
228 title string
229 number int64 // the issue last opened, 0 for none
230 record func(number int64) error
231 empty bool // nothing to report
232 changed bool // the set differs from the last report
233 save func() error
234 body func() string
235}
236
237// maintain opens the issue when something is first reported, rewrites it
238// when the set changes, and closes it when nothing is left.
239func (w *Worker) maintain(repo store.Repo, t tracked) error {
240 issue, hasIssue := w.openIssue(repo, t.number)
241 if t.empty {
169242 if hasIssue {
170243 w.St.SetIssueState(issue.ID, "closed")
171 w.St.SetDepIssue(repo.ID, 0)
244 t.record(0)
172245 }
173 if len(previous) > 0 {
174 return w.St.ReplaceDepReports(repo.ID, nil)
246 if t.changed {
247 return t.save()
175248 }
176249 return nil
177250 }
178251 // Nothing changed since the last report: leave it be, whether the issue
179252 // is still open or the maintainer has closed it. Reopening on an
180253 // unchanged set would make closing the issue pointless.
181 if same(previous, behind) {
254 if !t.changed {
182255 return nil
183256 }
184 if err := w.St.ReplaceDepReports(repo.ID, behind); err != nil {
257 if err := t.save(); err != nil {
185258 return err
186259 }
187 body := Body(repo.DefaultBranch, behind)
260 body := t.body()
188261 if hasIssue {
189262 if err := w.St.UpdateIssueText(issue.ID, nil, &body, nil); err != nil {
190263 return err
191264 }
192 w.notify(repo, issue.Number, fmt.Sprintf("updated issue #%d", issue.Number), body)
265 w.notify(repo, t.title, issue.Number, fmt.Sprintf("updated issue #%d", issue.Number), body)
193266 return nil
194267 }
195268 author, err := w.St.UserByUsername(store.BotUsername)
@@ -200,15 +273,15 @@ func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error {
200273 return fmt.Errorf("no %s account to author the issue (the name was taken when this instance upgraded): %w",
201274 store.BotUsername, err)
202275 }
203 number, err := w.St.CreateIssue(repo.ID, author.ID, IssueTitle, body, "md")
276 number, err := w.St.CreateIssue(repo.ID, author.ID, t.title, body, "md")
204277 if err != nil {
205278 return err
206279 }
207 if err := w.St.SetDepIssue(repo.ID, number); err != nil {
280 if err := t.record(number); err != nil {
208281 return err
209282 }
210283 w.St.RecordEvent(repo.ID, author.ID, "issue.created", fmt.Sprintf(`{"number":%d}`, number))
211 w.notify(repo, number, fmt.Sprintf("opened issue #%d", number), body)
284 w.notify(repo, t.title, number, fmt.Sprintf("opened issue #%d", number), body)
212285 return nil
213286}
214287
@@ -229,7 +302,7 @@ func (w *Worker) openIssue(repo store.Repo, number int64) (store.Issue, bool) {
229302// notify files an inbox row for the repo's owners and watchers and mails
230303// them, the same targets and shape as an issue opened over SSH.
231304// Best-effort, like every other notification.
232func (w *Worker) notify(repo store.Repo, number int64, action, body string) {
305func (w *Worker) notify(repo store.Repo, title string, number int64, action, body string) {
233306 targets, err := w.St.RepoNotifyTargets(repo)
234307 if err != nil {
235308 return
@@ -242,7 +315,7 @@ func (w *Worker) notify(repo store.Repo, number int64, action, body string) {
242315 if err != nil {
243316 return
244317 }
245 subject := fmt.Sprintf("[%s] #%d: %s", repo.Path(), number, IssueTitle)
318 subject := fmt.Sprintf("[%s] #%d: %s", repo.Path(), number, title)
246319 text := fmt.Sprintf("%s %s\n\n%s\n%s/%s/issues/%d\n", store.BotUsername, action, body,
247320 strings.TrimSuffix(w.Cfg.Server.SiteURL, "/"), repo.Path(), number)
248321 path := fmt.Sprintf("%s/issues/%d", repo.Path(), number)
internal/deps/worker_test.go +48
@@ -223,3 +223,51 @@ func TestReconcileLeavesClosedIssueClosedOnUnchangedSet(t *testing.T) {
223223 t.Error("the closed issue came back")
224224 }
225225}
226
227func TestReconcileAdvisoriesKeepsItsOwnIssue(t *testing.T) {
228 w, repo := testWorker(t)
229 if err := w.reconcile(repo, reports("github.com/a/b", "v1.0.0", "v1.1.0")); err != nil {
230 t.Fatal(err)
231 }
232 matched := []store.DepAdvisory{{Ecosystem: EcoGo, Name: "github.com/a/b", Version: "v1.0.0",
233 ID: "GO-1", Summary: "bad", Fixed: "1.1.0"}}
234 if err := w.reconcileAdvisories(repo, matched); err != nil {
235 t.Fatal(err)
236 }
237 check, _ := w.St.DepCheckFor(repo.ID)
238 if check.AdvisoryIssueNumber == 0 || check.AdvisoryIssueNumber == check.IssueNumber {
239 t.Fatalf("advisory issue #%d, updates issue #%d", check.AdvisoryIssueNumber, check.IssueNumber)
240 }
241 issue, _ := w.St.IssueByNumber(repo.ID, check.AdvisoryIssueNumber)
242 if issue.Title != AdvisoryTitle || !strings.Contains(issue.Body, "GO-1") {
243 t.Errorf("advisory issue = %q\n%s", issue.Title, issue.Body)
244 }
245 mail, _ := w.St.DueMail(10)
246 if len(mail) != 2 || !strings.Contains(mail[1].Subject, AdvisoryTitle) {
247 t.Fatalf("mail = %+v", mail)
248 }
249
250 // An upstream edit to the summary is not a change worth mailing.
251 edited := []store.DepAdvisory{matched[0]}
252 edited[0].Summary = "reworded"
253 if err := w.reconcileAdvisories(repo, edited); err != nil {
254 t.Fatal(err)
255 }
256 if mail, _ := w.St.DueMail(10); len(mail) != 2 {
257 t.Errorf("summary edit mailed: %d messages", len(mail))
258 }
259
260 // Fixed: the advisories issue closes, the updates issue stays open.
261 if err := w.reconcileAdvisories(repo, nil); err != nil {
262 t.Fatal(err)
263 }
264 if closed, _ := w.St.IssueByNumber(repo.ID, check.AdvisoryIssueNumber); closed.State != "closed" {
265 t.Errorf("advisory issue state = %q", closed.State)
266 }
267 if open, _ := w.St.IssueByNumber(repo.ID, check.IssueNumber); open.State != "open" {
268 t.Errorf("updates issue state = %q", open.State)
269 }
270 if left, _ := w.St.ReportedAdvisories(repo.ID); len(left) != 0 {
271 t.Errorf("advisories left behind: %v", left)
272 }
273}
internal/store/deps.go +66 −2
@@ -17,6 +17,9 @@ type DepCheck struct {
1717 LastCheck string
1818 LastError string
1919 IssueNumber int64 // 0 until an issue has been opened
20 // AdvisoryIssueNumber is the advisories issue, kept apart from the
21 // updates one.
22 AdvisoryIssueNumber int64
2023}
2124
2225// DepReport is one dependency found to be behind, as last reported.
@@ -27,6 +30,18 @@ type DepReport struct {
2730 Latest string
2831}
2932
33// DepAdvisory is one published advisory matching a resolved dependency,
34// as last reported.
35type DepAdvisory struct {
36 Ecosystem string
37 Name string
38 Version string
39 ID string
40 Summary string
41 Severity string
42 Fixed string // the first release past Version that fixes it, if any
43}
44
3045func (s *Store) EnableDepCheck(repoID int64) error {
3146 _, err := s.DB.Exec("INSERT OR IGNORE INTO dep_checks (repo_id) VALUES (?)", repoID)
3247 return err
@@ -43,6 +58,9 @@ func (s *Store) DisableDepCheck(repoID int64) error {
4358 if _, err := tx.Exec("DELETE FROM dep_reports WHERE repo_id = ?", repoID); err != nil {
4459 return err
4560 }
61 if _, err := tx.Exec("DELETE FROM dep_advisories WHERE repo_id = ?", repoID); err != nil {
62 return err
63 }
4664 if _, err := tx.Exec("DELETE FROM dep_checks WHERE repo_id = ?", repoID); err != nil {
4765 return err
4866 }
@@ -52,8 +70,8 @@ func (s *Store) DisableDepCheck(repoID int64) error {
5270func (s *Store) DepCheckFor(repoID int64) (DepCheck, error) {
5371 var d DepCheck
5472 err := s.DB.QueryRow(
55 "SELECT repo_id, last_check, last_error, issue_number FROM dep_checks WHERE repo_id = ?", repoID).
56 Scan(&d.RepoID, &d.LastCheck, &d.LastError, &d.IssueNumber)
73 "SELECT repo_id, last_check, last_error, issue_number, advisory_issue_number FROM dep_checks WHERE repo_id = ?", repoID).
74 Scan(&d.RepoID, &d.LastCheck, &d.LastError, &d.IssueNumber, &d.AdvisoryIssueNumber)
5775 if errors.Is(err, sql.ErrNoRows) {
5876 return d, ErrNotFound
5977 }
@@ -101,6 +119,11 @@ func (s *Store) SetDepIssue(repoID, number int64) error {
101119 return err
102120}
103121
122func (s *Store) SetDepAdvisoryIssue(repoID, number int64) error {
123 _, err := s.DB.Exec("UPDATE dep_checks SET advisory_issue_number = ? WHERE repo_id = ?", number, repoID)
124 return err
125}
126
104127func (s *Store) ReportedDeps(repoID int64) ([]DepReport, error) {
105128 rows, err := s.DB.Query(`
106129 SELECT ecosystem, name, current, latest FROM dep_reports
@@ -140,3 +163,44 @@ func (s *Store) ReplaceDepReports(repoID int64, reports []DepReport) error {
140163 }
141164 return tx.Commit()
142165}
166
167func (s *Store) ReportedAdvisories(repoID int64) ([]DepAdvisory, error) {
168 rows, err := s.DB.Query(`
169 SELECT ecosystem, name, version, advisory_id, summary, severity, fixed FROM dep_advisories
170 WHERE repo_id = ? ORDER BY ecosystem, name, version, advisory_id`, repoID)
171 if err != nil {
172 return nil, err
173 }
174 defer rows.Close()
175 var out []DepAdvisory
176 for rows.Next() {
177 var a DepAdvisory
178 if err := rows.Scan(&a.Ecosystem, &a.Name, &a.Version, &a.ID, &a.Summary, &a.Severity, &a.Fixed); err != nil {
179 return nil, err
180 }
181 out = append(out, a)
182 }
183 return out, rows.Err()
184}
185
186// ReplaceDepAdvisories swaps in the current matching set wholesale, as
187// ReplaceDepReports does for updates.
188func (s *Store) ReplaceDepAdvisories(repoID int64, advisories []DepAdvisory) error {
189 tx, err := s.DB.Begin()
190 if err != nil {
191 return err
192 }
193 defer tx.Rollback()
194 if _, err := tx.Exec("DELETE FROM dep_advisories WHERE repo_id = ?", repoID); err != nil {
195 return err
196 }
197 for _, a := range advisories {
198 if _, err := tx.Exec(`
199 INSERT INTO dep_advisories (repo_id, ecosystem, name, version, advisory_id, summary, severity, fixed)
200 VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
201 repoID, a.Ecosystem, a.Name, a.Version, a.ID, a.Summary, a.Severity, a.Fixed); err != nil {
202 return err
203 }
204 }
205 return tx.Commit()
206}
internal/store/migrations/0080_dep_advisories.down.sql added +2
@@ -0,0 +1,2 @@
1DROP TABLE dep_advisories;
2ALTER TABLE dep_checks DROP COLUMN advisory_issue_number;
internal/store/migrations/0080_dep_advisories.up.sql added +17
@@ -0,0 +1,17 @@
1-- Known vulnerabilities in dependencies: the same opt-in sweep checks the
2-- resolved dependency set against OSV and reports matches in an issue of
3-- its own, so an advisory is not filed among routine updates.
4ALTER TABLE dep_checks ADD COLUMN advisory_issue_number INTEGER NOT NULL DEFAULT 0;
5
6-- What each repo was last told about, as dep_reports is for updates.
7CREATE TABLE dep_advisories (
8 repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
9 ecosystem TEXT NOT NULL,
10 name TEXT NOT NULL,
11 version TEXT NOT NULL,
12 advisory_id TEXT NOT NULL,
13 summary TEXT NOT NULL DEFAULT '',
14 severity TEXT NOT NULL DEFAULT '',
15 fixed TEXT NOT NULL DEFAULT '',
16 PRIMARY KEY (repo_id, ecosystem, name, version, advisory_id)
17);
internal/web/templates/settings.html +12 −2
@@ -220,12 +220,12 @@
220220<section id="deps"><h2>Dependencies</h2>
221221<form method="post" action="{{$base}}" class="setform">
222222 <input type="hidden" name="field" value="deps">
223 <div><label for="deps-enabled">Check for updates</label><p class="hint">Evaluates the manifests on <code>{{.Repo.DefaultBranch}}</code> and opens an issue. Go, NPM, Crates, and PyPI only.</p></div>
223 <div><label for="deps-enabled">Check for updates and advisories</label><p class="hint">Evaluates the manifests and lockfiles on <code>{{.Repo.DefaultBranch}}</code> against the registries and OSV, and opens an issue for each. Updates for Go, NPM, Crates, and PyPI; advisories for those and SwiftPM.</p></div>
224224 <div class="check"><input type="checkbox" id="deps-enabled" name="deps" value="on"{{if .DepsEnabled}} checked{{end}}></div>
225225 <div><button type="submit" class="btn">Save</button></div>
226226</form>
227227{{if .DepsEnabled}}
228<p class="meta">Last checked {{if .Deps.LastCheck}}{{when .Deps.LastCheck}}{{else}}never{{end}}{{if .Deps.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Deps.IssueNumber}}">#{{.Deps.IssueNumber}}</a>{{end}}</p>
228<p class="meta">Last checked {{if .Deps.LastCheck}}{{when .Deps.LastCheck}}{{else}}never{{end}}{{if .Deps.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Deps.IssueNumber}}">#{{.Deps.IssueNumber}}</a>{{end}}{{if .Deps.AdvisoryIssueNumber}} · advisories <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Deps.AdvisoryIssueNumber}}">#{{.Deps.AdvisoryIssueNumber}}</a>{{end}}</p>
229229{{if .Deps.LastError}}<p class="error" role="alert">{{.Deps.LastError}}</p>{{end}}
230230{{if .Deps.Behind}}<div class="tablewrap"><table class="keys">
231231<tr class="cols"><th scope="col">dependency</th><th scope="col">pinned</th><th scope="col">latest</th></tr>
@@ -236,6 +236,16 @@
236236</tr>
237237{{end}}</table></div>
238238{{else}}<p class="none">Nothing behind{{if not .Deps.LastCheck}} — the first check has not run yet{{end}}.</p>{{end}}
239{{if .Deps.Advisories}}<div class="tablewrap"><table class="keys">
240<tr class="cols"><th scope="col">dependency</th><th scope="col">version</th><th scope="col">advisory</th><th scope="col">fixed in</th></tr>
241{{range .Deps.Advisories}}<tr>
242 <td class="mono">{{.Ecosystem}} {{.Name}}</td>
243 <td class="mono">{{.Version}}</td>
244 <td class="mono"><a href="https://osv.dev/vulnerability/{{.ID}}">{{.ID}}</a></td>
245 <td class="mono">{{.Fixed}}</td>
246</tr>
247{{end}}</table></div>
248{{else if .Deps.LastCheck}}<p class="none">No known advisories.</p>{{end}}
239249{{end}}
240250</section>
241251