Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: apply refactorings from a previous PR #4896

Merged
merged 6 commits into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cliv2/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
117 changes: 117 additions & 0 deletions cliv2/cmd/cliv2/logheader.go
Original file line number Diff line number Diff line change
@@ -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)

}
112 changes: 5 additions & 107 deletions cliv2/cmd/cliv2/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}

Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions cliv2/pkg/basic_workflows/legacycli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
12 changes: 6 additions & 6 deletions cliv2/pkg/basic_workflows/legacycli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Loading