Debian Codegraph @

gopls/internal/mod/diagnostics.go

raw symbols SCIP
1 // Copyright 2019 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 mod provides core features related to go.mod file
6 // handling for use by Go editors and tools.
7 package mod
8
9 import (
10 "context"
11 "fmt"
12 "runtime"
13 "sort"
14 "strings"
15 "sync"
16
17 "golang.org/x/mod/modfile"
18 "golang.org/x/mod/semver"
19 "golang.org/x/sync/errgroup"
20 "golang.org/x/tools/gopls/internal/cache"
21 "golang.org/x/tools/gopls/internal/file"
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/gopls/internal/protocol/command"
24 "golang.org/x/tools/gopls/internal/settings"
25 "golang.org/x/tools/gopls/internal/vulncheck/govulncheck"
26 "golang.org/x/tools/internal/event"
27 )
28
29 // ParseDiagnostics returns diagnostics from parsing the go.mod files in the workspace.
30 func ParseDiagnostics(ctx context.Context, snapshot *cache.Snapshot) (map[protocol.DocumentURI][]*cache.Diagnostic, error) {
31 ctx, done := event.Start(ctx, "mod.Diagnostics", snapshot.Labels()...)
32 defer done()
33
34 return collectDiagnostics(ctx, snapshot, parseDiagnostics)
35 }
36
37 // TidyDiagnostics returns diagnostics from running go mod tidy.
38 func TidyDiagnostics(ctx context.Context, snapshot *cache.Snapshot) (map[protocol.DocumentURI][]*cache.Diagnostic, error) {
39 ctx, done := event.Start(ctx, "mod.Diagnostics", snapshot.Labels()...)
40 defer done()
41
42 return collectDiagnostics(ctx, snapshot, tidyDiagnostics)
43 }
44
45 // UpgradeDiagnostics returns upgrade diagnostics for the modules in the
46 // workspace with known upgrades.
47 func UpgradeDiagnostics(ctx context.Context, snapshot *cache.Snapshot) (map[protocol.DocumentURI][]*cache.Diagnostic, error) {
48 ctx, done := event.Start(ctx, "mod.UpgradeDiagnostics", snapshot.Labels()...)
49 defer done()
50
51 return collectDiagnostics(ctx, snapshot, upgradeDiagnostics)
52 }
53
54 // VulnerabilityDiagnostics returns vulnerability diagnostics for the active modules in the
55 // workspace with known vulnerabilities.
56 func VulnerabilityDiagnostics(ctx context.Context, snapshot *cache.Snapshot) (map[protocol.DocumentURI][]*cache.Diagnostic, error) {
57 ctx, done := event.Start(ctx, "mod.VulnerabilityDiagnostics", snapshot.Labels()...)
58 defer done()
59
60 return collectDiagnostics(ctx, snapshot, vulnerabilityDiagnostics)
61 }
62
63 func collectDiagnostics(ctx context.Context, snapshot *cache.Snapshot, diagFn func(context.Context, *cache.Snapshot, file.Handle) ([]*cache.Diagnostic, error)) (map[protocol.DocumentURI][]*cache.Diagnostic, error) {
64 g, ctx := errgroup.WithContext(ctx)
65 cpulimit := runtime.GOMAXPROCS(0)
66 g.SetLimit(cpulimit)
67
68 var mu sync.Mutex
69 reports := make(map[protocol.DocumentURI][]*cache.Diagnostic)
70
71 for _, uri := range snapshot.View().ModFiles() {
72 g.Go(func() error {
73 fh, err := snapshot.ReadFile(ctx, uri)
74 if err != nil {
75 return err
76 }
77 diagnostics, err := diagFn(ctx, snapshot, fh)
78 if err != nil {
79 return err
80 }
81 for _, d := range diagnostics {
82 mu.Lock()
83 reports[d.URI] = append(reports[fh.URI()], d)
84 mu.Unlock()
85 }
86 return nil
87 })
88 }
89
90 if err := g.Wait(); err != nil {
91 return nil, err
92 }
93 return reports, nil
94 }
95
96 // parseDiagnostics reports diagnostics from parsing the mod file.
97 func parseDiagnostics(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) (diagnostics []*cache.Diagnostic, err error) {
98 pm, err := snapshot.ParseMod(ctx, fh)
99 if err != nil {
100 if pm == nil || len(pm.ParseErrors) == 0 {
101 return nil, err
102 }
103 return pm.ParseErrors, nil
104 }
105 return nil, nil
106 }
107
108 // tidyDiagnostics reports diagnostics from running go mod tidy.
109 func tidyDiagnostics(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]*cache.Diagnostic, error) {
110 pm, err := snapshot.ParseMod(ctx, fh) // memoized
111 if err != nil {
112 return nil, nil // errors reported by ModDiagnostics above
113 }
114
115 tidied, err := snapshot.ModTidy(ctx, pm)
116 if err != nil {
117 if err != cache.ErrNoModOnDisk && !strings.Contains(err.Error(), "GOPROXY=off") {
118 // TODO(rfindley): the check for ErrNoModOnDisk was historically determined
119 // to be benign, but may date back to the time when the Go command did not
120 // have overlay support.
121 //
122 // See if we can pass the overlay to the Go command, and eliminate this guard..
123
124 // TODO(golang/go#56395): remove the arbitrary suppression of the mod
125 // tidy error when GOPROXY=off. The true fix for this noisy log message
126 // is to fix the mod tidy diagnostics.
127 event.Error(ctx, fmt.Sprintf("tidy: diagnosing %s", pm.URI), err)
128 }
129 return nil, nil
130 }
131 return tidied.Diagnostics, nil
132 }
133
134 // upgradeDiagnostics adds upgrade quick fixes for individual modules if the upgrades
135 // are recorded in the view.
136 func upgradeDiagnostics(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) (upgradeDiagnostics []*cache.Diagnostic, err error) {
137 pm, err := snapshot.ParseMod(ctx, fh)
138 if err != nil {
139 // Don't return an error if there are parse error diagnostics to be shown, but also do not
140 // continue since we won't be able to show the upgrade diagnostics.
141 if pm != nil && len(pm.ParseErrors) != 0 {
142 return nil, nil
143 }
144 return nil, err
145 }
146
147 upgrades := snapshot.ModuleUpgrades(fh.URI())
148 for _, req := range pm.File.Require {
149 ver, ok := upgrades[req.Mod.Path]
150 if !ok || req.Mod.Version == ver {
151 continue
152 }
153 rng, err := pm.Mapper.OffsetRange(req.Syntax.Start.Byte, req.Syntax.End.Byte)
154 if err != nil {
155 return nil, err
156 }
157 // Upgrade to the exact version we offer the user, not the most recent.
158 title := fmt.Sprintf("%s%v", upgradeCodeActionPrefix, ver)
159 cmd := command.NewUpgradeDependencyCommand(title, command.DependencyArgs{
160 URI: fh.URI(),
161 AddRequire: false,
162 GoCmdArgs: []string{req.Mod.Path + "@" + ver},
163 })
164 upgradeDiagnostics = append(upgradeDiagnostics, &cache.Diagnostic{
165 URI: fh.URI(),
166 Range: rng,
167 Severity: protocol.SeverityInformation,
168 Source: cache.UpgradeNotification,
169 Message: fmt.Sprintf("%v can be upgraded", req.Mod.Path),
170 SuggestedFixes: []cache.SuggestedFix{cache.SuggestedFixFromCommand(cmd, protocol.QuickFix)},
171 })
172 }
173
174 return upgradeDiagnostics, nil
175 }
176
177 const upgradeCodeActionPrefix = "Upgrade to "
178
179 // vulnerabilityDiagnostics adds diagnostics for vulnerabilities in individual modules
180 // if the vulnerability is recorded in the view.
181 func vulnerabilityDiagnostics(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) (vulnDiagnostics []*cache.Diagnostic, err error) {
182 pm, err := snapshot.ParseMod(ctx, fh)
183 if err != nil {
184 // Don't return an error if there are parse error diagnostics to be shown, but also do not
185 // continue since we won't be able to show the vulnerability diagnostics.
186 if pm != nil && len(pm.ParseErrors) != 0 {
187 return nil, nil
188 }
189 return nil, err
190 }
191
192 diagSource := cache.Govulncheck
193 vs := snapshot.Vulnerabilities(fh.URI())[fh.URI()]
194 if vs == nil && snapshot.Options().Vulncheck == settings.ModeVulncheckImports {
195 vs, err = snapshot.ModVuln(ctx, fh.URI())
196 if err != nil {
197 return nil, err
198 }
199 diagSource = cache.Vulncheck
200 }
201 if vs == nil || len(vs.Findings) == 0 {
202 return nil, nil
203 }
204
205 suggestRunOrResetGovulncheck, err := suggestGovulncheckAction(diagSource == cache.Govulncheck, fh.URI())
206 if err != nil {
207 // must not happen
208 return nil, err // TODO: bug report
209 }
210 vulnsByModule := make(map[string][]*govulncheck.Finding)
211
212 for _, finding := range vs.Findings {
213 if vuln, typ := foundVuln(finding); typ == vulnCalled || typ == vulnImported {
214 vulnsByModule[vuln.Module] = append(vulnsByModule[vuln.Module], finding)
215 }
216 }
217 for _, req := range pm.File.Require {
218 mod := req.Mod.Path
219 findings := vulnsByModule[mod]
220 if len(findings) == 0 {
221 continue
222 }
223 // note: req.Syntax is the line corresponding to 'require', which means
224 // req.Syntax.Start can point to the beginning of the "require" keyword
225 // for a single line require (e.g. "require golang.org/x/mod v0.0.0").
226 start := req.Syntax.Start.Byte
227 if len(req.Syntax.Token) == 3 {
228 start += len("require ")
229 }
230 rng, err := pm.Mapper.OffsetRange(start, req.Syntax.End.Byte)
231 if err != nil {
232 return nil, err
233 }
234 // Map affecting vulns to 'warning' level diagnostics,
235 // others to 'info' level diagnostics.
236 // Fixes will include only the upgrades for warning level diagnostics.
237 var warningFixes, infoFixes []cache.SuggestedFix
238 var warningSet, infoSet = map[string]bool{}, map[string]bool{}
239 for _, finding := range findings {
240 // It is possible that the source code was changed since the last
241 // govulncheck run and information in the `vulns` info is stale.
242 // For example, imagine that a user is in the middle of updating
243 // problematic modules detected by the govulncheck run by applying
244 // quick fixes. Stale diagnostics can be confusing and prevent the
245 // user from quickly locating the next module to fix.
246 // Ideally we should rerun the analysis with the updated module
247 // dependencies or any other code changes, but we are not yet
248 // in the position of automatically triggering the analysis
249 // (govulncheck can take a while). We also don't know exactly what
250 // part of source code was changed since `vulns` was computed.
251 // As a heuristic, we assume that a user upgrades the affecting
252 // module to the version with the fix or the latest one, and if the
253 // version in the require statement is equal to or higher than the
254 // fixed version, skip generating a diagnostic about the vulnerability.
255 // Eventually, the user has to rerun govulncheck.
256 if finding.FixedVersion != "" && semver.IsValid(req.Mod.Version) && semver.Compare(finding.FixedVersion, req.Mod.Version) <= 0 {
257 continue
258 }
259 switch _, typ := foundVuln(finding); typ {
260 case vulnImported:
261 infoSet[finding.OSV] = true
262 case vulnCalled:
263 warningSet[finding.OSV] = true
264 }
265 // Upgrade to the exact version we offer the user, not the most recent.
266 if fixedVersion := finding.FixedVersion; semver.IsValid(fixedVersion) && semver.Compare(req.Mod.Version, fixedVersion) < 0 {
267 cmd := getUpgradeCodeAction(fh, req, fixedVersion)
268 sf := cache.SuggestedFixFromCommand(cmd, protocol.QuickFix)
269 switch _, typ := foundVuln(finding); typ {
270 case vulnImported:
271 infoFixes = append(infoFixes, sf)
272 case vulnCalled:
273 warningFixes = append(warningFixes, sf)
274 }
275 }
276 }
277
278 if len(warningSet) == 0 && len(infoSet) == 0 {
279 continue
280 }
281 // Remove affecting osvs from the non-affecting osv list if any.
282 if len(warningSet) > 0 {
283 for k := range infoSet {
284 if warningSet[k] {
285 delete(infoSet, k)
286 }
287 }
288 }
289 // Add an upgrade for module@latest.
290 // TODO(suzmue): verify if latest is the same as fixedVersion.
291 latest := getUpgradeCodeAction(fh, req, "latest")
292 sf := cache.SuggestedFixFromCommand(latest, protocol.QuickFix)
293 if len(warningFixes) > 0 {
294 warningFixes = append(warningFixes, sf)
295 }
296 if len(infoFixes) > 0 {
297 infoFixes = append(infoFixes, sf)
298 }
299 if len(warningSet) > 0 {
300 warning := sortedKeys(warningSet)
301 warningFixes = append(warningFixes, suggestRunOrResetGovulncheck)
302 vulnDiagnostics = append(vulnDiagnostics, &cache.Diagnostic{
303 URI: fh.URI(),
304 Range: rng,
305 Severity: protocol.SeverityWarning,
306 Source: diagSource,
307 Message: getVulnMessage(req.Mod.Path, warning, true, diagSource == cache.Govulncheck),
308 SuggestedFixes: warningFixes,
309 })
310 }
311 if len(infoSet) > 0 {
312 info := sortedKeys(infoSet)
313 infoFixes = append(infoFixes, suggestRunOrResetGovulncheck)
314 vulnDiagnostics = append(vulnDiagnostics, &cache.Diagnostic{
315 URI: fh.URI(),
316 Range: rng,
317 Severity: protocol.SeverityInformation,
318 Source: diagSource,
319 Message: getVulnMessage(req.Mod.Path, info, false, diagSource == cache.Govulncheck),
320 SuggestedFixes: infoFixes,
321 })
322 }
323 }
324
325 // TODO(hyangah): place this diagnostic on the `go` directive or `toolchain` directive
326 // after https://go.dev/issue/57001.
327 const diagnoseStdLib = false
328
329 // If diagnosing the stdlib, add standard library vulnerability diagnostics
330 // on the module declaration.
331 //
332 // Only proceed if we have a valid module declaration on which to position
333 // the diagnostics.
334 if diagnoseStdLib && pm.File.Module != nil && pm.File.Module.Syntax != nil {
335 // Add standard library vulnerabilities.
336 stdlibVulns := vulnsByModule["stdlib"]
337 if len(stdlibVulns) == 0 {
338 return vulnDiagnostics, nil
339 }
340
341 // Put the standard library diagnostic on the module declaration.
342 rng, err := pm.Mapper.OffsetRange(pm.File.Module.Syntax.Start.Byte, pm.File.Module.Syntax.End.Byte)
343 if err != nil {
344 return vulnDiagnostics, nil // TODO: bug report
345 }
346
347 var warningSet, infoSet = map[string]bool{}, map[string]bool{}
348 for _, finding := range stdlibVulns {
349 switch _, typ := foundVuln(finding); typ {
350 case vulnImported:
351 infoSet[finding.OSV] = true
352 case vulnCalled:
353 warningSet[finding.OSV] = true
354 }
355 }
356 if len(warningSet) > 0 {
357 warning := sortedKeys(warningSet)
358 fixes := []cache.SuggestedFix{suggestRunOrResetGovulncheck}
359 vulnDiagnostics = append(vulnDiagnostics, &cache.Diagnostic{
360 URI: fh.URI(),
361 Range: rng,
362 Severity: protocol.SeverityWarning,
363 Source: diagSource,
364 Message: getVulnMessage("go", warning, true, diagSource == cache.Govulncheck),
365 SuggestedFixes: fixes,
366 })
367
368 // remove affecting osvs from the non-affecting osv list if any.
369 for k := range infoSet {
370 if warningSet[k] {
371 delete(infoSet, k)
372 }
373 }
374 }
375 if len(infoSet) > 0 {
376 info := sortedKeys(infoSet)
377 fixes := []cache.SuggestedFix{suggestRunOrResetGovulncheck}
378 vulnDiagnostics = append(vulnDiagnostics, &cache.Diagnostic{
379 URI: fh.URI(),
380 Range: rng,
381 Severity: protocol.SeverityInformation,
382 Source: diagSource,
383 Message: getVulnMessage("go", info, false, diagSource == cache.Govulncheck),
384 SuggestedFixes: fixes,
385 })
386 }
387 }
388
389 return vulnDiagnostics, nil
390 }
391
392 type vulnFindingType int
393
394 const (
395 vulnUnknown vulnFindingType = iota
396 vulnCalled
397 vulnImported
398 vulnRequired
399 )
400
401 // foundVuln returns the frame info describing discovered vulnerable symbol/package/module
402 // and how this vulnerability affects the analyzed package or module.
403 func foundVuln(finding *govulncheck.Finding) (*govulncheck.Frame, vulnFindingType) {
404 // finding.Trace is sorted from the imported vulnerable symbol to
405 // the entry point in the callstack.
406 // If Function is set, then Package must be set. Module will always be set.
407 // If Function is set it was found in the call graph, otherwise if Package is set
408 // it was found in the import graph, otherwise it was found in the require graph.
409 // See the documentation of govulncheck.Finding.
410 if len(finding.Trace) == 0 { // this shouldn't happen, but just in case...
411 return nil, vulnUnknown
412 }
413 vuln := finding.Trace[0]
414 if vuln.Package == "" {
415 return vuln, vulnRequired
416 }
417 if vuln.Function == "" {
418 return vuln, vulnImported
419 }
420 return vuln, vulnCalled
421 }
422
423 func sortedKeys(m map[string]bool) []string {
424 ret := make([]string, 0, len(m))
425 for k := range m {
426 ret = append(ret, k)
427 }
428 sort.Strings(ret)
429 return ret
430 }
431
432 // suggestGovulncheckAction returns a code action that suggests either run govulncheck
433 // for more accurate investigation (if the present vulncheck diagnostics are based on
434 // analysis less accurate than govulncheck) or reset the existing govulncheck result
435 // (if the present vulncheck diagnostics are already based on govulncheck run).
436 func suggestGovulncheckAction(fromGovulncheck bool, uri protocol.DocumentURI) (cache.SuggestedFix, error) {
437 if fromGovulncheck {
438 resetVulncheck := command.NewResetGoModDiagnosticsCommand("Reset govulncheck result", command.ResetGoModDiagnosticsArgs{
439 URIArg: command.URIArg{URI: uri},
440 DiagnosticSource: string(cache.Govulncheck),
441 })
442 return cache.SuggestedFixFromCommand(resetVulncheck, protocol.QuickFix), nil
443 }
444 vulncheck := command.NewRunGovulncheckCommand("Run govulncheck to verify", command.VulncheckArgs{
445 URI: uri,
446 Pattern: "./...",
447 })
448 return cache.SuggestedFixFromCommand(vulncheck, protocol.QuickFix), nil
449 }
450
451 func getVulnMessage(mod string, vulns []string, used, fromGovulncheck bool) string {
452 var b strings.Builder
453 if used {
454 switch len(vulns) {
455 case 1:
456 fmt.Fprintf(&b, "%v has a vulnerability used in the code: %v.", mod, vulns[0])
457 default:
458 fmt.Fprintf(&b, "%v has vulnerabilities used in the code: %v.", mod, strings.Join(vulns, ", "))
459 }
460 } else {
461 if fromGovulncheck {
462 switch len(vulns) {
463 case 1:
464 fmt.Fprintf(&b, "%v has a vulnerability %v that is not used in the code.", mod, vulns[0])
465 default:
466 fmt.Fprintf(&b, "%v has known vulnerabilities %v that are not used in the code.", mod, strings.Join(vulns, ", "))
467 }
468 } else {
469 switch len(vulns) {
470 case 1:
471 fmt.Fprintf(&b, "%v has a vulnerability %v.", mod, vulns[0])
472 default:
473 fmt.Fprintf(&b, "%v has known vulnerabilities %v.", mod, strings.Join(vulns, ", "))
474 }
475 }
476 }
477 return b.String()
478 }
479
480 // href returns the url for the vulnerability information.
481 // Eventually we should retrieve the url embedded in the osv.Entry.
482 // While vuln.go.dev is under development, this always returns
483 // the page in pkg.go.dev.
484 func href(vulnID string) string {
485 return fmt.Sprintf("https://pkg.go.dev/vuln/%s", vulnID)
486 }
487
488 func getUpgradeCodeAction(fh file.Handle, req *modfile.Require, version string) *protocol.Command {
489 return command.NewUpgradeDependencyCommand(upgradeTitle(version), command.DependencyArgs{
490 URI: fh.URI(),
491 AddRequire: false,
492 GoCmdArgs: []string{req.Mod.Path + "@" + version},
493 })
494 }
495
496 func upgradeTitle(fixedVersion string) string {
497 title := fmt.Sprintf("%s%v", upgradeCodeActionPrefix, fixedVersion)
498 return title
499 }
500
501 // SelectUpgradeCodeActions takes a list of code actions for a required module
502 // and returns a more selective list of upgrade code actions,
503 // where the code actions have been deduped. Code actions unrelated to upgrade
504 // are deduplicated by the name.
505 func SelectUpgradeCodeActions(actions []protocol.CodeAction) []protocol.CodeAction {
506 if len(actions) <= 1 {
507 return actions // return early if no sorting necessary
508 }
509 var versionedUpgrade, latestUpgrade, resetAction protocol.CodeAction
510 var chosenVersionedUpgrade string
511 var selected []protocol.CodeAction
512
513 seenTitles := make(map[string]bool)
514
515 for _, action := range actions {
516 if strings.HasPrefix(action.Title, upgradeCodeActionPrefix) {
517 if v := getUpgradeVersion(action); v == "latest" && latestUpgrade.Title == "" {
518 latestUpgrade = action
519 } else if versionedUpgrade.Title == "" || semver.Compare(v, chosenVersionedUpgrade) > 0 {
520 chosenVersionedUpgrade = v
521 versionedUpgrade = action
522 }
523 } else if strings.HasPrefix(action.Title, "Reset govulncheck") {
524 resetAction = action
525 } else if !seenTitles[action.Command.Title] {
526 seenTitles[action.Command.Title] = true
527 selected = append(selected, action)
528 }
529 }
530 if versionedUpgrade.Title != "" {
531 selected = append(selected, versionedUpgrade)
532 }
533 if latestUpgrade.Title != "" {
534 selected = append(selected, latestUpgrade)
535 }
536 if resetAction.Title != "" {
537 selected = append(selected, resetAction)
538 }
539 return selected
540 }
541
542 func getUpgradeVersion(p protocol.CodeAction) string {
543 return strings.TrimPrefix(p.Title, upgradeCodeActionPrefix)
544 }