Debian Codegraph @

gopls/internal/mod/hover.go

raw symbols SCIP
1 // Copyright 2020 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
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11 "slices"
12 "sort"
13 "strings"
14
15 "golang.org/x/mod/modfile"
16 "golang.org/x/mod/module"
17 "golang.org/x/mod/semver"
18 "golang.org/x/tools/gopls/internal/cache"
19 "golang.org/x/tools/gopls/internal/file"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/settings"
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 "golang.org/x/tools/internal/event"
26 )
27
28 func Hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) (*protocol.Hover, error) {
29 // We only provide hover information for the view's go.mod files.
30 if !slices.Contains(snapshot.View().ModFiles(), fh.URI()) {
31 return nil, nil
32 }
33
34 ctx, done := event.Start(ctx, "mod.Hover")
35 defer done()
36
37 // Get the position of the cursor.
38 pm, err := snapshot.ParseMod(ctx, fh)
39 if err != nil {
40 return nil, fmt.Errorf("getting modfile handle: %w", err)
41 }
42 startOffset, endOffset, err := pm.Mapper.RangeOffsets(rng)
43 if err != nil {
44 return nil, fmt.Errorf("computing cursor position: %w", err)
45 }
46
47 // If the cursor position is on a module statement
48 if hover, ok := hoverOnModuleStatement(ctx, pm, startOffset, endOffset, snapshot, fh); ok {
49 return hover, nil
50 }
51 return hoverOnRequireStatement(ctx, pm, startOffset, endOffset, snapshot, fh)
52 }
53
54 func hoverOnRequireStatement(ctx context.Context, pm *cache.ParsedModule, startOffset, endOffset int, snapshot *cache.Snapshot, fh file.Handle) (*protocol.Hover, error) {
55 // Confirm that the cursor is at the position of a require statement.
56 var req *modfile.Require
57 var depStartOffset, depEndOffset int
58 for _, r := range pm.File.Require {
59 dep := []byte(r.Mod.Path)
60 s, e := r.Syntax.Start.Byte, r.Syntax.End.Byte
61 i := bytes.Index(pm.Mapper.Content[s:e], dep)
62 if i == -1 {
63 continue
64 }
65 // Shift the start position to the location of the
66 // dependency within the require statement.
67 depStartOffset, depEndOffset = s+i, e
68 if depStartOffset <= startOffset && endOffset <= depEndOffset {
69 req = r
70 break
71 }
72 }
73 // TODO(hyangah): find position for info about vulnerabilities in Go
74
75 // The cursor position is not on a require statement.
76 if req == nil {
77 return nil, nil
78 }
79
80 // Get the vulnerability info.
81 fromGovulncheck := true
82 vs := snapshot.Vulnerabilities(fh.URI())[fh.URI()]
83 if vs == nil && snapshot.Options().Vulncheck == settings.ModeVulncheckImports {
84 var err error
85 vs, err = snapshot.ModVuln(ctx, fh.URI())
86 if err != nil {
87 return nil, err
88 }
89 fromGovulncheck = false
90 }
91 affecting, nonaffecting, osvs := lookupVulns(vs, req.Mod.Path, req.Mod.Version)
92
93 // Get the `go mod why` results for the given file.
94 why, err := snapshot.ModWhy(ctx, fh)
95 if err != nil {
96 return nil, err
97 }
98 explanation, ok := why[req.Mod.Path]
99 if !ok {
100 return nil, nil
101 }
102
103 // Get the range to highlight for the hover.
104 // TODO(hyangah): adjust the hover range to include the version number
105 // to match the diagnostics' range.
106 rng, err := pm.Mapper.OffsetRange(startOffset, endOffset)
107 if err != nil {
108 return nil, err
109 }
110 options := snapshot.Options()
111 isPrivate := snapshot.IsGoPrivatePath(req.Mod.Path)
112 header := formatHeader(req.Mod.Path, options)
113 explanation = formatExplanation(explanation, pm.ReplaceMap, req, options, isPrivate)
114 vulns := formatVulnerabilities(affecting, nonaffecting, osvs, options, fromGovulncheck)
115
116 return &protocol.Hover{
117 Contents: protocol.MarkupContent{
118 Kind: options.PreferredContentFormat,
119 Value: header + vulns + explanation,
120 },
121 Range: rng,
122 }, nil
123 }
124
125 func hoverOnModuleStatement(ctx context.Context, pm *cache.ParsedModule, startOffset, endOffset int, snapshot *cache.Snapshot, fh file.Handle) (*protocol.Hover, bool) {
126 module := pm.File.Module
127 if module == nil {
128 return nil, false // no module stmt
129 }
130 if endOffset < module.Syntax.Start.Byte || startOffset > module.Syntax.End.Byte {
131 return nil, false // cursor not in module stmt
132 }
133
134 rng, err := pm.Mapper.OffsetRange(module.Syntax.Start.Byte, module.Syntax.End.Byte)
135 if err != nil {
136 return nil, false
137 }
138 fromGovulncheck := true
139 vs := snapshot.Vulnerabilities(fh.URI())[fh.URI()]
140
141 if vs == nil && snapshot.Options().Vulncheck == settings.ModeVulncheckImports {
142 vs, err = snapshot.ModVuln(ctx, fh.URI())
143 if err != nil {
144 return nil, false
145 }
146 fromGovulncheck = false
147 }
148 modpath := "stdlib"
149 goVersion := snapshot.View().GoVersionString()
150 affecting, nonaffecting, osvs := lookupVulns(vs, modpath, goVersion)
151 options := snapshot.Options()
152 vulns := formatVulnerabilities(affecting, nonaffecting, osvs, options, fromGovulncheck)
153
154 return &protocol.Hover{
155 Contents: protocol.MarkupContent{
156 Kind: options.PreferredContentFormat,
157 Value: vulns,
158 },
159 Range: rng,
160 }, true
161 }
162
163 func formatHeader(modpath string, options *settings.Options) string {
164 var b strings.Builder
165 // Write the heading as an H3.
166 b.WriteString("#### " + modpath)
167 if options.PreferredContentFormat == protocol.Markdown {
168 b.WriteString("\n\n")
169 } else {
170 b.WriteRune('\n')
171 }
172 return b.String()
173 }
174
175 func lookupVulns(vulns *vulncheck.Result, modpath, version string) (affecting, nonaffecting []*govulncheck.Finding, osvs map[string]*osv.Entry) {
176 if vulns == nil || len(vulns.Entries) == 0 {
177 return nil, nil, nil
178 }
179 for _, finding := range vulns.Findings {
180 vuln, typ := foundVuln(finding)
181 if vuln.Module != modpath {
182 continue
183 }
184 // It is possible that the source code was changed since the last
185 // govulncheck run and information in the `vulns` info is stale.
186 // For example, imagine that a user is in the middle of updating
187 // problematic modules detected by the govulncheck run by applying
188 // quick fixes. Stale diagnostics can be confusing and prevent the
189 // user from quickly locating the next module to fix.
190 // Ideally we should rerun the analysis with the updated module
191 // dependencies or any other code changes, but we are not yet
192 // in the position of automatically triggering the analysis
193 // (govulncheck can take a while). We also don't know exactly what
194 // part of source code was changed since `vulns` was computed.
195 // As a heuristic, we assume that a user upgrades the affecting
196 // module to the version with the fix or the latest one, and if the
197 // version in the require statement is equal to or higher than the
198 // fixed version, skip the vulnerability information in the hover.
199 // Eventually, the user has to rerun govulncheck.
200 if finding.FixedVersion != "" && semver.IsValid(version) && semver.Compare(finding.FixedVersion, version) <= 0 {
201 continue
202 }
203 switch typ {
204 case vulnCalled:
205 affecting = append(affecting, finding)
206 case vulnImported:
207 nonaffecting = append(nonaffecting, finding)
208 }
209 }
210
211 // Remove affecting elements from nonaffecting.
212 // An OSV entry can appear in both lists if an OSV entry covers
213 // multiple packages imported but not all vulnerable symbols are used.
214 // The current wording of hover message doesn't clearly
215 // present this case well IMO, so let's skip reporting nonaffecting.
216 if len(affecting) > 0 && len(nonaffecting) > 0 {
217 affectingSet := map[string]bool{}
218 for _, f := range affecting {
219 affectingSet[f.OSV] = true
220 }
221 n := 0
222 for _, v := range nonaffecting {
223 if !affectingSet[v.OSV] {
224 nonaffecting[n] = v
225 n++
226 }
227 }
228 nonaffecting = nonaffecting[:n]
229 }
230 sort.Slice(nonaffecting, func(i, j int) bool { return nonaffecting[i].OSV < nonaffecting[j].OSV })
231 sort.Slice(affecting, func(i, j int) bool { return affecting[i].OSV < affecting[j].OSV })
232 return affecting, nonaffecting, vulns.Entries
233 }
234
235 func fixedVersion(fixed string) string {
236 if fixed == "" {
237 return "No fix is available."
238 }
239 return "Fixed in " + fixed + "."
240 }
241
242 func formatVulnerabilities(affecting, nonaffecting []*govulncheck.Finding, osvs map[string]*osv.Entry, options *settings.Options, fromGovulncheck bool) string {
243 if len(osvs) == 0 || (len(affecting) == 0 && len(nonaffecting) == 0) {
244 return ""
245 }
246 byOSV := func(findings []*govulncheck.Finding) map[string][]*govulncheck.Finding {
247 m := make(map[string][]*govulncheck.Finding)
248 for _, f := range findings {
249 m[f.OSV] = append(m[f.OSV], f)
250 }
251 return m
252 }
253 affectingByOSV := byOSV(affecting)
254 nonaffectingByOSV := byOSV(nonaffecting)
255
256 // TODO(hyangah): can we use go templates to generate hover messages?
257 // Then, we can use a different template for markdown case.
258 useMarkdown := options.PreferredContentFormat == protocol.Markdown
259
260 var b strings.Builder
261
262 if len(affectingByOSV) > 0 {
263 // TODO(hyangah): make the message more eyecatching (icon/codicon/color)
264 if len(affectingByOSV) == 1 {
265 fmt.Fprintf(&b, "\n**WARNING:** Found %d reachable vulnerability.\n", len(affectingByOSV))
266 } else {
267 fmt.Fprintf(&b, "\n**WARNING:** Found %d reachable vulnerabilities.\n", len(affectingByOSV))
268 }
269 }
270 for id, findings := range affectingByOSV {
271 fix := fixedVersion(findings[0].FixedVersion)
272 pkgs := vulnerablePkgsInfo(findings, useMarkdown)
273 osvEntry := osvs[id]
274
275 if useMarkdown {
276 fmt.Fprintf(&b, "- [**%v**](%v) %v%v\n%v\n", id, href(id), osvEntry.Summary, pkgs, fix)
277 } else {
278 fmt.Fprintf(&b, " - [%v] %v (%v) %v%v\n", id, osvEntry.Summary, href(id), pkgs, fix)
279 }
280 }
281 if len(nonaffecting) > 0 {
282 if fromGovulncheck {
283 fmt.Fprintf(&b, "\n**Note:** The project imports packages with known vulnerabilities, but does not call the vulnerable code.\n")
284 } else {
285 fmt.Fprintf(&b, "\n**Note:** The project imports packages with known vulnerabilities. Use `govulncheck` to check if the project uses vulnerable symbols.\n")
286 }
287 }
288 for k, findings := range nonaffectingByOSV {
289 fix := fixedVersion(findings[0].FixedVersion)
290 pkgs := vulnerablePkgsInfo(findings, useMarkdown)
291 osvEntry := osvs[k]
292
293 if useMarkdown {
294 fmt.Fprintf(&b, "- [%v](%v) %v%v\n%v\n", k, href(k), osvEntry.Summary, pkgs, fix)
295 } else {
296 fmt.Fprintf(&b, " - [%v] %v (%v) %v\n%v\n", k, osvEntry.Summary, href(k), pkgs, fix)
297 }
298 }
299 b.WriteString("\n")
300 return b.String()
301 }
302
303 func vulnerablePkgsInfo(findings []*govulncheck.Finding, useMarkdown bool) string {
304 var b strings.Builder
305 seen := map[string]bool{}
306 for _, f := range findings {
307 p := f.Trace[0].Package
308 if !seen[p] {
309 seen[p] = true
310 if useMarkdown {
311 b.WriteString("\n * `")
312 } else {
313 b.WriteString("\n ")
314 }
315 b.WriteString(p)
316 if useMarkdown {
317 b.WriteString("`")
318 }
319 }
320 }
321 return b.String()
322 }
323
324 func formatExplanation(text string, replaceMap map[module.Version]module.Version, req *modfile.Require, options *settings.Options, isPrivate bool) string {
325 text = strings.TrimSuffix(text, "\n")
326 splt := strings.Split(text, "\n")
327 length := len(splt)
328
329 var b strings.Builder
330
331 // If the explanation is 2 lines, then it is of the form:
332 // # golang.org/x/text/encoding
333 // (main module does not need package golang.org/x/text/encoding)
334 if length == 2 {
335 b.WriteString(splt[1])
336 return b.String()
337 }
338
339 imp := splt[length-1] // import path
340 reference := imp
341 // See golang/go#36998: don't link to modules matching GOPRIVATE.
342 if !isPrivate && options.PreferredContentFormat == protocol.Markdown {
343 target := imp
344 if strings.ToLower(options.LinkTarget) == "pkg.go.dev" {
345 mod := req.Mod
346 // respect the replacement when constructing a module link.
347 if m, ok := replaceMap[req.Mod]; ok {
348 // Have: 'replace A v1.2.3 => A vx.x.x' or 'replace A v1.2.3 => B vx.x.x'.
349 mod = m
350 } else if m, ok := replaceMap[module.Version{Path: req.Mod.Path}]; ok &&
351 !modfile.IsDirectoryPath(m.Path) { // exclude local replacement.
352 // Have: 'replace A => A vx.x.x' or 'replace A => B vx.x.x'.
353 mod = m
354 }
355 target = strings.Replace(target, req.Mod.Path, mod.String(), 1)
356 }
357 reference = fmt.Sprintf("[%s](%s)", imp, cache.BuildLink(options.LinkTarget, target, ""))
358 }
359 b.WriteString("This module is necessary because " + reference + " is imported in")
360
361 // If the explanation is 3 lines, then it is of the form:
362 // # golang.org/x/tools
363 // modtest
364 // golang.org/x/tools/go/packages
365 if length == 3 {
366 msg := fmt.Sprintf(" `%s`.", splt[1])
367 b.WriteString(msg)
368 return b.String()
369 }
370
371 // If the explanation is more than 3 lines, then it is of the form:
372 // # golang.org/x/text/language
373 // rsc.io/quote
374 // rsc.io/sampler
375 // golang.org/x/text/language
376 b.WriteString(":\n```text")
377 var dash strings.Builder
378 for _, imp := range splt[1 : length-1] {
379 dash.WriteString("-")
380 b.WriteString("\n" + dash.String() + " " + imp)
381 }
382 b.WriteString("\n```")
383 return b.String()
384 }