From eeaf9f76d5b578f0a6f1e58c6f1bfe881cae7f6d Mon Sep 17 00:00:00 2001 From: Hidde Beydals Date: Mon, 14 Aug 2023 23:35:54 +0200 Subject: [PATCH] *: address various simple `staticcheck` warnings Deprecation of `io/ioutil`, removal of unused functions, possible nil pointer dereference, and other tiny nits. There are (many) more, but these would require their own (commit) context. Signed-off-by: Hidde Beydals --- audit/audit.go | 8 ++++---- cmd/sops/common/common.go | 11 +++++------ cmd/sops/edit.go | 22 +++++++++------------- cmd/sops/encrypt.go | 9 ++++----- cmd/sops/subcommand/exec/exec.go | 5 ++--- cmd/sops/subcommand/publish/publish.go | 11 ++--------- config/config.go | 7 +++---- decrypt/decrypt.go | 4 ++-- go.mod | 2 +- keyservice/server.go | 2 +- pgp/keysource.go | 8 ++++---- pgp/keysource_test.go | 2 +- stores/yaml/store.go | 20 ++++++++++---------- usererrors.go | 10 +++++----- 14 files changed, 53 insertions(+), 68 deletions(-) diff --git a/audit/audit.go b/audit/audit.go index 035783e4e..1bbfde1cd 100644 --- a/audit/audit.go +++ b/audit/audit.go @@ -4,7 +4,7 @@ import ( "database/sql" "flag" "fmt" - "io/ioutil" + "os" "os/user" "github.com/pkg/errors" @@ -12,16 +12,16 @@ import ( // empty import as per https://godoc.org/github.com/lib/pq _ "github.com/lib/pq" - "gopkg.in/yaml.v3" - "github.com/sirupsen/logrus" "github.com/getsops/sops/v3/logging" + "github.com/sirupsen/logrus" + "gopkg.in/yaml.v3" ) var log *logrus.Logger func init() { log = logging.NewLogger("AUDIT") - confBytes, err := ioutil.ReadFile(configFile) + confBytes, err := os.ReadFile(configFile) if err != nil { log.WithField("error", err).Debugf("Error reading config") return diff --git a/cmd/sops/common/common.go b/cmd/sops/common/common.go index b675195bc..907125d28 100644 --- a/cmd/sops/common/common.go +++ b/cmd/sops/common/common.go @@ -2,14 +2,11 @@ package common import ( "fmt" - "io/ioutil" "os" "path/filepath" "time" "github.com/fatih/color" - wordwrap "github.com/mitchellh/go-wordwrap" - "github.com/urfave/cli" "github.com/getsops/sops/v3" "github.com/getsops/sops/v3/cmd/sops/codes" . "github.com/getsops/sops/v3/cmd/sops/formats" @@ -21,7 +18,9 @@ import ( "github.com/getsops/sops/v3/stores/json" "github.com/getsops/sops/v3/stores/yaml" "github.com/getsops/sops/v3/version" - "golang.org/x/crypto/ssh/terminal" + "github.com/mitchellh/go-wordwrap" + "github.com/urfave/cli" + "golang.org/x/term" ) // ExampleFileEmitter emits example files. This is used by the `sops` binary @@ -127,7 +126,7 @@ func EncryptTree(opts EncryptTreeOpts) error { // LoadEncryptedFile loads an encrypted SOPS file, returning a SOPS tree func LoadEncryptedFile(loader sops.EncryptedFileLoader, inputPath string) (*sops.Tree, error) { - fileBytes, err := ioutil.ReadFile(inputPath) + fileBytes, err := os.ReadFile(inputPath) if err != nil { return nil, NewExitError(fmt.Sprintf("Error reading file: %s", err), codes.CouldNotReadInputFile) } @@ -262,7 +261,7 @@ func FixAWSKMSEncryptionContextBug(opts GenericDecryptOpts, tree *sops.Tree) (*s persistFix := false - if terminal.IsTerminal(int(os.Stdout.Fd())) { + if term.IsTerminal(int(os.Stdout.Fd())) { var response string for response != "y" && response != "n" { fmt.Println("Would you like sops to automatically fix this issue? (y/n): ") diff --git a/cmd/sops/edit.go b/cmd/sops/edit.go index e72d8fb23..730d99214 100644 --- a/cmd/sops/edit.go +++ b/cmd/sops/edit.go @@ -1,26 +1,22 @@ package main import ( - "fmt" - "io/ioutil" - "os" - - "crypto/md5" - exec "golang.org/x/sys/execabs" - "io" - "strings" - "bufio" "bytes" - + "crypto/md5" + "fmt" + "io" + "os" "path/filepath" + "strings" - "github.com/google/shlex" "github.com/getsops/sops/v3" "github.com/getsops/sops/v3/cmd/sops/codes" "github.com/getsops/sops/v3/cmd/sops/common" "github.com/getsops/sops/v3/keyservice" "github.com/getsops/sops/v3/version" + "github.com/google/shlex" + exec "golang.org/x/sys/execabs" ) type editOpts struct { @@ -109,7 +105,7 @@ func edit(opts editOpts) ([]byte, error) { func editTree(opts editOpts, tree *sops.Tree, dataKey []byte) ([]byte, error) { // Create temporary file for editing - tmpdir, err := ioutil.TempDir("", "") + tmpdir, err := os.MkdirTemp("", "") if err != nil { return nil, common.NewExitError(fmt.Sprintf("Could not create temporary directory: %s", err), codes.CouldNotWriteOutputFile) } @@ -181,7 +177,7 @@ func runEditorUntilOk(opts runEditorUntilOkOpts) error { if bytes.Equal(newHash, opts.OriginalHash) { return common.NewExitError("File has not changed, exiting.", codes.FileHasNotBeenModified) } - edited, err := ioutil.ReadFile(opts.TmpFile.Name()) + edited, err := os.ReadFile(opts.TmpFile.Name()) if err != nil { return common.NewExitError(fmt.Sprintf("Could not read edited file: %s", err), codes.CouldNotReadInputFile) } diff --git a/cmd/sops/encrypt.go b/cmd/sops/encrypt.go index 195833ae6..cfb16ab18 100644 --- a/cmd/sops/encrypt.go +++ b/cmd/sops/encrypt.go @@ -1,17 +1,16 @@ package main import ( - "io/ioutil" - "path/filepath" - "fmt" + "os" + "path/filepath" - wordwrap "github.com/mitchellh/go-wordwrap" "github.com/getsops/sops/v3" "github.com/getsops/sops/v3/cmd/sops/codes" "github.com/getsops/sops/v3/cmd/sops/common" "github.com/getsops/sops/v3/keyservice" "github.com/getsops/sops/v3/version" + "github.com/mitchellh/go-wordwrap" ) type encryptOpts struct { @@ -57,7 +56,7 @@ func ensureNoMetadata(opts encryptOpts, branch sops.TreeBranch) error { func encrypt(opts encryptOpts) (encryptedFile []byte, err error) { // Load the file - fileBytes, err := ioutil.ReadFile(opts.InputPath) + fileBytes, err := os.ReadFile(opts.InputPath) if err != nil { return nil, common.NewExitError(fmt.Sprintf("Error reading file: %s", err), codes.CouldNotReadInputFile) } diff --git a/cmd/sops/subcommand/exec/exec.go b/cmd/sops/subcommand/exec/exec.go index 720b2431d..c32739f20 100644 --- a/cmd/sops/subcommand/exec/exec.go +++ b/cmd/sops/subcommand/exec/exec.go @@ -2,7 +2,6 @@ package exec import ( "bytes" - "io/ioutil" "os" "runtime" "strings" @@ -28,7 +27,7 @@ type ExecOpts struct { } func GetFile(dir, filename string) *os.File { - handle, err := ioutil.TempFile(dir, filename) + handle, err := os.CreateTemp(dir, filename) if err != nil { log.Fatal(err) } @@ -45,7 +44,7 @@ func ExecWithFile(opts ExecOpts) error { opts.Fifo = false } - dir, err := ioutil.TempDir("", ".sops") + dir, err := os.MkdirTemp("", ".sops") if err != nil { log.Fatal(err) } diff --git a/cmd/sops/subcommand/publish/publish.go b/cmd/sops/subcommand/publish/publish.go index ee0dd27ae..dcaf0f31e 100644 --- a/cmd/sops/subcommand/publish/publish.go +++ b/cmd/sops/subcommand/publish/publish.go @@ -3,7 +3,7 @@ package publish import ( "errors" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" @@ -130,7 +130,7 @@ func Run(opts Opts) error { return common.NewExitError(fmt.Sprintf("Could not marshal tree: %s", err), codes.ErrorDumpingTree) } } else { - fileContents, err = ioutil.ReadFile(path) + fileContents, err = os.ReadFile(path) if err != nil { return fmt.Errorf("could not read file: %s", err) } @@ -184,10 +184,3 @@ func Run(opts Opts) error { return nil } - -func min(a, b int) int { - if a < b { - return a - } - return b -} diff --git a/config/config.go b/config/config.go index a96593068..311604634 100644 --- a/config/config.go +++ b/config/config.go @@ -5,14 +5,12 @@ package config //import "github.com/getsops/sops/v3/config" import ( "fmt" - "io/ioutil" "os" "path" "path/filepath" "regexp" "strings" - "github.com/sirupsen/logrus" "github.com/getsops/sops/v3" "github.com/getsops/sops/v3/age" "github.com/getsops/sops/v3/azkv" @@ -22,6 +20,7 @@ import ( "github.com/getsops/sops/v3/logging" "github.com/getsops/sops/v3/pgp" "github.com/getsops/sops/v3/publish" + "github.com/sirupsen/logrus" "gopkg.in/yaml.v3" ) @@ -223,7 +222,7 @@ func getKeyGroupsFromCreationRule(cRule *creationRule, kmsEncryptionContext map[ } func loadConfigFile(confPath string) (*configFile, error) { - confBytes, err := ioutil.ReadFile(confPath) + confBytes, err := os.ReadFile(confPath) if err != nil { return nil, fmt.Errorf("could not read config file: %s", err) } @@ -329,7 +328,7 @@ func parseCreationRuleForFile(conf *configFile, confPath, filePath string, kmsEn } // compare file path relative to path of config file - filePath = strings.TrimPrefix(filePath, configDir + string(filepath.Separator)) + filePath = strings.TrimPrefix(filePath, configDir+string(filepath.Separator)) var rule *creationRule diff --git a/decrypt/decrypt.go b/decrypt/decrypt.go index 506132894..874f59e9a 100644 --- a/decrypt/decrypt.go +++ b/decrypt/decrypt.go @@ -6,7 +6,7 @@ package decrypt // import "github.com/getsops/sops/v3/decrypt" import ( "fmt" - "io/ioutil" + "os" "time" "github.com/getsops/sops/v3/aes" @@ -18,7 +18,7 @@ import ( // file and returns its cleartext data in an []byte func File(path, format string) (cleartext []byte, err error) { // Read the file into an []byte - encryptedData, err := ioutil.ReadFile(path) + encryptedData, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("Failed to read %q: %w", path, err) } diff --git a/go.mod b/go.mod index 77e8f7228..fb0fbb92b 100644 --- a/go.mod +++ b/go.mod @@ -33,7 +33,6 @@ require ( github.com/sirupsen/logrus v1.9.3 github.com/stretchr/testify v1.8.4 github.com/urfave/cli v1.22.14 - golang.org/x/crypto v0.12.0 golang.org/x/net v0.14.0 golang.org/x/sys v0.11.0 golang.org/x/term v0.11.0 @@ -117,6 +116,7 @@ require ( github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect go.opencensus.io v0.24.0 // indirect + golang.org/x/crypto v0.12.0 // indirect golang.org/x/mod v0.9.0 // indirect golang.org/x/oauth2 v0.11.0 // indirect golang.org/x/sync v0.3.0 // indirect diff --git a/keyservice/server.go b/keyservice/server.go index 480a66e8b..85829621a 100644 --- a/keyservice/server.go +++ b/keyservice/server.go @@ -224,7 +224,7 @@ func keyToString(key *Key) string { case *Key_VaultKey: return fmt.Sprintf("Hashicorp Vault key with URI %s/v1/%s/keys/%s", k.VaultKey.VaultAddress, k.VaultKey.EnginePath, k.VaultKey.KeyName) default: - return fmt.Sprintf("Unknown key type") + return "Unknown key type" } } diff --git a/pgp/keysource.go b/pgp/keysource.go index c8e16fa7d..6bbc33d86 100644 --- a/pgp/keysource.go +++ b/pgp/keysource.go @@ -20,9 +20,9 @@ import ( "github.com/ProtonMail/go-crypto/openpgp" "github.com/ProtonMail/go-crypto/openpgp/armor" + "github.com/getsops/sops/v3/logging" "github.com/sirupsen/logrus" gpgagent "github.com/getsops/gopgagent" - "github.com/getsops/sops/v3/logging" "golang.org/x/term" ) @@ -49,8 +49,8 @@ var ( // log is the global logger for any PGP MasterKey. // TODO(hidde): this is not-so-nice for any implementation other than the CLI, -// as it becomes difficult to sugar the logger with data for e.g. individual -// processes. +// as it becomes difficult to sugar the logger with data for e.g. individual +// processes. var log *logrus.Logger func init() { @@ -588,8 +588,8 @@ func loadRing(path string) (openpgp.EntityList, error) { func fingerprintIndex(ring openpgp.EntityList) map[string]openpgp.Entity { fps := make(map[string]openpgp.Entity) for _, entity := range ring { - fp := strings.ToUpper(hex.EncodeToString(entity.PrimaryKey.Fingerprint[:])) if entity != nil { + fp := strings.ToUpper(hex.EncodeToString(entity.PrimaryKey.Fingerprint[:])) fps[fp] = *entity } } diff --git a/pgp/keysource_test.go b/pgp/keysource_test.go index 093e14216..1c7c436b4 100644 --- a/pgp/keysource_test.go +++ b/pgp/keysource_test.go @@ -689,7 +689,7 @@ func Test_shortenFingerprint(t *testing.T) { func TestPGP(t *testing.T) { key := NewMasterKeyFromFingerprint("FBC7B9E2A4F9289AC0C1D4843D16CEE4A27381B4") f := func(x []byte) bool { - if x == nil || len(x) == 0 { + if len(x) == 0 { return true } if err := key.Encrypt(x); err != nil { diff --git a/stores/yaml/store.go b/stores/yaml/store.go index 4782428b6..1481dff8f 100644 --- a/stores/yaml/store.go +++ b/stores/yaml/store.go @@ -6,9 +6,9 @@ import ( "io" "strings" - "gopkg.in/yaml.v3" "github.com/getsops/sops/v3" "github.com/getsops/sops/v3/stores" + "gopkg.in/yaml.v3" ) // Store handles storage of YAML data @@ -76,7 +76,7 @@ func (store Store) nodeToTreeValue(node *yaml.Node, commentsWereHandled bool) (i node.Decode(&result) return result, nil case yaml.AliasNode: - return store.nodeToTreeValue(node.Alias, false); + return store.nodeToTreeValue(node.Alias, false) } return nil, nil } @@ -100,7 +100,7 @@ func (store Store) appendYamlNodeToTreeBranch(node *yaml.Node, branch sops.TreeB case yaml.MappingNode: for i := 0; i < len(node.Content); i += 2 { key := node.Content[i] - value := node.Content[i + 1] + value := node.Content[i+1] branch = store.appendCommentToMap(key.HeadComment, branch) branch = store.appendCommentToMap(key.LineComment, branch) handleValueComments := value.Kind == yaml.ScalarNode || value.Kind == yaml.AliasNode @@ -206,7 +206,7 @@ func (store *Store) appendSequence(in []interface{}, sequence *yaml.Node) { if beginning { comments = store.addCommentsHead(sequence, comments) } else { - comments = store.addCommentsFoot(sequence.Content[len(sequence.Content) - 1], comments) + comments = store.addCommentsFoot(sequence.Content[len(sequence.Content)-1], comments) } } } @@ -233,7 +233,7 @@ func (store *Store) appendTreeBranch(branch sops.TreeBranch, mapping *yaml.Node) if beginning { comments = store.addCommentsHead(mapping, comments) } else { - comments = store.addCommentsFoot(mapping.Content[len(mapping.Content) - 2], comments) + comments = store.addCommentsFoot(mapping.Content[len(mapping.Content)-2], comments) } } } @@ -262,7 +262,7 @@ func (store *Store) LoadEncryptedFile(in []byte) (sops.Tree, error) { } var branches sops.TreeBranches d := yaml.NewDecoder(bytes.NewReader(in)) - for true { + for { var data yaml.Node err := d.Decode(&data) if err == io.EOF { @@ -295,7 +295,7 @@ func (store *Store) LoadEncryptedFile(in []byte) (sops.Tree, error) { func (store *Store) LoadPlainFile(in []byte) (sops.TreeBranches, error) { var branches sops.TreeBranches d := yaml.NewDecoder(bytes.NewReader(in)) - for true { + for { var data yaml.Node err := d.Decode(&data) if err == io.EOF { @@ -317,7 +317,7 @@ func (store *Store) LoadPlainFile(in []byte) (sops.TreeBranches, error) { // EmitEncryptedFile returns the encrypted bytes of the yaml file corresponding to a // sops.Tree runtime object func (store *Store) EmitEncryptedFile(in sops.Tree) ([]byte, error) { - var b bytes.Buffer + var b bytes.Buffer e := yaml.NewEncoder(io.Writer(&b)) e.SetIndent(4) for _, branch := range in.Branches { @@ -331,7 +331,7 @@ func (store *Store) EmitEncryptedFile(in sops.Tree) ([]byte, error) { // Create copy of branch with metadata appended branch = append(sops.TreeBranch(nil), branch...) branch = append(branch, sops.TreeItem{ - Key: "sops", + Key: "sops", Value: stores.MetadataFromInternal(in.Metadata), }) // Marshal branch to global mapping node @@ -349,7 +349,7 @@ func (store *Store) EmitEncryptedFile(in sops.Tree) ([]byte, error) { // EmitPlainFile returns the plaintext bytes of the yaml file corresponding to a // sops.TreeBranches runtime object func (store *Store) EmitPlainFile(branches sops.TreeBranches) ([]byte, error) { - var b bytes.Buffer + var b bytes.Buffer e := yaml.NewEncoder(io.Writer(&b)) e.SetIndent(4) for _, branch := range branches { diff --git a/usererrors.go b/usererrors.go index 2476b0083..c800bad60 100644 --- a/usererrors.go +++ b/usererrors.go @@ -2,12 +2,12 @@ package sops import ( "fmt" - "io/ioutil" + "io" "strings" "github.com/fatih/color" "github.com/goware/prefixer" - wordwrap "github.com/mitchellh/go-wordwrap" + "github.com/mitchellh/go-wordwrap" ) // UserError is a well-formatted error for the purpose of being displayed to @@ -97,7 +97,7 @@ func (r *decryptGroupError) UserError() string { } reader := prefixer.New(strings.NewReader(message), " ") // Safe to ignore this error, as reading from a strings.Reader can't fail - errMsg, _ := ioutil.ReadAll(reader) + errMsg, _ := io.ReadAll(reader) return fmt.Sprintf("%s\n%s", header, string(errMsg)) } @@ -153,12 +153,12 @@ func (e *decryptKeyError) UserError() string { wrappedErr := wordwrap.WrapString(err.Error(), 60) reader := prefixer.New(strings.NewReader(wrappedErr), " | ") // Safe to ignore this error, as reading from a strings.Reader can't fail - errMsg, _ := ioutil.ReadAll(reader) + errMsg, _ := io.ReadAll(reader) errMsg[0] = '-' errMessages = append(errMessages, string(errMsg)) } joinedMsgs := strings.Join(errMessages, "\n\n") reader := prefixer.New(strings.NewReader(joinedMsgs), " ") - errMsg, _ := ioutil.ReadAll(reader) + errMsg, _ := io.ReadAll(reader) return fmt.Sprintf("%s\n%s", header, string(errMsg)) }