Debian Codegraph @

gopls/internal/vulncheck/vulntest/db.go

raw symbols SCIP
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package vulntest provides helpers for vulncheck functionality testing.
6 package vulntest
7
8 import (
9 "bytes"
10 "context"
11 "encoding/json"
12 "fmt"
13 "os"
14 "path/filepath"
15 "slices"
16 "sort"
17 "strings"
18 "time"
19
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/vulncheck/osv"
22 "golang.org/x/tools/txtar"
23 )
24
25 // NewDatabase returns a read-only DB containing the provided
26 // txtar-format collection of vulnerability reports.
27 // Each vulnerability report is a YAML file whose format
28 // is defined in golang.org/x/vulndb/doc/format.md.
29 // A report file name must have the id as its base name,
30 // and have .yaml as its extension.
31 //
32 // db, err := NewDatabase(ctx, reports)
33 // ...
34 // defer db.Clean()
35 // client, err := NewClient(db)
36 // ...
37 //
38 // The returned DB's Clean method must be called to clean up the
39 // generated database.
40 func NewDatabase(ctx context.Context, txtarReports []byte) (*DB, error) {
41 disk, err := os.MkdirTemp("", "vulndb-test")
42 if err != nil {
43 return nil, err
44 }
45 if err := generateDB(ctx, txtarReports, disk, false); err != nil {
46 os.RemoveAll(disk) // ignore error
47 return nil, err
48 }
49
50 return &DB{disk: disk}, nil
51 }
52
53 // DB is a read-only vulnerability database on disk.
54 // Users can use this database with golang.org/x/vuln APIs
55 // by setting the `VULNDB` environment variable.
56 type DB struct {
57 disk string
58 }
59
60 // URI returns the file URI that can be used for VULNDB environment
61 // variable.
62 func (db *DB) URI() string {
63 u := protocol.URIFromPath(filepath.Join(db.disk, "ID"))
64 return string(u)
65 }
66
67 // Clean deletes the database.
68 func (db *DB) Clean() error {
69 return os.RemoveAll(db.disk)
70 }
71
72 //
73 // The following was selectively copied from golang.org/x/vulndb/internal/database
74 //
75
76 const (
77 dbURL = "https://pkg.go.dev/vuln/"
78
79 // idDirectory is the name of the directory that contains entries
80 // listed by their IDs.
81 idDirectory = "ID"
82
83 // cmdModule is the name of the module containing Go toolchain
84 // binaries.
85 cmdModule = "cmd"
86
87 // stdModule is the name of the module containing Go std packages.
88 stdModule = "std"
89 )
90
91 // generateDB generates the file-based vuln DB in the directory jsonDir.
92 func generateDB(ctx context.Context, txtarData []byte, jsonDir string, indent bool) error {
93 archive := txtar.Parse(txtarData)
94
95 entries, err := generateEntries(ctx, archive)
96 if err != nil {
97 return err
98 }
99 return writeEntriesByID(filepath.Join(jsonDir, idDirectory), entries, indent)
100 }
101
102 func generateEntries(_ context.Context, archive *txtar.Archive) ([]osv.Entry, error) {
103 now := time.Now()
104 var entries []osv.Entry
105 for _, f := range archive.Files {
106 if !strings.HasSuffix(f.Name, ".yaml") {
107 continue
108 }
109 r, err := readReport(bytes.NewReader(f.Data))
110 if err != nil {
111 return nil, err
112 }
113 name := strings.TrimSuffix(filepath.Base(f.Name), filepath.Ext(f.Name))
114 linkName := fmt.Sprintf("%s%s", dbURL, name)
115 entry := generateOSVEntry(name, linkName, now, *r)
116 entries = append(entries, entry)
117 }
118 return entries, nil
119 }
120
121 func writeEntriesByID(idDir string, entries []osv.Entry, indent bool) error {
122 // Write a directory containing entries by ID.
123 if err := os.MkdirAll(idDir, 0755); err != nil {
124 return fmt.Errorf("failed to create directory %q: %v", idDir, err)
125 }
126 for _, e := range entries {
127 outPath := filepath.Join(idDir, e.ID+".json")
128 if err := writeJSON(outPath, e, indent); err != nil {
129 return err
130 }
131 }
132 return nil
133 }
134
135 func writeJSON(filename string, value any, indent bool) (err error) {
136 j, err := jsonMarshal(value, indent)
137 if err != nil {
138 return err
139 }
140 return os.WriteFile(filename, j, 0644)
141 }
142
143 func jsonMarshal(v any, indent bool) ([]byte, error) {
144 if indent {
145 return json.MarshalIndent(v, "", " ")
146 }
147 return json.Marshal(v)
148 }
149
150 // generateOSVEntry create an osv.Entry for a report. In addition to the report, it
151 // takes the ID for the vuln and a URL that will point to the entry in the vuln DB.
152 // It returns the osv.Entry and a list of module paths that the vuln affects.
153 func generateOSVEntry(id, url string, lastModified time.Time, r Report) osv.Entry {
154 entry := osv.Entry{
155 ID: id,
156 Published: r.Published,
157 Modified: lastModified,
158 Withdrawn: r.Withdrawn,
159 Summary: r.Summary,
160 Details: r.Description,
161 DatabaseSpecific: &osv.DatabaseSpecific{URL: url},
162 }
163
164 moduleMap := make(map[string]bool)
165 for _, m := range r.Modules {
166 switch m.Module {
167 case stdModule:
168 moduleMap[osv.GoStdModulePath] = true
169 case cmdModule:
170 moduleMap[osv.GoCmdModulePath] = true
171 default:
172 moduleMap[m.Module] = true
173 }
174 entry.Affected = append(entry.Affected, toAffected(m))
175 }
176 for _, ref := range r.References {
177 entry.References = append(entry.References, osv.Reference{
178 Type: ref.Type,
179 URL: ref.URL,
180 })
181 }
182 return entry
183 }
184
185 func AffectedRanges(versions []VersionRange) []osv.Range {
186 a := osv.Range{Type: osv.RangeTypeSemver}
187 if len(versions) == 0 || versions[0].Introduced == "" {
188 a.Events = append(a.Events, osv.RangeEvent{Introduced: "0"})
189 }
190 for _, v := range versions {
191 if v.Introduced != "" {
192 a.Events = append(a.Events, osv.RangeEvent{Introduced: v.Introduced.Canonical()})
193 }
194 if v.Fixed != "" {
195 a.Events = append(a.Events, osv.RangeEvent{Fixed: v.Fixed.Canonical()})
196 }
197 }
198 return []osv.Range{a}
199 }
200
201 func toOSVPackages(pkgs []*Package) (imps []osv.Package) {
202 for _, p := range pkgs {
203 syms := slices.Clone(p.Symbols)
204 syms = append(syms, p.DerivedSymbols...)
205 sort.Strings(syms)
206 imps = append(imps, osv.Package{
207 Path: p.Package,
208 GOOS: p.GOOS,
209 GOARCH: p.GOARCH,
210 Symbols: syms,
211 })
212 }
213 return imps
214 }
215
216 func toAffected(m *Module) osv.Affected {
217 name := m.Module
218 switch name {
219 case stdModule:
220 name = osv.GoStdModulePath
221 case cmdModule:
222 name = osv.GoCmdModulePath
223 }
224 return osv.Affected{
225 Module: osv.Module{
226 Path: name,
227 Ecosystem: osv.GoEcosystem,
228 },
229 Ranges: AffectedRanges(m.Versions),
230 EcosystemSpecific: osv.EcosystemSpecific{
231 Packages: toOSVPackages(m.Packages),
232 },
233 }
234 }