/
cliv2.go
368 lines (296 loc) · 9.81 KB
/
cliv2.go
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
Entry point class for the CLIv2 version.
*/
package cliv2
import (
_ "embed"
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
"regexp"
"strings"
"github.com/snyk/cli/cliv2/internal/constants"
"github.com/snyk/cli/cliv2/internal/embedded"
"github.com/snyk/cli/cliv2/internal/embedded/cliv1"
"github.com/snyk/cli/cliv2/internal/proxy"
"github.com/snyk/go-application-framework/pkg/utils"
)
type Handler int
type CLI struct {
DebugLogger *log.Logger
CacheDirectory string
v1BinaryLocation string
stdin io.Reader
stdout io.Writer
stderr io.Writer
}
type EnvironmentWarning struct {
message string
}
const (
V1_DEFAULT Handler = iota
V2_VERSION Handler = iota
V2_ABOUT Handler = iota
)
//go:embed cliv2.version
var version_prefix string
func NewCLIv2(cacheDirectory string, debugLogger *log.Logger) (*CLI, error) {
v1BinaryLocation, err := cliv1.GetFullCLIV1TargetPath(cacheDirectory)
if err != nil {
fmt.Println(err)
return nil, err
}
cli := CLI{
DebugLogger: debugLogger,
CacheDirectory: cacheDirectory,
v1BinaryLocation: v1BinaryLocation,
stdin: os.Stdin,
stdout: os.Stdout,
stderr: os.Stderr,
}
cli.ClearCache()
err = cli.ExtractV1Binary()
if err != nil {
fmt.Println(err)
return nil, err
}
return &cli, nil
}
func (c *CLI) ClearCache() error {
// Get files in directory
fileInfo, err := os.ReadDir(c.CacheDirectory)
if err != nil {
return err
}
// Get current version binary's path
v1BinaryPath := path.Dir(c.v1BinaryLocation)
var maxVersionToDelete = 5
for i, file := range fileInfo {
currentPath := path.Join(c.CacheDirectory, file.Name())
if currentPath != v1BinaryPath {
err = os.RemoveAll(currentPath)
if err != nil {
c.DebugLogger.Println("Error deleting an old version directory: ", currentPath)
}
}
// Stop the loop after 5 deletions to not create too much overhead
if i == maxVersionToDelete {
break
}
}
return nil
}
func (c *CLI) ExtractV1Binary() error {
cliV1ExpectedSHA256 := cliv1.ExpectedSHA256()
isValid, err := embedded.ValidateFile(c.v1BinaryLocation, cliV1ExpectedSHA256, c.DebugLogger)
if err != nil || !isValid {
c.DebugLogger.Println("cliv1 is not valid, start extracting ", c.v1BinaryLocation)
err = cliv1.ExtractTo(c.v1BinaryLocation)
if err != nil {
return err
}
isValid, err := embedded.ValidateFile(c.v1BinaryLocation, cliV1ExpectedSHA256, c.DebugLogger)
if err != nil {
return err
}
if isValid {
c.DebugLogger.Println("cliv1 is valid after extracting", c.v1BinaryLocation)
} else {
fmt.Println("cliv1 is not valid after sha256 check")
return err
}
} else {
c.DebugLogger.Println("cliv1 already exists and is valid at", c.v1BinaryLocation)
}
return nil
}
func GetFullVersion() string {
v1Version := cliv1.CLIV1Version()
v2Version := strings.TrimSpace(version_prefix)
if len(v2Version) > 0 {
return v2Version + "." + v1Version
} else {
return v1Version
}
}
func (c *CLI) GetIntegrationName() string {
return constants.SNYK_INTEGRATION_NAME
}
func (c *CLI) GetBinaryLocation() string {
return c.v1BinaryLocation
}
func (c *CLI) printVersion() {
fmt.Println(GetFullVersion())
}
func (c *CLI) commandVersion(passthroughArgs []string) error {
if utils.Contains(passthroughArgs, "--json-file-output") {
return fmt.Errorf("The following option combination is not currently supported: version + json-file-output")
} else {
c.printVersion()
return nil
}
}
func (c *CLI) commandAbout(proxyInfo *proxy.ProxyInfo, passthroughArgs []string) error {
err := c.executeV1Default(proxyInfo, passthroughArgs)
if err != nil {
return err
}
separator := "\n+-+-+-+-+-+-+\n\n"
allEmbeddedFiles := embedded.ListFiles()
for i := range allEmbeddedFiles {
f := &allEmbeddedFiles[i]
path := f.Path()
if strings.Contains(path, "licenses") {
size := f.Size()
data := make([]byte, size)
_, err := f.Read(data)
if err != nil {
continue
}
fmt.Printf("Package: %s \n", strings.ReplaceAll(strings.ReplaceAll(path, "/licenses/", ""), "/"+f.Name(), ""))
fmt.Println(string(data))
fmt.Println(separator)
}
}
return nil
}
func determineHandler(passthroughArgs []string) Handler {
result := V1_DEFAULT
if utils.Contains(passthroughArgs, "--version") ||
utils.Contains(passthroughArgs, "-v") ||
utils.Contains(passthroughArgs, "version") {
result = V2_VERSION
} else if utils.Contains(passthroughArgs, "--about") {
result = V2_ABOUT
}
return result
}
func PrepareV1EnvironmentVariables(input []string, integrationName string, integrationVersion string, proxyAddress string, caCertificateLocation string) (result []string, err error) {
inputAsMap := utils.ToKeyValueMap(input, "=")
result = input
_, integrationNameExists := inputAsMap[constants.SNYK_INTEGRATION_NAME_ENV]
_, integrationVersionExists := inputAsMap[constants.SNYK_INTEGRATION_VERSION_ENV]
if !integrationNameExists && !integrationVersionExists {
inputAsMap[constants.SNYK_INTEGRATION_NAME_ENV] = integrationName
inputAsMap[constants.SNYK_INTEGRATION_VERSION_ENV] = integrationVersion
} else if !(integrationNameExists && integrationVersionExists) {
err = EnvironmentWarning{message: fmt.Sprintf("Partially defined environment, please ensure to provide both %s and %s together!", constants.SNYK_INTEGRATION_NAME_ENV, constants.SNYK_INTEGRATION_VERSION_ENV)}
}
// preserve original proxy settings
inputAsMap[constants.SNYK_HTTPS_PROXY_ENV_SYSTEM], _ = utils.FindValueCaseInsensitive(inputAsMap, constants.SNYK_HTTPS_PROXY_ENV)
inputAsMap[constants.SNYK_HTTP_PROXY_ENV_SYSTEM], _ = utils.FindValueCaseInsensitive(inputAsMap, constants.SNYK_HTTP_PROXY_ENV)
inputAsMap[constants.SNYK_HTTP_NO_PROXY_ENV_SYSTEM], _ = utils.FindValueCaseInsensitive(inputAsMap, constants.SNYK_HTTP_NO_PROXY_ENV)
if err == nil {
// apply blacklist: ensure that no existing no_proxy or other configuration causes redirecting internal communication that is meant to stay between cliv1 and cliv2
blackList := []string{
constants.SNYK_HTTPS_PROXY_ENV,
constants.SNYK_HTTP_PROXY_ENV,
constants.SNYK_CA_CERTIFICATE_LOCATION_ENV,
constants.SNYK_HTTP_NO_PROXY_ENV,
constants.SNYK_NPM_NO_PROXY_ENV,
constants.SNYK_NPM_HTTPS_PROXY_ENV,
constants.SNYK_NPM_HTTP_PROXY_ENV,
constants.SNYK_NPM_PROXY_ENV,
constants.SNYK_NPM_ALL_PROXY,
}
for _, key := range blackList {
inputAsMap = utils.Remove(inputAsMap, key)
}
// fill expected values
inputAsMap[constants.SNYK_HTTPS_PROXY_ENV] = proxyAddress
inputAsMap[constants.SNYK_HTTP_PROXY_ENV] = proxyAddress
inputAsMap[constants.SNYK_CA_CERTIFICATE_LOCATION_ENV] = caCertificateLocation
// merge user defined (external) and internal no_proxy configuration
if len(inputAsMap[constants.SNYK_HTTP_NO_PROXY_ENV_SYSTEM]) > 0 {
internalNoProxy := strings.Split(constants.SNYK_INTERNAL_NO_PROXY, ",")
externalNoProxy := regexp.MustCompile("[,;]").Split(inputAsMap[constants.SNYK_HTTP_NO_PROXY_ENV_SYSTEM], -1)
mergedNoProxy := utils.Merge(internalNoProxy, externalNoProxy)
inputAsMap[constants.SNYK_HTTP_NO_PROXY_ENV] = strings.Join(mergedNoProxy, ",")
} else {
inputAsMap[constants.SNYK_HTTP_NO_PROXY_ENV] = constants.SNYK_INTERNAL_NO_PROXY
}
result = utils.ToSlice(inputAsMap, "=")
}
return result, err
}
func PrepareV1Command(cmd string, args []string, proxyInfo *proxy.ProxyInfo, integrationName string, integrationVersion string) (snykCmd *exec.Cmd, err error) {
proxyAddress := fmt.Sprintf("http://%s:%s@127.0.0.1:%d", proxy.PROXY_USERNAME, proxyInfo.Password, proxyInfo.Port)
snykCmd = exec.Command(cmd, args...)
snykCmd.Env, err = PrepareV1EnvironmentVariables(os.Environ(), integrationName, integrationVersion, proxyAddress, proxyInfo.CertificateLocation)
return snykCmd, err
}
func (c *CLI) executeV1Default(proxyInfo *proxy.ProxyInfo, passthroughArgs []string) error {
snykCmd, err := PrepareV1Command(
c.v1BinaryLocation,
passthroughArgs,
proxyInfo,
c.GetIntegrationName(),
GetFullVersion(),
)
if c.DebugLogger.Writer() != io.Discard {
c.DebugLogger.Println("Launching: ")
c.DebugLogger.Println(" ", c.v1BinaryLocation)
c.DebugLogger.Println(" With Arguments:")
c.DebugLogger.Println(" ", strings.Join(passthroughArgs, ", "))
c.DebugLogger.Println(" With Environment: ")
variablesMap := utils.ToKeyValueMap(snykCmd.Env, "=")
listedEnvironmentVariables := []string{
constants.SNYK_CA_CERTIFICATE_LOCATION_ENV,
constants.SNYK_HTTPS_PROXY_ENV,
constants.SNYK_HTTP_PROXY_ENV,
constants.SNYK_HTTP_NO_PROXY_ENV,
constants.SNYK_HTTPS_PROXY_ENV_SYSTEM,
constants.SNYK_HTTP_PROXY_ENV_SYSTEM,
constants.SNYK_HTTP_NO_PROXY_ENV_SYSTEM,
}
for _, key := range listedEnvironmentVariables {
c.DebugLogger.Println(" ", key, "=", variablesMap[key])
}
}
snykCmd.Stdin = c.stdin
snykCmd.Stdout = c.stdout
snykCmd.Stderr = c.stderr
if err != nil {
if evWarning, ok := err.(EnvironmentWarning); ok {
fmt.Println("WARNING! ", evWarning)
}
}
err = snykCmd.Run()
return err
}
func (c *CLI) Execute(proxyInfo *proxy.ProxyInfo, passthroughArgs []string) error {
var err error
handler := determineHandler(passthroughArgs)
switch {
case handler == V2_VERSION:
err = c.commandVersion(passthroughArgs)
case handler == V2_ABOUT:
err = c.commandAbout(proxyInfo, passthroughArgs)
default:
err = c.executeV1Default(proxyInfo, passthroughArgs)
}
return err
}
func DeriveExitCode(err error) int {
returnCode := constants.SNYK_EXIT_CODE_OK
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
returnCode = exitError.ExitCode()
} else {
// got an error but it's not an ExitError
returnCode = constants.SNYK_EXIT_CODE_ERROR
}
}
return returnCode
}
func (e EnvironmentWarning) Error() string {
return e.message
}
func (c *CLI) SetIoStreams(stdin io.Reader, stdout io.Writer, stderr io.Writer) {
c.stdin = stdin
c.stdout = stdout
c.stderr = stderr
}