-
Notifications
You must be signed in to change notification settings - Fork 534
/
main.go
514 lines (432 loc) · 16.5 KB
/
main.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
package main
// !!! This import needs to be the first import, please do not change this !!!
import _ "github.com/snyk/go-application-framework/pkg/networking/fips_enable"
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/snyk/cli-extension-dep-graph/pkg/depgraph"
"github.com/snyk/cli-extension-iac-rules/iacrules"
"github.com/snyk/cli-extension-sbom/pkg/sbom"
"github.com/snyk/container-cli/pkg/container"
"github.com/snyk/go-application-framework/pkg/analytics"
"github.com/snyk/go-application-framework/pkg/app"
"github.com/snyk/go-application-framework/pkg/auth"
"github.com/snyk/go-application-framework/pkg/configuration"
localworkflows "github.com/snyk/go-application-framework/pkg/local_workflows"
"github.com/snyk/go-application-framework/pkg/local_workflows/content_type"
"github.com/snyk/go-application-framework/pkg/local_workflows/json_schemas"
"github.com/snyk/go-application-framework/pkg/networking"
"github.com/snyk/go-application-framework/pkg/runtimeinfo"
"github.com/snyk/go-application-framework/pkg/utils"
"github.com/snyk/go-application-framework/pkg/workflow"
"github.com/snyk/go-httpauth/pkg/httpauth"
"github.com/snyk/snyk-iac-capture/pkg/capture"
snykls "github.com/snyk/snyk-ls/ls_extension"
"github.com/snyk/cli/cliv2/internal/cliv2"
"github.com/snyk/cli/cliv2/internal/constants"
cli_errors "github.com/snyk/cli/cliv2/internal/errors"
"github.com/snyk/cli/cliv2/pkg/basic_workflows"
)
var internalOS string
var globalEngine workflow.Engine
var globalConfiguration configuration.Configuration
var helpProvided bool
var noopLogger zerolog.Logger = zerolog.New(io.Discard)
var globalLogger *zerolog.Logger = &noopLogger
const (
unknownCommandMessage string = "unknown command"
disable_analytics_flag string = "DISABLE_ANALYTICS"
)
type JsonErrorStruct struct {
Ok bool `json:"ok"`
ErrorMsg string `json:"error"`
Path string `json:"path"`
}
type HandleError int
const (
handleErrorFallbackToLegacyCLI HandleError = iota
handleErrorShowHelp HandleError = iota
handleErrorUnhandled HandleError = iota
)
func main() {
errorCode := MainWithErrorCode()
os.Exit(errorCode)
}
// Initialize the given configuration with CLI specific aspects
func initApplicationConfiguration(config configuration.Configuration) {
config.AddAlternativeKeys(configuration.AUTHENTICATION_TOKEN, []string{"snyk_cfg_api", "api"})
config.AddAlternativeKeys(configuration.AUTHENTICATION_BEARER_TOKEN, []string{"snyk_docker_token"})
config.AddAlternativeKeys(configuration.API_URL, []string{"endpoint"})
config.AddAlternativeKeys(configuration.ADD_TRUSTED_CA_FILE, []string{"NODE_EXTRA_CA_CERTS"})
config.AddAlternativeKeys(configuration.ANALYTICS_DISABLED, []string{strings.ToLower(constants.SNYK_ANALYTICS_DISABLED_ENV), "snyk_cfg_disable_analytics", "disable-analytics", "disable_analytics"})
config.AddAlternativeKeys(configuration.ORGANIZATION, []string{"snyk_cfg_org"})
// if the CONFIG_KEY_OAUTH_TOKEN is specified as env var, we don't apply any additional logic
_, ok := os.LookupEnv(auth.CONFIG_KEY_OAUTH_TOKEN)
if !ok {
alternativeBearerKeys := config.GetAlternativeKeys(configuration.AUTHENTICATION_BEARER_TOKEN)
alternativeBearerKeys = append(alternativeBearerKeys, configuration.AUTHENTICATION_BEARER_TOKEN)
for _, key := range alternativeBearerKeys {
hasPrefix := strings.HasPrefix(key, "snyk_")
if hasPrefix {
formattedKey := strings.ToUpper(key)
_, ok := os.LookupEnv(formattedKey)
if ok {
globalLogger.Printf("Found environment variable %s, disabling OAuth flow", formattedKey)
config.Set(configuration.FF_OAUTH_AUTH_FLOW_ENABLED, false)
break
}
}
}
}
}
func getFullCommandString(cmd *cobra.Command) string {
fullCommandPath := []string{cmd.Name()}
fn := func(c *cobra.Command) {
if c.HasParent() {
fullCommandPath = append(fullCommandPath, c.Name())
}
}
cmd.VisitParents(fn)
for i, j := 0, len(fullCommandPath)-1; i < j; i, j = i+1, j-1 {
fullCommandPath[i], fullCommandPath[j] = fullCommandPath[j], fullCommandPath[i]
}
name := strings.Join(fullCommandPath, " ")
return name
}
func updateConfigFromParameter(config configuration.Configuration, args []string, rawArgs []string) {
// extract everything behind --
doubleDashArgs := []string{}
doubleDashFound := false
for _, v := range rawArgs {
if doubleDashFound {
doubleDashArgs = append(doubleDashArgs, v)
} else if v == "--" {
doubleDashFound = true
}
}
config.Set(configuration.UNKNOWN_ARGS, doubleDashArgs)
// only consider the first positional argument as input directory if it is not behind a double dash.
if len(args) > 0 && !utils.Contains(doubleDashArgs, args[0]) {
config.Set(configuration.INPUT_DIRECTORY, args[0])
}
}
// main workflow
func runCommand(cmd *cobra.Command, args []string) error {
// since cobra doesn't tell us if -- was found, os.Args is required in addition
return runMainWorkflow(globalConfiguration, cmd, args, os.Args)
}
func runMainWorkflow(config configuration.Configuration, cmd *cobra.Command, args []string, rawArgs []string) error {
err := config.AddFlagSet(cmd.Flags())
if err != nil {
globalLogger.Print("Failed to add flags", err)
return err
}
updateConfigFromParameter(config, args, rawArgs)
name := getFullCommandString(cmd)
globalLogger.Print("Running ", name)
globalEngine.GetAnalytics().SetCommand(name)
err = runWorkflowAndProcessData(globalEngine, globalLogger, name)
return err
}
func runWorkflowAndProcessData(engine workflow.Engine, logger *zerolog.Logger, name string) error {
data, err := engine.Invoke(workflow.NewWorkflowIdentifier(name))
if err == nil {
_, err = engine.InvokeWithInput(localworkflows.WORKFLOWID_OUTPUT_WORKFLOW, data)
if err == nil {
err = getErrorFromWorkFlowData(data)
}
} else {
logger.Print("Failed to execute the command!", err)
}
return err
}
func getErrorFromWorkFlowData(data []workflow.Data) error {
for i := range data {
mimeType := data[i].GetContentType()
if strings.EqualFold(mimeType, content_type.TEST_SUMMARY) {
singleData, ok := data[i].GetPayload().([]byte)
if !ok {
return fmt.Errorf("invalid payload type: %T", data[i].GetPayload())
}
summary := json_schemas.TestSummary{}
err := json.Unmarshal(singleData, &summary)
if err != nil {
return fmt.Errorf("failed to parse test summary payload: %w", err)
}
// We are missing an understanding of ignored issues here
// this should be supported in the future
for _, result := range summary.Results {
if result.Open > 0 {
return cli_errors.ErrorWithExitCode{
ExitCode: constants.SNYK_EXIT_CODE_VULNERABILITIES_FOUND,
}
}
}
return nil
}
}
return nil
}
func sendAnalytics(analytics analytics.Analytics, debugLogger *zerolog.Logger) {
debugLogger.Print("Sending Analytics")
res, err := analytics.Send()
if err != nil {
debugLogger.Err(err).Msg("Failed to send Analytics")
return
}
defer res.Body.Close()
successfullySend := 200 <= res.StatusCode && res.StatusCode < 300
if successfullySend {
debugLogger.Print("Analytics successfully send")
} else {
var details string
if res != nil {
details = res.Status
}
debugLogger.Print("Failed to send Analytics:", details)
}
}
func help(_ *cobra.Command, _ []string) error {
helpProvided = true
args := utils.RemoveSimilar(os.Args[1:], "--") // remove all double dash arguments to avoid issues with the help command
args = append(args, "--help")
return defaultCmd(args)
}
func defaultCmd(args []string) error {
// prepare the invocation of the legacy CLI by
// * enabling stdio
// * by specifying the raw cmd args for it
globalConfiguration.Set(configuration.WORKFLOW_USE_STDIO, true)
globalConfiguration.Set(configuration.RAW_CMD_ARGS, args)
_, err := globalEngine.Invoke(basic_workflows.WORKFLOWID_LEGACY_CLI)
return err
}
func getGlobalFLags() *pflag.FlagSet {
globalConfigurationOptions := workflow.GetGlobalConfiguration()
globalFLags := workflow.FlagsetFromConfigurationOptions(globalConfigurationOptions)
globalFLags.Bool(basic_workflows.PROXY_NOAUTH, false, "")
globalFLags.Bool(disable_analytics_flag, false, "")
return globalFLags
}
func emptyCommandFunction(_ *cobra.Command, _ []string) error {
return fmt.Errorf(unknownCommandMessage)
}
func createCommandsForWorkflows(rootCommand *cobra.Command, engine workflow.Engine) {
workflowIdList := engine.GetWorkflows()
commandMap := make(map[string]*cobra.Command)
for i := range workflowIdList {
currentId := workflowIdList[i]
currentCommandString := workflow.GetCommandFromWorkflowIdentifier(currentId)
workflowEntry, _ := engine.GetWorkflow(currentId)
workflowOptions := workflowEntry.GetConfigurationOptions()
flagset := workflow.FlagsetFromConfigurationOptions(workflowOptions)
workflowParts := strings.Split(currentCommandString, " ")
parentCommand := rootCommand
var currentParts string
for level := 0; level < len(workflowParts); level++ {
subCmdName := workflowParts[level]
currentParts += " " + subCmdName
subCmd := commandMap[currentParts]
if subCmd == nil {
subCmd = &cobra.Command{
Use: subCmdName,
Hidden: true,
RunE: emptyCommandFunction, // ensure to trigger the fallback case
DisableFlagParsing: true, // disable flag parsing to allow arbitrary flags for commands that will trigger the fallback
}
parentCommand.AddCommand(subCmd)
commandMap[currentParts] = subCmd
}
parentCommand = subCmd
}
// last parentCommand is the last level of the command, e.g. in the snyk iac capture workflow, it would be 'capture'
// we add flags and command line only to that one
if flagset != nil {
parentCommand.Flags().AddFlagSet(flagset)
}
parentCommand.RunE = runCommand
parentCommand.Hidden = !workflowEntry.IsVisible()
parentCommand.DisableFlagParsing = false
// special case for snyk code test, to preserve backwards compatibility we will need to relax flag validation
if currentCommandString == "code test" {
parentCommand.FParseErrWhitelist.UnknownFlags = true
}
}
}
func prepareRootCommand() *cobra.Command {
rootCommand := cobra.Command{
Use: "snyk",
RunE: func(cmd *cobra.Command, _ []string) error {
return defaultCmd(os.Args[1:])
},
}
// help for all commands is handled by the legacy cli
// TODO: discuss how to move help to extensions
helpCommand := cobra.Command{
Use: "help",
RunE: help,
}
// some static/global cobra configuration
rootCommand.CompletionOptions.DisableDefaultCmd = true
rootCommand.SilenceErrors = true
rootCommand.SilenceUsage = true
rootCommand.FParseErrWhitelist.UnknownFlags = true
// ensure that help and usage information comes from the legacy cli instead of cobra's default help
rootCommand.SetHelpFunc(func(c *cobra.Command, args []string) { _ = help(c, args) })
rootCommand.SetHelpCommand(&helpCommand)
rootCommand.PersistentFlags().AddFlagSet(getGlobalFLags())
return &rootCommand
}
func handleError(err error) HandleError {
resultError := handleErrorUnhandled
preCondition := err != nil && !helpProvided
// Cases:
// - error from extension -> ignore
// - error unknown command -> fallback
// - error known command but unknown flag -> help
if preCondition {
errString := err.Error()
flagError := strings.Contains(errString, "unknown flag") ||
strings.Contains(errString, "flag needs") ||
strings.Contains(errString, "invalid argument")
commandError := strings.Contains(errString, unknownCommandMessage)
// filter for known cobra errors, since cobra errors shall trigger a fallback, but not others.
if commandError {
resultError = handleErrorFallbackToLegacyCLI
} else if flagError {
// handle flag errors explicitly since we need to delegate the help to the legacy CLI. This includes disabling the cobra default help/usage
resultError = handleErrorShowHelp
}
}
return resultError
}
func displayError(err error, output io.Writer, config configuration.Configuration) {
if err != nil {
var exitError *exec.ExitError
isExitError := errors.As(err, &exitError)
isErrorWithCode := errors.As(err, &cli_errors.ErrorWithExitCode{})
if isExitError || isErrorWithCode {
return
}
if config.GetBool(localworkflows.OUTPUT_CONFIG_KEY_JSON) {
jsonError := JsonErrorStruct{
Ok: false,
ErrorMsg: err.Error(),
Path: globalConfiguration.GetString(configuration.INPUT_DIRECTORY),
}
jsonErrorBuffer, _ := json.MarshalIndent(jsonError, "", " ")
fmt.Fprintln(output, string(jsonErrorBuffer))
} else {
if errors.Is(err, context.DeadlineExceeded) {
fmt.Fprintln(output, "command timed out")
} else {
fmt.Fprintln(output, err)
}
}
}
}
func MainWithErrorCode() int {
var err error
rInfo := runtimeinfo.New(runtimeinfo.WithName("snyk-cli"), runtimeinfo.WithVersion(cliv2.GetFullVersion()))
rootCommand := prepareRootCommand()
_ = rootCommand.ParseFlags(os.Args)
// create engine
globalConfiguration = configuration.New()
err = globalConfiguration.AddFlagSet(rootCommand.LocalFlags())
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to add flags to root command", err)
}
// ensure to init configuration before using it
initApplicationConfiguration(globalConfiguration)
debugEnabled := globalConfiguration.GetBool(configuration.DEBUG)
globalLogger = initDebugLogger(globalConfiguration)
globalEngine = app.CreateAppEngineWithOptions(app.WithZeroLogger(globalLogger), app.WithConfiguration(globalConfiguration), app.WithRuntimeInfo(rInfo))
if noProxyAuth := globalConfiguration.GetBool(basic_workflows.PROXY_NOAUTH); noProxyAuth {
globalConfiguration.Set(configuration.PROXY_AUTHENTICATION_MECHANISM, httpauth.StringFromAuthenticationMechanism(httpauth.NoAuth))
}
// initialize the extensions -> they register themselves at the engine
globalEngine.AddExtensionInitializer(basic_workflows.Init)
globalEngine.AddExtensionInitializer(sbom.Init)
globalEngine.AddExtensionInitializer(depgraph.Init)
globalEngine.AddExtensionInitializer(capture.Init)
globalEngine.AddExtensionInitializer(iacrules.Init)
globalEngine.AddExtensionInitializer(snykls.Init)
globalEngine.AddExtensionInitializer(container.Init)
globalEngine.AddExtensionInitializer(localworkflows.InitCodeWorkflow)
// init engine
err = globalEngine.Init()
if err != nil {
globalLogger.Print("Failed to init Workflow Engine!", err)
return constants.SNYK_EXIT_CODE_ERROR
}
// add output flags as persistent flags
outputWorkflow, _ := globalEngine.GetWorkflow(localworkflows.WORKFLOWID_OUTPUT_WORKFLOW)
outputFlags := workflow.FlagsetFromConfigurationOptions(outputWorkflow.GetConfigurationOptions())
rootCommand.PersistentFlags().AddFlagSet(outputFlags)
// add workflows as commands
createCommandsForWorkflows(rootCommand, globalEngine)
// init NetworkAccess
networkAccess := globalEngine.GetNetworkAccess()
networkAccess.AddHeaderField("x-snyk-cli-version", cliv2.GetFullVersion())
networkAccess.AddHeaderField(
"User-Agent",
networking.UserAgent(
networking.UaWithConfig(globalConfiguration),
networking.UaWithRuntimeInfo(rInfo),
networking.UaWithOS(internalOS)).String(),
)
if debugEnabled {
writeLogHeader(globalConfiguration, networkAccess)
}
// init Analytics
cliAnalytics := globalEngine.GetAnalytics()
cliAnalytics.SetVersion(cliv2.GetFullVersion())
cliAnalytics.SetCmdArguments(os.Args[1:])
cliAnalytics.SetOperatingSystem(internalOS)
if !globalConfiguration.GetBool(configuration.ANALYTICS_DISABLED) {
defer sendAnalytics(cliAnalytics, globalLogger)
}
setTimeout(globalConfiguration, func() {
os.Exit(constants.SNYK_EXIT_CODE_EX_UNAVAILABLE)
})
// run the extensible cli
err = rootCommand.Execute()
// fallback to the legacy cli or show help
handleErrorResult := handleError(err)
if handleErrorResult == handleErrorFallbackToLegacyCLI {
globalLogger.Printf("Using Legacy CLI to serve the command. (reason: %v)", err)
err = defaultCmd(os.Args[1:])
} else if handleErrorResult == handleErrorShowHelp {
err = help(nil, []string{})
}
if err != nil {
cliAnalytics.AddError(err)
}
displayError(err, os.Stdout, globalConfiguration)
exitCode := cliv2.DeriveExitCode(err)
globalLogger.Printf("Exiting with %d", exitCode)
return exitCode
}
func setTimeout(config configuration.Configuration, onTimeout func()) {
timeout := config.GetInt(configuration.TIMEOUT)
if timeout == 0 {
return
}
globalLogger.Printf("Command timeout set for %d seconds", timeout)
go func() {
const gracePeriodForSubProcesses = 3
<-time.After(time.Duration(timeout+gracePeriodForSubProcesses) * time.Second)
fmt.Fprintf(os.Stdout, "command timed out")
onTimeout()
}()
}