Debian Codegraph @

gopls/internal/server/vulncheck_prompt.go

raw symbols SCIP
1 // Copyright 2025 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 server
6
7 import (
8 "bytes"
9 "context"
10 "crypto/sha256"
11 "encoding/hex"
12 "encoding/json"
13 "fmt"
14 "maps"
15 "os"
16 "path/filepath"
17 "slices"
18 "sort"
19 "strings"
20
21 "golang.org/x/mod/modfile"
22 "golang.org/x/mod/semver"
23 "golang.org/x/tools/gopls/internal/cache"
24 "golang.org/x/tools/gopls/internal/filecache"
25 "golang.org/x/tools/gopls/internal/progress"
26 "golang.org/x/tools/gopls/internal/protocol"
27 "golang.org/x/tools/gopls/internal/settings"
28 "golang.org/x/tools/gopls/internal/vulncheck/govulncheck"
29 "golang.org/x/tools/internal/event"
30 )
31
32 const (
33 // dependencyHashKind is the kind for the dependency hash in the filecache.
34 dependencyHashKind = "dephash"
35 maxVulnsToShow = 10
36 )
37
38 type vulncheckAction string
39
40 const (
41 vulncheckActionYes vulncheckAction = "Yes"
42 vulncheckActionNo vulncheckAction = "No"
43 vulncheckActionAlways vulncheckAction = "Always"
44 vulncheckActionNever vulncheckAction = "Never"
45 )
46
47 type vulnupgradeAction string
48
49 const (
50 vulnupgradeActionUpgradeAll vulnupgradeAction = "Upgrade All"
51 vulnupgradeActionIgnore vulnupgradeAction = "Ignore"
52 vulnupgradeActionEmpty vulnupgradeAction = ""
53 )
54
55 // computeGoModHash computes the SHA256 hash of the go.mod file's dependencies.
56 // It only considers the Require, Exclude, and Replace directives and ignores
57 // other parts of the file.
58 func computeGoModHash(file *modfile.File) (string, error) {
59 h := sha256.New()
60 for _, req := range file.Require {
61 if _, err := h.Write([]byte(req.Mod.Path + "\x00" + req.Mod.Version)); err != nil {
62 return "", err
63 }
64 }
65 for _, exc := range file.Exclude {
66 if _, err := h.Write([]byte(exc.Mod.Path + "\x00" + exc.Mod.Version)); err != nil {
67 return "", err
68 }
69 }
70 for _, rep := range file.Replace {
71 if _, err := h.Write([]byte(rep.Old.Path + "\x00" + rep.Old.Version + "\x00" + rep.New.Path + "\x00" + rep.New.Version)); err != nil {
72 return "", err
73 }
74 }
75 return hex.EncodeToString(h.Sum(nil)), nil
76 }
77
78 // computeGoWorkHash computes the SHA256 hash of the go.work file's dependencies.
79 // It only considers the Use and Replace directives and ignores other parts of
80 // the file.
81 func computeGoWorkHash(file *modfile.WorkFile) (string, error) {
82 h := sha256.New()
83 for _, use := range file.Use {
84 if _, err := h.Write([]byte(use.Path + "\x00")); err != nil {
85 return "", err
86 }
87 }
88 for _, rep := range file.Replace {
89 if _, err := h.Write([]byte(rep.Old.Path + "\x00" + rep.Old.Version + "\x00" + rep.New.Path + "\x00" + rep.New.Version)); err != nil {
90 return "", err
91 }
92 }
93 return hex.EncodeToString(h.Sum(nil)), nil
94 }
95
96 func getDependencyHashes(uri protocol.DocumentURI) (contentHash string, pathHash [32]byte, err error) {
97 content, err := os.ReadFile(uri.Path())
98 if err != nil {
99 return "", [32]byte{}, err
100 }
101 filename := filepath.Base(uri.Path())
102 switch filename {
103 case "go.mod":
104 modFile, err := modfile.Parse(filename, content, nil)
105 if err != nil {
106 return "", [32]byte{}, err
107 }
108 contentHash, err = computeGoModHash(modFile)
109 if err != nil {
110 return "", [32]byte{}, err
111 }
112 case "go.work":
113 workFile, err := modfile.ParseWork(filename, content, nil)
114 if err != nil {
115 return "", [32]byte{}, err
116 }
117 contentHash, err = computeGoWorkHash(workFile)
118 if err != nil {
119 return "", [32]byte{}, err
120 }
121 default:
122 return "", [32]byte{}, fmt.Errorf("unsupported file: %s", filename)
123 }
124 pathHash = sha256.Sum256([]byte(uri.Path()))
125 return contentHash, pathHash, nil
126 }
127
128 func (s *server) checkDependencyChanges(ctx context.Context, uri protocol.DocumentURI) {
129 if s.Options().Vulncheck != settings.ModeVulncheckPrompt {
130 return
131 }
132 ctx, done := event.Start(ctx, "server.checkDependencyChanges")
133 defer done()
134
135 newHash, pathHash, err := getDependencyHashes(uri)
136 if err != nil {
137 event.Error(ctx, "getting dependency hashes failed", err)
138 return
139 }
140
141 oldHashBytes, err := filecache.Get(dependencyHashKind, pathHash, filecache.Bytes)
142 if err != nil && err != filecache.ErrNotFound {
143 event.Error(ctx, "reading old dependency hash from filecache failed", err)
144 return
145 }
146 oldHash := string(oldHashBytes)
147
148 if oldHash != newHash {
149 if err := filecache.Set(dependencyHashKind, pathHash, []byte(newHash)); err != nil {
150 event.Error(ctx, "writing new dependency hash to filecache failed", err)
151 }
152
153 action, err := getVulncheckPreference()
154 if err != nil {
155 event.Error(ctx, "reading vulncheck preference failed", err)
156 }
157
158 if !(action == vulncheckActionAlways || action == vulncheckActionNever) {
159 // No valid saved prior preference. Prompt.
160 message := fmt.Sprintf("Dependencies changed in %s. Run govulncheck to check for vulnerabilities?", uri.Path())
161 actions := []string{
162 string(vulncheckActionYes),
163 string(vulncheckActionNo),
164 string(vulncheckActionAlways),
165 string(vulncheckActionNever),
166 }
167 choice, err := showMessageRequest(ctx, s.client, protocol.Info, message, actions...)
168 if err != nil {
169 event.Error(ctx, "showing dependency changed notification failed", err)
170 return
171 }
172 action, ok := parseVulncheckAction(choice)
173 if !ok {
174 event.Error(ctx, "parsing vulncheck action failed", fmt.Errorf("unexpected action: %s", choice))
175 return
176 }
177 recordVulncheckAction(action)
178 if action == vulncheckActionAlways || action == vulncheckActionNever {
179 if err := setVulncheckPreference(action); err != nil {
180 event.Error(ctx, "writing vulncheck preference failed", err)
181 showMessage(ctx, s.client, protocol.Error, fmt.Sprintf("Failed to save vulncheck preference: %v", err))
182 }
183 }
184 }
185
186 if !(action == vulncheckActionYes || action == vulncheckActionAlways) {
187 return
188 }
189
190 go s.handleVulncheck(ctx, uri)
191 }
192 }
193
194 func recordVulncheckAction(action vulncheckAction) {
195 switch action {
196 case vulncheckActionYes:
197 countVulncheckPromptYes.Inc()
198 case vulncheckActionNo:
199 countVulncheckPromptNo.Inc()
200 case vulncheckActionAlways:
201 countVulncheckPromptAlways.Inc()
202 case vulncheckActionNever:
203 countVulncheckPromptNever.Inc()
204 }
205 }
206
207 func recordVulncheckupgradeAction(action vulnupgradeAction) {
208 switch action {
209 case vulnupgradeActionUpgradeAll:
210 countVulncheckUpgradeAll.Inc()
211 case vulnupgradeActionIgnore:
212 countVulncheckUpgradeIgnore.Inc()
213 }
214 }
215
216 func (s *server) handleVulncheck(ctx context.Context, uri protocol.DocumentURI) {
217 _, snapshot, release, err := s.session.FileOf(ctx, uri)
218 if err != nil {
219 event.Error(ctx, "getting file snapshot failed", err)
220 return
221 }
222 defer release()
223 ctx = context.WithoutCancel(ctx)
224
225 work := s.progress.Start(ctx, GoVulncheckCommandTitle, "Running govulncheck...", nil, nil)
226 defer work.End(ctx, "Done.")
227 workDoneWriter := progress.NewWorkDoneWriter(ctx, work)
228 result, err := s.runVulncheck(ctx, snapshot, uri, "./...", workDoneWriter)
229 if err != nil {
230 event.Error(ctx, "govulncheck failed", err)
231 showMessage(ctx, s.client, protocol.Error, fmt.Sprintf("govulncheck failed: %v", err))
232 return
233 }
234
235 affecting, stdLibVulns, modulesToUpgrade := computeModulesToUpgrade(result.Findings)
236 numStdLib := len(stdLibVulns)
237 if len(affecting) == 0 && numStdLib == 0 {
238 showMessage(ctx, s.client, protocol.Info, "No vulnerabilities found.")
239 return
240 }
241
242 affectingOSVs := slices.Sorted(maps.Keys(affecting))
243
244 var b strings.Builder
245 fmt.Fprintf(&b, "Found %d actionable vulnerabilities and %d standard library vulnerabilities affecting your dependencies:\n\n", len(affectingOSVs), numStdLib)
246
247 for i, id := range affectingOSVs {
248 if i >= maxVulnsToShow {
249 break
250 }
251 cveURL := fmt.Sprintf("https://pkg.go.dev/vuln/%s", id)
252 if s.Options().LinkifyShowMessage {
253 fmt.Fprintf(&b, "Vulnerability #%d: [%s](%s)", i+1, id, cveURL)
254 } else {
255 fmt.Fprintf(&b, "Vulnerability #%d: %s (%s)", i+1, id, cveURL)
256 }
257 if i < len(affectingOSVs)-1 && i < maxVulnsToShow-1 {
258 b.WriteString(", ")
259 }
260 }
261 if len(affectingOSVs) > maxVulnsToShow {
262 fmt.Fprintf(&b, "\n\n...and %d more.", len(affectingOSVs)-maxVulnsToShow)
263 }
264
265 if numStdLib > 0 {
266 if b.Len() > 0 {
267 b.WriteString("\n\n")
268 }
269 b.WriteString("Upgrading your Go version may address vulnerabilities in the standard library.")
270 }
271
272 actions := []string{string(vulnupgradeActionIgnore)}
273 if len(modulesToUpgrade) > 0 {
274 actions = append([]string{string(vulnupgradeActionUpgradeAll)}, actions...)
275 }
276
277 action, err := showMessageRequest(ctx, s.client, protocol.Warning, b.String(), actions...)
278 if err != nil {
279 event.Error(ctx, "vulncheck remediation failed", err)
280 return
281 }
282 upgradeAction, ok := parseVulnupgradeAction(action)
283 if !ok {
284 event.Error(ctx, "parsing vulncheck remediation action failed", fmt.Errorf("unexpected action: %s", action))
285 return
286 }
287 recordVulncheckupgradeAction(upgradeAction)
288
289 if upgradeAction == vulnupgradeActionUpgradeAll {
290 if err := s.upgradeModules(ctx, snapshot, uri, modulesToUpgrade); err != nil {
291 event.Error(ctx, "upgrading modules failed", err)
292 }
293 }
294 }
295
296 func computeModulesToUpgrade(findings []*govulncheck.Finding) (affecting map[string]bool, stdLibVulns map[string]bool, modulesToUpgrade map[string]string) {
297 affecting = make(map[string]bool)
298 stdLibVulns = make(map[string]bool)
299 modulesToUpgrade = make(map[string]string)
300
301 for _, f := range findings {
302 if len(f.Trace) == 0 {
303 continue
304 }
305 mod := f.Trace[0].Module
306 // An empty module path or "stdlib" indicates a standard library package.
307 // These vulnerabilities cannot be remediated via module upgrades and
308 // instead require updating the Go toolchain.
309 if mod == "stdlib" || mod == "" {
310 stdLibVulns[f.OSV] = true
311 } else {
312 affecting[f.OSV] = true
313 if f.FixedVersion != "" {
314 current, ok := modulesToUpgrade[mod]
315 if !ok || current == "latest" || semver.Compare(f.FixedVersion, current) > 0 {
316 modulesToUpgrade[mod] = f.FixedVersion
317 }
318 } else if _, ok := modulesToUpgrade[mod]; !ok {
319 modulesToUpgrade[mod] = "latest"
320 }
321 }
322 }
323 return affecting, stdLibVulns, modulesToUpgrade
324 }
325
326 func (s *server) upgradeModules(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, modulesToUpgrade map[string]string) error {
327 if err := s.runGoGet(ctx, snapshot, uri, modulesToUpgrade); err != nil {
328 return err
329 }
330 if err := s.runGoModTidy(ctx, snapshot, uri); err != nil {
331 return err
332 }
333
334 var (
335 upgradedStrs []string
336 upgrades []string
337 )
338 for module, version := range modulesToUpgrade {
339 upgrades = append(upgrades, module+"@"+version)
340 upgradedStrs = append(upgradedStrs, fmt.Sprintf("%s to %s", module, version))
341 }
342 sort.Strings(upgradedStrs)
343
344 msg := fmt.Sprintf("Successfully upgraded vulnerable modules:\n %s", strings.Join(upgradedStrs, ",\n "))
345 showMessage(ctx, s.client, protocol.Info, msg)
346 if hash, pathHash, err := getDependencyHashes(uri); err == nil {
347 if err := filecache.Set(dependencyHashKind, pathHash, []byte(hash)); err != nil {
348 event.Error(ctx, "failed to update dependency hash after upgrade", err)
349 }
350 } else {
351 event.Error(ctx, "failed to get dependency hash after upgrade", err)
352 }
353 return nil
354 }
355
356 func (s *server) runGoGet(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, modulesToUpgrade map[string]string) error {
357 work := s.progress.Start(ctx, "Upgrading Modules", "Running go get...", nil, nil)
358 defer work.End(ctx, "Done.")
359
360 var upgrades []string
361 for module, version := range modulesToUpgrade {
362 upgrades = append(upgrades, module+"@"+version)
363 }
364
365 if err := runGoCommand(ctx, snapshot, uri, "get", upgrades); err != nil {
366 msg := fmt.Sprintf("Failed to upgrade modules: %v", err)
367 showMessage(ctx, s.client, protocol.Error, msg)
368 return err
369 }
370 return nil
371 }
372
373 func (s *server) runGoModTidy(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) error {
374 work := s.progress.Start(ctx, "Upgrading Modules", "Running go mod tidy...", nil, nil)
375 defer work.End(ctx, "Done.")
376
377 if err := runGoCommand(ctx, snapshot, uri, "mod", []string{"tidy"}); err != nil {
378 event.Error(ctx, "go mod tidy failed", err)
379 showMessage(ctx, s.client, protocol.Error, fmt.Sprintf("go mod tidy failed: %v", err))
380 return err
381 }
382 return nil
383 }
384
385 func runGoCommand(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, verb string, args []string) error {
386 dir := uri.DirPath()
387 inv, cleanup, err := snapshot.GoCommandInvocation(cache.NetworkOK, dir, verb, args)
388 if err != nil {
389 return err
390 }
391 defer cleanup()
392 var stdout, stderr bytes.Buffer
393 if err := snapshot.View().GoCommandRunner().RunPiped(ctx, *inv, &stdout, &stderr); err != nil {
394 return fmt.Errorf("go %s %s failed: %v\n-- stdout --\n%s\n-- stderr --\n%s", verb, strings.Join(args, " "), err, stdout.String(), stderr.String())
395 }
396 return nil
397 }
398
399 type vulncheckConfig struct {
400 VulncheckMode string `json:"vulncheck"`
401 }
402
403 func parseVulncheckAction(s string) (vulncheckAction, bool) {
404 return parseAction(s, []vulncheckAction{vulncheckActionYes, vulncheckActionNo, vulncheckActionAlways, vulncheckActionNever})
405 }
406
407 func parseVulnupgradeAction(s string) (vulnupgradeAction, bool) {
408 return parseAction(s, []vulnupgradeAction{vulnupgradeActionUpgradeAll, vulnupgradeActionIgnore})
409 }
410
411 func parseAction[T ~string](s string, actions []T) (T, bool) {
412 for _, a := range actions {
413 if strings.EqualFold(string(a), s) {
414 return a, true
415 }
416 }
417 return "", false
418 }
419
420 func getVulncheckPreference() (vulncheckAction, error) {
421 path, err := vulncheckFilename()
422 if err != nil {
423 return "", err
424 }
425 content, err := os.ReadFile(path)
426 if err != nil {
427 if os.IsNotExist(err) {
428 return "", nil
429 }
430 return "", err
431 }
432 var config vulncheckConfig
433 if err := json.Unmarshal(content, &config); err != nil {
434 return "", err
435 }
436 action, ok := parseVulncheckAction(config.VulncheckMode)
437 if !ok {
438 return "", fmt.Errorf("unexpected vulncheck mode in config: %s", config.VulncheckMode)
439 }
440 return action, nil
441 }
442
443 func setVulncheckPreference(preference vulncheckAction) error {
444 path, err := vulncheckFilename()
445 if err != nil {
446 return err
447 }
448 if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
449 return err
450 }
451 config := vulncheckConfig{VulncheckMode: string(preference)}
452 content, err := json.Marshal(config)
453 if err != nil {
454 return err
455 }
456 return os.WriteFile(path, content, 0644)
457 }
458
459 func vulncheckFilename() (string, error) {
460 configDir := os.Getenv(GoplsConfigDirEnvvar) // set for testing
461 if configDir != "" {
462 return filepath.Join(configDir, "vulncheck", "settings.json"), nil
463 }
464 userDir, err := os.UserConfigDir()
465 if err != nil {
466 return "", err
467 }
468 return filepath.Join(userDir, "gopls", "vulncheck", "settings.json"), nil
469 }