internal/deps/osv_test.go

99 lines · 3783 bytes

 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}