From 3e821ff4e55042b034d6c565ce4a24540550ee30 Mon Sep 17 00:00:00 2001 From: Ryan Mulligan Date: Tue, 18 Feb 2025 17:06:40 -0800 Subject: [PATCH] more lint fixes --- .gitignore | 1 + .golangci.yml | 20 ++++--------------- cmd/eiam/config.go | 6 +++--- internal/appconfig/arch_util/vars_amd64.go | 1 + internal/appconfig/arch_util/vars_linux.go | 1 + internal/eiamutil/fs_util.go | 16 +++++++++++++-- internal/errors/googleapi_error.go | 2 +- internal/errors/grpc_error.go | 14 +++++++------ internal/gcpclient/gcloud_config.go | 8 ++++---- internal/gcpclient/gke.go | 2 +- internal/gcpclient/iam.go | 2 +- .../gcpclient/query_iam/query_testable.go | 8 ++++---- internal/plugins/hclog_adapter.go | 2 ++ internal/plugins/install.go | 3 +-- internal/proxy/ca.go | 12 +++++------ internal/proxy/generate_certs.go | 3 +-- internal/proxy/http_proxy.go | 8 ++++++-- internal/proxy/shell.go | 3 +-- internal/root_command.go | 2 +- 19 files changed, 61 insertions(+), 53 deletions(-) diff --git a/.gitignore b/.gitignore index cc1accb..f6368a1 100644 --- a/.gitignore +++ b/.gitignore @@ -59,3 +59,4 @@ scripts/ # Ignore nix output result +/ephemeral-iam diff --git a/.golangci.yml b/.golangci.yml index 2ad1eaf..42a9d88 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -48,24 +48,11 @@ linters-settings: - HACK # marks hack-arounds that should be removed before merging goimports: local-prefixes: github.com/rigup/ephemeral-iam - golint: - min-confidence: 0 - gomnd: - settings: - mnd: - checks: argument,case,return - ifshort: - max-decl-lines: 1 - # Maximum length of variable declaration measured in number of characters, after which linter won't suggest using short syntax. - max-decl-chars: 30 lll: line-length: 120 - maligned: - suggest-new: true misspell: locale: US nolintlint: - allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space) allow-unused: false # report any unused nolint directives require-explanation: false # don't require an explanation for nolint directives require-specific: false # don't require nolint directives to be specific about which linter is being skipped @@ -77,7 +64,7 @@ linters: disable-all: true enable: - bodyclose - - depguard + # - depguard - dogsled - dupl - errcheck @@ -138,7 +125,9 @@ run: ############################################################################### output: # colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions - formats: tab + formats: + - format: tab + path: stdout sort-results: true ############################################################################### @@ -155,7 +144,6 @@ issues: linters: - errcheck - dupl - - gomnd - gosec - path: cmd linters: diff --git a/cmd/eiam/config.go b/cmd/eiam/config.go index 4678e7b..37a850a 100644 --- a/cmd/eiam/config.go +++ b/cmd/eiam/config.go @@ -17,7 +17,7 @@ package eiam import ( "errors" "fmt" - "io/ioutil" + "os" "strconv" "strings" @@ -117,7 +117,7 @@ func newCmdConfigPrint() *cobra.Command { Short: "Print the current configuration", RunE: func(cmd *cobra.Command, args []string) error { configFile := viper.ConfigFileUsed() - data, err := ioutil.ReadFile(configFile) + data, err := os.ReadFile(configFile) if err != nil { return errorsutil.New("Failed to read configuration file", err) } @@ -162,7 +162,7 @@ func newCmdConfigView() *cobra.Command { cmd := &cobra.Command{ Use: "view", Short: "View the value of a provided config item", - Args: cobra.ExactValidArgs(1), + Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), ValidArgs: viper.AllKeys(), Run: func(cmd *cobra.Command, args []string) { val := viper.Get(args[0]) diff --git a/internal/appconfig/arch_util/vars_amd64.go b/internal/appconfig/arch_util/vars_amd64.go index 9449a07..5a517ac 100644 --- a/internal/appconfig/arch_util/vars_amd64.go +++ b/internal/appconfig/arch_util/vars_amd64.go @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build amd64 // +build amd64 package archutil diff --git a/internal/appconfig/arch_util/vars_linux.go b/internal/appconfig/arch_util/vars_linux.go index 1b0b177..0633232 100644 --- a/internal/appconfig/arch_util/vars_linux.go +++ b/internal/appconfig/arch_util/vars_linux.go @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build linux // +build linux package archutil diff --git a/internal/eiamutil/fs_util.go b/internal/eiamutil/fs_util.go index d67786b..08ea9ac 100644 --- a/internal/eiamutil/fs_util.go +++ b/internal/eiamutil/fs_util.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "math" "net/http" "os" "path/filepath" @@ -36,10 +37,17 @@ func MoveFile(src, dst string) error { return nil } +func safeInt64ToUint32(num int64) (uint32, error) { + if num < 0 || num > math.MaxUint32 { + return 0, fmt.Errorf("value %d out of range for uint32", num) + } + return uint32(num), nil +} + func DownloadAndExtract(url, tmpDir, token string) error { Logger.Infof("Downloading archive from %s", url) - req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, http.NoBody) if err != nil { return err } @@ -83,7 +91,11 @@ func DownloadAndExtract(url, tmpDir, token string) error { case tar.TypeReg: target := filepath.Join(tmpDir, filepath.Clean(header.Name)) var f *os.File - f, err = os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode)) + mode, err := safeInt64ToUint32(header.Mode) + if err != nil { + return err + } + f, err = os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(mode)) if err != nil { return err } diff --git a/internal/errors/googleapi_error.go b/internal/errors/googleapi_error.go index d56f516..183e974 100644 --- a/internal/errors/googleapi_error.go +++ b/internal/errors/googleapi_error.go @@ -50,7 +50,7 @@ func checkGoogleAPIError(err error) EiamError { // TODO Check if message can be parsed from body. errMsg = gerr.Body } - return New(fmt.Sprintf("[Google API Error] %s", errStatusMsg), errors.New(errMsg)).(EiamError) + return New(fmt.Sprintf("[Google API Error] %s", errStatusMsg), errors.New(errMsg)).(EiamError) //nolint: errcheck } return EiamError{} } diff --git a/internal/errors/grpc_error.go b/internal/errors/grpc_error.go index 8662c93..2df2d4e 100644 --- a/internal/errors/grpc_error.go +++ b/internal/errors/grpc_error.go @@ -70,9 +70,11 @@ func checkGoogleRPCError(err error) EiamError { for title, details := range errDetails { errMsg += fmt.Sprintf("[%s]\n%s\n", title, details) } - return New(errMsg, errField).(EiamError) + return New(errMsg, errField).(EiamError) //nolint: errcheck } - return New("A gRPC error occurred. For more information, set the logging level to debug", errField).(EiamError) + return New( //nolint: errcheck + "A gRPC error occurred. For more information, set the logging level to debug", + errField).(EiamError) } return EiamError{} } @@ -105,7 +107,7 @@ func parseRPCStatusDebugInfo(detail *anypb.Any) string { if len(traces) > 0 { fmt.Fprintf(&buf, " Stack Trace:\n %s", strings.Join(traces, "\n ")) } - if len(details) > 0 { + if details != "" { fmt.Fprintf(&buf, " Details:\n %s", details) } } @@ -123,11 +125,11 @@ func parseRPCStatusErrorInfo(detail *anypb.Any) string { } else { domain := errInfo.GetDomain() reason := errInfo.GetReason() - if len(domain) > 0 && len(reason) > 0 { + if domain != "" && reason != "" { fmt.Fprintf(&buf, " Reason:\n %s: %s\n", domain, reason) - } else if len(domain) > 0 { + } else if domain != "" { fmt.Fprintf(&buf, " Domain:\n %s\n", domain) - } else if len(reason) > 0 { + } else if reason != "" { fmt.Fprintf(&buf, " Reason:\n %s\n", reason) } diff --git a/internal/gcpclient/gcloud_config.go b/internal/gcpclient/gcloud_config.go index 9172cf5..4745709 100644 --- a/internal/gcpclient/gcloud_config.go +++ b/internal/gcpclient/gcloud_config.go @@ -15,8 +15,8 @@ package gcpclient import ( + "errors" "fmt" - "io/ioutil" "os" "os/user" "path" @@ -84,7 +84,7 @@ func getActiveConfig(configDir string) (string, error) { return activeConfig, nil } - configFromFile, err := ioutil.ReadFile(activeConfigFile) + configFromFile, err := os.ReadFile(activeConfigFile) if err != nil { return "", errorsutil.New("Failed to get active gcloud config", err) } @@ -118,7 +118,7 @@ func setActiveConfig(configsDir, activeConfigFile string) (string, error) { defer fd.Close() util.Logger.Infof("Setting active gcloud config to %s", configName) - if _, err := fd.Write([]byte(configName)); err != nil { + if _, err := fd.WriteString(configName); err != nil { return "", errorsutil.New("Failed to write gcloud config file", err) } return configName, nil @@ -189,7 +189,7 @@ func CheckActiveAccountSet() (string, error) { } acct := gcloudConfig.Section("core").Key("account").String() if acct == "" { - err := fmt.Errorf(dedent.Dedent(`no active account set for gcloud. please run: + err := errors.New(dedent.Dedent(`no active account set for gcloud. please run: $ gcloud auth login diff --git a/internal/gcpclient/gke.go b/internal/gcpclient/gke.go index e909cd5..7bd47c5 100644 --- a/internal/gcpclient/gke.go +++ b/internal/gcpclient/gke.go @@ -19,8 +19,8 @@ import ( "fmt" container "cloud.google.com/go/container/apiv1" + "cloud.google.com/go/container/apiv1/containerpb" "google.golang.org/api/option" - containerpb "google.golang.org/genproto/googleapis/container/v1" util "github.com/replit/ephemeral-iam/internal/eiamutil" errorsutil "github.com/replit/ephemeral-iam/internal/errors" diff --git a/internal/gcpclient/iam.go b/internal/gcpclient/iam.go index 4a6322d..b4ffb1d 100644 --- a/internal/gcpclient/iam.go +++ b/internal/gcpclient/iam.go @@ -20,8 +20,8 @@ import ( "sync" "time" + "cloud.google.com/go/iam/credentials/apiv1/credentialspb" "google.golang.org/api/iam/v1" - credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" "google.golang.org/protobuf/types/known/durationpb" util "github.com/replit/ephemeral-iam/internal/eiamutil" diff --git a/internal/gcpclient/query_iam/query_testable.go b/internal/gcpclient/query_iam/query_testable.go index 1275a3c..b97f7d9 100644 --- a/internal/gcpclient/query_iam/query_testable.go +++ b/internal/gcpclient/query_iam/query_testable.go @@ -84,7 +84,7 @@ func QueryComputeInstancePermissions( var computeService *compute.Service if svcAcct != "" { clientOptions := []option.ClientOption{ - option.ImpersonateCredentials(svcAcct), + option.ImpersonateCredentials(svcAcct), //nolint: staticcheck option.WithRequestReason(reason), } if svc, err := compute.NewService(ctx, clientOptions...); err == nil { @@ -131,7 +131,7 @@ func QueryProjectPermissions(permsToTest []string, project, svcAcct, reason stri var crmService *crm.Service if svcAcct != "" { clientOptions := []option.ClientOption{ - option.ImpersonateCredentials(svcAcct), + option.ImpersonateCredentials(svcAcct), //nolint: staticcheck option.WithRequestReason(reason), } if svc, err := crm.NewService(ctx, clientOptions...); err == nil { @@ -186,7 +186,7 @@ func QueryPubSubPermissions(permsToTest []string, project, topic, svcAcct, reaso var pubsubService *pubsub.Service if svcAcct != "" { clientOptions := []option.ClientOption{ - option.ImpersonateCredentials(svcAcct), + option.ImpersonateCredentials(svcAcct), //nolint: staticcheck option.WithRequestReason(reason), } if svc, err := pubsub.NewService(ctx, clientOptions...); err == nil { @@ -241,7 +241,7 @@ func QueryStorageBucketPermissions(permsToTest []string, bucket, svcAcct, reason var storageService *storage.Service if svcAcct != "" { clientOptions := []option.ClientOption{ - option.ImpersonateCredentials(svcAcct), + option.ImpersonateCredentials(svcAcct), //nolint: staticcheck option.WithRequestReason(reason), } if svc, err := storage.NewService(ctx, clientOptions...); err == nil { diff --git a/internal/plugins/hclog_adapter.go b/internal/plugins/hclog_adapter.go index cd2caa7..601d103 100644 --- a/internal/plugins/hclog_adapter.go +++ b/internal/plugins/hclog_adapter.go @@ -43,6 +43,8 @@ type HCLogAdapter struct { func (h HCLogAdapter) Log(level hclog.Level, msg string, args ...interface{}) { switch level { + case hclog.Off: + return case hclog.NoLevel: return case hclog.Trace: diff --git a/internal/plugins/install.go b/internal/plugins/install.go index a55b062..0267ca8 100644 --- a/internal/plugins/install.go +++ b/internal/plugins/install.go @@ -3,7 +3,6 @@ package plugins import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" @@ -64,7 +63,7 @@ func installDownloadedPlugin(tmpDir string) error { pluginDir := filepath.Join(appconfig.GetConfigDir(), "plugins") for _, file := range files { fp := filepath.Join(tmpDir, file.Name()) - buf, err := ioutil.ReadFile(fp) + buf, err := os.ReadFile(fp) if err != nil { return errorsutil.New("Failed to read file downloaded in release", err) } diff --git a/internal/proxy/ca.go b/internal/proxy/ca.go index 4c786e7..5eee3ac 100644 --- a/internal/proxy/ca.go +++ b/internal/proxy/ca.go @@ -21,9 +21,9 @@ import ( "crypto/x509" "crypto/x509/pkix" "fmt" - "io/ioutil" "math/big" "net" + "os" "strconv" "strings" "time" @@ -35,11 +35,11 @@ import ( // See https://github.com/rhaidiz/broxy/modules/coreproxy/coreproxy.go func setCa(caCertFile, caKeyFile string) error { - caCert, err := ioutil.ReadFile(caCertFile) + caCert, err := os.ReadFile(caCertFile) if err != nil { return errorsutil.New(fmt.Sprintf("Failed to read CA certificate file %s", caCertFile), err) } - caKey, err := ioutil.ReadFile(caKeyFile) + caKey, err := os.ReadFile(caKeyFile) if err != nil { return errorsutil.New(fmt.Sprintf("Failed to read CA certificate key file %s", caCertFile), err) } @@ -98,7 +98,7 @@ func signHost(ca *tls.Certificate, host string) (cert *tls.Certificate, err erro var template x509.Certificate if x509ca, err = x509.ParseCertificate(ca.Certificate[0]); err != nil { - return + return cert, err } notBefore := time.Now() @@ -132,12 +132,12 @@ func signHost(ca *tls.Certificate, host string) (cert *tls.Certificate, err erro var certpriv *rsa.PrivateKey if certpriv, err = rsa.GenerateKey(rand.Reader, 2048); err != nil { - return + return cert, err } derBytes, err := x509.CreateCertificate(rand.Reader, &template, x509ca, &certpriv.PublicKey, ca.PrivateKey) if err != nil { - return + return cert, err } return &tls.Certificate{ diff --git a/internal/proxy/generate_certs.go b/internal/proxy/generate_certs.go index c38da43..5a22824 100644 --- a/internal/proxy/generate_certs.go +++ b/internal/proxy/generate_certs.go @@ -22,7 +22,6 @@ import ( "crypto/x509/pkix" "encoding/pem" "fmt" - "io/ioutil" "math/big" "os" "path/filepath" @@ -196,7 +195,7 @@ func readCert(certFile string) (cert *x509.Certificate, err error) { var certBytes []byte var certBlock *pem.Block - if certBytes, err = ioutil.ReadFile(certFile); err != nil { + if certBytes, err = os.ReadFile(certFile); err != nil { return nil, errorsutil.New("Failed to read certificate file", err) } if certBlock, _ = pem.Decode(certBytes); certBlock == nil { diff --git a/internal/proxy/http_proxy.go b/internal/proxy/http_proxy.go index db1ce60..6bc4ef5 100644 --- a/internal/proxy/http_proxy.go +++ b/internal/proxy/http_proxy.go @@ -154,8 +154,12 @@ func createProxy(accessToken, reason string) (*http.Server, error) { }) srv := &http.Server{ - Addr: fmt.Sprintf("%s:%s", viper.GetString(appconfig.AuthProxyAddress), viper.GetString(appconfig.AuthProxyPort)), - Handler: proxy, + Addr: fmt.Sprintf( + "%s:%s", + viper.GetString(appconfig.AuthProxyAddress), + viper.GetString(appconfig.AuthProxyPort)), + Handler: proxy, + ReadHeaderTimeout: 5 * time.Second, } return srv, nil } diff --git a/internal/proxy/shell.go b/internal/proxy/shell.go index d0ede00..9ab59c4 100644 --- a/internal/proxy/shell.go +++ b/internal/proxy/shell.go @@ -19,7 +19,6 @@ import ( "fmt" "io" "io/fs" - "io/ioutil" "os" "os/exec" "os/signal" @@ -159,7 +158,7 @@ func createTempKubeConfig() (*os.File, error) { func writeCredsToKubeConfig(tmpKubeConfig *os.File, accessToken, expiry string) error { // Read the tmpKubeConfig into a client-go config object. config := clientcmdapi.NewConfig() - configBytes, err := ioutil.ReadFile(tmpKubeConfig.Name()) + configBytes, err := os.ReadFile(tmpKubeConfig.Name()) if err != nil { return errorsutil.New("Failed to read generated tmp kubeconfig", err) } diff --git a/internal/root_command.go b/internal/root_command.go index 4977409..a844654 100644 --- a/internal/root_command.go +++ b/internal/root_command.go @@ -99,7 +99,7 @@ func loadPlugin(pf, pluginsDir string) (plugins.EIAMPlugin, *hcplugin.Client, er if err != nil { return nil, nil, err } - return raw.(plugins.EIAMPlugin), client, nil + return raw.(plugins.EIAMPlugin), client, nil //nolint: errcheck } func addPluginCmd(p plugins.EIAMPlugin) (cmd *cobra.Command, name, desc, version string, err error) {