File: command.go

package info (click to toggle)
golang-golang-x-tools 1%3A0.25.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 22,724 kB
  • sloc: javascript: 2,027; asm: 1,645; sh: 166; yacc: 155; makefile: 49; ansic: 8
file content (165 lines) | stat: -rw-r--r-- 4,916 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package scan

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"os"
	"os/exec"
	"sort"
	"time"

	"golang.org/x/sync/errgroup"
	"golang.org/x/tools/gopls/internal/cache"
	"golang.org/x/tools/gopls/internal/vulncheck"
	"golang.org/x/tools/gopls/internal/vulncheck/govulncheck"
	"golang.org/x/tools/gopls/internal/vulncheck/osv"
	"golang.org/x/vuln/scan"
)

// Main implements gopls vulncheck.
func Main(ctx context.Context, args ...string) error {
	// wrapping govulncheck.
	cmd := scan.Command(ctx, args...)
	if err := cmd.Start(); err != nil {
		return err
	}
	return cmd.Wait()
}

// RunGovulncheck implements the codelens "Run Govulncheck"
// that runs 'gopls vulncheck' and converts the output to gopls's internal data
// used for diagnostics and hover message construction.
//
// TODO(rfindley): this should accept a *View (which exposes) Options, rather
// than a snapshot.
func RunGovulncheck(ctx context.Context, pattern string, snapshot *cache.Snapshot, dir string, log io.Writer) (*vulncheck.Result, error) {
	vulncheckargs := []string{
		"vulncheck", "--",
		"-json",
		"-mode", "source",
		"-scan", "symbol",
	}
	if dir != "" {
		vulncheckargs = append(vulncheckargs, "-C", dir)
	}
	if db := cache.GetEnv(snapshot, "GOVULNDB"); db != "" {
		vulncheckargs = append(vulncheckargs, "-db", db)
	}
	vulncheckargs = append(vulncheckargs, pattern)
	// TODO: support -tags. need to compute tags args from opts.BuildFlags.
	// TODO: support -test.

	ir, iw := io.Pipe()
	handler := &govulncheckHandler{logger: log, osvs: map[string]*osv.Entry{}}

	stderr := new(bytes.Buffer)
	var g errgroup.Group
	// We run the govulncheck's analysis in a separate process as it can
	// consume a lot of CPUs and memory, and terminates: a separate process
	// is a perfect garbage collector and affords us ways to limit its resource usage.
	g.Go(func() error {
		defer iw.Close()

		cmd := exec.CommandContext(ctx, os.Args[0], vulncheckargs...)
		cmd.Env = getEnvSlices(snapshot)
		if goversion := cache.GetEnv(snapshot, cache.GoVersionForVulnTest); goversion != "" {
			// Let govulncheck API use a different Go version using the (undocumented) hook
			// in https://go.googlesource.com/vuln/+/v1.0.1/internal/scan/run.go#76
			cmd.Env = append(cmd.Env, "GOVERSION="+goversion)
		}
		cmd.Stderr = stderr // stream vulncheck's STDERR as progress reports
		cmd.Stdout = iw     // let the other goroutine parses the result.

		if err := cmd.Start(); err != nil {
			return fmt.Errorf("failed to start govulncheck: %v", err)
		}
		if err := cmd.Wait(); err != nil {
			return fmt.Errorf("failed to run govulncheck: %v", err)
		}
		return nil
	})
	g.Go(func() error {
		return govulncheck.HandleJSON(ir, handler)
	})
	if err := g.Wait(); err != nil {
		if stderr.Len() > 0 {
			log.Write(stderr.Bytes())
		}
		return nil, fmt.Errorf("failed to read govulncheck output: %v", err)
	}

	findings := handler.findings // sort so the findings in the result is deterministic.
	sort.Slice(findings, func(i, j int) bool {
		x, y := findings[i], findings[j]
		if x.OSV != y.OSV {
			return x.OSV < y.OSV
		}
		return x.Trace[0].Package < y.Trace[0].Package
	})
	result := &vulncheck.Result{
		Mode:     vulncheck.ModeGovulncheck,
		AsOf:     time.Now(),
		Entries:  handler.osvs,
		Findings: findings,
	}
	return result, nil
}

type govulncheckHandler struct {
	logger io.Writer // forward progress reports to logger.

	osvs     map[string]*osv.Entry
	findings []*govulncheck.Finding
}

// Config implements vulncheck.Handler.
func (h *govulncheckHandler) Config(config *govulncheck.Config) error {
	if config.GoVersion != "" {
		fmt.Fprintf(h.logger, "Go: %v\n", config.GoVersion)
	}
	if config.ScannerName != "" {
		scannerName := fmt.Sprintf("Scanner: %v", config.ScannerName)
		if config.ScannerVersion != "" {
			scannerName += "@" + config.ScannerVersion
		}
		fmt.Fprintln(h.logger, scannerName)
	}
	if config.DB != "" {
		dbInfo := fmt.Sprintf("DB: %v", config.DB)
		if config.DBLastModified != nil {
			dbInfo += fmt.Sprintf(" (DB updated: %v)", config.DBLastModified.String())
		}
		fmt.Fprintln(h.logger, dbInfo)
	}
	return nil
}

// Finding implements vulncheck.Handler.
func (h *govulncheckHandler) Finding(finding *govulncheck.Finding) error {
	h.findings = append(h.findings, finding)
	return nil
}

// OSV implements vulncheck.Handler.
func (h *govulncheckHandler) OSV(entry *osv.Entry) error {
	h.osvs[entry.ID] = entry
	return nil
}

// Progress implements vulncheck.Handler.
func (h *govulncheckHandler) Progress(progress *govulncheck.Progress) error {
	if progress.Message != "" {
		fmt.Fprintf(h.logger, "%v\n", progress.Message)
	}
	return nil
}

func getEnvSlices(snapshot *cache.Snapshot) []string {
	return append(os.Environ(), snapshot.Options().EnvSlice()...)
}