Debian Codegraph @

gopls/internal/server/vulncheck_prompt_test.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 "context"
9 "crypto/sha256"
10 "encoding/hex"
11 "os"
12 "path/filepath"
13 "runtime"
14 "testing"
15
16 "golang.org/x/mod/modfile"
17 "golang.org/x/tools/gopls/internal/cache"
18 "golang.org/x/tools/gopls/internal/filecache"
19 "golang.org/x/tools/gopls/internal/progress"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/settings"
22 "golang.org/x/tools/internal/testenv"
23 )
24
25 func TestComputeGoModHash(t *testing.T) {
26 tests := []struct {
27 name string
28 content string
29 want string
30 wantErr bool
31 }{
32 {
33 name: "empty file",
34 content: "module example.com",
35 want: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", // sha256 of empty string
36 },
37 {
38 name: "with require",
39 content: `
40 module example.com
41 require (
42 golang.org/x/tools v0.1.0
43 golang.org/x/vuln v0.2.0
44 )
45 `,
46 want: func() string {
47 h := sha256.New()
48 h.Write([]byte("golang.org/x/tools\x00v0.1.0"))
49 h.Write([]byte("golang.org/x/vuln\x00v0.2.0"))
50 return hex.EncodeToString(h.Sum(nil))
51 }(),
52 },
53 {
54 name: "with exclude",
55 content: `
56 module example.com
57 exclude (
58 golang.org/x/tools v0.1.0
59 )
60 `,
61 want: func() string {
62 h := sha256.New()
63 h.Write([]byte("golang.org/x/tools\x00v0.1.0"))
64 return hex.EncodeToString(h.Sum(nil))
65 }(),
66 },
67 {
68 name: "with replace",
69 content: `
70 module example.com
71 replace (
72 golang.org/x/tools v0.1.0 => golang.org/x/tools v0.2.0
73 )
74 `,
75 want: func() string {
76 h := sha256.New()
77 h.Write([]byte("golang.org/x/tools\x00v0.1.0\x00golang.org/x/tools\x00v0.2.0"))
78 return hex.EncodeToString(h.Sum(nil))
79 }(),
80 },
81 }
82 for _, tt := range tests {
83 t.Run(tt.name, func(t *testing.T) {
84 modFile, err := modfile.Parse("go.mod", []byte(tt.content), nil)
85 if err != nil {
86 t.Fatal(err)
87 }
88 got, err := computeGoModHash(modFile)
89 if (err != nil) != tt.wantErr {
90 t.Errorf("computeGoModHash() error = %v, wantErr %v", err, tt.wantErr)
91 return
92 }
93 if got != tt.want {
94 t.Errorf("computeGoModHash() = %v, want %v", got, tt.want)
95 }
96 })
97 }
98 }
99
100 func TestComputeGoWorkHash(t *testing.T) {
101 tests := []struct {
102 name string
103 content string
104 want string
105 wantErr bool
106 }{
107 {
108 name: "empty file",
109 content: "go 1.25",
110 want: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", // sha256 of empty string
111 },
112 {
113 name: "with use",
114 content: `
115 go 1.25
116 use (
117 ./foo
118 ./bar
119 )
120 `,
121 want: func() string {
122 h := sha256.New()
123 h.Write([]byte("./foo\x00"))
124 h.Write([]byte("./bar\x00"))
125 return hex.EncodeToString(h.Sum(nil))
126 }(),
127 },
128 {
129 name: "with replace",
130 content: `
131 go 1.25
132 replace golang.org/x/tools v0.1.0 => ./tools
133 `,
134 want: func() string {
135 h := sha256.New()
136 h.Write([]byte("golang.org/x/tools\x00v0.1.0\x00./tools\x00"))
137 return hex.EncodeToString(h.Sum(nil))
138 }(),
139 },
140 }
141 for _, tt := range tests {
142 t.Run(tt.name, func(t *testing.T) {
143 workFile, err := modfile.ParseWork("go.work", []byte(tt.content), nil)
144 if err != nil {
145 t.Fatal(err)
146 }
147 got, err := computeGoWorkHash(workFile)
148 if (err != nil) != tt.wantErr {
149 t.Errorf("computeGoWorkHash() error = %v, wantErr %v", err, tt.wantErr)
150 return
151 }
152 if got != tt.want {
153 t.Errorf("computeGoWorkHash() = %v, want %v", got, tt.want)
154 }
155 })
156 }
157 }
158
159 type mockClient struct {
160 protocol.Client
161 showMessageRequest func(context.Context, *protocol.ShowMessageRequestParams) (*protocol.MessageActionItem, error)
162 }
163
164 func (c *mockClient) ShowMessageRequest(ctx context.Context, params *protocol.ShowMessageRequestParams) (*protocol.MessageActionItem, error) {
165 if c.showMessageRequest != nil {
166 return c.showMessageRequest(ctx, params)
167 }
168 return nil, nil
169 }
170
171 func (c *mockClient) ShowMessage(ctx context.Context, params *protocol.ShowMessageParams) error {
172 return nil
173 }
174
175 func (c *mockClient) Close() error {
176 return nil
177 }
178
179 func TestCheckDependencyChanges(t *testing.T) {
180 testenv.NeedsExec(t)
181 const (
182 yes = "Yes"
183 no = "No"
184 always = "Always"
185 never = "Never"
186 )
187
188 tests := []struct {
189 name string
190 filename string
191 vulncheckMode settings.VulncheckMode
192 oldContent string
193 newContent string
194 userAction string
195 wantPrompt bool
196 wantHashUpdated bool
197 }{
198 {
199 name: "go.mod: vulncheck disabled",
200 filename: "go.mod",
201 vulncheckMode: settings.ModeVulncheckOff,
202 oldContent: "module example.com",
203 newContent: `
204 module example.com
205 require golang.org/x/tools v0.1.0
206 `,
207 wantPrompt: false,
208 },
209 {
210 name: "go.mod: no changes",
211 filename: "go.mod",
212 vulncheckMode: settings.ModeVulncheckPrompt,
213 oldContent: "module example.com",
214 newContent: "module example.com",
215 wantPrompt: false,
216 },
217 {
218 name: "go.mod: user says yes",
219 filename: "go.mod",
220 vulncheckMode: settings.ModeVulncheckPrompt,
221 oldContent: "module example.com",
222 newContent: `
223 module example.com
224 require golang.org/x/tools v0.1.0
225 `,
226 userAction: yes,
227 wantPrompt: true,
228 wantHashUpdated: true,
229 },
230 {
231 name: "go.mod: user says yes (lowercase)",
232 filename: "go.mod",
233 vulncheckMode: settings.ModeVulncheckPrompt,
234 oldContent: "module example.com",
235 newContent: `
236 module example.com
237 require golang.org/x/tools v0.1.0
238 `,
239 userAction: "yes", // lowercase
240 wantPrompt: true,
241 wantHashUpdated: true,
242 },
243 {
244 name: "go.work: user says yes",
245 filename: "go.work",
246 vulncheckMode: settings.ModeVulncheckPrompt,
247 oldContent: "go 1.25",
248 newContent: `
249 go 1.25
250 use ./foo
251 `,
252 userAction: yes,
253 wantPrompt: true,
254 wantHashUpdated: true,
255 },
256 {
257 name: "go.work: no changes",
258 filename: "go.work",
259 vulncheckMode: settings.ModeVulncheckPrompt,
260 oldContent: "go 1.25\nuse ./foo",
261 newContent: "go 1.25\nuse ./foo",
262 wantPrompt: false,
263 },
264 }
265
266 for _, tt := range tests {
267 t.Run(tt.name, func(t *testing.T) {
268 t.Setenv(GoplsConfigDirEnvvar, t.TempDir())
269 ctx := context.Background()
270 var promptShown bool
271 client := &mockClient{
272 showMessageRequest: func(ctx context.Context, params *protocol.ShowMessageRequestParams) (*protocol.MessageActionItem, error) {
273 promptShown = true
274 if tt.userAction == "" {
275 return nil, nil
276 }
277 return &protocol.MessageActionItem{Title: tt.userAction}, nil
278 },
279 }
280 s := &server{
281 client: client,
282 session: cache.NewSession(ctx, cache.New(nil)),
283 progress: progress.NewTracker(client),
284 options: &settings.Options{
285 UserOptions: settings.UserOptions{
286 UIOptions: settings.UIOptions{
287 DiagnosticOptions: settings.DiagnosticOptions{
288 Vulncheck: tt.vulncheckMode,
289 },
290 },
291 },
292 },
293 }
294 dir := t.TempDir()
295 filePath := filepath.Join(dir, tt.filename)
296 if err := os.WriteFile(filePath, []byte(tt.oldContent), 0644); err != nil {
297 t.Fatal(err)
298 }
299 uri := protocol.URIFromPath(filePath)
300
301 // Set the initial hash in the cache.
302 oldHash, _, err := getDependencyHashes(uri)
303 if err != nil {
304 t.Fatal(err)
305 }
306 pathHash := sha256.Sum256([]byte(uri.Path()))
307 if err := filecache.Set(dependencyHashKind, pathHash, []byte(oldHash)); err != nil {
308 t.Fatal(err)
309 }
310
311 // Simulate the file change.
312 if err := os.WriteFile(filePath, []byte(tt.newContent), 0644); err != nil {
313 t.Fatal(err)
314 }
315
316 s.checkDependencyChanges(ctx, uri)
317
318 if promptShown != tt.wantPrompt {
319 t.Errorf("promptShown = %v, want %v", promptShown, tt.wantPrompt)
320 }
321
322 // Check if the hash was updated.
323 newHash, _, err := getDependencyHashes(uri)
324 if err != nil {
325 t.Fatal(err)
326 }
327
328 cachedHashBytes, err := filecache.Get(dependencyHashKind, pathHash, filecache.Bytes)
329 if err != nil && err != filecache.ErrNotFound {
330 t.Fatal(err)
331 }
332 cachedHash := string(cachedHashBytes)
333
334 if tt.wantHashUpdated {
335 if cachedHash != newHash {
336 t.Errorf("hash was not updated in cache")
337 }
338 } else {
339 if cachedHash == newHash && oldHash != newHash {
340 t.Errorf("hash was updated in cache, but should not have been")
341 }
342 }
343 })
344 }
345 }
346
347 func TestVulncheckPreference(t *testing.T) {
348 if runtime.GOARCH == "wasm" {
349 t.Skip("test not supported in wasm")
350 }
351 t.Setenv(GoplsConfigDirEnvvar, t.TempDir())
352
353 pref, err := getVulncheckPreference()
354 if err != nil {
355 t.Fatalf("getVulncheckPreference() failed: %v", err)
356 }
357 if pref != "" {
358 t.Errorf("got %q, want empty string", pref)
359 }
360
361 want := vulncheckActionAlways
362 if err := setVulncheckPreference(want); err != nil {
363 t.Fatalf("setVulncheckPreference() failed: %v", err)
364 }
365
366 got, err := getVulncheckPreference()
367 if err != nil {
368 t.Fatalf("getVulncheckPreference() failed: %v", err)
369 }
370
371 if got != want {
372 t.Errorf("got %q, want %q", got, want)
373 }
374
375 path, err := vulncheckFilename()
376 if err != nil {
377 t.Fatal(err)
378 }
379 if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
380 t.Fatal(err)
381 }
382 if err := os.WriteFile(path, []byte(`{"vulncheck": "always"}`), 0644); err != nil {
383 t.Fatal(err)
384 }
385
386 got, err = getVulncheckPreference()
387 if err != nil {
388 t.Fatalf("getVulncheckPreference() failed: %v", err)
389 }
390 if got != want {
391 t.Errorf("got %q, want %q", got, want)
392 }
393 }