From 414282a2c97e837e8e135032fdcbdb1d980b5425 Mon Sep 17 00:00:00 2001 From: mmetc <92726601+mmetc@users.noreply.github.com> Date: Tue, 6 Sep 2022 13:55:03 +0200 Subject: [PATCH] golangci-lint 1.49 and related fixes (#1736) --- .github/workflows/ci_golangci-lint.yml | 2 +- .golangci.yml | 69 +++++++++++----------- cmd/crowdsec-cli/capi.go | 4 +- cmd/crowdsec-cli/config.go | 6 +- cmd/crowdsec-cli/lapi.go | 4 +- cmd/crowdsec-cli/machines.go | 4 +- cmd/crowdsec-cli/simulation.go | 6 +- cmd/crowdsec-cli/support.go | 13 ++-- cmd/crowdsec-cli/utils.go | 9 ++- pkg/acquisition/modules/kafka/kafka.go | 4 +- pkg/acquisition/modules/kinesis/kinesis.go | 4 +- pkg/apiclient/client.go | 4 +- pkg/apiclient/decisions_service_test.go | 9 ++- pkg/apiclient/signal.go | 2 +- pkg/apiserver/apiserver.go | 3 +- pkg/apiserver/controllers/v1/alerts.go | 4 +- pkg/apiserver/controllers/v1/decisions.go | 4 +- pkg/apiserver/middlewares/v1/tls_auth.go | 7 ++- pkg/csconfig/api.go | 6 +- pkg/csconfig/api_test.go | 3 +- pkg/csconfig/console.go | 3 +- pkg/csplugin/broker_test.go | 27 ++++----- pkg/cstest/hubtest.go | 5 +- pkg/cstest/hubtest_item.go | 3 +- pkg/cstest/parser_assert.go | 4 +- pkg/cstest/scenario_assert.go | 6 +- pkg/cstest/utils.go | 11 ++-- pkg/cwhub/cwhub_test.go | 3 +- pkg/cwhub/download.go | 9 ++- pkg/cwhub/loader.go | 3 +- pkg/leakybucket/buckets_test.go | 5 +- pkg/leakybucket/manager_load.go | 3 +- pkg/leakybucket/manager_run.go | 3 +- pkg/metabase/metabase.go | 9 ++- pkg/parser/parsing_test.go | 7 +-- pkg/parser/unix_parser.go | 4 +- pkg/types/dataset.go | 6 +- pkg/types/dataset_test.go | 3 +- pkg/types/utils.go | 3 +- pkg/yamlpatch/merge_test.go | 4 +- plugins/notifications/http/main.go | 4 +- plugins/notifications/splunk/main.go | 6 +- 42 files changed, 140 insertions(+), 158 deletions(-) diff --git a/.github/workflows/ci_golangci-lint.yml b/.github/workflows/ci_golangci-lint.yml index 97585a3d9..1aed2c8c5 100644 --- a/.github/workflows/ci_golangci-lint.yml +++ b/.github/workflows/ci_golangci-lint.yml @@ -28,7 +28,7 @@ jobs: uses: golangci/golangci-lint-action@v3 with: # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version - version: v1.48 + version: v1.49 # Optional: golangci-lint command line arguments. args: --issues-exit-code=1 --timeout 10m # Optional: show only new issues if it's a pull request. The default value is `false`. diff --git a/.golangci.yml b/.golangci.yml index 10127d85a..2250ba8e8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -38,21 +38,28 @@ linters: # # DEPRECATED by golangi-lint # + - deadcode # The owner seems to have abandoned the linter. Replaced by unused. - exhaustivestruct # The owner seems to have abandoned the linter. Replaced by exhaustruct. - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes + - ifshort # Checks that your code uses short syntax for if-statements whenever possible - interfacer # Linter that suggests narrower interface types - maligned # Tool to detect Go structs that would take less memory if their fields were sorted + - nosnakecase # nosnakecase is a linter that detects snake case of variable naming and function name. - scopelint # Scopelint checks for unpinned variables in go programs + - structcheck # The owner seems to have abandoned the linter. Replaced by unused. + - varcheck # The owner seems to have abandoned the linter. Replaced by unused. # # Enabled # + # - asasalint # check for pass []any as any in variadic func(...any) # - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers # - bidichk # Checks for dangerous unicode character sequences # - decorder # check declaration order and count of types, constants, variables and functions # - depguard # Go linter that checks if package imports are in a list of acceptable packages # - durationcheck # check for two durations multiplied together + # - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases # - exportloopref # checks for pointers to enclosing loop variables # - funlen # Tool for detection of long functions # - gochecknoinits # Checks that no init functions are present in Go code @@ -60,60 +67,53 @@ linters: # - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. # - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. # - goprintffuncname # Checks that printf-like functions are named with `f` at the end + # - gosimple # (megacheck): Linter for Go source code that specializes in simplifying a code + # - govet # (vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string # - grouper # An analyzer to analyze expression groups. # - importas # Enforces consistent import aliases + # - ineffassign # Detects when assignments to existing variables are not used + # - interfacebloat # A linter that checks the number of methods inside an interface. + # - logrlint # Check logr arguments. # - makezero # Finds slice declarations with non-zero initial length # - misspell # Finds commonly misspelled English words in comments # - nolintlint # Reports ill-formed or insufficient nolint directives # - predeclared # find code that shadows one of Go's predeclared identifiers + # - reassign # Checks that package variables are not reassigned # - rowserrcheck # checks whether Err of rows is checked successfully # - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. + # - staticcheck # (megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks # - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 # - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes # - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code # - unconvert # Remove unnecessary type conversions + # - unused # (megacheck): Checks Go code for unused constants, variables, functions and types # - usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. - # - varcheck # Finds unused global variables and constants - - # - # Enabled by default by golangci (but requires fixing current issues, see at the end of this file) There - # is some redundancy, but never 1 to 1 (staticcheck seems to find more - # cases than ineffassign, deadcore more than unused..). - # - # - deadcode # Finds unused code - # - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - # - gosimple # (megacheck): Linter for Go source code that specializes in simplifying a code - # - govet # (vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - # - ineffassign # Detects when assignments to existing variables are not used - # - staticcheck # (megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks - # - structcheck # Finds unused struct fields - # - unused # (megacheck): Checks Go code for unused constants, variables, functions and types # # Recommended? (easy) # + + - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. + - exhaustive # check exhaustiveness of enum switch statements - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. + - gocritic # Provides diagnostics that check for bugs, performance and style issues. + - godot # Check if comments end in a period - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification - goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. - gosec # (gas): Inspects source code for security problems + - lll # Reports long lines - nakedret # Finds naked returns in functions greater than a specified function length - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - nonamedreturns # Reports all named returns - nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL. - promlinter # Check Prometheus metrics naming via promlint - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. - - wastedassign # wastedassign finds wasted assignment statements. - - gocritic # Provides diagnostics that check for bugs, performance and style issues. - - exhaustive # check exhaustiveness of enum switch statements - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) + - wastedassign # wastedassign finds wasted assignment statements. - wrapcheck # Checks that errors returned from external packages are wrapped - - lll # Reports long lines - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - godot # Check if comments end in a period # # Recommended? (requires some work) @@ -122,12 +122,12 @@ linters: - bodyclose # checks whether HTTP response body is closed successfully - containedctx # containedctx is a linter that detects struct contained context.Context field - contextcheck # check the function whether use a non-inherited context - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - - noctx # noctx finds sending http request without context.Context - - unparam # Reports unused function parameters - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - gomnd # An analyzer to detect magic numbers. - ireturn # Accept Interfaces, Return Concrete Types + - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. + - noctx # noctx finds sending http request without context.Context + - unparam # Reports unused function parameters # # Formatting only, useful in IDE but should not be forced on CI? @@ -141,29 +141,28 @@ linters: # # Well intended, but not ready for this # - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - cyclop # checks function and package cyclomatic complexity + - dupl # Tool for code clone detection - gocognit # Computes and checks the cognitive complexity of functions - - maintidx # maintidx measures the maintainability index of each function. - - goerr113 # Golang linter to check the errors handling expressions - - nestif # Reports deeply nested if statements - gocyclo # Computes and checks the cyclomatic complexity of functions - godox # Tool for detection of FIXME, TODO and other comment keywords - - dupl # Tool for code clone detection + - goerr113 # Golang linter to check the errors handling expressions + - maintidx # maintidx measures the maintainability index of each function. + - nestif # Reports deeply nested if statements + - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - testpackage # linter that makes you use a separate _test package # # Too strict / too many false positives (for now?) # - execinquery # execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds - - forbidigo # Forbids identifiers - - tagliatelle # Checks the struct tags. - - varnamelen # checks that the length of a variable's name matches its scope - - gochecknoglobals # check that no global variables exist - exhaustruct # Checks if all structure fields are initialized + - forbidigo # Forbids identifiers + - gochecknoglobals # check that no global variables exist - goconst # Finds repeated strings that could be replaced by a constant - stylecheck # Stylecheck is a replacement for golint - - nosnakecase # nosnakecase is a linter that detects snake case of variable naming and function name. + - tagliatelle # Checks the struct tags. + - varnamelen # checks that the length of a variable's name matches its scope # # Under evaluation diff --git a/cmd/crowdsec-cli/capi.go b/cmd/crowdsec-cli/capi.go index ef8b2f0bd..fb8424b99 100644 --- a/cmd/crowdsec-cli/capi.go +++ b/cmd/crowdsec-cli/capi.go @@ -3,8 +3,8 @@ package main import ( "context" "fmt" - "io/ioutil" "net/url" + "os" "github.com/crowdsecurity/crowdsec/pkg/apiclient" "github.com/crowdsecurity/crowdsec/pkg/csconfig" @@ -89,7 +89,7 @@ func NewCapiCmd() *cobra.Command { log.Fatalf("unable to marshal api credentials: %s", err) } if dumpFile != "" { - err = ioutil.WriteFile(dumpFile, apiConfigDump, 0600) + err = os.WriteFile(dumpFile, apiConfigDump, 0600) if err != nil { log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err) } diff --git a/cmd/crowdsec-cli/config.go b/cmd/crowdsec-cli/config.go index b9dd00439..e7cc62f04 100644 --- a/cmd/crowdsec-cli/config.go +++ b/cmd/crowdsec-cli/config.go @@ -3,7 +3,7 @@ package main import ( "encoding/json" "fmt" - "io/ioutil" + "io" "os" "path/filepath" @@ -181,7 +181,7 @@ func restoreConfigFromDirectory(dirPath string) error { if err != nil { log.Warningf("failed to open %s : %s", backupOldAPICfg, err) } else { - byteValue, _ := ioutil.ReadAll(jsonFile) + byteValue, _ := io.ReadAll(jsonFile) err = json.Unmarshal(byteValue, &oldAPICfg) if err != nil { return fmt.Errorf("failed to load json file %s : %s", backupOldAPICfg, err) @@ -200,7 +200,7 @@ func restoreConfigFromDirectory(dirPath string) error { if csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.CredentialsFilePath != "" { apiConfigDumpFile = csConfig.API.Server.OnlineClient.CredentialsFilePath } - err = ioutil.WriteFile(apiConfigDumpFile, apiConfigDump, 0644) + err = os.WriteFile(apiConfigDumpFile, apiConfigDump, 0644) if err != nil { return fmt.Errorf("write api credentials in '%s' failed: %s", apiConfigDumpFile, err) } diff --git a/cmd/crowdsec-cli/lapi.go b/cmd/crowdsec-cli/lapi.go index 4a8cf3806..7c65cbad6 100644 --- a/cmd/crowdsec-cli/lapi.go +++ b/cmd/crowdsec-cli/lapi.go @@ -3,8 +3,8 @@ package main import ( "context" "fmt" - "io/ioutil" "net/url" + "os" "strings" "github.com/crowdsecurity/crowdsec/pkg/apiclient" @@ -103,7 +103,7 @@ Keep in mind the machine needs to be validated by an administrator on LAPI side log.Fatalf("unable to marshal api credentials: %s", err) } if dumpFile != "" { - err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644) + err = os.WriteFile(dumpFile, apiConfigDump, 0644) if err != nil { log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err) } diff --git a/cmd/crowdsec-cli/machines.go b/cmd/crowdsec-cli/machines.go index 05dede05c..a102da35c 100644 --- a/cmd/crowdsec-cli/machines.go +++ b/cmd/crowdsec-cli/machines.go @@ -6,8 +6,8 @@ import ( "encoding/csv" "encoding/json" "fmt" - "io/ioutil" "math/big" + "os" "strings" "time" @@ -294,7 +294,7 @@ cscli machines add MyTestMachine --password MyPassword log.Fatalf("unable to marshal api credentials: %s", err) } if dumpFile != "" && dumpFile != "-" { - err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644) + err = os.WriteFile(dumpFile, apiConfigDump, 0644) if err != nil { log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err) } diff --git a/cmd/crowdsec-cli/simulation.go b/cmd/crowdsec-cli/simulation.go index 853a4b617..1bd7ee942 100644 --- a/cmd/crowdsec-cli/simulation.go +++ b/cmd/crowdsec-cli/simulation.go @@ -2,7 +2,7 @@ package main import ( "fmt" - "io/ioutil" + "os" "github.com/crowdsecurity/crowdsec/pkg/cwhub" log "github.com/sirupsen/logrus" @@ -45,7 +45,7 @@ func dumpSimulationFile() error { if err != nil { return fmt.Errorf("unable to marshal simulation configuration: %s", err) } - err = ioutil.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644) + err = os.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644) if err != nil { return fmt.Errorf("write simulation config in '%s' failed: %s", csConfig.ConfigPaths.SimulationFilePath, err) } @@ -63,7 +63,7 @@ func disableGlobalSimulation() error { if err != nil { return fmt.Errorf("unable to marshal new simulation configuration: %s", err) } - err = ioutil.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644) + err = os.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644) if err != nil { return fmt.Errorf("unable to write new simulation config in '%s' : %s", csConfig.ConfigPaths.SimulationFilePath, err) } diff --git a/cmd/crowdsec-cli/support.go b/cmd/crowdsec-cli/support.go index 49b6fdd41..dc858c9bd 100644 --- a/cmd/crowdsec-cli/support.go +++ b/cmd/crowdsec-cli/support.go @@ -5,9 +5,10 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net/http" "net/url" + "os" "path/filepath" "regexp" "strings" @@ -73,7 +74,7 @@ func collectMetrics() ([]byte, []byte, error) { defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, nil, fmt.Errorf("could not read metrics from prometheus endpoint: %s", err) } @@ -176,7 +177,7 @@ func collectAPIStatus(login string, password string, endpoint string, prefix str func collectCrowdsecConfig() []byte { log.Info("Collecting crowdsec config") - config, err := ioutil.ReadFile(*csConfig.FilePath) + config, err := os.ReadFile(*csConfig.FilePath) if err != nil { return []byte(fmt.Sprintf("could not read config file: %s", err)) } @@ -188,7 +189,7 @@ func collectCrowdsecConfig() []byte { func collectCrowdsecProfile() []byte { log.Info("Collecting crowdsec profile") - config, err := ioutil.ReadFile(csConfig.API.Server.ProfilesPath) + config, err := os.ReadFile(csConfig.API.Server.ProfilesPath) if err != nil { return []byte(fmt.Sprintf("could not read profile file: %s", err)) } @@ -200,7 +201,7 @@ func collectAcquisitionConfig() map[string][]byte { ret := make(map[string][]byte) for _, filename := range csConfig.Crowdsec.AcquisitionFiles { - fileContent, err := ioutil.ReadFile(filename) + fileContent, err := os.ReadFile(filename) if err != nil { ret[filename] = []byte(fmt.Sprintf("could not read file: %s", err)) } else { @@ -379,7 +380,7 @@ cscli support dump -f /tmp/crowdsec-support.zip if err != nil { log.Fatalf("could not finalize zip file: %s", err) } - err = ioutil.WriteFile(outFile, w.Bytes(), 0600) + err = os.WriteFile(outFile, w.Bytes(), 0600) if err != nil { log.Fatalf("could not write zip file to %s: %s", outFile, err) } diff --git a/cmd/crowdsec-cli/utils.go b/cmd/crowdsec-cli/utils.go index 6175adf37..f6bd0f51a 100644 --- a/cmd/crowdsec-cli/utils.go +++ b/cmd/crowdsec-cli/utils.go @@ -5,7 +5,6 @@ import ( "encoding/csv" "encoding/json" "fmt" - "io/ioutil" "math" "net" "net/http" @@ -593,7 +592,7 @@ func RestoreHub(dirPath string) error { } /*restore the upstream items*/ upstreamListFN := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itype) - file, err := ioutil.ReadFile(upstreamListFN) + file, err := os.ReadFile(upstreamListFN) if err != nil { return fmt.Errorf("error while opening %s : %s", upstreamListFN, err) } @@ -614,7 +613,7 @@ func RestoreHub(dirPath string) error { } /*restore the local and tainted items*/ - files, err := ioutil.ReadDir(itemDirectory) + files, err := os.ReadDir(itemDirectory) if err != nil { return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory, err) } @@ -635,7 +634,7 @@ func RestoreHub(dirPath string) error { return fmt.Errorf("error while creating stage directory %s : %s", stagedir, err) } /*find items*/ - ifiles, err := ioutil.ReadDir(itemDirectory + "/" + stage + "/") + ifiles, err := os.ReadDir(itemDirectory + "/" + stage + "/") if err != nil { return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory+"/"+stage, err) } @@ -719,7 +718,7 @@ func BackupHub(dirPath string) error { if err != nil { return fmt.Errorf("failed marshaling upstream parsers : %s", err) } - err = ioutil.WriteFile(upstreamParsersFname, upstreamParsersContent, 0644) + err = os.WriteFile(upstreamParsersFname, upstreamParsersContent, 0644) if err != nil { return fmt.Errorf("unable to write to %s %s : %s", itemType, upstreamParsersFname, err) } diff --git a/pkg/acquisition/modules/kafka/kafka.go b/pkg/acquisition/modules/kafka/kafka.go index 147f64f18..b8b8937e5 100644 --- a/pkg/acquisition/modules/kafka/kafka.go +++ b/pkg/acquisition/modules/kafka/kafka.go @@ -6,7 +6,7 @@ import ( "crypto/x509" "fmt" "io" - "io/ioutil" + "os" "strconv" "time" @@ -188,7 +188,7 @@ func (kc *KafkaConfiguration) NewTLSConfig() (*tls.Config, error) { } tlsConfig.Certificates = []tls.Certificate{cert} - caCert, err := ioutil.ReadFile(kc.TLS.CaCert) + caCert, err := os.ReadFile(kc.TLS.CaCert) if err != nil { return &tlsConfig, err } diff --git a/pkg/acquisition/modules/kinesis/kinesis.go b/pkg/acquisition/modules/kinesis/kinesis.go index e7c4c7a3c..cce5ffbfc 100644 --- a/pkg/acquisition/modules/kinesis/kinesis.go +++ b/pkg/acquisition/modules/kinesis/kinesis.go @@ -5,7 +5,7 @@ import ( "compress/gzip" "encoding/json" "fmt" - "io/ioutil" + "io" "strings" "time" @@ -171,7 +171,7 @@ func (k *KinesisSource) decodeFromSubscription(record []byte) ([]CloudwatchSubsc k.logger.Error(err) return nil, err } - decompressed, err := ioutil.ReadAll(r) + decompressed, err := io.ReadAll(r) if err != nil { k.logger.Error(err) return nil, err diff --git a/pkg/apiclient/client.go b/pkg/apiclient/client.go index 0f758f1e3..f6cc73894 100644 --- a/pkg/apiclient/client.go +++ b/pkg/apiclient/client.go @@ -6,7 +6,7 @@ import ( "crypto/x509" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" @@ -152,7 +152,7 @@ func CheckResponse(r *http.Response) error { return nil } errorResponse := &ErrorResponse{} - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err == nil && data != nil { err := json.Unmarshal(data, errorResponse) if err != nil { diff --git a/pkg/apiclient/decisions_service_test.go b/pkg/apiclient/decisions_service_test.go index fb668ce90..ebdf2d952 100644 --- a/pkg/apiclient/decisions_service_test.go +++ b/pkg/apiclient/decisions_service_test.go @@ -105,9 +105,8 @@ func TestDecisionsStream(t *testing.T) { mux.HandleFunc("/decisions/stream", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, r.Header.Get("X-Api-Key"), "ixu") - testMethod(t, r, "GET") - if r.Method == "GET" { - + testMethod(t, r, http.MethodGet) + if r.Method == http.MethodGet { if r.URL.RawQuery == "startup=true" { w.WriteHeader(http.StatusOK) w.Write([]byte(`{"deleted":null,"new":[{"duration":"3h59m55.756182786s","id":4,"origin":"cscli","scenario":"manual 'ban' from '82929df7ee394b73b81252fe3b4e50203yaT2u6nXiaN7Ix9'","scope":"Ip","type":"ban","value":"1.2.3.4"}]}`)) @@ -119,8 +118,8 @@ func TestDecisionsStream(t *testing.T) { }) mux.HandleFunc("/decisions", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, r.Header.Get("X-Api-Key"), "ixu") - testMethod(t, r, "DELETE") - if r.Method == "DELETE" { + testMethod(t, r, http.MethodDelete) + if r.Method == http.MethodDelete { w.WriteHeader(http.StatusOK) } }) diff --git a/pkg/apiclient/signal.go b/pkg/apiclient/signal.go index 4d974f8bc..27d2e3693 100644 --- a/pkg/apiclient/signal.go +++ b/pkg/apiclient/signal.go @@ -26,7 +26,7 @@ func (s *SignalService) Add(ctx context.Context, signals *models.AddSignalsReque if err != nil { return nil, resp, errors.Wrap(err, "while performing request") } - if resp.Response.StatusCode != 200 { + if resp.Response.StatusCode != http.StatusOK { log.Warnf("Signal push response : http %s", resp.Response.Status) } else { log.Debugf("Signal push response : http %s", resp.Response.Status) diff --git a/pkg/apiserver/apiserver.go b/pkg/apiserver/apiserver.go index d67c0bdc4..460fd45a0 100644 --- a/pkg/apiserver/apiserver.go +++ b/pkg/apiserver/apiserver.go @@ -6,7 +6,6 @@ import ( "crypto/x509" "fmt" "io" - "io/ioutil" "net" "net/http" "os" @@ -267,7 +266,7 @@ func (s *APIServer) GetTLSConfig() (*tls.Config, error) { if s.TLS.CACertPath != "" { if clientAuthType > tls.RequestClientCert { log.Infof("(tls) Client Auth Type set to %s", clientAuthType.String()) - caCert, err = ioutil.ReadFile(s.TLS.CACertPath) + caCert, err = os.ReadFile(s.TLS.CACertPath) if err != nil { return nil, errors.Wrap(err, "Error opening cert file") } diff --git a/pkg/apiserver/controllers/v1/alerts.go b/pkg/apiserver/controllers/v1/alerts.go index 4d79af907..53b533eb2 100644 --- a/pkg/apiserver/controllers/v1/alerts.go +++ b/pkg/apiserver/controllers/v1/alerts.go @@ -210,7 +210,7 @@ func (c *Controller) FindAlerts(gctx *gin.Context) { data := FormatAlerts(result) - if gctx.Request.Method == "HEAD" { + if gctx.Request.Method == http.MethodHead { gctx.String(http.StatusOK, "") return } @@ -232,7 +232,7 @@ func (c *Controller) FindAlertByID(gctx *gin.Context) { } data := FormatOneAlert(result) - if gctx.Request.Method == "HEAD" { + if gctx.Request.Method == http.MethodHead { gctx.String(http.StatusOK, "") return } diff --git a/pkg/apiserver/controllers/v1/decisions.go b/pkg/apiserver/controllers/v1/decisions.go index dcc91a493..02d6c7d33 100644 --- a/pkg/apiserver/controllers/v1/decisions.go +++ b/pkg/apiserver/controllers/v1/decisions.go @@ -70,7 +70,7 @@ func (c *Controller) GetDecision(gctx *gin.Context) { PrometheusBouncersHasEmptyDecision(gctx) } - if gctx.Request.Method == "HEAD" { + if gctx.Request.Method == http.MethodHead { gctx.String(http.StatusOK, "") return } @@ -181,7 +181,7 @@ func (c *Controller) StreamDecision(gctx *gin.Context) { gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()}) return } - if gctx.Request.Method == "HEAD" { + if gctx.Request.Method == http.MethodHead { gctx.String(http.StatusOK, "") return } diff --git a/pkg/apiserver/middlewares/v1/tls_auth.go b/pkg/apiserver/middlewares/v1/tls_auth.go index eda51d265..a0b837a41 100644 --- a/pkg/apiserver/middlewares/v1/tls_auth.go +++ b/pkg/apiserver/middlewares/v1/tls_auth.go @@ -5,9 +5,10 @@ import ( "crypto" "crypto/x509" "fmt" - "io/ioutil" + "io" "net/http" "net/url" + "os" "time" "github.com/gin-gonic/gin" @@ -56,7 +57,7 @@ func (ta *TLSAuth) ocspQuery(server string, cert *x509.Certificate, issuer *x509 return nil, err } defer httpResponse.Body.Close() - output, err := ioutil.ReadAll(httpResponse.Body) + output, err := io.ReadAll(httpResponse.Body) if err != nil { ta.logger.Error("TLSAuth: cannot read HTTP response from OCSP") return nil, err @@ -109,7 +110,7 @@ func (ta *TLSAuth) isCRLRevoked(cert *x509.Certificate) (bool, error) { ta.logger.Warn("no crl_path, skipping CRL check") return false, nil } - crlContent, err := ioutil.ReadFile(ta.CrlPath) + crlContent, err := os.ReadFile(ta.CrlPath) if err != nil { ta.logger.Warnf("could not read CRL file, skipping check: %s", err) return false, nil diff --git a/pkg/csconfig/api.go b/pkg/csconfig/api.go index cc41fb241..a1d762348 100644 --- a/pkg/csconfig/api.go +++ b/pkg/csconfig/api.go @@ -4,8 +4,8 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "net" + "os" "strings" "time" @@ -45,7 +45,7 @@ type LocalApiClientCfg struct { func (o *OnlineApiClientCfg) Load() error { o.Credentials = new(ApiCredentialsCfg) - fcontent, err := ioutil.ReadFile(o.CredentialsFilePath) + fcontent, err := os.ReadFile(o.CredentialsFilePath) if err != nil { return errors.Wrapf(err, "failed to read api server credentials configuration file '%s'", o.CredentialsFilePath) } @@ -96,7 +96,7 @@ func (l *LocalApiClientCfg) Load() error { return errors.Wrapf(err, "failed to load api client certificate") } - caCert, err := ioutil.ReadFile(l.Credentials.CACertPath) + caCert, err := os.ReadFile(l.Credentials.CACertPath) if err != nil { return errors.Wrapf(err, "failed to load cacert") } diff --git a/pkg/csconfig/api_test.go b/pkg/csconfig/api_test.go index f34042358..dace4a0a2 100644 --- a/pkg/csconfig/api_test.go +++ b/pkg/csconfig/api_test.go @@ -2,7 +2,6 @@ package csconfig import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -162,7 +161,7 @@ func TestLoadAPIServer(t *testing.T) { } config := &Config{} - fcontent, err := ioutil.ReadFile("./tests/config.yaml") + fcontent, err := os.ReadFile("./tests/config.yaml") if err != nil { t.Fatalf(err.Error()) } diff --git a/pkg/csconfig/console.go b/pkg/csconfig/console.go index f885f2dc8..e00d0146c 100644 --- a/pkg/csconfig/console.go +++ b/pkg/csconfig/console.go @@ -2,7 +2,6 @@ package csconfig import ( "fmt" - "io/ioutil" "os" "github.com/crowdsecurity/crowdsec/pkg/types" @@ -37,7 +36,7 @@ func (c *LocalApiServerCfg) LoadConsoleConfig() error { return nil } - yamlFile, err := ioutil.ReadFile(c.ConsoleConfigPath) + yamlFile, err := os.ReadFile(c.ConsoleConfigPath) if err != nil { return fmt.Errorf("reading console config file '%s': %s", c.ConsoleConfigPath, err) } diff --git a/pkg/csplugin/broker_test.go b/pkg/csplugin/broker_test.go index 5a22eb059..bd3bb08a2 100644 --- a/pkg/csplugin/broker_test.go +++ b/pkg/csplugin/broker_test.go @@ -4,7 +4,6 @@ package csplugin import ( "encoding/json" - "io/ioutil" "os" "os/exec" "path" @@ -264,7 +263,7 @@ func TestBrokerInit(t *testing.T) { func readconfig(t *testing.T, path string) ([]byte, PluginConfig) { var config PluginConfig - orig, err := ioutil.ReadFile("tests/notifications/dummy.yaml") + orig, err := os.ReadFile("tests/notifications/dummy.yaml") if err != nil { t.Fatalf("unable to read config file %s : %s", path, err) } @@ -279,7 +278,7 @@ func writeconfig(t *testing.T, config PluginConfig, path string) { if err != nil { t.Fatalf("unable to marshal config file : %s", err) } - if err := ioutil.WriteFile(path, data, 0644); err != nil { + if err := os.WriteFile(path, data, 0644); err != nil { t.Fatalf("unable to write config file %s : %s", path, err) } } @@ -311,7 +310,7 @@ func TestBrokerNoThreshold(t *testing.T) { pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}} time.Sleep(200 * time.Millisecond) //we expect one now - content, err := ioutil.ReadFile("./out") + content, err := os.ReadFile("./out") if err != nil { log.Errorf("Error reading file: %s", err) } @@ -325,7 +324,7 @@ func TestBrokerNoThreshold(t *testing.T) { pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}} time.Sleep(200 * time.Millisecond) //we expect one again, as we cleaned the file - content, err = ioutil.ReadFile("./out") + content, err = os.ReadFile("./out") if err != nil { log.Errorf("Error reading file: %s", err) } @@ -371,14 +370,14 @@ func TestBrokerRunGroupAndTimeThreshold_TimeFirst(t *testing.T) { assert.NoFileExists(t, "./out") time.Sleep(1 * time.Second) //after 1 seconds, we should have data - content, err := ioutil.ReadFile("./out") + content, err := os.ReadFile("./out") assert.NoError(t, err) var alerts []models.Alert err = json.Unmarshal(content, &alerts) assert.NoError(t, err) assert.Equal(t, 3, len(alerts)) //restore config - if err := ioutil.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil { + if err := os.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil { t.Fatalf("unable to write config file %s", err) } } @@ -418,7 +417,7 @@ func TestBrokerRunGroupAndTimeThreshold_CountFirst(t *testing.T) { pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}} time.Sleep(100 * time.Millisecond) //and now we should - content, err := ioutil.ReadFile("./out") + content, err := os.ReadFile("./out") if err != nil { log.Errorf("Error reading file: %s", err) } @@ -427,7 +426,7 @@ func TestBrokerRunGroupAndTimeThreshold_CountFirst(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 4, len(alerts)) //restore config - if err := ioutil.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil { + if err := os.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil { t.Fatalf("unable to write config file %s", err) } } @@ -467,7 +466,7 @@ func TestBrokerRunGroupThreshold(t *testing.T) { pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}} time.Sleep(100 * time.Millisecond) //and now we should - content, err := ioutil.ReadFile("./out") + content, err := os.ReadFile("./out") if err != nil { log.Errorf("Error reading file: %s", err) } @@ -476,7 +475,7 @@ func TestBrokerRunGroupThreshold(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 4, len(alerts)) //restore config - if err := ioutil.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil { + if err := os.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil { t.Fatalf("unable to write config file %s", err) } } @@ -512,7 +511,7 @@ func TestBrokerRunTimeThreshold(t *testing.T) { assert.NoFileExists(t, "./out") time.Sleep(1 * time.Second) //and now we should - content, err := ioutil.ReadFile("./out") + content, err := os.ReadFile("./out") if err != nil { log.Errorf("Error reading file: %s", err) } @@ -521,7 +520,7 @@ func TestBrokerRunTimeThreshold(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 1, len(alerts)) //restore config - if err := ioutil.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil { + if err := os.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil { t.Fatalf("unable to write config file %s", err) } } @@ -553,7 +552,7 @@ func TestBrokerRunSimple(t *testing.T) { pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}} time.Sleep(time.Millisecond * 200) - content, err := ioutil.ReadFile("./out") + content, err := os.ReadFile("./out") if err != nil { log.Errorf("Error reading file: %s", err) } diff --git a/pkg/cstest/hubtest.go b/pkg/cstest/hubtest.go index 804fe0de3..4a4d886db 100644 --- a/pkg/cstest/hubtest.go +++ b/pkg/cstest/hubtest.go @@ -2,7 +2,6 @@ package cstest import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -58,7 +57,7 @@ func NewHubTest(hubPath string, crowdsecPath string, cscliPath string) (HubTest, } hubIndexFile := filepath.Join(hubPath, ".index.json") - bidx, err := ioutil.ReadFile(hubIndexFile) + bidx, err := os.ReadFile(hubIndexFile) if err != nil { return HubTest{}, fmt.Errorf("unable to read index file: %s", err) } @@ -98,7 +97,7 @@ func (h *HubTest) LoadTestItem(name string) (*HubTestItem, error) { } func (h *HubTest) LoadAllTests() error { - testsFolder, err := ioutil.ReadDir(h.HubTestPath) + testsFolder, err := os.ReadDir(h.HubTestPath) if err != nil { return err } diff --git a/pkg/cstest/hubtest_item.go b/pkg/cstest/hubtest_item.go index 3ff85963d..4b48f88e6 100644 --- a/pkg/cstest/hubtest_item.go +++ b/pkg/cstest/hubtest_item.go @@ -2,7 +2,6 @@ package cstest import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -93,7 +92,7 @@ func NewTest(name string, hubTest *HubTest) (*HubTestItem, error) { // read test configuration file configFileData := &HubTestItemConfig{} - yamlFile, err := ioutil.ReadFile(configFilePath) + yamlFile, err := os.ReadFile(configFilePath) if err != nil { log.Printf("no config file found in '%s': %v", testPath, err) } diff --git a/pkg/cstest/parser_assert.go b/pkg/cstest/parser_assert.go index 776f44afb..160819dc9 100644 --- a/pkg/cstest/parser_assert.go +++ b/pkg/cstest/parser_assert.go @@ -3,7 +3,7 @@ package cstest import ( "bufio" "fmt" - "io/ioutil" + "io" "os" "regexp" "sort" @@ -260,7 +260,7 @@ func LoadParserDump(filepath string) (*ParserResults, error) { } defer dumpData.Close() - results, err := ioutil.ReadAll(dumpData) + results, err := io.ReadAll(dumpData) if err != nil { return nil, err } diff --git a/pkg/cstest/scenario_assert.go b/pkg/cstest/scenario_assert.go index 899c92ae9..10f32bde0 100644 --- a/pkg/cstest/scenario_assert.go +++ b/pkg/cstest/scenario_assert.go @@ -3,7 +3,7 @@ package cstest import ( "bufio" "fmt" - "io/ioutil" + "io" "os" "regexp" "sort" @@ -237,7 +237,7 @@ func LoadBucketPourDump(filepath string) (*BucketPourInfo, error) { } defer dumpData.Close() - results, err := ioutil.ReadAll(dumpData) + results, err := io.ReadAll(dumpData) if err != nil { return nil, err } @@ -258,7 +258,7 @@ func LoadScenarioDump(filepath string) (*BucketResults, error) { } defer dumpData.Close() - results, err := ioutil.ReadAll(dumpData) + results, err := io.ReadAll(dumpData) if err != nil { return nil, err } diff --git a/pkg/cstest/utils.go b/pkg/cstest/utils.go index 00be61ceb..96ed256cc 100644 --- a/pkg/cstest/utils.go +++ b/pkg/cstest/utils.go @@ -2,7 +2,6 @@ package cstest import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -11,12 +10,12 @@ import ( ) func Copy(sourceFile string, destinationFile string) error { - input, err := ioutil.ReadFile(sourceFile) + input, err := os.ReadFile(sourceFile) if err != nil { return err } - err = ioutil.WriteFile(destinationFile, input, 0644) + err = os.WriteFile(destinationFile, input, 0644) if err != nil { return err } @@ -73,7 +72,7 @@ func CopyDir(src string, dest string) error { return err } - files, err := ioutil.ReadDir(src) + files, err := os.ReadDir(src) if err != nil { return err } @@ -91,13 +90,13 @@ func CopyDir(src string, dest string) error { if !f.IsDir() { - content, err := ioutil.ReadFile(src + "/" + f.Name()) + content, err := os.ReadFile(src + "/" + f.Name()) if err != nil { return err } - err = ioutil.WriteFile(dest+"/"+f.Name(), content, 0755) + err = os.WriteFile(dest+"/"+f.Name(), content, 0755) if err != nil { return err diff --git a/pkg/cwhub/cwhub_test.go b/pkg/cwhub/cwhub_test.go index 68da87ba7..6aa943196 100644 --- a/pkg/cwhub/cwhub_test.go +++ b/pkg/cwhub/cwhub_test.go @@ -3,7 +3,6 @@ package cwhub import ( "fmt" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -391,7 +390,7 @@ func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) { log.Fatalf("unexpected url :/ %s", req.URL.Path) } - response.Body = ioutil.NopCloser(strings.NewReader(responseBody)) + response.Body = io.NopCloser(strings.NewReader(responseBody)) return response, nil } diff --git a/pkg/cwhub/download.go b/pkg/cwhub/download.go index 024fe68e4..bad69751d 100644 --- a/pkg/cwhub/download.go +++ b/pkg/cwhub/download.go @@ -5,7 +5,6 @@ import ( "crypto/sha256" "fmt" "io" - "io/ioutil" "net/http" "os" "path" @@ -48,11 +47,11 @@ func DownloadHubIdx(hub *csconfig.Hub) ([]byte, error) { if err != nil { return nil, errors.Wrap(err, "failed http request for hub index") } - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("bad http code %d while requesting %s", resp.StatusCode, req.URL.String()) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, errors.Wrap(err, "failed to read request answer for hub index") } @@ -152,11 +151,11 @@ func DownloadItem(hub *csconfig.Hub, target Item, overwrite bool) (Item, error) if err != nil { return target, errors.Wrap(err, fmt.Sprintf("while downloading %s", req.URL.String())) } - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { return target, fmt.Errorf("bad http code %d for %s", resp.StatusCode, req.URL.String()) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return target, errors.Wrap(err, fmt.Sprintf("while reading %s", req.URL.String())) } diff --git a/pkg/cwhub/loader.go b/pkg/cwhub/loader.go index e9bab9f00..8c23fdc8f 100644 --- a/pkg/cwhub/loader.go +++ b/pkg/cwhub/loader.go @@ -3,7 +3,6 @@ package cwhub import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -357,7 +356,7 @@ func GetHubIdx(hub *csconfig.Hub) error { return fmt.Errorf("no configuration found for hub") } log.Debugf("loading hub idx %s", hub.HubIndexFile) - bidx, err := ioutil.ReadFile(hub.HubIndexFile) + bidx, err := os.ReadFile(hub.HubIndexFile) if err != nil { return errors.Wrap(err, "unable to read index file") } diff --git a/pkg/leakybucket/buckets_test.go b/pkg/leakybucket/buckets_test.go index 23e5b1c79..f4ca7b9fa 100644 --- a/pkg/leakybucket/buckets_test.go +++ b/pkg/leakybucket/buckets_test.go @@ -6,7 +6,6 @@ import ( "fmt" "html/template" "io" - "io/ioutil" "os" "reflect" "sync" @@ -44,7 +43,7 @@ func TestBucket(t *testing.T) { } } else { wg := new(sync.WaitGroup) - fds, err := ioutil.ReadDir("./tests/") + fds, err := os.ReadDir("./tests/") if err != nil { t.Fatalf("Unable to read test directory : %s", err) } @@ -91,7 +90,7 @@ func testOneBucket(t *testing.T, dir string, tomb *tomb.Tomb) error { /*load the scenarios*/ stagecfg = dir + "/scenarios.yaml" - if stagefiles, err = ioutil.ReadFile(stagecfg); err != nil { + if stagefiles, err = os.ReadFile(stagecfg); err != nil { t.Fatalf("Failed to load stage file %s : %s", stagecfg, err) } diff --git a/pkg/leakybucket/manager_load.go b/pkg/leakybucket/manager_load.go index 11f0e0a3a..fd0e6f43d 100644 --- a/pkg/leakybucket/manager_load.go +++ b/pkg/leakybucket/manager_load.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -355,7 +354,7 @@ func LoadBucket(bucketFactory *BucketFactory, tomb *tomb.Tomb) error { func LoadBucketsState(file string, buckets *Buckets, bucketFactories []BucketFactory) error { var state map[string]Leaky - body, err := ioutil.ReadFile(file) + body, err := os.ReadFile(file) if err != nil { return fmt.Errorf("can't state file %s : %s", file, err) } diff --git a/pkg/leakybucket/manager_run.go b/pkg/leakybucket/manager_run.go index 2a891957e..95271c987 100644 --- a/pkg/leakybucket/manager_run.go +++ b/pkg/leakybucket/manager_run.go @@ -3,7 +3,6 @@ package leakybucket import ( "encoding/json" "fmt" - "io/ioutil" "math" "os" "time" @@ -87,7 +86,7 @@ func DumpBucketsStateAt(deadline time.Time, outputdir string, buckets *Buckets) if outputdir == "" { return "", fmt.Errorf("empty output dir for dump bucket state") } - tmpFd, err := ioutil.TempFile(os.TempDir(), "crowdsec-buckets-dump-") + tmpFd, err := os.CreateTemp(os.TempDir(), "crowdsec-buckets-dump-") if err != nil { return "", fmt.Errorf("failed to create temp file : %s", err) } diff --git a/pkg/metabase/metabase.go b/pkg/metabase/metabase.go index 0220fc16a..e2f7e0eaa 100644 --- a/pkg/metabase/metabase.go +++ b/pkg/metabase/metabase.go @@ -6,7 +6,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "os" "path" @@ -109,7 +108,7 @@ func NewMetabase(configPath string, containerName string) (*Metabase, error) { } func (m *Metabase) LoadConfig(configPath string) error { - yamlFile, err := ioutil.ReadFile(configPath) + yamlFile, err := os.ReadFile(configPath) if err != nil { return err } @@ -303,7 +302,7 @@ func (m *Metabase) DumpConfig(path string) error { if err != nil { return err } - return ioutil.WriteFile(path, data, 0600) + return os.WriteFile(path, data, 0600) } func (m *Metabase) DownloadDatabase(force bool) error { @@ -329,11 +328,11 @@ func (m *Metabase) DownloadDatabase(force bool) error { if err != nil { return fmt.Errorf("failed request to fetch metabase db : %s", err) } - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { return fmt.Errorf("got http %d while requesting metabase db %s, stop", resp.StatusCode, m.InternalDBURL) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("failed request read while fetching metabase db : %s", err) } diff --git a/pkg/parser/parsing_test.go b/pkg/parser/parsing_test.go index 6a6e8dbf0..7fe99b5ee 100644 --- a/pkg/parser/parsing_test.go +++ b/pkg/parser/parsing_test.go @@ -5,7 +5,6 @@ import ( "fmt" "html/template" "io" - "io/ioutil" "os" "sort" "strings" @@ -39,7 +38,7 @@ func TestParser(t *testing.T) { t.Fatalf("Test '%s' failed : %s", envSetting, err) } } else { - fds, err := ioutil.ReadDir("./tests/") + fds, err := os.ReadDir("./tests/") if err != nil { t.Fatalf("Unable to read test directory : %s", err) } @@ -72,7 +71,7 @@ func BenchmarkParser(t *testing.B) { t.Fatalf("Test '%s' failed : %s", envSetting, err) } } else { - fds, err := ioutil.ReadDir("./tests/") + fds, err := os.ReadDir("./tests/") if err != nil { t.Fatalf("Unable to read test directory : %s", err) } @@ -99,7 +98,7 @@ func testOneParser(pctx *UnixParserCtx, ectx EnricherCtx, dir string, b *testing ) log.Warningf("testing %s", dir) parser_cfg_file := fmt.Sprintf("%s/parsers.yaml", dir) - cfg, err := ioutil.ReadFile(parser_cfg_file) + cfg, err := os.ReadFile(parser_cfg_file) if err != nil { return fmt.Errorf("failed opening %s : %s", parser_cfg_file, err) } diff --git a/pkg/parser/unix_parser.go b/pkg/parser/unix_parser.go index 62a04f633..0d9ee7d82 100644 --- a/pkg/parser/unix_parser.go +++ b/pkg/parser/unix_parser.go @@ -2,7 +2,7 @@ package parser import ( "fmt" - "io/ioutil" + "os" "path" "github.com/crowdsecurity/crowdsec/pkg/csconfig" @@ -31,7 +31,7 @@ type Parsers struct { func Init(c map[string]interface{}) (*UnixParserCtx, error) { r := UnixParserCtx{} r.Grok = grokky.NewBase() - files, err := ioutil.ReadDir(c["patterns"].(string)) + files, err := os.ReadDir(c["patterns"].(string)) if err != nil { return nil, err } diff --git a/pkg/types/dataset.go b/pkg/types/dataset.go index adb665e54..3074f18ac 100644 --- a/pkg/types/dataset.go +++ b/pkg/types/dataset.go @@ -2,7 +2,7 @@ package types import ( "fmt" - "io/ioutil" + "io" "net/http" "os" "path" @@ -33,12 +33,12 @@ func downloadFile(url string, destPath string) error { } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return err } - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { return fmt.Errorf("download response 'HTTP %d' : %s", resp.StatusCode, string(body)) } diff --git a/pkg/types/dataset_test.go b/pkg/types/dataset_test.go index 4e42a5cb2..956e3316f 100644 --- a/pkg/types/dataset_test.go +++ b/pkg/types/dataset_test.go @@ -1,7 +1,6 @@ package types import ( - "io/ioutil" "os" "testing" @@ -29,7 +28,7 @@ func TestDownladFile(t *testing.T) { ) err := downloadFile("https://example.com/xx", examplePath) assert.NoError(t, err) - content, err := ioutil.ReadFile(examplePath) + content, err := os.ReadFile(examplePath) assert.Equal(t, "example content oneoneone", string(content)) assert.NoError(t, err) //bad uri diff --git a/pkg/types/utils.go b/pkg/types/utils.go index 366d1adf6..23738c2f6 100644 --- a/pkg/types/utils.go +++ b/pkg/types/utils.go @@ -6,7 +6,6 @@ import ( "encoding/gob" "fmt" "io" - "io/ioutil" "os" "path/filepath" "runtime/debug" @@ -100,7 +99,7 @@ func Clone(a, b interface{}) error { } func WriteStackTrace(iErr interface{}) string { - tmpfile, err := ioutil.TempFile("", "crowdsec-crash.*.txt") + tmpfile, err := os.CreateTemp("", "crowdsec-crash.*.txt") if err != nil { log.Fatal(err) } diff --git a/pkg/yamlpatch/merge_test.go b/pkg/yamlpatch/merge_test.go index 40a67934d..92fdbd3e8 100644 --- a/pkg/yamlpatch/merge_test.go +++ b/pkg/yamlpatch/merge_test.go @@ -22,7 +22,7 @@ package yamlpatch import ( "bytes" - "io/ioutil" + "os" "strings" "testing" @@ -36,7 +36,7 @@ func trimcr(s string) string { } func mustRead(t testing.TB, fname string) []byte { - contents, err := ioutil.ReadFile(fname) + contents, err := os.ReadFile(fname) require.NoError(t, err, "failed to read file: %s", fname) return contents } diff --git a/plugins/notifications/http/main.go b/plugins/notifications/http/main.go index c2564162e..4f7ffe5d7 100644 --- a/plugins/notifications/http/main.go +++ b/plugins/notifications/http/main.go @@ -5,7 +5,7 @@ import ( "context" "crypto/tls" "fmt" - "io/ioutil" + "io" "net/http" "os" @@ -71,7 +71,7 @@ func (s *HTTPPlugin) Notify(ctx context.Context, notification *protobufs.Notific } defer resp.Body.Close() - respData, err := ioutil.ReadAll(resp.Body) + respData, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read response body got error %s", err) } diff --git a/plugins/notifications/splunk/main.go b/plugins/notifications/splunk/main.go index c4c408dcd..e3e20edf8 100644 --- a/plugins/notifications/splunk/main.go +++ b/plugins/notifications/splunk/main.go @@ -5,7 +5,7 @@ import ( "crypto/tls" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "os" "strings" @@ -71,13 +71,13 @@ func (s *Splunk) Notify(ctx context.Context, notification *protobufs.Notificatio } if resp.StatusCode != 200 { - content, err := ioutil.ReadAll(resp.Body) + content, err := io.ReadAll(resp.Body) if err != nil { return &protobufs.Empty{}, fmt.Errorf("got non 200 response and failed to read error %s", err) } return &protobufs.Empty{}, fmt.Errorf("got non 200 response %s", string(content)) } - respData, err := ioutil.ReadAll(resp.Body) + respData, err := io.ReadAll(resp.Body) if err != nil { return &protobufs.Empty{}, fmt.Errorf("failed to read response body got error %s", err) }