From 2dab7ba1e2beac2934109e8fe479f2cb25b9bb35 Mon Sep 17 00:00:00 2001 From: PeterSchafer <101886095+PeterSchafer@users.noreply.github.com> Date: Mon, 9 Oct 2023 09:08:28 +0200 Subject: [PATCH] chore: apply refactorings from a previous PR (#4896) * chore: rename FilteredArgs() * chore: use boolean instead of int * chore: add missing comment * chore: move logheader functions in separate file * chore: fix spelling * fix: add missing import for fips --- cliv2/Makefile | 2 +- cliv2/cmd/cliv2/logheader.go | 117 ++++++++++++++++++++ cliv2/cmd/cliv2/main.go | 112 +------------------ cliv2/pkg/basic_workflows/legacycli.go | 4 +- cliv2/pkg/basic_workflows/legacycli_test.go | 12 +- 5 files changed, 131 insertions(+), 116 deletions(-) create mode 100644 cliv2/cmd/cliv2/logheader.go diff --git a/cliv2/Makefile b/cliv2/Makefile index 95bd16d9e6..e3cc81c3f6 100644 --- a/cliv2/Makefile +++ b/cliv2/Makefile @@ -144,7 +144,7 @@ configure: summary $(CACHE_DIR) $(CACHE_DIR)/variables.mk $(V1_DIRECTORY)/$(V1_E $(BUILD_DIR)/$(V2_EXECUTABLE_NAME): $(BUILD_DIR) $(SRCS) generate-ls-protocol-metadata @echo "$(LOG_PREFIX) Building ( $(BUILD_DIR)/$(V2_EXECUTABLE_NAME) )" - @GOEXPERIMENT=$(FIPS_CRYPTO_BACKEND) GOOS=$(_GO_OS) GOARCH=$(GOARCH) $(GOCMD) build -tags=application -ldflags="$(LDFLAGS) -X github.com/snyk/snyk-ls/application/config.Version=$(LS_COMMIT_HASH) -X github.com/snyk/snyk-ls/application/config.LsProtocolVersion=$(LS_PROTOCOL_VERSION) -X main.internalOS=$(GOOS) -X github.com/snyk/cli/cliv2/internal/embedded/cliv1.snykCLIVersion=$(CLI_V1_VERSION_TAG)" -o $(BUILD_DIR)/$(V2_EXECUTABLE_NAME) $(WORKING_DIR)/cmd/cliv2/main.go + @GOEXPERIMENT=$(FIPS_CRYPTO_BACKEND) GOOS=$(_GO_OS) GOARCH=$(GOARCH) $(GOCMD) build -tags=application -ldflags="$(LDFLAGS) -X github.com/snyk/snyk-ls/application/config.Version=$(LS_COMMIT_HASH) -X github.com/snyk/snyk-ls/application/config.LsProtocolVersion=$(LS_PROTOCOL_VERSION) -X main.internalOS=$(GOOS) -X github.com/snyk/cli/cliv2/internal/embedded/cliv1.snykCLIVersion=$(CLI_V1_VERSION_TAG)" -o $(BUILD_DIR)/$(V2_EXECUTABLE_NAME) $(WORKING_DIR)/cmd/cliv2/*.go .PHONY: fips fips: diff --git a/cliv2/cmd/cliv2/logheader.go b/cliv2/cmd/cliv2/logheader.go new file mode 100644 index 0000000000..04129518a2 --- /dev/null +++ b/cliv2/cmd/cliv2/logheader.go @@ -0,0 +1,117 @@ +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 ( + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" + "regexp" + "strings" + + "github.com/snyk/go-application-framework/pkg/auth" + "github.com/snyk/go-application-framework/pkg/configuration" + "github.com/snyk/go-application-framework/pkg/networking" + "github.com/snyk/go-application-framework/pkg/networking/fips" + + "github.com/snyk/cli/cliv2/internal/cliv2" +) + +func logHeaderAuthorizationInfo( + config configuration.Configuration, + networkAccess networking.NetworkAccess, +) (string, string, string) { + oauthEnabled := "Disabled" + authorization := "" + tokenShaSum := "" + tokenDetails := "" + userAgent := "" + + apiRequest := &http.Request{ + URL: config.GetUrl(configuration.API_URL), + Header: http.Header{}, + } + + err := networkAccess.AddHeaders(apiRequest) + if err != nil { + debugLogger.Print(err) + } + + authHeader := apiRequest.Header.Get("Authorization") + splitHeader := strings.Split(authHeader, " ") + if len(splitHeader) == 2 { + tokenType := splitHeader[0] + token := splitHeader[1] + temp := sha256.Sum256([]byte(token)) + tokenShaSum = hex.EncodeToString(temp[0:16]) + "[...]" + tokenDetails = fmt.Sprintf(" (type=%s)", tokenType) + } + + if config.GetBool(configuration.FF_OAUTH_AUTH_FLOW_ENABLED) { + oauthEnabled = "Enabled" + token, err := auth.GetOAuthToken(config) + if token != nil && err == nil { + tokenDetails = fmt.Sprintf(" (type=oauth; expiry=%v)", token.Expiry.UTC()) + temp := sha256.Sum256([]byte(token.AccessToken)) + tokenShaSum = hex.EncodeToString(temp[0:16]) + "[...]" + } + } + + userAgent = apiRequest.Header.Get("User-Agent") + platformFromUserAgent := strings.Split(userAgent, " ") + if len(platformFromUserAgent) > 1 { + userAgent = strings.Join(platformFromUserAgent[1:], " ") + r, _ := regexp.Compile("[();]") + userAgent = strings.TrimSpace(r.ReplaceAllString(userAgent, " ")) + } + + authorization = fmt.Sprintf("%s %s", tokenShaSum, tokenDetails) + + return authorization, oauthEnabled, userAgent +} + +func getFipsStatus(config configuration.Configuration) string { + fipsEnabled := "Disabled" + if !fips.IsAvailable() { + fipsEnabled = "Not available" + } else if config.GetBool(configuration.FIPS_ENABLED) { + fipsEnabled = "Enabled" + } + return fipsEnabled +} + +func writeLogHeader(config configuration.Configuration, networkAccess networking.NetworkAccess) { + authorization, oauthEnabled, userAgent := logHeaderAuthorizationInfo(config, networkAccess) + + org := config.GetString(configuration.ORGANIZATION) + insecureHTTPS := "false" + if config.GetBool(configuration.INSECURE_HTTPS) { + insecureHTTPS = "true" + } + + analytics := "enabled" + if config.GetBool(configuration.ANALYTICS_DISABLED) { + analytics = "disabled" + } + + tablePrint := func(name string, value string) { + debugLogger.Printf("%-22s %s", name+":", value) + } + + fipsEnabled := getFipsStatus(config) + + tablePrint("Version", cliv2.GetFullVersion()) + tablePrint("Platform", userAgent) + tablePrint("API", config.GetString(configuration.API_URL)) + tablePrint("Cache", config.GetString(configuration.CACHE_PATH)) + tablePrint("Organization", org) + tablePrint("Insecure HTTPS", insecureHTTPS) + tablePrint("Analytics", analytics) + tablePrint("Authorization", authorization) + tablePrint("Features", "") + tablePrint(" oauth", oauthEnabled) + tablePrint(" fips", fipsEnabled) + +} diff --git a/cliv2/cmd/cliv2/main.go b/cliv2/cmd/cliv2/main.go index 1c3ab77f87..04f750478b 100644 --- a/cliv2/cmd/cliv2/main.go +++ b/cliv2/cmd/cliv2/main.go @@ -4,20 +4,14 @@ package main import _ "github.com/snyk/go-application-framework/pkg/networking/fips_enable" import ( - "crypto/sha256" - "encoding/hex" "encoding/json" "fmt" "io" - "net/http" "os" "os/exec" - "regexp" "strings" "time" - "github.com/snyk/go-application-framework/pkg/networking/fips" - "github.com/rs/zerolog" "github.com/snyk/cli-extension-dep-graph/pkg/depgraph" "github.com/snyk/cli-extension-iac-rules/iacrules" @@ -145,12 +139,12 @@ func getFullCommandString(cmd *cobra.Command) string { func updateConfigFromParameter(config configuration.Configuration, args []string, rawArgs []string) { // extract everything behind -- doubleDashArgs := []string{} - doubleDashPosition := -1 - for i, v := range rawArgs { - if doubleDashPosition >= 0 { + doubleDashFound := false + for _, v := range rawArgs { + if doubleDashFound { doubleDashArgs = append(doubleDashArgs, v) } else if v == "--" { - doubleDashPosition = i + doubleDashFound = true } } config.Set(configuration.UNKNOWN_ARGS, doubleDashArgs) @@ -163,6 +157,7 @@ func updateConfigFromParameter(config configuration.Configuration, args []string // 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) } @@ -357,103 +352,6 @@ func displayError(err error) { } } -func logHeaderAuthorizationInfo( - config configuration.Configuration, - networkAccess networking.NetworkAccess, -) (string, string, string) { - oauthEnabled := "Disabled" - authorization := "" - tokenShaSum := "" - tokenDetails := "" - userAgent := "" - - apiRequest := &http.Request{ - URL: config.GetUrl(configuration.API_URL), - Header: http.Header{}, - } - - err := networkAccess.AddHeaders(apiRequest) - if err != nil { - debugLogger.Print(err) - } - - authHeader := apiRequest.Header.Get("Authorization") - splitHeader := strings.Split(authHeader, " ") - if len(splitHeader) == 2 { - tokenType := splitHeader[0] - token := splitHeader[1] - temp := sha256.Sum256([]byte(token)) - tokenShaSum = hex.EncodeToString(temp[0:16]) + "[...]" - tokenDetails = fmt.Sprintf(" (type=%s)", tokenType) - } - - if config.GetBool(configuration.FF_OAUTH_AUTH_FLOW_ENABLED) { - oauthEnabled = "Enabled" - token, err := auth.GetOAuthToken(config) - if token != nil && err == nil { - tokenDetails = fmt.Sprintf(" (type=oauth; expiry=%v)", token.Expiry.UTC()) - temp := sha256.Sum256([]byte(token.AccessToken)) - tokenShaSum = hex.EncodeToString(temp[0:16]) + "[...]" - } - } - - userAgent = apiRequest.Header.Get("User-Agent") - platformFromUserAgent := strings.Split(userAgent, " ") - if len(platformFromUserAgent) > 1 { - userAgent = strings.Join(platformFromUserAgent[1:], " ") - r, _ := regexp.Compile("[();]") - userAgent = strings.TrimSpace(r.ReplaceAllString(userAgent, " ")) - } - - authorization = fmt.Sprintf("%s %s", tokenShaSum, tokenDetails) - - return authorization, oauthEnabled, userAgent -} - -func getFipsStatus(config configuration.Configuration) string { - fipsEnabled := "Disabled" - if !fips.IsAvailable() { - fipsEnabled = "Not available" - } else if config.GetBool(configuration.FIPS_ENABLED) { - fipsEnabled = "Enabled" - } - return fipsEnabled -} - -func writeLogHeader(config configuration.Configuration, networkAccess networking.NetworkAccess) { - authorization, oauthEnabled, userAgent := logHeaderAuthorizationInfo(config, networkAccess) - - org := config.GetString(configuration.ORGANIZATION) - insecureHTTPS := "false" - if config.GetBool(configuration.INSECURE_HTTPS) { - insecureHTTPS = "true" - } - - analytics := "enabled" - if config.GetBool(configuration.ANALYTICS_DISABLED) { - analytics = "disabled" - } - - tablePrint := func(name string, value string) { - debugLogger.Printf("%-22s %s", name+":", value) - } - - fipsEnabled := getFipsStatus(config) - - tablePrint("Version", cliv2.GetFullVersion()) - tablePrint("Platform", userAgent) - tablePrint("API", config.GetString(configuration.API_URL)) - tablePrint("Cache", config.GetString(configuration.CACHE_PATH)) - tablePrint("Organization", org) - tablePrint("Insecure HTTPS", insecureHTTPS) - tablePrint("Analytics", analytics) - tablePrint("Authorization", authorization) - tablePrint("Features", "") - tablePrint(" oauth", oauthEnabled) - tablePrint(" fips", fipsEnabled) - -} - func MainWithErrorCode() int { var err error diff --git a/cliv2/pkg/basic_workflows/legacycli.go b/cliv2/pkg/basic_workflows/legacycli.go index c05ccfabcb..3ad2da0c14 100644 --- a/cliv2/pkg/basic_workflows/legacycli.go +++ b/cliv2/pkg/basic_workflows/legacycli.go @@ -38,7 +38,7 @@ func Init(engine workflow.Engine) error { return nil } -func FilteredArgs(args []string, unknownArgs []string) []string { +func finalizeArguments(args []string, unknownArgs []string) []string { // filter args not meant to be forwarded to CLIv1 or an Extensions elementsToFilter := []string{"--" + PROXY_NOAUTH} filteredArgs := args @@ -150,7 +150,7 @@ func legacycliWorkflow( // run the cli proxyInfo := wrapperProxy.ProxyInfo() - err = cli.Execute(proxyInfo, FilteredArgs(args, config.GetStringSlice(configuration.UNKNOWN_ARGS))) + err = cli.Execute(proxyInfo, finalizeArguments(args, config.GetStringSlice(configuration.UNKNOWN_ARGS))) if !useStdIo { outWriter.Flush() diff --git a/cliv2/pkg/basic_workflows/legacycli_test.go b/cliv2/pkg/basic_workflows/legacycli_test.go index f024033ed8..3e226c81c4 100644 --- a/cliv2/pkg/basic_workflows/legacycli_test.go +++ b/cliv2/pkg/basic_workflows/legacycli_test.go @@ -6,20 +6,20 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_FilteredArgs(t *testing.T) { +func Test_finalizeArguments(t *testing.T) { expected := []string{"a", "b", "c", "--", "d", "e", "f"} - actual := FilteredArgs([]string{"a", "b", "c"}, []string{"d", "e", "f"}) + actual := finalizeArguments([]string{"a", "b", "c"}, []string{"d", "e", "f"}) assert.Equal(t, expected, actual) } -func Test_FilteredArgs_doubleDashNotAppend(t *testing.T) { +func Test_finalizeArguments_doubleDashNotAppend(t *testing.T) { expected := []string{"a", "b", "c", "--", "x"} - actual := FilteredArgs([]string{"a", "b", "c", "--", "x"}, []string{"d", "e", "f"}) + actual := finalizeArguments([]string{"a", "b", "c", "--", "x"}, []string{"d", "e", "f"}) assert.Equal(t, expected, actual) } -func Test_FilteredArgs_(t *testing.T) { +func Test_finalizeArguments_(t *testing.T) { expected := []string{"a", "b", "c", "--", "d", "e", "f"} - actual := FilteredArgs([]string{"a", "b", "--proxy-noauth", "c"}, []string{"d", "e", "f"}) + actual := finalizeArguments([]string{"a", "b", "--proxy-noauth", "c"}, []string{"d", "e", "f"}) assert.Equal(t, expected, actual) }