internal/deps/osv.go
302 lines · 7937 bytes
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}