Debian Codegraph @

gopls/internal/cache/mod_vuln.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 cache
6
7 import (
8 "context"
9 "fmt"
10 "io"
11 "os"
12 "sort"
13 "strings"
14 "sync"
15
16 "golang.org/x/mod/semver"
17 "golang.org/x/sync/errgroup"
18 "golang.org/x/tools/go/packages"
19 "golang.org/x/tools/gopls/internal/cache/metadata"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/util/memoize"
22 "golang.org/x/tools/gopls/internal/vulncheck"
23 "golang.org/x/tools/gopls/internal/vulncheck/govulncheck"
24 "golang.org/x/tools/gopls/internal/vulncheck/osv"
25 isem "golang.org/x/tools/gopls/internal/vulncheck/semver"
26 "golang.org/x/vuln/scan"
27 )
28
29 // ModVuln returns import vulnerability analysis for the given go.mod URI.
30 // Concurrent requests are combined into a single command.
31 func (s *Snapshot) ModVuln(ctx context.Context, modURI protocol.DocumentURI) (*vulncheck.Result, error) {
32 s.mu.Lock()
33 entry, hit := s.modVulnHandles.Get(modURI)
34 s.mu.Unlock()
35
36 type modVuln struct {
37 result *vulncheck.Result
38 err error
39 }
40
41 // Cache miss?
42 if !hit {
43 handle := memoize.NewPromise("modVuln", func(ctx context.Context, arg any) any {
44 result, err := modVulnImpl(ctx, arg.(*Snapshot))
45 return modVuln{result, err}
46 })
47
48 entry = handle
49 s.mu.Lock()
50 s.modVulnHandles.Set(modURI, entry, nil)
51 s.mu.Unlock()
52 }
53
54 // Await result.
55 v, err := s.awaitPromise(ctx, entry)
56 if err != nil {
57 return nil, err
58 }
59 res := v.(modVuln)
60 return res.result, res.err
61 }
62
63 // GoVersionForVulnTest is an internal environment variable used in gopls
64 // testing to examine govulncheck behavior with a go version different
65 // than what `go version` returns in the system.
66 const GoVersionForVulnTest = "_GOPLS_TEST_VULNCHECK_GOVERSION"
67
68 // modVulnImpl queries the vulndb and reports which vulnerabilities
69 // apply to this snapshot. The result contains a set of packages,
70 // grouped by vuln ID and by module. This implements the "import-based"
71 // vulnerability report on go.mod files.
72 func modVulnImpl(ctx context.Context, snapshot *Snapshot) (*vulncheck.Result, error) {
73 // TODO(hyangah): can we let 'govulncheck' take a package list
74 // used in the workspace and implement this function?
75
76 // We want to report the intersection of vulnerable packages in the vulndb
77 // and packages transitively imported by this module ('go list -deps all').
78 // We use snapshot.AllMetadata to retrieve the list of packages
79 // as an approximation.
80 //
81 // TODO(hyangah): snapshot.AllMetadata is a superset of
82 // `go list all` - e.g. when the workspace has multiple main modules
83 // (multiple go.mod files), that can include packages that are not
84 // used by this module. Vulncheck behavior with go.work is not well
85 // defined. Figure out the meaning, and if we decide to present
86 // the result as if each module is analyzed independently, make
87 // gopls track a separate build list for each module and use that
88 // information instead of snapshot.AllMetadata.
89 allMeta, err := snapshot.AllMetadata(ctx)
90 if err != nil {
91 return nil, err
92 }
93
94 // TODO(hyangah): handle vulnerabilities in the standard library.
95
96 // Group packages by modules since vuln db is keyed by module.
97 packagesByModule := map[metadata.PackagePath][]*metadata.Package{}
98 for _, mp := range allMeta {
99 modulePath := metadata.PackagePath(osv.GoStdModulePath)
100 if mi := mp.Module; mi != nil {
101 modulePath = metadata.PackagePath(mi.Path)
102 }
103 packagesByModule[modulePath] = append(packagesByModule[modulePath], mp)
104 }
105
106 var (
107 mu sync.Mutex
108 // Keys are osv.Entry.ID
109 osvs = map[string]*osv.Entry{}
110 findings []*govulncheck.Finding
111 )
112
113 goVersion := snapshot.Options().Env[GoVersionForVulnTest]
114 if goVersion == "" {
115 goVersion = snapshot.GoVersionString()
116 }
117
118 stdlibModule := &packages.Module{
119 Path: osv.GoStdModulePath,
120 Version: goVersion,
121 }
122
123 // GOVULNDB may point the test db URI.
124 db := GetEnv(snapshot, "GOVULNDB")
125
126 var group errgroup.Group
127 group.SetLimit(10) // limit govulncheck api runs
128 for _, mps := range packagesByModule {
129 group.Go(func() error {
130 effectiveModule := stdlibModule
131 if m := mps[0].Module; m != nil {
132 effectiveModule = m
133 }
134 for effectiveModule.Replace != nil {
135 effectiveModule = effectiveModule.Replace
136 }
137 ver := effectiveModule.Version
138 if ver == "" || !isem.Valid(ver) {
139 // skip invalid version strings. the underlying scan api is strict.
140 return nil
141 }
142
143 // TODO(hyangah): batch these requests and add in-memory cache for efficiency.
144 vulns, err := osvsByModule(ctx, db, effectiveModule.Path+"@"+ver)
145 if err != nil {
146 return err
147 }
148 if len(vulns) == 0 { // No known vulnerability.
149 return nil
150 }
151
152 // set of packages in this module known to gopls.
153 // This will be lazily initialized when we need it.
154 var knownPkgs map[metadata.PackagePath]bool
155
156 // Report vulnerabilities that affect packages of this module.
157 for _, entry := range vulns {
158 var vulnerablePkgs []*govulncheck.Finding
159 fixed := fixedVersion(effectiveModule.Path, entry.Affected)
160
161 for _, a := range entry.Affected {
162 if a.Module.Ecosystem != osv.GoEcosystem || a.Module.Path != effectiveModule.Path {
163 continue
164 }
165 for _, imp := range a.EcosystemSpecific.Packages {
166 if knownPkgs == nil {
167 knownPkgs = toPackagePathSet(mps)
168 }
169 if knownPkgs[metadata.PackagePath(imp.Path)] {
170 vulnerablePkgs = append(vulnerablePkgs, &govulncheck.Finding{
171 OSV: entry.ID,
172 FixedVersion: fixed,
173 Trace: []*govulncheck.Frame{
174 {
175 Module: effectiveModule.Path,
176 Version: effectiveModule.Version,
177 Package: imp.Path,
178 },
179 },
180 })
181 }
182 }
183 }
184 if len(vulnerablePkgs) == 0 {
185 continue
186 }
187 mu.Lock()
188 osvs[entry.ID] = entry
189 findings = append(findings, vulnerablePkgs...)
190 mu.Unlock()
191 }
192 return nil
193 })
194 }
195 if err := group.Wait(); err != nil {
196 return nil, err
197 }
198
199 // Sort so the results are deterministic.
200 sort.Slice(findings, func(i, j int) bool {
201 x, y := findings[i], findings[j]
202 if x.OSV != y.OSV {
203 return x.OSV < y.OSV
204 }
205 return x.Trace[0].Package < y.Trace[0].Package
206 })
207 ret := &vulncheck.Result{
208 Entries: osvs,
209 Findings: findings,
210 Mode: vulncheck.ModeImports,
211 }
212 return ret, nil
213 }
214
215 // TODO(rfindley): this function was exposed during refactoring. Reconsider it.
216 func GetEnv(snapshot *Snapshot, key string) string {
217 val, ok := snapshot.Options().Env[key]
218 if ok {
219 return val
220 }
221 return os.Getenv(key)
222 }
223
224 // toPackagePathSet transforms the metadata to a set of package paths.
225 func toPackagePathSet(mds []*metadata.Package) map[metadata.PackagePath]bool {
226 pkgPaths := make(map[metadata.PackagePath]bool, len(mds))
227 for _, md := range mds {
228 pkgPaths[md.PkgPath] = true
229 }
230 return pkgPaths
231 }
232
233 func fixedVersion(modulePath string, affected []osv.Affected) string {
234 fixed := latestFixed(modulePath, affected)
235 if fixed != "" {
236 fixed = versionString(modulePath, fixed)
237 }
238 return fixed
239 }
240
241 // latestFixed returns the latest fixed version in the list of affected ranges,
242 // or the empty string if there are no fixed versions.
243 func latestFixed(modulePath string, as []osv.Affected) string {
244 v := ""
245 for _, a := range as {
246 if a.Module.Path != modulePath {
247 continue
248 }
249 for _, r := range a.Ranges {
250 if r.Type == osv.RangeTypeSemver {
251 for _, e := range r.Events {
252 if e.Fixed != "" && (v == "" ||
253 semver.Compare(isem.CanonicalizeSemverPrefix(e.Fixed), isem.CanonicalizeSemverPrefix(v)) > 0) {
254 v = e.Fixed
255 }
256 }
257 }
258 }
259 }
260 return v
261 }
262
263 // versionString prepends a version string prefix (`v` or `go`
264 // depending on the modulePath) to the given semver-style version string.
265 func versionString(modulePath, version string) string {
266 if version == "" {
267 return ""
268 }
269 v := "v" + version
270 // These are internal Go module paths used by the vuln DB
271 // when listing vulns in standard library and the go command.
272 if modulePath == "stdlib" || modulePath == "toolchain" {
273 return semverToGoTag(v)
274 }
275 return v
276 }
277
278 // semverToGoTag returns the Go standard library repository tag corresponding
279 // to semver, a version string without the initial "v".
280 // Go tags differ from standard semantic versions in a few ways,
281 // such as beginning with "go" instead of "v".
282 func semverToGoTag(v string) string {
283 if strings.HasPrefix(v, "v0.0.0") {
284 return "master"
285 }
286 // Special case: v1.0.0 => go1.
287 if v == "v1.0.0" {
288 return "go1"
289 }
290 if !semver.IsValid(v) {
291 return fmt.Sprintf("<!%s:invalid semver>", v)
292 }
293 goVersion := semver.Canonical(v)
294 prerelease := semver.Prerelease(goVersion)
295 versionWithoutPrerelease := strings.TrimSuffix(goVersion, prerelease)
296 patch := strings.TrimPrefix(versionWithoutPrerelease, semver.MajorMinor(goVersion)+".")
297 if patch == "0" {
298 versionWithoutPrerelease = strings.TrimSuffix(versionWithoutPrerelease, ".0")
299 }
300 goVersion = fmt.Sprintf("go%s", strings.TrimPrefix(versionWithoutPrerelease, "v"))
301 if prerelease != "" {
302 // Go prereleases look like "beta1" instead of "beta.1".
303 // "beta1" is bad for sorting (since beta10 comes before beta9), so
304 // require the dot form.
305 i := finalDigitsIndex(prerelease)
306 if i >= 1 {
307 if prerelease[i-1] != '.' {
308 return fmt.Sprintf("<!%s:final digits in a prerelease must follow a period>", v)
309 }
310 // Remove the dot.
311 prerelease = prerelease[:i-1] + prerelease[i:]
312 }
313 goVersion += strings.TrimPrefix(prerelease, "-")
314 }
315 return goVersion
316 }
317
318 // finalDigitsIndex returns the index of the first digit in the sequence of digits ending s.
319 // If s doesn't end in digits, it returns -1.
320 func finalDigitsIndex(s string) int {
321 // Assume ASCII (since the semver package does anyway).
322 var i int
323 for i = len(s) - 1; i >= 0; i-- {
324 if s[i] < '0' || s[i] > '9' {
325 break
326 }
327 }
328 if i == len(s)-1 {
329 return -1
330 }
331 return i + 1
332 }
333
334 // osvsByModule runs a govulncheck database query.
335 func osvsByModule(ctx context.Context, db, moduleVersion string) ([]*osv.Entry, error) {
336 var args []string
337 args = append(args, "-mode=query", "-json")
338 if db != "" {
339 args = append(args, "-db="+db)
340 }
341 args = append(args, moduleVersion)
342
343 ir, iw := io.Pipe()
344 handler := &osvReader{}
345
346 var g errgroup.Group
347 g.Go(func() error {
348 defer iw.Close() // scan API doesn't close cmd.Stderr/cmd.Stdout.
349 cmd := scan.Command(ctx, args...)
350 cmd.Stdout = iw
351 // TODO(hakim): Do we need to set cmd.Env = getEnvSlices(),
352 // or is the process environment good enough?
353 if err := cmd.Start(); err != nil {
354 return err
355 }
356 return cmd.Wait()
357 })
358 g.Go(func() error {
359 return govulncheck.HandleJSON(ir, handler)
360 })
361
362 if err := g.Wait(); err != nil {
363 return nil, err
364 }
365 return handler.entry, nil
366 }
367
368 // osvReader implements govulncheck.Handler.
369 type osvReader struct {
370 entry []*osv.Entry
371 }
372
373 func (h *osvReader) OSV(entry *osv.Entry) error {
374 h.entry = append(h.entry, entry)
375 return nil
376 }
377
378 func (h *osvReader) Config(config *govulncheck.Config) error {
379 return nil
380 }
381
382 func (h *osvReader) Finding(finding *govulncheck.Finding) error {
383 return nil
384 }
385
386 func (h *osvReader) Progress(progress *govulncheck.Progress) error {
387 return nil
388 }