internal/deps/osv.go

325 lines · 8577 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		EcosystemSpecific struct {
 68			Imports []struct {
 69				Path string `json:"path"`
 70			} `json:"imports"`
 71		} `json:"ecosystem_specific"`
 72	} `json:"affected"`
 73	DatabaseSpecific struct {
 74		Severity string `json:"severity"`
 75	} `json:"database_specific"`
 76}
 77
 78// Advisories returns the published advisories matching the resolved set.
 79// One record often appears under several IDs (a GHSA and a PYSEC for the
 80// same flaw); each is reported once per dependency, under whichever ID
 81// sorts first. Withdrawn advisories are left out.
 82func (c *Client) Advisories(ctx context.Context, found []Dep) ([]store.DepAdvisory, error) {
 83	ids, err := c.matches(ctx, found)
 84	if err != nil {
 85		return nil, err
 86	}
 87	records, err := c.records(ctx, ids)
 88	if err != nil {
 89		return nil, err
 90	}
 91	var out []store.DepAdvisory
 92	for i, d := range found {
 93		seen := map[string]bool{}
 94		for _, id := range ids[i] {
 95			v, ok := records[id]
 96			if !ok || seen[id] || v.Withdrawn != "" {
 97				continue
 98			}
 99			seen[id] = true
100			for _, alias := range v.Aliases {
101				seen[alias] = true
102			}
103			out = append(out, store.DepAdvisory{
104				Ecosystem: d.Ecosystem, Name: d.Name, Version: d.Current, ID: v.ID,
105				Summary: summarize(v), Severity: strings.ToLower(v.DatabaseSpecific.Severity),
106				Fixed:   fixedAfter(v, osvEcosystems[d.Ecosystem], d.Name, d.Current),
107				Imports: importsOf(v, osvEcosystems[d.Ecosystem], d.Name),
108			})
109		}
110	}
111	return out, nil
112}
113
114// matches asks OSV which advisory IDs affect each dependency, returning
115// them sorted, indexed like found.
116func (c *Client) matches(ctx context.Context, found []Dep) ([][]string, error) {
117	ids := make([][]string, len(found))
118	var pending []int
119	queries := make([]osvQuery, len(found))
120	for i, d := range found {
121		queries[i].Package.Ecosystem = osvEcosystems[d.Ecosystem]
122		queries[i].Package.Name = d.Name
123		queries[i].Version = d.Current
124		pending = append(pending, i)
125	}
126	for page := 0; len(pending) > 0 && page < osvPages; page++ {
127		var next []int
128		for start := 0; start < len(pending); start += osvBatch {
129			chunk := pending[start:min(start+osvBatch, len(pending))]
130			batch := make([]osvQuery, len(chunk))
131			for j, i := range chunk {
132				batch[j] = queries[i]
133			}
134			results, err := c.queryBatch(ctx, batch)
135			if err != nil {
136				return nil, err
137			}
138			for j, i := range chunk {
139				if j >= len(results) {
140					break
141				}
142				for _, v := range results[j].Vulns {
143					ids[i] = append(ids[i], v.ID)
144				}
145				if results[j].NextPageToken != "" {
146					queries[i].PageToken = results[j].NextPageToken
147					next = append(next, i)
148				}
149			}
150		}
151		pending = next
152	}
153	for i := range ids {
154		sort.Strings(ids[i])
155	}
156	return ids, nil
157}
158
159type osvResult struct {
160	Vulns []struct {
161		ID string `json:"id"`
162	} `json:"vulns"`
163	NextPageToken string `json:"next_page_token"`
164}
165
166func (c *Client) queryBatch(ctx context.Context, batch []osvQuery) ([]osvResult, error) {
167	payload, err := json.Marshal(map[string]any{"queries": batch})
168	if err != nil {
169		return nil, err
170	}
171	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.osv()+"/v1/querybatch", bytes.NewReader(payload))
172	if err != nil {
173		return nil, err
174	}
175	req.Header.Set("Content-Type", "application/json")
176	body, err := c.do(req)
177	if err != nil {
178		return nil, err
179	}
180	var doc struct {
181		Results []osvResult `json:"results"`
182	}
183	if err := json.Unmarshal(body, &doc); err != nil {
184		return nil, fmt.Errorf("osv querybatch: %w", err)
185	}
186	return doc.Results, nil
187}
188
189// records fetches each distinct advisory once. One that fails to fetch is
190// dropped from this sweep, as a failed registry lookup is; all of them
191// failing is an error.
192func (c *Client) records(ctx context.Context, ids [][]string) (map[string]osvVuln, error) {
193	var distinct []string
194	seen := map[string]bool{}
195	for _, list := range ids {
196		for _, id := range list {
197			if !seen[id] && len(distinct) < maxAdvisories {
198				seen[id] = true
199				distinct = append(distinct, id)
200			}
201		}
202	}
203	var (
204		mu      sync.Mutex
205		out     = map[string]osvVuln{}
206		failed  []error
207		wg      sync.WaitGroup
208		tickets = make(chan struct{}, lookups)
209	)
210	for _, id := range distinct {
211		wg.Add(1)
212		go func(id string) {
213			defer wg.Done()
214			tickets <- struct{}{}
215			defer func() { <-tickets }()
216			v, err := c.record(ctx, id)
217			mu.Lock()
218			defer mu.Unlock()
219			if err != nil {
220				failed = append(failed, err)
221				return
222			}
223			out[id] = v
224		}(id)
225	}
226	wg.Wait()
227	if ctx.Err() != nil {
228		return nil, ctx.Err()
229	}
230	if len(failed) > 0 && len(failed) == len(distinct) {
231		return nil, failed[0]
232	}
233	return out, nil
234}
235
236func (c *Client) record(ctx context.Context, id string) (osvVuln, error) {
237	var v osvVuln
238	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.osv()+"/v1/vulns/"+url.PathEscape(id), nil)
239	if err != nil {
240		return v, err
241	}
242	body, err := c.do(req)
243	if err != nil {
244		return v, err
245	}
246	if err := json.Unmarshal(body, &v); err != nil {
247		return v, fmt.Errorf("osv %s: %w", id, err)
248	}
249	return v, nil
250}
251
252func (c *Client) osv() string {
253	if c.OSV != "" {
254		return c.OSV
255	}
256	return osvAPI
257}
258
259func (c *Client) do(req *http.Request) ([]byte, error) {
260	req.Header.Set("User-Agent", "gitbay/"+c.Version+" (+https://gitbay.org)")
261	resp, err := c.HTTP.Do(req)
262	if err != nil {
263		return nil, err
264	}
265	defer resp.Body.Close()
266	if resp.StatusCode != http.StatusOK {
267		return nil, fmt.Errorf("%s: %s", req.URL, resp.Status)
268	}
269	return io.ReadAll(io.LimitReader(resp.Body, maxBody))
270}
271
272// summarize is the record's summary, or the first line of its details when
273// it has none, cut to fit a table cell.
274func summarize(v osvVuln) string {
275	s := strings.TrimSpace(v.Summary)
276	if s == "" {
277		s, _, _ = strings.Cut(strings.TrimSpace(v.Details), "\n")
278	}
279	s = strings.Join(strings.Fields(s), " ")
280	if r := []rune(s); len(r) > 120 {
281		s = string(r[:119]) + "…"
282	}
283	return s
284}
285
286// fixedAfter is the lowest fixed release above current among the record's
287// ranges for this package, or "" when no fix is published. A record can
288// carry one range per maintained branch, so the lowest one past current is
289// the nearest upgrade that clears it.
290func fixedAfter(v osvVuln, ecosystem, name, current string) string {
291	best := ""
292	for _, a := range v.Affected {
293		if a.Package.Ecosystem != ecosystem || a.Package.Name != name {
294			continue
295		}
296		for _, r := range a.Ranges {
297			for _, e := range r.Events {
298				if e.Fixed == "" || !Newer(current, e.Fixed) {
299					continue
300				}
301				if best == "" || Newer(e.Fixed, best) {
302					best = e.Fixed
303				}
304			}
305		}
306	}
307	return best
308}
309
310// importsOf returns the packages of a module an advisory names, which Go
311// advisories carry and others do not.
312func importsOf(v osvVuln, ecosystem, name string) []string {
313	var out []string
314	for _, a := range v.Affected {
315		if a.Package.Ecosystem != ecosystem || a.Package.Name != name {
316			continue
317		}
318		for _, imp := range a.EcosystemSpecific.Imports {
319			if imp.Path != "" {
320				out = append(out, imp.Path)
321			}
322		}
323	}
324	return out
325}