diff --git a/.changelog/15297.txt b/.changelog/15297.txt new file mode 100644 index 000000000000..66fa6450dad4 --- /dev/null +++ b/.changelog/15297.txt @@ -0,0 +1,7 @@ +```release-note:improvement +api: updated the go module directive to 1.18. +``` + +```release-note:improvement +sdk: updated the go module directive to 1.18. +``` diff --git a/.changelog/16263.txt b/.changelog/16263.txt new file mode 100644 index 000000000000..a8cd3f9043af --- /dev/null +++ b/.changelog/16263.txt @@ -0,0 +1,4 @@ +```release-note:security +Upgrade to use Go 1.20.1. +This resolves vulnerabilities [CVE-2022-41724](https://go.dev/issue/58001) in `crypto/tls` and [CVE-2022-41723](https://go.dev/issue/57855) in `net/http`. +``` diff --git a/.changelog/17240.txt b/.changelog/17240.txt new file mode 100644 index 000000000000..59d120f747ba --- /dev/null +++ b/.changelog/17240.txt @@ -0,0 +1,12 @@ +```release-note:security +Upgrade to use Go 1.20.4. +This resolves vulnerabilities [CVE-2023-24537](https://github.com/advisories/GHSA-9f7g-gqwh-jpf5)(`go/scanner`), +[CVE-2023-24538](https://github.com/advisories/GHSA-v4m2-x4rp-hv22)(`html/template`), +[CVE-2023-24534](https://github.com/advisories/GHSA-8v5j-pwr7-w5f8)(`net/textproto`) and +[CVE-2023-24536](https://github.com/advisories/GHSA-9f7g-gqwh-jpf5)(`mime/multipart`). +Also, `golang.org/x/net` has been updated to v0.7.0 to resolve CVEs [CVE-2022-41721 +](https://github.com/advisories/GHSA-fxg5-wq6x-vr4w +), [CVE-2022-27664](https://github.com/advisories/GHSA-69cg-p879-7622) and [CVE-2022-41723 +](https://github.com/advisories/GHSA-vvpx-j8f3-3w6h +.) +``` diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f499796e677a..4d80435817ec 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -80,15 +80,15 @@ jobs: strategy: matrix: include: - - {go: "1.19.6", goos: "linux", goarch: "386"} - - {go: "1.19.6", goos: "linux", goarch: "amd64"} - - {go: "1.19.6", goos: "linux", goarch: "arm"} - - {go: "1.19.6", goos: "linux", goarch: "arm64"} - - {go: "1.19.6", goos: "freebsd", goarch: "386"} - - {go: "1.19.6", goos: "freebsd", goarch: "amd64"} - - {go: "1.19.6", goos: "windows", goarch: "386"} - - {go: "1.19.6", goos: "windows", goarch: "amd64"} - - {go: "1.19.6", goos: "solaris", goarch: "amd64"} + - {go: "1.20.4", goos: "linux", goarch: "386"} + - {go: "1.20.4", goos: "linux", goarch: "amd64"} + - {go: "1.20.4", goos: "linux", goarch: "arm"} + - {go: "1.20.4", goos: "linux", goarch: "arm64"} + - {go: "1.20.4", goos: "freebsd", goarch: "386"} + - {go: "1.20.4", goos: "freebsd", goarch: "amd64"} + - {go: "1.20.4", goos: "windows", goarch: "386"} + - {go: "1.20.4", goos: "windows", goarch: "amd64"} + - {go: "1.20.4", goos: "solaris", goarch: "amd64"} fail-fast: true name: Go ${{ matrix.go }} ${{ matrix.goos }} ${{ matrix.goarch }} build @@ -177,7 +177,7 @@ jobs: matrix: goos: [ darwin ] goarch: [ "amd64", "arm64" ] - go: [ "1.19.6" ] + go: [ "1.20.4" ] fail-fast: true name: Go ${{ matrix.go }} ${{ matrix.goos }} ${{ matrix.goarch }} build diff --git a/.github/workflows/reusable-lint.yml b/.github/workflows/reusable-lint.yml index fe20d4e81b9d..3cee2abd7a66 100644 --- a/.github/workflows/reusable-lint.yml +++ b/.github/workflows/reusable-lint.yml @@ -46,7 +46,7 @@ jobs: uses: golangci/golangci-lint-action@08e2f20817b15149a52b5b3ebe7de50aff2ba8c5 # pin@v3.4.0 with: working-directory: ${{ matrix.directory }} - version: v1.50.1 + version: v1.51.1 args: --build-tags="${{ env.GOTAGS }}" -v - name: Notify Slack if: ${{ failure() }} diff --git a/.golangci.yml b/.golangci.yml index 7a7e2cac73b9..b43a917587d4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -73,6 +73,7 @@ linters-settings: forbidigo: # Forbid the following identifiers (list of regexp). forbid: + - '\bioutil\b(# Use io and os packages instead of ioutil)?' - '\brequire\.New\b(# Use package-level functions with explicit TestingT)?' - '\bassert\.New\b(# Use package-level functions with explicit TestingT)?' # Exclude godoc examples from forbidigo checks. diff --git a/GNUmakefile b/GNUmakefile index 18345e5c1f03..e84118626e2f 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -7,11 +7,11 @@ SHELL = bash # These version variables can either be a valid string for "go install @" # or the string @DEV to imply use what is currently installed locally. ### -GOLANGCI_LINT_VERSION='v1.50.1' -MOCKERY_VERSION='v2.12.2' +GOLANGCI_LINT_VERSION='v1.51.1' +MOCKERY_VERSION='v2.20.0' BUF_VERSION='v1.4.0' PROTOC_GEN_GO_GRPC_VERSION="v1.2.0" -MOG_VERSION='v0.3.0' +MOG_VERSION='v0.4.0' PROTOC_GO_INJECT_TAG_VERSION='v1.3.0' PROTOC_GEN_GO_BINARY_VERSION="v0.0.1" DEEP_COPY_VERSION='bc3f5aa5735d8a54961580a3a24422c308c831c2' diff --git a/agent/agent.go b/agent/agent.go index 5718068b25da..c152d715f3bc 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "os" @@ -2021,7 +2020,7 @@ func (a *Agent) readPersistedServiceConfigs() (map[structs.ServiceID]*structs.Se out := make(map[structs.ServiceID]*structs.ServiceConfigResponse) configDir := filepath.Join(a.config.DataDir, serviceConfigDir) - files, err := ioutil.ReadDir(configDir) + files, err := os.ReadDir(configDir) if err != nil { if os.IsNotExist(err) { return nil, nil @@ -2043,7 +2042,7 @@ func (a *Agent) readPersistedServiceConfigs() (map[structs.ServiceID]*structs.Se // Read the contents into a buffer file := filepath.Join(configDir, fi.Name()) - buf, err := ioutil.ReadFile(file) + buf, err := os.ReadFile(file) if err != nil { return nil, fmt.Errorf("failed reading service config file %q: %w", file, err) } @@ -3223,7 +3222,7 @@ func (a *Agent) persistCheckState(check *checks.CheckTTL, status, output string) tempFile := file + ".tmp" // persistCheckState is called frequently, so don't use writeFileAtomic to avoid calling fsync here - if err := ioutil.WriteFile(tempFile, buf, 0600); err != nil { + if err := os.WriteFile(tempFile, buf, 0600); err != nil { return fmt.Errorf("failed writing temp file %q: %s", tempFile, err) } if err := os.Rename(tempFile, file); err != nil { @@ -3238,12 +3237,12 @@ func (a *Agent) loadCheckState(check *structs.HealthCheck) error { cid := check.CompoundCheckID() // Try to read the persisted state for this check file := filepath.Join(a.config.DataDir, checkStateDir, cid.StringHashSHA256()) - buf, err := ioutil.ReadFile(file) + buf, err := os.ReadFile(file) if err != nil { if os.IsNotExist(err) { // try the md5 based name. This can be removed once we no longer support upgrades from versions that use MD5 hashing oldFile := filepath.Join(a.config.DataDir, checkStateDir, cid.StringHashMD5()) - buf, err = ioutil.ReadFile(oldFile) + buf, err = os.ReadFile(oldFile) if err != nil { if os.IsNotExist(err) { return nil @@ -3450,7 +3449,7 @@ func (a *Agent) loadServices(conf *config.RuntimeConfig, snap map[structs.CheckI // Load any persisted services svcDir := filepath.Join(a.config.DataDir, servicesDir) - files, err := ioutil.ReadDir(svcDir) + files, err := os.ReadDir(svcDir) if err != nil { if os.IsNotExist(err) { return nil @@ -3471,7 +3470,7 @@ func (a *Agent) loadServices(conf *config.RuntimeConfig, snap map[structs.CheckI // Read the contents into a buffer file := filepath.Join(svcDir, fi.Name()) - buf, err := ioutil.ReadFile(file) + buf, err := os.ReadFile(file) if err != nil { return fmt.Errorf("failed reading service file %q: %w", file, err) } @@ -3618,7 +3617,7 @@ func (a *Agent) loadChecks(conf *config.RuntimeConfig, snap map[structs.CheckID] // Load any persisted checks checkDir := filepath.Join(a.config.DataDir, checksDir) - files, err := ioutil.ReadDir(checkDir) + files, err := os.ReadDir(checkDir) if err != nil { if os.IsNotExist(err) { return nil @@ -3633,7 +3632,7 @@ func (a *Agent) loadChecks(conf *config.RuntimeConfig, snap map[structs.CheckID] // Read the contents into a buffer file := filepath.Join(checkDir, fi.Name()) - buf, err := ioutil.ReadFile(file) + buf, err := os.ReadFile(file) if err != nil { return fmt.Errorf("failed reading check file %q: %w", file, err) } diff --git a/agent/agent_endpoint_test.go b/agent/agent_endpoint_test.go index e1f26b05d00e..ebb4e14c0cff 100644 --- a/agent/agent_endpoint_test.go +++ b/agent/agent_endpoint_test.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -1741,7 +1740,7 @@ func TestAgent_ReloadDoesNotTriggerWatch(t *testing.T) { } dc1 := "dc1" - tmpFileRaw, err := ioutil.TempFile("", "rexec") + tmpFileRaw, err := os.CreateTemp("", "rexec") require.NoError(t, err) tmpFile := tmpFileRaw.Name() defer os.Remove(tmpFile) @@ -1780,7 +1779,7 @@ func TestAgent_ReloadDoesNotTriggerWatch(t *testing.T) { contentsStr := "" // Wait for watch to be populated for i := 1; i < 7; i++ { - contents, err := ioutil.ReadFile(tmpFile) + contents, err := os.ReadFile(tmpFile) if err != nil { t.Fatalf("should be able to read file, but had: %#v", err) } diff --git a/agent/agent_test.go b/agent/agent_test.go index 8b74394ee4dd..4293cfdc28cc 100644 --- a/agent/agent_test.go +++ b/agent/agent_test.go @@ -4,13 +4,13 @@ import ( "bytes" "context" "crypto/md5" + "crypto/rand" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/json" "fmt" - "io/ioutil" - "math/rand" + mathrand "math/rand" "net" "net/http" "net/http/httptest" @@ -699,7 +699,7 @@ func testAgent_AddServices_AliasUpdateCheckNotReverted(t *testing.T, extraHCL st func test_createAlias(t *testing.T, agent *TestAgent, chk *structs.CheckType, expectedResult string) func(r *retry.R) { t.Helper() - serviceNum := rand.Int() + serviceNum := mathrand.Int() srv := &structs.NodeService{ Service: fmt.Sprintf("serviceAlias-%d", serviceNum), Tags: []string{"tag1"}, @@ -2274,7 +2274,7 @@ func testAgent_PersistService(t *testing.T, extraHCL string) { if err != nil { t.Fatalf("err: %s", err) } - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) if err != nil { t.Fatalf("err: %s", err) } @@ -2295,7 +2295,7 @@ func testAgent_PersistService(t *testing.T, extraHCL string) { if err != nil { t.Fatalf("err: %s", err) } - content, err = ioutil.ReadFile(file) + content, err = os.ReadFile(file) if err != nil { t.Fatalf("err: %s", err) } @@ -2364,7 +2364,7 @@ func testAgent_persistedService_compat(t *testing.T, extraHCL string) { if err := os.MkdirAll(filepath.Dir(file), 0700); err != nil { t.Fatalf("err: %s", err) } - if err := ioutil.WriteFile(file, encoded, 0600); err != nil { + if err := os.WriteFile(file, encoded, 0600); err != nil { t.Fatalf("err: %s", err) } @@ -2419,7 +2419,7 @@ func testAgent_persistedService_compat_hash(t *testing.T, extraHCL string) { if err := os.MkdirAll(filepath.Dir(file), 0700); err != nil { t.Fatalf("err: %s", err) } - if err := ioutil.WriteFile(file, encoded, 0600); err != nil { + if err := os.WriteFile(file, encoded, 0600); err != nil { t.Fatalf("err: %s", err) } @@ -2438,7 +2438,7 @@ func testAgent_persistedService_compat_hash(t *testing.T, extraHCL string) { if err := os.MkdirAll(filepath.Dir(configFile), 0700); err != nil { t.Fatalf("err: %s", err) } - if err := ioutil.WriteFile(configFile, encodedConfig, 0600); err != nil { + if err := os.WriteFile(configFile, encodedConfig, 0600); err != nil { t.Fatalf("err: %s", err) } @@ -2619,7 +2619,7 @@ func TestAgent_PersistCheck(t *testing.T) { }) require.NoError(t, err) - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) require.Equal(t, expected, content) @@ -2634,7 +2634,7 @@ func TestAgent_PersistCheck(t *testing.T) { Source: "local", }) require.NoError(t, err) - content, err = ioutil.ReadFile(file) + content, err = os.ReadFile(file) require.NoError(t, err) require.Equal(t, expected, content) a.Shutdown() @@ -3665,7 +3665,7 @@ func TestAgent_persistCheckState(t *testing.T) { // Check the persisted file exists and has the content file := filepath.Join(a.Config.DataDir, checkStateDir, cid.StringHashSHA256()) - buf, err := ioutil.ReadFile(file) + buf, err := os.ReadFile(file) if err != nil { t.Fatalf("err: %s", err) } @@ -5062,9 +5062,9 @@ func TestAutoConfig_Integration(t *testing.T) { caFile := filepath.Join(cfgDir, "cacert.pem") keyFile := filepath.Join(cfgDir, "key.pem") - require.NoError(t, ioutil.WriteFile(certFile, []byte(cert), 0600)) - require.NoError(t, ioutil.WriteFile(caFile, []byte(cacert), 0600)) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(key), 0600)) + require.NoError(t, os.WriteFile(certFile, []byte(cert), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(cacert), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(key), 0600)) // generate a gossip key gossipKey := make([]byte, 32) @@ -5191,7 +5191,7 @@ func TestAutoConfig_Integration(t *testing.T) { require.NotEqual(r, cert1, client.Agent.tlsConfigurator.Cert()) // check that the on disk certs match expectations - data, err := ioutil.ReadFile(filepath.Join(client.DataDir, "auto-config.json")) + data, err := os.ReadFile(filepath.Join(client.DataDir, "auto-config.json")) require.NoError(r, err) rdr := strings.NewReader(string(data)) @@ -5226,9 +5226,9 @@ func TestAgent_AutoEncrypt(t *testing.T) { caFile := filepath.Join(cfgDir, "cacert.pem") keyFile := filepath.Join(cfgDir, "key.pem") - require.NoError(t, ioutil.WriteFile(certFile, []byte(cert), 0600)) - require.NoError(t, ioutil.WriteFile(caFile, []byte(cacert), 0600)) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(key), 0600)) + require.NoError(t, os.WriteFile(certFile, []byte(cert), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(cacert), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(key), 0600)) hclConfig := TestACLConfigWithParams(nil) + ` verify_incoming = true @@ -5421,9 +5421,9 @@ func TestAgent_AutoReloadDoReload_WhenCertAndKeyUpdated(t *testing.T) { caFile := filepath.Join(certsDir, "cacert.pem") keyFile := filepath.Join(certsDir, "key.pem") - require.NoError(t, ioutil.WriteFile(certFile, []byte(cert), 0600)) - require.NoError(t, ioutil.WriteFile(caFile, []byte(ca), 0600)) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKey), 0600)) + require.NoError(t, os.WriteFile(certFile, []byte(cert), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(ca), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKey), 0600)) // generate a gossip key gossipKey := make([]byte, 32) @@ -5463,8 +5463,8 @@ func TestAgent_AutoReloadDoReload_WhenCertAndKeyUpdated(t *testing.T) { ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, }) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(certFile, []byte(cert2), 0600)) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKey2), 0600)) + require.NoError(t, os.WriteFile(certFile, []byte(cert2), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKey2), 0600)) retry.Run(t, func(r *retry.R) { aeCert2 := srv.tlsConfigurator.Cert() @@ -5502,9 +5502,9 @@ func TestAgent_AutoReloadDoNotReload_WhenCaUpdated(t *testing.T) { caFile := filepath.Join(certsDir, "cacert.pem") keyFile := filepath.Join(certsDir, "key.pem") - require.NoError(t, ioutil.WriteFile(certFile, []byte(cert), 0600)) - require.NoError(t, ioutil.WriteFile(caFile, []byte(ca), 0600)) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKey), 0600)) + require.NoError(t, os.WriteFile(certFile, []byte(cert), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(ca), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKey), 0600)) // generate a gossip key gossipKey := make([]byte, 32) @@ -5537,7 +5537,7 @@ func TestAgent_AutoReloadDoNotReload_WhenCaUpdated(t *testing.T) { ca2, _, err := tlsutil.GenerateCA(tlsutil.CAOpts{Signer: signer}) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(caFile, []byte(ca2), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(ca2), 0600)) // wait a bit to see if it get updated. time.Sleep(time.Second) @@ -5576,9 +5576,9 @@ func TestAgent_AutoReloadDoReload_WhenCertThenKeyUpdated(t *testing.T) { caFile := filepath.Join(certsDir, "cacert.pem") keyFile := filepath.Join(certsDir, "key.pem") - require.NoError(t, ioutil.WriteFile(certFile, []byte(cert), 0600)) - require.NoError(t, ioutil.WriteFile(caFile, []byte(ca), 0600)) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKey), 0600)) + require.NoError(t, os.WriteFile(certFile, []byte(cert), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(ca), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKey), 0600)) // generate a gossip key gossipKey := make([]byte, 32) @@ -5590,7 +5590,7 @@ func TestAgent_AutoReloadDoReload_WhenCertThenKeyUpdated(t *testing.T) { hclConfig := TestACLConfigWithParams(nil) configFile := testutil.TempDir(t, "config") + "/config.hcl" - require.NoError(t, ioutil.WriteFile(configFile, []byte(` + require.NoError(t, os.WriteFile(configFile, []byte(` encrypt = "`+gossipKeyEncoded+`" encrypt_verify_incoming = true encrypt_verify_outgoing = true @@ -5622,8 +5622,8 @@ func TestAgent_AutoReloadDoReload_WhenCertThenKeyUpdated(t *testing.T) { }) require.NoError(t, err) certFileNew := filepath.Join(certsDir, "cert_new.pem") - require.NoError(t, ioutil.WriteFile(certFileNew, []byte(certNew), 0600)) - require.NoError(t, ioutil.WriteFile(configFile, []byte(` + require.NoError(t, os.WriteFile(certFileNew, []byte(certNew), 0600)) + require.NoError(t, os.WriteFile(configFile, []byte(` encrypt = "`+gossipKeyEncoded+`" encrypt_verify_incoming = true encrypt_verify_outgoing = true @@ -5646,7 +5646,7 @@ func TestAgent_AutoReloadDoReload_WhenCertThenKeyUpdated(t *testing.T) { require.Equal(r, cert1Key, cert.PrivateKey) }) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKeyNew), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKeyNew), 0600)) // cert should change as we did not update the associated key time.Sleep(1 * time.Second) @@ -5685,9 +5685,9 @@ func TestAgent_AutoReloadDoReload_WhenKeyThenCertUpdated(t *testing.T) { caFile := filepath.Join(certsDir, "cacert.pem") keyFile := filepath.Join(certsDir, "key.pem") - require.NoError(t, ioutil.WriteFile(certFile, []byte(cert), 0600)) - require.NoError(t, ioutil.WriteFile(caFile, []byte(ca), 0600)) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKey), 0600)) + require.NoError(t, os.WriteFile(certFile, []byte(cert), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(ca), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKey), 0600)) // generate a gossip key gossipKey := make([]byte, 32) @@ -5699,7 +5699,7 @@ func TestAgent_AutoReloadDoReload_WhenKeyThenCertUpdated(t *testing.T) { hclConfig := TestACLConfigWithParams(nil) configFile := testutil.TempDir(t, "config") + "/config.hcl" - require.NoError(t, ioutil.WriteFile(configFile, []byte(` + require.NoError(t, os.WriteFile(configFile, []byte(` encrypt = "`+gossipKeyEncoded+`" encrypt_verify_incoming = true encrypt_verify_outgoing = true @@ -5732,7 +5732,7 @@ func TestAgent_AutoReloadDoReload_WhenKeyThenCertUpdated(t *testing.T) { }) require.NoError(t, err) certFileNew := filepath.Join(certsDir, "cert_new.pem") - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKeyNew), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKeyNew), 0600)) // cert should not change as we did not update the associated key time.Sleep(1 * time.Second) retry.Run(t, func(r *retry.R) { @@ -5742,8 +5742,8 @@ func TestAgent_AutoReloadDoReload_WhenKeyThenCertUpdated(t *testing.T) { require.Equal(r, cert1Key, cert.PrivateKey) }) - require.NoError(t, ioutil.WriteFile(certFileNew, []byte(certNew), 0600)) - require.NoError(t, ioutil.WriteFile(configFile, []byte(` + require.NoError(t, os.WriteFile(certFileNew, []byte(certNew), 0600)) + require.NoError(t, os.WriteFile(configFile, []byte(` encrypt = "`+gossipKeyEncoded+`" encrypt_verify_incoming = true encrypt_verify_outgoing = true @@ -5777,7 +5777,7 @@ func TestAgent_AutoReloadDoReload_WhenKeyThenCertUpdated(t *testing.T) { ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, }) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKeyNew2), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKeyNew2), 0600)) // cert should not change as we did not update the associated cert time.Sleep(1 * time.Second) retry.Run(t, func(r *retry.R) { @@ -5787,7 +5787,7 @@ func TestAgent_AutoReloadDoReload_WhenKeyThenCertUpdated(t *testing.T) { require.Equal(r, cert2Key, cert.PrivateKey) }) - require.NoError(t, ioutil.WriteFile(certFileNew, []byte(certNew2), 0600)) + require.NoError(t, os.WriteFile(certFileNew, []byte(certNew2), 0600)) // cert should change as we did update the associated key time.Sleep(1 * time.Second) @@ -5825,9 +5825,9 @@ func Test_coalesceTimerTwoPeriods(t *testing.T) { caFile := filepath.Join(certsDir, "cacert.pem") keyFile := filepath.Join(certsDir, "key.pem") - require.NoError(t, ioutil.WriteFile(certFile, []byte(cert), 0600)) - require.NoError(t, ioutil.WriteFile(caFile, []byte(ca), 0600)) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKey), 0600)) + require.NoError(t, os.WriteFile(certFile, []byte(cert), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(ca), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKey), 0600)) // generate a gossip key gossipKey := make([]byte, 32) @@ -5839,7 +5839,7 @@ func Test_coalesceTimerTwoPeriods(t *testing.T) { hclConfig := TestACLConfigWithParams(nil) configFile := testutil.TempDir(t, "config") + "/config.hcl" - require.NoError(t, ioutil.WriteFile(configFile, []byte(` + require.NoError(t, os.WriteFile(configFile, []byte(` encrypt = "`+gossipKeyEncoded+`" encrypt_verify_incoming = true encrypt_verify_outgoing = true @@ -5875,8 +5875,8 @@ func Test_coalesceTimerTwoPeriods(t *testing.T) { }) require.NoError(t, err) certFileNew := filepath.Join(certsDir, "cert_new.pem") - require.NoError(t, ioutil.WriteFile(certFileNew, []byte(certNew), 0600)) - require.NoError(t, ioutil.WriteFile(configFile, []byte(` + require.NoError(t, os.WriteFile(certFileNew, []byte(certNew), 0600)) + require.NoError(t, os.WriteFile(configFile, []byte(` encrypt = "`+gossipKeyEncoded+`" encrypt_verify_incoming = true encrypt_verify_outgoing = true @@ -5899,7 +5899,7 @@ func Test_coalesceTimerTwoPeriods(t *testing.T) { require.Equal(r, cert1Key, cert.PrivateKey) }) - require.NoError(t, ioutil.WriteFile(keyFile, []byte(privateKeyNew), 0600)) + require.NoError(t, os.WriteFile(keyFile, []byte(privateKeyNew), 0600)) // cert should change as we did not update the associated key time.Sleep(coalesceInterval * 2) @@ -5979,7 +5979,7 @@ func TestAgent_startListeners(t *testing.T) { func getExpectedCaPoolByFile(t *testing.T) *x509.CertPool { pool := x509.NewCertPool() - data, err := ioutil.ReadFile("../test/ca/root.cer") + data, err := os.ReadFile("../test/ca/root.cer") require.NoError(t, err) if !pool.AppendCertsFromPEM(data) { t.Fatal("could not add test ca ../test/ca/root.cer to pool") @@ -5995,7 +5995,7 @@ func getExpectedCaPoolByDir(t *testing.T) *x509.CertPool { for _, entry := range entries { filename := path.Join("../test/ca_path", entry.Name()) - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) require.NoError(t, err) if !pool.AppendCertsFromPEM(data) { diff --git a/agent/auto-config/auto_config.go b/agent/auto-config/auto_config.go index 9abbd4bb7f7c..df4fe3d29df6 100644 --- a/agent/auto-config/auto_config.go +++ b/agent/auto-config/auto_config.go @@ -3,7 +3,7 @@ package autoconf import ( "context" "fmt" - "io/ioutil" + "os" "sync" "time" @@ -208,7 +208,7 @@ func (ac *AutoConfig) introToken() (string, error) { token := conf.IntroToken if token == "" { // load the intro token from the file - content, err := ioutil.ReadFile(conf.IntroTokenFile) + content, err := os.ReadFile(conf.IntroTokenFile) if err != nil { return "", fmt.Errorf("Failed to read intro token from file: %w", err) } diff --git a/agent/auto-config/auto_config_test.go b/agent/auto-config/auto_config_test.go index c810ed926060..ea23fa049aba 100644 --- a/agent/auto-config/auto_config_test.go +++ b/agent/auto-config/auto_config_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/x509" "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -309,7 +308,7 @@ func TestInitialConfiguration_restored(t *testing.T) { } data, err := pbMarshaler.MarshalToString(response) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(persistedFile, []byte(data), 0600)) + require.NoError(t, os.WriteFile(persistedFile, []byte(data), 0600)) // recording the initial configuration even when restoring is going to update // the agent token in the token store @@ -1139,7 +1138,7 @@ func TestIntroToken(t *testing.T) { tokenFromFile := "8ae34d3a-8adf-446a-b236-69874597cb5b" tokenFromConfig := "3ad9b572-ea42-4e47-9cd0-53a398a98abf" - require.NoError(t, ioutil.WriteFile(tokenFile.Name(), []byte(tokenFromFile), 0600)) + require.NoError(t, os.WriteFile(tokenFile.Name(), []byte(tokenFromFile), 0600)) type testCase struct { config *config.RuntimeConfig diff --git a/agent/auto-config/persist.go b/agent/auto-config/persist.go index 9f94f445c786..cbb0d21516e8 100644 --- a/agent/auto-config/persist.go +++ b/agent/auto-config/persist.go @@ -2,7 +2,6 @@ package autoconf import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -39,7 +38,7 @@ func (ac *AutoConfig) readPersistedAutoConfig() (*pbautoconf.AutoConfigResponse, path := filepath.Join(ac.config.DataDir, autoConfigFileName) ac.logger.Debug("attempting to restore any persisted configuration", "path", path) - content, err := ioutil.ReadFile(path) + content, err := os.ReadFile(path) if err == nil { rdr := strings.NewReader(string(content)) @@ -75,7 +74,7 @@ func (ac *AutoConfig) persistAutoConfig(resp *pbautoconf.AutoConfigResponse) err path := filepath.Join(ac.config.DataDir, autoConfigFileName) - err = ioutil.WriteFile(path, []byte(serialized), 0660) + err = os.WriteFile(path, []byte(serialized), 0660) if err != nil { return fmt.Errorf("failed to write auto-config configurations: %w", err) } diff --git a/agent/checks/check.go b/agent/checks/check.go index 3712b31b82ff..57c8f8eb133a 100644 --- a/agent/checks/check.go +++ b/agent/checks/check.go @@ -6,7 +6,6 @@ import ( "crypto/tls" "fmt" "io" - "io/ioutil" "net" "net/http" "os" @@ -859,7 +858,7 @@ func (c *CheckDocker) Start() { } if c.Logger == nil { - c.Logger = hclog.New(&hclog.LoggerOptions{Output: ioutil.Discard}) + c.Logger = hclog.New(&hclog.LoggerOptions{Output: io.Discard}) } if c.Shell == "" { diff --git a/agent/checks/docker.go b/agent/checks/docker.go index 78acf6b616a7..17974b96822d 100644 --- a/agent/checks/docker.go +++ b/agent/checks/docker.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strings" @@ -106,7 +105,7 @@ func (c *DockerClient) call(method, uri string, v interface{}) (*circbuf.Buffer, if err := json.NewEncoder(&b).Encode(v); err != nil { return nil, 0, err } - req.Body = ioutil.NopCloser(&b) + req.Body = io.NopCloser(&b) req.Header.Set("Content-Type", "application/json") } diff --git a/agent/checks/grpc_test.go b/agent/checks/grpc_test.go index 63f5405a6442..6db78bfa5a0b 100644 --- a/agent/checks/grpc_test.go +++ b/agent/checks/grpc_test.go @@ -4,7 +4,7 @@ import ( "crypto/tls" "flag" "fmt" - "io/ioutil" + "io" "log" "net" "os" @@ -110,7 +110,7 @@ func TestGRPC_Proxied(t *testing.T) { notif := mock.NewNotify() logger := hclog.New(&hclog.LoggerOptions{ Name: uniqueID(), - Output: ioutil.Discard, + Output: io.Discard, }) statusHandler := NewStatusHandler(notif, logger, 0, 0, 0) @@ -144,7 +144,7 @@ func TestGRPC_NotProxied(t *testing.T) { notif := mock.NewNotify() logger := hclog.New(&hclog.LoggerOptions{ Name: uniqueID(), - Output: ioutil.Discard, + Output: io.Discard, }) statusHandler := NewStatusHandler(notif, logger, 0, 0, 0) diff --git a/agent/config/builder.go b/agent/config/builder.go index 963cca674dd9..db54aa226dbf 100644 --- a/agent/config/builder.go +++ b/agent/config/builder.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "net" "net/url" "os" @@ -276,7 +275,7 @@ func (b *builder) sourcesFromPath(path string, format string) ([]Source, error) // newSourceFromFile creates a Source from the contents of the file at path. func newSourceFromFile(path string, format string) (Source, error) { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("config: failed to read %s: %s", path, err) } diff --git a/agent/config/builder_test.go b/agent/config/builder_test.go index 195bbd3c5161..8820cedc1e55 100644 --- a/agent/config/builder_test.go +++ b/agent/config/builder_test.go @@ -2,7 +2,6 @@ package config import ( "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -104,7 +103,7 @@ func TestNewBuilder_PopulatesSourcesFromConfigFiles_WithConfigFormat(t *testing. // TODO: this would be much nicer with gotest.tools/fs func setupConfigFiles(t *testing.T) []string { t.Helper() - path, err := ioutil.TempDir("", t.Name()) + path, err := os.MkdirTemp("", t.Name()) require.NoError(t, err) t.Cleanup(func() { os.RemoveAll(path) }) @@ -113,13 +112,13 @@ func setupConfigFiles(t *testing.T) []string { require.NoError(t, err) for _, dir := range []string{path, subpath} { - err = ioutil.WriteFile(filepath.Join(dir, "a.hcl"), []byte("content a"), 0644) + err = os.WriteFile(filepath.Join(dir, "a.hcl"), []byte("content a"), 0644) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(dir, "b.json"), []byte("content b"), 0644) + err = os.WriteFile(filepath.Join(dir, "b.json"), []byte("content b"), 0644) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(dir, "c.yaml"), []byte("content c"), 0644) + err = os.WriteFile(filepath.Join(dir, "c.yaml"), []byte("content c"), 0644) require.NoError(t, err) } return []string{ diff --git a/agent/config/golden_test.go b/agent/config/golden_test.go index 6ba2cc15ec9c..da49f3fce4dd 100644 --- a/agent/config/golden_test.go +++ b/agent/config/golden_test.go @@ -2,7 +2,6 @@ package config import ( "flag" - "io/ioutil" "os" "path/filepath" "testing" @@ -26,11 +25,11 @@ func golden(t *testing.T, actual, filename string) string { if dir := filepath.Dir(path); dir != "." { require.NoError(t, os.MkdirAll(dir, 0755)) } - err := ioutil.WriteFile(path, []byte(actual), 0644) + err := os.WriteFile(path, []byte(actual), 0644) require.NoError(t, err) } - expected, err := ioutil.ReadFile(path) + expected, err := os.ReadFile(path) require.NoError(t, err) return string(expected) } diff --git a/agent/config/runtime_test.go b/agent/config/runtime_test.go index c0766a59c132..02ee9127b8bf 100644 --- a/agent/config/runtime_test.go +++ b/agent/config/runtime_test.go @@ -7,7 +7,6 @@ import ( "errors" "flag" "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -7120,7 +7119,7 @@ func writeFile(path string, data []byte) { if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil { panic(err) } - if err := ioutil.WriteFile(path, data, 0640); err != nil { + if err := os.WriteFile(path, data, 0640); err != nil { panic(err) } } diff --git a/agent/connect/ca/provider_vault.go b/agent/connect/ca/provider_vault.go index 2f1862da66ad..8c3bc3e4c874 100644 --- a/agent/connect/ca/provider_vault.go +++ b/agent/connect/ca/provider_vault.go @@ -6,7 +6,7 @@ import ( "crypto/x509" "encoding/pem" "fmt" - "io/ioutil" + "io" "net/http" "os" "strings" @@ -550,7 +550,7 @@ func (v *VaultProvider) getCA(namespace, path string) (string, error) { return "", err } - bytes, err := ioutil.ReadAll(resp.Body) + bytes, err := io.ReadAll(resp.Body) if err != nil { return "", err } @@ -579,7 +579,7 @@ func (v *VaultProvider) getCAChain(namespace, path string) (string, error) { return "", err } - raw, err := ioutil.ReadAll(resp.Body) + raw, err := io.ReadAll(resp.Body) if err != nil { return "", err } diff --git a/agent/connect/ca/provider_vault_test.go b/agent/connect/ca/provider_vault_test.go index ab0575eabef6..3c5a1f44df13 100644 --- a/agent/connect/ca/provider_vault_test.go +++ b/agent/connect/ca/provider_vault_test.go @@ -4,7 +4,7 @@ import ( "crypto/x509" "encoding/json" "fmt" - "io/ioutil" + "io" "sync/atomic" "testing" "time" @@ -359,7 +359,7 @@ func TestVaultCAProvider_Bootstrap(t *testing.T) { req := client.NewRequest("GET", "/v1/"+tc.backendPath+"ca/pem") resp, err := client.RawRequest(req) require.NoError(t, err) - bytes, err := ioutil.ReadAll(resp.Body) + bytes, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, cert, string(bytes)+"\n") diff --git a/agent/connect/ca/testing.go b/agent/connect/ca/testing.go index bcba2bbcc170..450c13d6dd89 100644 --- a/agent/connect/ca/testing.go +++ b/agent/connect/ca/testing.go @@ -3,7 +3,7 @@ package ca import ( "errors" "fmt" - "io/ioutil" + "io" "os" "os/exec" "strings" @@ -81,7 +81,7 @@ func CASigningKeyTypeCases() []CASigningKeyTypes { // TestConsulProvider creates a new ConsulProvider, taking care to stub out it's // Logger so that logging calls don't panic. If logging output is important func TestConsulProvider(t testing.T, d ConsulProviderStateDelegate) *ConsulProvider { - logger := hclog.New(&hclog.LoggerOptions{Output: ioutil.Discard}) + logger := hclog.New(&hclog.LoggerOptions{Output: io.Discard}) provider := &ConsulProvider{Delegate: d, logger: logger} return provider } @@ -152,8 +152,8 @@ func NewTestVaultServer(t testing.T) *TestVaultServer { } cmd := exec.Command(vaultBinaryName, args...) - cmd.Stdout = ioutil.Discard - cmd.Stderr = ioutil.Discard + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard require.NoError(t, cmd.Start()) testVault := &TestVaultServer{ diff --git a/agent/connect/testing_ca_test.go b/agent/connect/testing_ca_test.go index fa0233c19ff8..7d3cb95798a1 100644 --- a/agent/connect/testing_ca_test.go +++ b/agent/connect/testing_ca_test.go @@ -2,7 +2,6 @@ package connect import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -34,13 +33,13 @@ func testCAAndLeaf(t *testing.T, keyType string, keyBits int) { leaf, _ := TestLeaf(t, "web", ca) // Create a temporary directory for storing the certs - td, err := ioutil.TempDir("", "consul") + td, err := os.MkdirTemp("", "consul") require.NoError(t, err) defer os.RemoveAll(td) // Write the cert - require.NoError(t, ioutil.WriteFile(filepath.Join(td, "ca.pem"), []byte(ca.RootCert), 0644)) - require.NoError(t, ioutil.WriteFile(filepath.Join(td, "leaf.pem"), []byte(leaf[:]), 0644)) + require.NoError(t, os.WriteFile(filepath.Join(td, "ca.pem"), []byte(ca.RootCert), 0644)) + require.NoError(t, os.WriteFile(filepath.Join(td, "leaf.pem"), []byte(leaf[:]), 0644)) // Use OpenSSL to verify so we have an external, known-working process // that can verify this outside of our own implementations. @@ -66,7 +65,7 @@ func testCAAndLeaf_xc(t *testing.T, keyType string, keyBits int) { leaf2, _ := TestLeaf(t, "web", ca2) // Create a temporary directory for storing the certs - td, err := ioutil.TempDir("", "consul") + td, err := os.MkdirTemp("", "consul") assert.Nil(t, err) defer os.RemoveAll(td) @@ -74,9 +73,9 @@ func testCAAndLeaf_xc(t *testing.T, keyType string, keyBits int) { xcbundle := []byte(ca1.RootCert) xcbundle = append(xcbundle, '\n') xcbundle = append(xcbundle, []byte(ca2.SigningCert)...) - assert.Nil(t, ioutil.WriteFile(filepath.Join(td, "ca.pem"), xcbundle, 0644)) - assert.Nil(t, ioutil.WriteFile(filepath.Join(td, "leaf1.pem"), []byte(leaf1), 0644)) - assert.Nil(t, ioutil.WriteFile(filepath.Join(td, "leaf2.pem"), []byte(leaf2), 0644)) + assert.Nil(t, os.WriteFile(filepath.Join(td, "ca.pem"), xcbundle, 0644)) + assert.Nil(t, os.WriteFile(filepath.Join(td, "leaf1.pem"), []byte(leaf1), 0644)) + assert.Nil(t, os.WriteFile(filepath.Join(td, "leaf2.pem"), []byte(leaf2), 0644)) // OpenSSL verify the cross-signed leaf (leaf2) { diff --git a/agent/connect_ca_endpoint_test.go b/agent/connect_ca_endpoint_test.go index 2a299bc76139..1296ab317556 100644 --- a/agent/connect_ca_endpoint_test.go +++ b/agent/connect_ca_endpoint_test.go @@ -4,7 +4,7 @@ import ( "bytes" "crypto/x509" "encoding/pem" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -287,7 +287,7 @@ func TestConnectCARoots_PEMEncoding(t *testing.T) { resp := recorder.Result() require.Equal(t, resp.Header.Get("Content-Type"), "application/pem-certificate-chain") - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) require.NoError(t, err) // expecting the root cert from dc1 and an intermediate in dc2 diff --git a/agent/consul/acl_endpoint.go b/agent/consul/acl_endpoint.go index 5d65af03993a..63c637da0c23 100644 --- a/agent/consul/acl_endpoint.go +++ b/agent/consul/acl_endpoint.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "time" @@ -127,7 +126,7 @@ func (a *ACL) fileBootstrapResetIndex() uint64 { path := filepath.Join(a.srv.config.DataDir, aclBootstrapReset) // Read the file - raw, err := ioutil.ReadFile(path) + raw, err := os.ReadFile(path) if err != nil { if !os.IsNotExist(err) { a.logger.Error("bootstrap: failed to read path", diff --git a/agent/consul/acl_endpoint_test.go b/agent/consul/acl_endpoint_test.go index 79846beaa543..35be03857853 100644 --- a/agent/consul/acl_endpoint_test.go +++ b/agent/consul/acl_endpoint_test.go @@ -2,7 +2,6 @@ package consul import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -61,7 +60,7 @@ func TestACLEndpoint_BootstrapTokens(t *testing.T) { require.NoError(t, err) resetPath := filepath.Join(dir, "acl-bootstrap-reset") - require.NoError(t, ioutil.WriteFile(resetPath, []byte(fmt.Sprintf("%d", resetIdx)), 0600)) + require.NoError(t, os.WriteFile(resetPath, []byte(fmt.Sprintf("%d", resetIdx)), 0600)) oldID := out.AccessorID // Finally, make sure that another attempt is rejected. @@ -2944,7 +2943,7 @@ func TestACLEndpoint_AuthMethodSet(t *testing.T) { t.Parallel() - tempDir, err := ioutil.TempDir("", "consul") + tempDir, err := os.MkdirTemp("", "consul") require.NoError(t, err) t.Cleanup(func() { os.RemoveAll(tempDir) }) _, srv, codec := testACLServerWithConfig(t, nil, false) diff --git a/agent/consul/authmethod/kubeauth/testing.go b/agent/consul/authmethod/kubeauth/testing.go index 87938f406bad..83e5d4fa29de 100644 --- a/agent/consul/authmethod/kubeauth/testing.go +++ b/agent/consul/authmethod/kubeauth/testing.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" "encoding/pem" - "io/ioutil" + "io" "log" "net/http" "net/http/httptest" @@ -43,7 +43,7 @@ type TestAPIServer struct { func StartTestAPIServer(t testing.T) *TestAPIServer { s := &TestAPIServer{} s.srv = httptest.NewUnstartedServer(s) - s.srv.Config.ErrorLog = log.New(ioutil.Discard, "", 0) + s.srv.Config.ErrorLog = log.New(io.Discard, "", 0) s.srv.StartTLS() bs := s.srv.TLS.Certificates[0].Certificate[0] @@ -162,7 +162,7 @@ func (s *TestAPIServer) handleTokenReview(w http.ResponseWriter, req *http.Reque } defer req.Body.Close() - b, err := ioutil.ReadAll(req.Body) + b, err := io.ReadAll(req.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) return diff --git a/agent/consul/auto_config_endpoint_test.go b/agent/consul/auto_config_endpoint_test.go index 1036044fabca..f8bec6ae6383 100644 --- a/agent/consul/auto_config_endpoint_test.go +++ b/agent/consul/auto_config_endpoint_test.go @@ -8,10 +8,9 @@ import ( "encoding/base64" "encoding/pem" "fmt" - "io/ioutil" - "math/rand" "net" "net/url" + "os" "path" "testing" "time" @@ -107,7 +106,7 @@ func TestAutoConfigInitialConfiguration(t *testing.T) { gossipKey := make([]byte, 32) // this is not cryptographic randomness and is not secure but for the sake of this test its all we need. - n, err := rand.Read(gossipKey) + n, err := crand.Read(gossipKey) require.NoError(t, err) require.Equal(t, 32, n) @@ -162,15 +161,15 @@ func TestAutoConfigInitialConfiguration(t *testing.T) { c.AutoConfigAuthzAllowReuse = true cafile := path.Join(c.DataDir, "cacert.pem") - err := ioutil.WriteFile(cafile, []byte(cacert), 0600) + err := os.WriteFile(cafile, []byte(cacert), 0600) require.NoError(t, err) certfile := path.Join(c.DataDir, "cert.pem") - err = ioutil.WriteFile(certfile, []byte(cert), 0600) + err = os.WriteFile(certfile, []byte(cert), 0600) require.NoError(t, err) keyfile := path.Join(c.DataDir, "key.pem") - err = ioutil.WriteFile(keyfile, []byte(key), 0600) + err = os.WriteFile(keyfile, []byte(key), 0600) require.NoError(t, err) c.TLSConfig.InternalRPC.CAFile = cafile @@ -426,7 +425,7 @@ func TestAutoConfig_updateTLSSettingsInConfig(t *testing.T) { dir := testutil.TempDir(t, "auto-config-tls-settings") cafile := path.Join(dir, "cacert.pem") - err = ioutil.WriteFile(cafile, []byte(cacert), 0600) + err = os.WriteFile(cafile, []byte(cacert), 0600) require.NoError(t, err) type testCase struct { @@ -505,7 +504,7 @@ func TestAutoConfig_updateGossipEncryptionInConfig(t *testing.T) { gossipKey := make([]byte, 32) // this is not cryptographic randomness and is not secure but for the sake of this test its all we need. - n, err := rand.Read(gossipKey) + n, err := crand.Read(gossipKey) require.NoError(t, err) require.Equal(t, 32, n) gossipKeyEncoded := base64.StdEncoding.EncodeToString(gossipKey) @@ -632,7 +631,7 @@ func TestAutoConfig_updateTLSCertificatesInConfig(t *testing.T) { // will error if it cannot load the CA certificate from disk dir := testutil.TempDir(t, "auto-config-tls-certificate") cafile := path.Join(dir, "cacert.pem") - err = ioutil.WriteFile(cafile, []byte(cacert), 0600) + err = os.WriteFile(cafile, []byte(cacert), 0600) require.NoError(t, err) // translate the roots response to protobuf to be embedded diff --git a/agent/consul/internal_endpoint_test.go b/agent/consul/internal_endpoint_test.go index 698fc5681820..b9379c05b20b 100644 --- a/agent/consul/internal_endpoint_test.go +++ b/agent/consul/internal_endpoint_test.go @@ -1,9 +1,9 @@ package consul import ( + "crypto/rand" "encoding/base64" "fmt" - "math/rand" "os" "strings" "testing" diff --git a/agent/consul/leader_connect_test.go b/agent/consul/leader_connect_test.go index f66406ee9151..bfa1fefc2556 100644 --- a/agent/consul/leader_connect_test.go +++ b/agent/consul/leader_connect_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/x509" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -1473,7 +1472,7 @@ func TestNewCARoot(t *testing.T) { func readTestData(t *testing.T, name string) string { t.Helper() path := filepath.Join("testdata", name) - bs, err := ioutil.ReadFile(path) + bs, err := os.ReadFile(path) if err != nil { t.Fatalf("failed reading fixture file %s: %s", name, err) } diff --git a/agent/consul/leader_peering_test.go b/agent/consul/leader_peering_test.go index b8d7b8cf3a1d..722b84fe8353 100644 --- a/agent/consul/leader_peering_test.go +++ b/agent/consul/leader_peering_test.go @@ -6,7 +6,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "os" "testing" "time" @@ -292,15 +292,15 @@ func TestLeader_PeeringSync_FailsForTLSError(t *testing.T) { t.Run("server-name-validation", func(t *testing.T) { testLeader_PeeringSync_failsForTLSError(t, func(token *structs.PeeringToken) { token.ServerName = "wrong.name" - }, `transport: authentication handshake failed: x509: certificate is valid for server.dc1.consul, bob.server.dc1.consul, not wrong.name`) + }, `transport: authentication handshake failed: tls: failed to verify certificate: x509: certificate is valid for server.dc1.consul, bob.server.dc1.consul, not wrong.name`) }) t.Run("bad-ca-roots", func(t *testing.T) { - wrongRoot, err := ioutil.ReadFile("../../test/client_certs/rootca.crt") + wrongRoot, err := os.ReadFile("../../test/client_certs/rootca.crt") require.NoError(t, err) testLeader_PeeringSync_failsForTLSError(t, func(token *structs.PeeringToken) { token.CA = []string{string(wrongRoot)} - }, `transport: authentication handshake failed: x509: certificate signed by unknown authority`) + }, `transport: authentication handshake failed: tls: failed to verify certificate: x509: certificate signed by unknown authority`) }) } diff --git a/agent/consul/rpc_test.go b/agent/consul/rpc_test.go index ff586157083f..01ea34961b8d 100644 --- a/agent/consul/rpc_test.go +++ b/agent/consul/rpc_test.go @@ -9,7 +9,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "net" "os" @@ -1390,13 +1389,13 @@ func TestRPC_AuthorizeRaftRPC(t *testing.T) { require.NoError(t, err) dir := testutil.TempDir(t, "certs") - err = ioutil.WriteFile(filepath.Join(dir, "ca.pem"), []byte(caPEM), 0600) + err = os.WriteFile(filepath.Join(dir, "ca.pem"), []byte(caPEM), 0600) require.NoError(t, err) intermediatePEM, intermediatePK, err := tlsutil.GenerateCert(tlsutil.CertOpts{IsCA: true, CA: caPEM, Signer: caSigner, Days: 5}) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(dir, "intermediate.pem"), []byte(intermediatePEM), 0600) + err = os.WriteFile(filepath.Join(dir, "intermediate.pem"), []byte(intermediatePEM), 0600) require.NoError(t, err) newCert := func(t *testing.T, caPEM, pk, node, name string) { @@ -1415,9 +1414,9 @@ func TestRPC_AuthorizeRaftRPC(t *testing.T) { }) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(dir, node+"-"+name+".pem"), []byte(pem), 0600) + err = os.WriteFile(filepath.Join(dir, node+"-"+name+".pem"), []byte(pem), 0600) require.NoError(t, err) - err = ioutil.WriteFile(filepath.Join(dir, node+"-"+name+".key"), []byte(key), 0600) + err = os.WriteFile(filepath.Join(dir, node+"-"+name+".key"), []byte(key), 0600) require.NoError(t, err) } diff --git a/agent/consul/server.go b/agent/consul/server.go index 1d395e4bf71d..464802ff54c0 100644 --- a/agent/consul/server.go +++ b/agent/consul/server.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "os" "path/filepath" @@ -950,7 +949,7 @@ func (s *Server) setupRaft() error { peersFile := filepath.Join(path, "peers.json") peersInfoFile := filepath.Join(path, "peers.info") if _, err := os.Stat(peersInfoFile); os.IsNotExist(err) { - if err := ioutil.WriteFile(peersInfoFile, []byte(peersInfoContent), 0755); err != nil { + if err := os.WriteFile(peersInfoFile, []byte(peersInfoContent), 0755); err != nil { return fmt.Errorf("failed to write peers.info file: %v", err) } diff --git a/agent/consul/snapshot_endpoint.go b/agent/consul/snapshot_endpoint.go index 80e255bd9e14..102bc0a38a5c 100644 --- a/agent/consul/snapshot_endpoint.go +++ b/agent/consul/snapshot_endpoint.go @@ -12,7 +12,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "time" @@ -138,7 +137,7 @@ func (s *Server) dispatchSnapshotRequest(args *structs.SnapshotRequest, in io.Re // Give the caller back an empty reader since there's nothing to // stream back. - return ioutil.NopCloser(bytes.NewReader([]byte(""))), nil + return io.NopCloser(bytes.NewReader([]byte(""))), nil default: return nil, fmt.Errorf("unrecognized snapshot op %q", args.Op) diff --git a/agent/consul/state/acl_test.go b/agent/consul/state/acl_test.go index 9634bf52f105..b91707391d3e 100644 --- a/agent/consul/state/acl_test.go +++ b/agent/consul/state/acl_test.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/consul/acl" "github.com/hashicorp/consul/agent/structs" - "github.com/hashicorp/consul/lib" "github.com/hashicorp/consul/proto/pbacl" ) @@ -3690,7 +3689,6 @@ func TestStateStore_ACLPolicies_Snapshot_Restore(t *testing.T) { } func TestTokenPoliciesIndex(t *testing.T) { - lib.SeedMathRand() idIndex := &memdb.IndexSchema{ Name: "id", diff --git a/agent/coordinate_endpoint_test.go b/agent/coordinate_endpoint_test.go index 331451641f3a..bef55e50c61d 100644 --- a/agent/coordinate_endpoint_test.go +++ b/agent/coordinate_endpoint_test.go @@ -39,9 +39,9 @@ func TestCoordinate_Disabled_Response(t *testing.T) { req, _ := http.NewRequest("PUT", "/should/not/care", nil) resp := httptest.NewRecorder() obj, err := tt(resp, req) - if err, ok := err.(HTTPError); ok { - if err.StatusCode != 401 { - t.Fatalf("expected status 401 but got %d", err.StatusCode) + if httpErr, ok := err.(HTTPError); ok { + if httpErr.StatusCode != 401 { + t.Fatalf("expected status 401 but got %d", httpErr.StatusCode) } } else { t.Fatalf("expected HTTP error but got %v", err) diff --git a/agent/http_test.go b/agent/http_test.go index 617a0ec66a67..ac4612fa9e31 100644 --- a/agent/http_test.go +++ b/agent/http_test.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -92,7 +91,7 @@ func TestHTTPServer_UnixSocket(t *testing.T) { } defer resp.Body.Close() - if body, err := ioutil.ReadAll(resp.Body); err != nil || len(body) == 0 { + if body, err := io.ReadAll(resp.Body); err != nil || len(body) == 0 { t.Fatalf("bad: %s %v", body, err) } } @@ -111,7 +110,7 @@ func TestHTTPServer_UnixSocket_FileExists(t *testing.T) { socket := filepath.Join(tempDir, "test.sock") // Create a regular file at the socket path - if err := ioutil.WriteFile(socket, []byte("hello world"), 0644); err != nil { + if err := os.WriteFile(socket, []byte("hello world"), 0644); err != nil { t.Fatalf("err: %s", err) } fi, err := os.Stat(socket) @@ -210,7 +209,7 @@ func TestSetupHTTPServer_HTTP2(t *testing.T) { t.Fatalf("err: %v", err) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("err: %v", err) } @@ -738,7 +737,7 @@ func testPrettyPrint(pretty string, t *testing.T) { expected, _ := json.MarshalIndent(r, "", " ") expected = append(expected, "\n"...) - actual, err := ioutil.ReadAll(resp.Body) + actual, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("err: %s", err) } diff --git a/agent/keyring.go b/agent/keyring.go index 506da70f7494..a430eee92cf8 100644 --- a/agent/keyring.go +++ b/agent/keyring.go @@ -5,7 +5,6 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" @@ -186,7 +185,7 @@ func loadKeyringFile(c *serf.Config) error { return err } - keyringData, err := ioutil.ReadFile(c.KeyringFile) + keyringData, err := os.ReadFile(c.KeyringFile) if err != nil { return err } diff --git a/agent/keyring_test.go b/agent/keyring_test.go index 3362a2c70b6a..26b29b747618 100644 --- a/agent/keyring_test.go +++ b/agent/keyring_test.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/base64" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -267,7 +267,7 @@ func TestAgent_InitKeyring(t *testing.T) { t.Fatalf("err: %s", err) } - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) if err != nil { t.Fatalf("err: %s", err) } @@ -281,7 +281,7 @@ func TestAgent_InitKeyring(t *testing.T) { } // Content should still be the same - content, err = ioutil.ReadFile(file) + content, err = os.ReadFile(file) if err != nil { t.Fatalf("err: %s", err) } diff --git a/agent/metrics_test.go b/agent/metrics_test.go index fde40471308d..b027cbfad285 100644 --- a/agent/metrics_test.go +++ b/agent/metrics_test.go @@ -4,9 +4,9 @@ import ( "context" "crypto/x509" "fmt" - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "strings" "testing" @@ -313,7 +313,7 @@ func TestHTTPHandlers_AgentMetrics_TLSCertExpiry_Prometheus(t *testing.T) { require.NoError(t, err) caPath := filepath.Join(dir, "ca.pem") - err = ioutil.WriteFile(caPath, []byte(caPEM), 0600) + err = os.WriteFile(caPath, []byte(caPEM), 0600) require.NoError(t, err) signer, err := tlsutil.ParseSigner(caPK) @@ -329,11 +329,11 @@ func TestHTTPHandlers_AgentMetrics_TLSCertExpiry_Prometheus(t *testing.T) { require.NoError(t, err) certPath := filepath.Join(dir, "cert.pem") - err = ioutil.WriteFile(certPath, []byte(pem), 0600) + err = os.WriteFile(certPath, []byte(pem), 0600) require.NoError(t, err) keyPath := filepath.Join(dir, "cert.key") - err = ioutil.WriteFile(keyPath, []byte(key), 0600) + err = os.WriteFile(keyPath, []byte(key), 0600) require.NoError(t, err) hcl := fmt.Sprintf(` diff --git a/agent/nodeid.go b/agent/nodeid.go index 27a734670035..4e6f3e8d5f00 100644 --- a/agent/nodeid.go +++ b/agent/nodeid.go @@ -3,7 +3,6 @@ package agent import ( "crypto/sha512" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -36,7 +35,7 @@ func newNodeIDFromConfig(config *config.RuntimeConfig, logger hclog.Logger) (typ // Load saved state, if any. Since a user could edit this, we also validate it. filename := filepath.Join(config.DataDir, "node-id") if _, err := os.Stat(filename); err == nil { - rawID, err := ioutil.ReadFile(filename) + rawID, err := os.ReadFile(filename) if err != nil { return "", err } @@ -56,7 +55,7 @@ func newNodeIDFromConfig(config *config.RuntimeConfig, logger hclog.Logger) (typ if err := lib.EnsurePath(filename, false); err != nil { return "", err } - if err := ioutil.WriteFile(filename, []byte(id), 0600); err != nil { + if err := os.WriteFile(filename, []byte(id), 0600); err != nil { return "", fmt.Errorf("failed to write NodeID to disk: %w", err) } return types.NodeID(id), nil diff --git a/agent/nodeid_test.go b/agent/nodeid_test.go index 647aea14c53f..da9df2bd2358 100644 --- a/agent/nodeid_test.go +++ b/agent/nodeid_test.go @@ -2,7 +2,7 @@ package agent import ( "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -59,7 +59,7 @@ func TestNewNodeIDFromConfig(t *testing.T) { t.Run("invalid NodeID in file", func(t *testing.T) { cfg.NodeID = "" filename := filepath.Join(cfg.DataDir, "node-id") - err := ioutil.WriteFile(filename, []byte("adf4238a!882b!9ddc!4a9d!5b6758e4159e"), 0600) + err := os.WriteFile(filename, []byte("adf4238a!882b!9ddc!4a9d!5b6758e4159e"), 0600) require.NoError(t, err) _, err = newNodeIDFromConfig(cfg, logger) @@ -70,7 +70,7 @@ func TestNewNodeIDFromConfig(t *testing.T) { t.Run("valid NodeID in file", func(t *testing.T) { cfg.NodeID = "" filename := filepath.Join(cfg.DataDir, "node-id") - err := ioutil.WriteFile(filename, []byte("ADF4238a-882b-9ddc-4a9d-5b6758e4159e"), 0600) + err := os.WriteFile(filename, []byte("ADF4238a-882b-9ddc-4a9d-5b6758e4159e"), 0600) require.NoError(t, err) nodeID, err := newNodeIDFromConfig(cfg, logger) diff --git a/agent/pool/peek_test.go b/agent/pool/peek_test.go index b9e74ad9342f..d51012799366 100644 --- a/agent/pool/peek_test.go +++ b/agent/pool/peek_test.go @@ -5,7 +5,7 @@ import ( "crypto/x509" "errors" "fmt" - "io/ioutil" + "io" "net" "testing" "time" @@ -55,7 +55,7 @@ func TestPeekForTLS_not_TLS(t *testing.T) { require.NoError(t, err) require.False(t, isTLS) - all, err := ioutil.ReadAll(wrapped) + all, err := io.ReadAll(wrapped) require.NoError(t, err) require.Equal(t, tc.connData, all) }) @@ -160,7 +160,7 @@ func testPeekForTLS_withTLS(t *testing.T, connData []byte) { return } - all, err := ioutil.ReadAll(tlsConn) + all, err := io.ReadAll(tlsConn) if err != nil { serverErrCh <- err return diff --git a/agent/prepared_query_endpoint_test.go b/agent/prepared_query_endpoint_test.go index 9cf805b88c3f..89578683ae88 100644 --- a/agent/prepared_query_endpoint_test.go +++ b/agent/prepared_query_endpoint_test.go @@ -12,9 +12,10 @@ import ( "github.com/hashicorp/consul/testrpc" + "github.com/stretchr/testify/require" + "github.com/hashicorp/consul/agent/structs" "github.com/hashicorp/consul/types" - "github.com/stretchr/testify/require" ) // MockPreparedQuery is a fake endpoint that we inject into the Consul server @@ -621,9 +622,9 @@ func TestPreparedQuery_Execute(t *testing.T) { req, _ := http.NewRequest("GET", "/v1/query/not-there/execute", body) resp := httptest.NewRecorder() _, err := a.srv.PreparedQuerySpecific(resp, req) - if err, ok := err.(HTTPError); ok { - if err.StatusCode != 404 { - t.Fatalf("expected status 404 but got %d", err.StatusCode) + if httpErr, ok := err.(HTTPError); ok { + if httpErr.StatusCode != 404 { + t.Fatalf("expected status 404 but got %d", httpErr.StatusCode) } } else { t.Fatalf("expected HTTP error but got %v", err) @@ -760,9 +761,9 @@ func TestPreparedQuery_Explain(t *testing.T) { req, _ := http.NewRequest("GET", "/v1/query/not-there/explain", body) resp := httptest.NewRecorder() _, err := a.srv.PreparedQuerySpecific(resp, req) - if err, ok := err.(HTTPError); ok { - if err.StatusCode != 404 { - t.Fatalf("expected status 404 but got %d", err.StatusCode) + if httpErr, ok := err.(HTTPError); ok { + if httpErr.StatusCode != 404 { + t.Fatalf("expected status 404 but got %d", httpErr.StatusCode) } } else { t.Fatalf("expected HTTP error but got %v", err) @@ -853,9 +854,9 @@ func TestPreparedQuery_Get(t *testing.T) { req, _ := http.NewRequest("GET", "/v1/query/f004177f-2c28-83b7-4229-eacc25fe55d1", body) resp := httptest.NewRecorder() _, err := a.srv.PreparedQuerySpecific(resp, req) - if err, ok := err.(HTTPError); ok { - if err.StatusCode != 404 { - t.Fatalf("expected status 404 but got %d", err.StatusCode) + if httpErr, ok := err.(HTTPError); ok { + if httpErr.StatusCode != 404 { + t.Fatalf("expected status 404 but got %d", httpErr.StatusCode) } } else { t.Fatalf("expected HTTP error but got %v", err) diff --git a/agent/proxycfg/testing.go b/agent/proxycfg/testing.go index 0493e30daefb..4dc2b3829c99 100644 --- a/agent/proxycfg/testing.go +++ b/agent/proxycfg/testing.go @@ -3,7 +3,7 @@ package proxycfg import ( "context" "fmt" - "io/ioutil" + "os" "path" "path/filepath" "runtime" @@ -922,7 +922,7 @@ func golden(t testing.T, name string) string { t.Helper() golden := filepath.Join(projectRoot(), "../", "/xds/testdata", name+".golden") - expected, err := ioutil.ReadFile(golden) + expected, err := os.ReadFile(golden) require.NoError(t, err) return string(expected) diff --git a/agent/remote_exec.go b/agent/remote_exec.go index d097e9c2c994..3668ef8406aa 100644 --- a/agent/remote_exec.go +++ b/agent/remote_exec.go @@ -3,7 +3,6 @@ package agent import ( "encoding/json" "fmt" - "io/ioutil" "os" osexec "os/exec" "path" @@ -145,7 +144,7 @@ func (a *Agent) handleRemoteExec(msg *UserEvent) { // Check if this is a script, we may need to spill to disk var script string if len(spec.Script) != 0 { - tmpFile, err := ioutil.TempFile("", "rexec") + tmpFile, err := os.CreateTemp("", "rexec") if err != nil { a.logger.Debug("failed to make tmp file", "error", err) exitCode = 255 diff --git a/agent/routine-leak-checker/leak_test.go b/agent/routine-leak-checker/leak_test.go index fd64e9c05d9f..34f098923885 100644 --- a/agent/routine-leak-checker/leak_test.go +++ b/agent/routine-leak-checker/leak_test.go @@ -2,7 +2,7 @@ package leakcheck import ( "crypto/x509" - "io/ioutil" + "os" "path/filepath" "testing" @@ -51,9 +51,9 @@ func setupPrimaryServer(t *testing.T) *agent.TestAgent { keyPath := filepath.Join(d, "key.pem") caPath := filepath.Join(d, "cacert.pem") - require.NoError(t, ioutil.WriteFile(certPath, []byte(certPEM), 0600)) - require.NoError(t, ioutil.WriteFile(keyPath, []byte(keyPEM), 0600)) - require.NoError(t, ioutil.WriteFile(caPath, []byte(caPEM), 0600)) + require.NoError(t, os.WriteFile(certPath, []byte(certPEM), 0600)) + require.NoError(t, os.WriteFile(keyPath, []byte(keyPEM), 0600)) + require.NoError(t, os.WriteFile(caPath, []byte(caPEM), 0600)) aclParams := agent.DefaultTestACLConfigParams() aclParams.PrimaryDatacenter = "primary" diff --git a/agent/rpc/peering/service_test.go b/agent/rpc/peering/service_test.go index 8c33766459e1..a2c26cb43d5f 100644 --- a/agent/rpc/peering/service_test.go +++ b/agent/rpc/peering/service_test.go @@ -5,8 +5,8 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "net" + "os" "path" "testing" "time" @@ -64,7 +64,7 @@ func TestPeeringService_GenerateToken(t *testing.T) { signer, _, _ := tlsutil.GeneratePrivateKey() ca, _, _ := tlsutil.GenerateCA(tlsutil.CAOpts{Signer: signer}) cafile := path.Join(dir, "cacert.pem") - require.NoError(t, ioutil.WriteFile(cafile, []byte(ca), 0600)) + require.NoError(t, os.WriteFile(cafile, []byte(ca), 0600)) // TODO(peering): see note on newTestServer, refactor to not use this s := newTestServer(t, func(c *consul.Config) { @@ -167,7 +167,7 @@ func TestPeeringService_GenerateTokenExternalAddress(t *testing.T) { signer, _, _ := tlsutil.GeneratePrivateKey() ca, _, _ := tlsutil.GenerateCA(tlsutil.CAOpts{Signer: signer}) cafile := path.Join(dir, "cacert.pem") - require.NoError(t, ioutil.WriteFile(cafile, []byte(ca), 0600)) + require.NoError(t, os.WriteFile(cafile, []byte(ca), 0600)) // TODO(peering): see note on newTestServer, refactor to not use this s := newTestServer(t, func(c *consul.Config) { diff --git a/agent/service_manager_test.go b/agent/service_manager_test.go index cbbd9e5e9dec..6b7757a76e29 100644 --- a/agent/service_manager_test.go +++ b/agent/service_manager_test.go @@ -3,7 +3,6 @@ package agent import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -802,7 +801,7 @@ func expectJSONFile(t *testing.T, file string, expect interface{}, fixupContentB expected, err := json.Marshal(expect) require.NoError(t, err) - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) if fixupContentBeforeCompareFn != nil { diff --git a/agent/testagent.go b/agent/testagent.go index 5701834b7cc8..ab0f35812d5c 100644 --- a/agent/testagent.go +++ b/agent/testagent.go @@ -6,7 +6,6 @@ import ( "crypto/x509" "fmt" "io" - "math/rand" "net" "net/http/httptest" "path/filepath" @@ -32,10 +31,6 @@ import ( "github.com/hashicorp/consul/tlsutil" ) -func init() { - rand.Seed(time.Now().UnixNano()) // seed random number generator -} - // TestAgent encapsulates an Agent with a default configuration and // startup procedure suitable for testing. It panics if there are errors // during creation or startup instead of returning errors. It manages a diff --git a/agent/token/persistence.go b/agent/token/persistence.go index c78e2289127a..c28afd4506d1 100644 --- a/agent/token/persistence.go +++ b/agent/token/persistence.go @@ -3,7 +3,6 @@ package token import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" @@ -142,7 +141,7 @@ func readPersistedFromFile(filename string) (persistedTokens, error) { LegacyAgentMaster string `json:"agent_master"` } - buf, err := ioutil.ReadFile(filename) + buf, err := os.ReadFile(filename) switch { case os.IsNotExist(err): // non-existence is not an error we care about diff --git a/agent/token/persistence_test.go b/agent/token/persistence_test.go index 1bfe971fdb51..fc52df7e7870 100644 --- a/agent/token/persistence_test.go +++ b/agent/token/persistence_test.go @@ -1,7 +1,7 @@ package token import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -63,7 +63,7 @@ func TestStore_Load(t *testing.T) { "replication" : "lima" }` - require.NoError(t, ioutil.WriteFile(tokenFile, []byte(tokens), 0600)) + require.NoError(t, os.WriteFile(tokenFile, []byte(tokens), 0600)) require.NoError(t, store.Load(cfg, logger)) // no updates since token persistence is not enabled @@ -92,7 +92,7 @@ func TestStore_Load(t *testing.T) { } tokens := `{"agent_master": "juliett"}` - require.NoError(t, ioutil.WriteFile(tokenFile, []byte(tokens), 0600)) + require.NoError(t, os.WriteFile(tokenFile, []byte(tokens), 0600)) require.NoError(t, store.Load(cfg, logger)) require.Equal(t, "juliett", store.AgentRecoveryToken()) @@ -115,7 +115,7 @@ func TestStore_Load(t *testing.T) { ACLReplicationToken: "tango", } - require.NoError(t, ioutil.WriteFile(tokenFile, []byte(tokens), 0600)) + require.NoError(t, os.WriteFile(tokenFile, []byte(tokens), 0600)) require.NoError(t, store.Load(cfg, logger)) require.Equal(t, "mike", store.AgentToken()) @@ -139,7 +139,7 @@ func TestStore_Load(t *testing.T) { ACLReplicationToken: "zulu", } - require.NoError(t, ioutil.WriteFile(tokenFile, []byte(tokens), 0600)) + require.NoError(t, os.WriteFile(tokenFile, []byte(tokens), 0600)) require.NoError(t, store.Load(cfg, logger)) require.Equal(t, "uniform", store.AgentToken()) @@ -158,7 +158,7 @@ func TestStore_Load(t *testing.T) { ACLReplicationToken: "four", } - require.NoError(t, ioutil.WriteFile(tokenFile, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, 0600)) + require.NoError(t, os.WriteFile(tokenFile, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, 0600)) err := store.Load(cfg, logger) require.Error(t, err) require.Contains(t, err.Error(), "failed to decode tokens file") @@ -179,7 +179,7 @@ func TestStore_Load(t *testing.T) { ACLReplicationToken: "foxtrot", } - require.NoError(t, ioutil.WriteFile(tokenFile, []byte("[1,2,3]"), 0600)) + require.NoError(t, os.WriteFile(tokenFile, []byte("[1,2,3]"), 0600)) err := store.Load(cfg, logger) require.Error(t, err) require.Contains(t, err.Error(), "failed to decode tokens file") diff --git a/agent/txn_endpoint_test.go b/agent/txn_endpoint_test.go index f6f47b8fab59..2dc5287e3bdf 100644 --- a/agent/txn_endpoint_test.go +++ b/agent/txn_endpoint_test.go @@ -67,9 +67,9 @@ func TestTxnEndpoint_Bad_Size_Item(t *testing.T) { t.Fatalf("err: %v", err) } } else { - if err, ok := err.(HTTPError); ok { - if err.StatusCode != 413 { - t.Fatalf("expected 413 but got %d", err.StatusCode) + if httpErr, ok := err.(HTTPError); ok { + if httpErr.StatusCode != 413 { + t.Fatalf("expected 413 but got %d", httpErr.StatusCode) } } else { t.Fatalf("excected HTTP error but got %v", err) @@ -150,9 +150,9 @@ func TestTxnEndpoint_Bad_Size_Net(t *testing.T) { t.Fatalf("err: %v", err) } } else { - if err, ok := err.(HTTPError); ok { - if err.StatusCode != 413 { - t.Fatalf("expected 413 but got %d", err.StatusCode) + if httpErr, ok := err.(HTTPError); ok { + if httpErr.StatusCode != 413 { + t.Fatalf("expected 413 but got %d", httpErr.StatusCode) } } else { t.Fatalf("excected HTTP error but got %v", err) @@ -220,9 +220,9 @@ func TestTxnEndpoint_Bad_Size_Ops(t *testing.T) { resp := httptest.NewRecorder() _, err := a.srv.Txn(resp, req) - if err, ok := err.(HTTPError); ok { - if err.StatusCode != 413 { - t.Fatalf("expected 413 but got %d", err.StatusCode) + if httpErr, ok := err.(HTTPError); ok { + if httpErr.StatusCode != 413 { + t.Fatalf("expected 413 but got %d", httpErr.StatusCode) } } else { t.Fatalf("expected HTTP error but got %v", err) diff --git a/agent/ui_endpoint_test.go b/agent/ui_endpoint_test.go index e74ca818b05f..78a4777a8f05 100644 --- a/agent/ui_endpoint_test.go +++ b/agent/ui_endpoint_test.go @@ -6,10 +6,10 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" + "os" "path/filepath" "sync/atomic" "testing" @@ -49,7 +49,7 @@ func TestUIIndex(t *testing.T) { // Create file path := filepath.Join(a.Config.UIConfig.Dir, "my-file") - if err := ioutil.WriteFile(path, []byte("test"), 0644); err != nil { + if err := os.WriteFile(path, []byte("test"), 0644); err != nil { t.Fatalf("err: %v", err) } diff --git a/agent/uiserver/uiserver_test.go b/agent/uiserver/uiserver_test.go index 47110da5ab68..1c310a63ce0b 100644 --- a/agent/uiserver/uiserver_test.go +++ b/agent/uiserver/uiserver_test.go @@ -3,7 +3,6 @@ package uiserver import ( "bytes" "io" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -380,7 +379,7 @@ func TestCustomDir(t *testing.T) { defer os.RemoveAll(uiDir) path := filepath.Join(uiDir, "test-file") - require.NoError(t, ioutil.WriteFile(path, []byte("test"), 0644)) + require.NoError(t, os.WriteFile(path, []byte("test"), 0644)) cfg := basicUIEnabledConfig() cfg.UIConfig.Dir = uiDir @@ -427,7 +426,7 @@ func TestCompiledJS(t *testing.T) { require.Equal(t, http.StatusOK, rec.Code) require.Equal(t, rec.Result().Header["Content-Type"][0], "application/javascript") - wantCompiled, err := ioutil.ReadFile("testdata/compiled-metrics-providers-golden.js") + wantCompiled, err := os.ReadFile("testdata/compiled-metrics-providers-golden.js") require.NoError(t, err) require.Equal(t, rec.Body.String(), string(wantCompiled)) }) diff --git a/agent/watch_handler_test.go b/agent/watch_handler_test.go index 33c0909fe5e5..a5ff8f7c723c 100644 --- a/agent/watch_handler_test.go +++ b/agent/watch_handler_test.go @@ -1,7 +1,7 @@ package agent import ( - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -20,14 +20,14 @@ func TestMakeWatchHandler(t *testing.T) { script := "bash -c 'echo $CONSUL_INDEX >> handler_index_out && cat >> handler_out'" handler := makeWatchHandler(testutil.Logger(t), script) handler(100, []string{"foo", "bar", "baz"}) - raw, err := ioutil.ReadFile("handler_out") + raw, err := os.ReadFile("handler_out") if err != nil { t.Fatalf("err: %v", err) } if string(raw) != "[\"foo\",\"bar\",\"baz\"]\n" { t.Fatalf("bad: %s", raw) } - raw, err = ioutil.ReadFile("handler_index_out") + raw, err = os.ReadFile("handler_index_out") if err != nil { t.Fatalf("err: %v", err) } @@ -47,7 +47,7 @@ func TestMakeHTTPWatchHandler(t *testing.T) { if customHeader != "abc" { t.Fatalf("bad: %s", idx) } - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { t.Fatalf("err: %v", err) } diff --git a/agent/xds/golden_test.go b/agent/xds/golden_test.go index 0efcc155b95f..11ab299d4ec0 100644 --- a/agent/xds/golden_test.go +++ b/agent/xds/golden_test.go @@ -3,7 +3,6 @@ package xds import ( "flag" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -88,7 +87,7 @@ func golden(t *testing.T, name, subname, latestSubname, got string) string { latestExpected := "" if latestSubname != "" && subname != latestSubname { latestGolden := filepath.Join("testdata", fmt.Sprintf("%s.%s.golden", name, latestSubname)) - raw, err := ioutil.ReadFile(latestGolden) + raw, err := os.ReadFile(latestGolden) require.NoError(t, err, "%q %q %q", name, subname, latestSubname) latestExpected = string(raw) } @@ -110,11 +109,11 @@ func golden(t *testing.T, name, subname, latestSubname, got string) string { return got } - require.NoError(t, ioutil.WriteFile(golden, []byte(got), 0644)) + require.NoError(t, os.WriteFile(golden, []byte(got), 0644)) return got } - expected, err := ioutil.ReadFile(golden) + expected, err := os.ReadFile(golden) if latestExpected != "" && os.IsNotExist(err) { // In readonly mode if a specific golden file isn't found, we fallback // on the latest one. @@ -127,7 +126,7 @@ func golden(t *testing.T, name, subname, latestSubname, got string) string { func loadTestResource(t *testing.T, name string) string { t.Helper() - expected, err := ioutil.ReadFile(filepath.Join("testdata", name+".golden")) + expected, err := os.ReadFile(filepath.Join("testdata", name+".golden")) require.NoError(t, err) return string(expected) } diff --git a/api/acl.go b/api/acl.go index bd6d82563278..ceafaddc2b70 100644 --- a/api/acl.go +++ b/api/acl.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/url" "time" @@ -1047,7 +1046,7 @@ func (a *ACL) RulesTranslate(rules io.Reader) (string, error) { parseQueryMeta(resp, qm) qm.RequestTime = rtt - ruleBytes, err := ioutil.ReadAll(resp.Body) + ruleBytes, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("Failed to read translated rule body: %v", err) } @@ -1074,7 +1073,7 @@ func (a *ACL) RulesTranslateToken(tokenID string) (string, error) { parseQueryMeta(resp, qm) qm.RequestTime = rtt - ruleBytes, err := ioutil.ReadAll(resp.Body) + ruleBytes, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("Failed to read translated rule body: %v", err) } diff --git a/api/agent_test.go b/api/agent_test.go index 0c1660b1e9df..57f3453e5d29 100644 --- a/api/agent_test.go +++ b/api/agent_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "net/http/httputil" @@ -104,7 +103,7 @@ func TestAPI_AgentReload(t *testing.T) { // Update the config file with a service definition config := `{"service":{"name":"redis", "port":1234, "Meta": {"some": "meta"}}}` - err = ioutil.WriteFile(configFile.Name(), []byte(config), 0644) + err = os.WriteFile(configFile.Name(), []byte(config), 0644) if err != nil { t.Fatalf("err: %v", err) } diff --git a/api/api_test.go b/api/api_test.go index 3574240d1a64..2487a1cf999a 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "net" "net/http" "net/url" @@ -614,15 +613,15 @@ func TestAPI_SetupTLSConfig(t *testing.T) { assertDeepEqual(t, expectedCaPoolByDir, cc.RootCAs, cmpCertPool) // Load certs in-memory - certPEM, err := ioutil.ReadFile("../test/hostname/Alice.crt") + certPEM, err := os.ReadFile("../test/hostname/Alice.crt") if err != nil { t.Fatalf("err: %v", err) } - keyPEM, err := ioutil.ReadFile("../test/hostname/Alice.key") + keyPEM, err := os.ReadFile("../test/hostname/Alice.key") if err != nil { t.Fatalf("err: %v", err) } - caPEM, err := ioutil.ReadFile("../test/hostname/CertAuth.crt") + caPEM, err := os.ReadFile("../test/hostname/CertAuth.crt") if err != nil { t.Fatalf("err: %v", err) } @@ -1187,7 +1186,7 @@ func getExpectedCaPoolByDir(t *testing.T) *x509.CertPool { for _, entry := range entries { filename := path.Join("../test/ca_path", entry.Name()) - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) require.NoError(t, err) if !pool.AppendCertsFromPEM(data) { diff --git a/api/go.mod b/api/go.mod index 64093899a0c8..b7d519d62b4c 100644 --- a/api/go.mod +++ b/api/go.mod @@ -1,30 +1,45 @@ module github.com/hashicorp/consul/api -go 1.12 +go 1.20 replace github.com/hashicorp/consul/sdk => ../sdk require ( - github.com/armon/go-metrics v0.3.10 // indirect - github.com/google/btree v1.0.0 // indirect github.com/google/go-cmp v0.5.7 github.com/hashicorp/consul/sdk v0.11.0 github.com/hashicorp/go-cleanhttp v0.5.1 github.com/hashicorp/go-hclog v0.14.1 + github.com/hashicorp/go-rootcerts v1.0.2 + github.com/hashicorp/go-uuid v1.0.2 + github.com/hashicorp/serf v0.9.7 + github.com/mitchellh/mapstructure v1.4.1 + github.com/stretchr/testify v1.7.0 +) + +require ( + github.com/armon/go-metrics v0.3.10 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fatih/color v1.9.0 // indirect + github.com/google/btree v1.0.0 // indirect + github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.0 // indirect github.com/hashicorp/go-msgpack v0.5.5 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-rootcerts v1.0.2 github.com/hashicorp/go-sockaddr v1.0.2 // indirect - github.com/hashicorp/go-uuid v1.0.2 github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/hashicorp/memberlist v0.3.1 // indirect - github.com/hashicorp/serf v0.9.7 github.com/kr/pretty v0.2.1 // indirect github.com/kr/text v0.2.0 // indirect - github.com/mitchellh/mapstructure v1.4.1 + github.com/mattn/go-colorable v0.1.6 // indirect + github.com/mattn/go-isatty v0.0.12 // indirect + github.com/miekg/dns v1.1.41 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/stretchr/testify v1.7.0 + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect + github.com/stretchr/objx v0.1.1 // indirect golang.org/x/net v0.0.0-20211216030914-fe4d6282115f // indirect + golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect ) diff --git a/api/go.sum b/api/go.sum index c47deef054b7..1ad3f91a61b8 100644 --- a/api/go.sum +++ b/api/go.sum @@ -45,7 +45,6 @@ github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brv github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v0.14.1 h1:nQcJDQwIAGnmoUWp8ubocEX40cCml/17YkF6csQLReU= github.com/hashicorp/go-hclog v0.14.1/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= @@ -85,7 +84,6 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -190,7 +188,6 @@ golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -212,6 +209,5 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/api/mock_api_test.go b/api/mock_api_test.go index dc4de0a3e4e2..fa18faa7aef2 100644 --- a/api/mock_api_test.go +++ b/api/mock_api_test.go @@ -3,7 +3,6 @@ package api import ( "encoding/json" "io" - "io/ioutil" "net/http" "net/http/httptest" "testing" @@ -39,7 +38,7 @@ func (m *mockAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) { var body interface{} if r.Body != nil { - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err == nil && len(bodyBytes) > 0 { body = bodyBytes diff --git a/api/operator_license.go b/api/operator_license.go index 7b654317cacd..14c548b1a354 100644 --- a/api/operator_license.go +++ b/api/operator_license.go @@ -1,7 +1,7 @@ package api import ( - "io/ioutil" + "io" "strings" "time" ) @@ -71,7 +71,7 @@ func (op *Operator) LicenseGetSigned(q *QueryOptions) (string, error) { return "", err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return "", err } diff --git a/build-support/docker/Build-Go.dockerfile b/build-support/docker/Build-Go.dockerfile index 18c29f5739a2..8ab8e8cb9a99 100644 --- a/build-support/docker/Build-Go.dockerfile +++ b/build-support/docker/Build-Go.dockerfile @@ -1,4 +1,7 @@ -ARG GOLANG_VERSION=1.19.6 +# Copyright (c) HashiCorp, Inc. +# SPDX-License-Identifier: MPL-2.0 + +ARG GOLANG_VERSION=1.20.4 FROM golang:${GOLANG_VERSION} WORKDIR /consul diff --git a/command/acl/authmethod/create/authmethod_create_test.go b/command/acl/authmethod/create/authmethod_create_test.go index 03bdcd1e8625..e5a442c61631 100644 --- a/command/acl/authmethod/create/authmethod_create_test.go +++ b/command/acl/authmethod/create/authmethod_create_test.go @@ -3,7 +3,7 @@ package authmethodcreate import ( "encoding/json" "io" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -468,7 +468,7 @@ func TestAuthMethodCreateCommand_k8s(t *testing.T) { }) caFile := filepath.Join(testDir, "ca.crt") - require.NoError(t, ioutil.WriteFile(caFile, []byte(ca.RootCert), 0600)) + require.NoError(t, os.WriteFile(caFile, []byte(ca.RootCert), 0600)) t.Run("create k8s with cert file", func(t *testing.T) { name := getTestName(t) @@ -540,7 +540,7 @@ func TestAuthMethodCreateCommand_config(t *testing.T) { name := getTestName(t) configFile := filepath.Join(testDir, "config.json") jsonConfig := `{"SessionID":"foo"}` - require.NoError(t, ioutil.WriteFile(configFile, []byte(jsonConfig), 0644)) + require.NoError(t, os.WriteFile(configFile, []byte(jsonConfig), 0644)) args := []string{ "-http-addr=" + a.HTTPAddr(), diff --git a/command/acl/authmethod/update/authmethod_update_test.go b/command/acl/authmethod/update/authmethod_update_test.go index 263f0b774a98..4afe1dfb4770 100644 --- a/command/acl/authmethod/update/authmethod_update_test.go +++ b/command/acl/authmethod/update/authmethod_update_test.go @@ -3,7 +3,7 @@ package authmethodupdate import ( "encoding/json" "io" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -455,7 +455,7 @@ func TestAuthMethodUpdateCommand_k8s(t *testing.T) { }) ca2File := filepath.Join(testDir, "ca2.crt") - require.NoError(t, ioutil.WriteFile(ca2File, []byte(ca2.RootCert), 0600)) + require.NoError(t, os.WriteFile(ca2File, []byte(ca2.RootCert), 0600)) t.Run("update all fields with cert file", func(t *testing.T) { name := createAuthMethod(t) @@ -750,7 +750,7 @@ func TestAuthMethodUpdateCommand_k8s_noMerge(t *testing.T) { }) ca2File := filepath.Join(testDir, "ca2.crt") - require.NoError(t, ioutil.WriteFile(ca2File, []byte(ca2.RootCert), 0600)) + require.NoError(t, os.WriteFile(ca2File, []byte(ca2.RootCert), 0600)) t.Run("update all fields with cert file", func(t *testing.T) { name := createAuthMethod(t) @@ -849,7 +849,7 @@ func TestAuthMethodUpdateCommand_config(t *testing.T) { methodName := createAuthMethod(t) configFile := filepath.Join(testDir, "config.json") jsonConfig := `{"SessionID":"update"}` - require.NoError(t, ioutil.WriteFile(configFile, []byte(jsonConfig), 0644)) + require.NoError(t, os.WriteFile(configFile, []byte(jsonConfig), 0644)) args := []string{ "-http-addr=" + a.HTTPAddr(), diff --git a/command/acl/policy/create/policy_create_test.go b/command/acl/policy/create/policy_create_test.go index 4466ad2d5d62..39c837ab89d6 100644 --- a/command/acl/policy/create/policy_create_test.go +++ b/command/acl/policy/create/policy_create_test.go @@ -2,7 +2,7 @@ package policycreate import ( "encoding/json" - "io/ioutil" + "os" "strings" "testing" @@ -47,7 +47,7 @@ func TestPolicyCreateCommand(t *testing.T) { cmd := New(ui) rules := []byte("service \"\" { policy = \"write\" }") - err := ioutil.WriteFile(testDir+"/rules.hcl", rules, 0644) + err := os.WriteFile(testDir+"/rules.hcl", rules, 0644) require.NoError(t, err) args := []string{ @@ -87,7 +87,7 @@ func TestPolicyCreateCommand_JSON(t *testing.T) { cmd := New(ui) rules := []byte("service \"\" { policy = \"write\" }") - err := ioutil.WriteFile(testDir+"/rules.hcl", rules, 0644) + err := os.WriteFile(testDir+"/rules.hcl", rules, 0644) require.NoError(t, err) args := []string{ diff --git a/command/acl/policy/update/policy_update_test.go b/command/acl/policy/update/policy_update_test.go index c11d2b76e58a..485425be07ee 100644 --- a/command/acl/policy/update/policy_update_test.go +++ b/command/acl/policy/update/policy_update_test.go @@ -2,7 +2,7 @@ package policyupdate import ( "encoding/json" - "io/ioutil" + "os" "strings" "testing" @@ -47,7 +47,7 @@ func TestPolicyUpdateCommand(t *testing.T) { cmd := New(ui) rules := []byte("service \"\" { policy = \"write\" }") - err := ioutil.WriteFile(testDir+"/rules.hcl", rules, 0644) + err := os.WriteFile(testDir+"/rules.hcl", rules, 0644) assert.NoError(t, err) // Create a policy @@ -97,7 +97,7 @@ func TestPolicyUpdateCommand_JSON(t *testing.T) { cmd := New(ui) rules := []byte("service \"\" { policy = \"write\" }") - err := ioutil.WriteFile(testDir+"/rules.hcl", rules, 0644) + err := os.WriteFile(testDir+"/rules.hcl", rules, 0644) assert.NoError(t, err) // Create a policy diff --git a/command/acl/role/formatter_test.go b/command/acl/role/formatter_test.go index b6b3bd7c2c52..0e0721dc4dd1 100644 --- a/command/acl/role/formatter_test.go +++ b/command/acl/role/formatter_test.go @@ -3,7 +3,7 @@ package role import ( "flag" "fmt" - "io/ioutil" + "os" "path" "path/filepath" "testing" @@ -22,11 +22,11 @@ func golden(t *testing.T, name, got string) string { golden := filepath.Join("testdata", name+".golden") if *update && got != "" { - err := ioutil.WriteFile(golden, []byte(got), 0644) + err := os.WriteFile(golden, []byte(got), 0644) require.NoError(t, err) } - expected, err := ioutil.ReadFile(golden) + expected, err := os.ReadFile(golden) require.NoError(t, err) return string(expected) diff --git a/command/acl/rules/translate_test.go b/command/acl/rules/translate_test.go index 830cb2403789..6772d60d6991 100644 --- a/command/acl/rules/translate_test.go +++ b/command/acl/rules/translate_test.go @@ -2,7 +2,7 @@ package rules import ( "io" - "io/ioutil" + "os" "strings" "testing" @@ -52,7 +52,7 @@ func TestRulesTranslateCommand(t *testing.T) { // From a file t.Run("file", func(t *testing.T) { - err := ioutil.WriteFile(testDir+"/rules.hcl", []byte(rules), 0644) + err := os.WriteFile(testDir+"/rules.hcl", []byte(rules), 0644) require.NoError(t, err) args := []string{ diff --git a/command/acl/token/formatter_test.go b/command/acl/token/formatter_test.go index aafe1fcfb268..92df4105af11 100644 --- a/command/acl/token/formatter_test.go +++ b/command/acl/token/formatter_test.go @@ -3,7 +3,7 @@ package token import ( "flag" "fmt" - "io/ioutil" + "os" "path" "path/filepath" "testing" @@ -23,11 +23,11 @@ func golden(t *testing.T, name, got string) string { golden := filepath.Join("testdata", name+".golden") if *update && got != "" { - err := ioutil.WriteFile(golden, []byte(got), 0644) + err := os.WriteFile(golden, []byte(got), 0644) require.NoError(t, err) } - expected, err := ioutil.ReadFile(golden) + expected, err := os.ReadFile(golden) require.NoError(t, err) return string(expected) diff --git a/command/agent/agent.go b/command/agent/agent.go index cc08213e1c31..af284d72988a 100644 --- a/command/agent/agent.go +++ b/command/agent/agent.go @@ -4,7 +4,7 @@ import ( "context" "flag" "fmt" - "io/ioutil" + "io" "os" "os/signal" "path/filepath" @@ -191,7 +191,7 @@ func (c *cmd) run(args []string) int { if config.Logging.LogJSON { // Hide all non-error output when JSON logging is enabled. ui.Ui = &cli.BasicUI{ - BasicUi: mcli.BasicUi{ErrorWriter: c.ui.Stderr(), Writer: ioutil.Discard}, + BasicUi: mcli.BasicUi{ErrorWriter: c.ui.Stderr(), Writer: io.Discard}, } } diff --git a/command/connect/ca/set/connect_ca_set.go b/command/connect/ca/set/connect_ca_set.go index 29922b5b9938..54f8854d5cc9 100644 --- a/command/connect/ca/set/connect_ca_set.go +++ b/command/connect/ca/set/connect_ca_set.go @@ -4,7 +4,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "os" "github.com/hashicorp/consul/api" "github.com/hashicorp/consul/command/flags" @@ -66,7 +66,7 @@ func (c *cmd) Run(args []string) int { return 1 } - bytes, err := ioutil.ReadFile(c.configFile.String()) + bytes, err := os.ReadFile(c.configFile.String()) if err != nil { c.UI.Error(fmt.Sprintf("Error reading config file: %s", err)) return 1 diff --git a/command/connect/envoy/envoy_test.go b/command/connect/envoy/envoy_test.go index 6e3b3e2a4e07..07809d7d6c54 100644 --- a/command/connect/envoy/envoy_test.go +++ b/command/connect/envoy/envoy_test.go @@ -3,7 +3,6 @@ package envoy import ( "encoding/json" "flag" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -994,7 +993,7 @@ func TestGenerateConfig(t *testing.T) { if len(tc.Files) > 0 { for fn, fv := range tc.Files { fullname := filepath.Join(testDir, fn) - require.NoError(t, ioutil.WriteFile(fullname, []byte(fv), 0600)) + require.NoError(t, os.WriteFile(fullname, []byte(fv), 0600)) } } @@ -1045,10 +1044,10 @@ func TestGenerateConfig(t *testing.T) { // If we got the arg handling write, verify output golden := filepath.Join("testdata", tc.Name+".golden") if *update { - ioutil.WriteFile(golden, actual, 0644) + os.WriteFile(golden, actual, 0644) } - expected, err := ioutil.ReadFile(golden) + expected, err := os.ReadFile(golden) require.NoError(t, err) require.Equal(t, string(expected), string(actual)) }) diff --git a/command/connect/envoy/exec_test.go b/command/connect/envoy/exec_test.go index 9c7fc276bb83..3765003e6adb 100644 --- a/command/connect/envoy/exec_test.go +++ b/command/connect/envoy/exec_test.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/exec" "strings" @@ -234,7 +233,7 @@ func TestHelperProcess(t *testing.T) { os.Exit(1) } - d, err := ioutil.ReadFile(data.ConfigPath) + d, err := os.ReadFile(data.ConfigPath) if err != nil { fmt.Fprintf(os.Stderr, "could not read provided --config-path file %q: %v\n", data.ConfigPath, err) os.Exit(1) diff --git a/command/flags/http.go b/command/flags/http.go index e82e024fbbac..b4a2a9038c16 100644 --- a/command/flags/http.go +++ b/command/flags/http.go @@ -2,7 +2,7 @@ package flags import ( "flag" - "io/ioutil" + "os" "strings" "github.com/hashicorp/consul/api" @@ -131,7 +131,7 @@ func (f *HTTPFlags) ReadTokenFile() (string, error) { return "", nil } - data, err := ioutil.ReadFile(tokenFile) + data, err := os.ReadFile(tokenFile) if err != nil { return "", err } diff --git a/command/helpers/helpers.go b/command/helpers/helpers.go index 56ad6f7d367e..493c9ff4ab04 100644 --- a/command/helpers/helpers.go +++ b/command/helpers/helpers.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "time" @@ -15,7 +14,7 @@ import ( ) func loadFromFile(path string) (string, error) { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return "", fmt.Errorf("Failed to read file: %v", err) } diff --git a/command/kv/imp/kv_import.go b/command/kv/imp/kv_import.go index d5796f24d206..0d8570dd60c5 100644 --- a/command/kv/imp/kv_import.go +++ b/command/kv/imp/kv_import.go @@ -8,7 +8,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "path" @@ -123,7 +122,7 @@ func (c *cmd) dataFromArgs(args []string) (string, error) { switch data[0] { case '@': - data, err := ioutil.ReadFile(data[1:]) + data, err := os.ReadFile(data[1:]) if err != nil { return "", fmt.Errorf("Failed to read file: %s", err) } diff --git a/command/lock/lock_test.go b/command/lock/lock_test.go index c0f5381e31fa..e9a03fc8809b 100644 --- a/command/lock/lock_test.go +++ b/command/lock/lock_test.go @@ -1,7 +1,7 @@ package lock import ( - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -63,7 +63,7 @@ func TestLockCommand(t *testing.T) { } // Check for the file - _, err := ioutil.ReadFile(filePath) + _, err := os.ReadFile(filePath) if err != nil { t.Fatalf("err: %v", err) } @@ -92,7 +92,7 @@ func TestLockCommand_NoShell(t *testing.T) { } // Check for the file - _, err := ioutil.ReadFile(filePath) + _, err := os.ReadFile(filePath) if err != nil { t.Fatalf("err: %v", err) } @@ -121,7 +121,7 @@ func TestLockCommand_TryLock(t *testing.T) { if code != 0 { t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String()) } - _, err := ioutil.ReadFile(filePath) + _, err := os.ReadFile(filePath) if err != nil { t.Fatalf("err: %v", err) } @@ -159,7 +159,7 @@ func TestLockCommand_TrySemaphore(t *testing.T) { if code != 0 { t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String()) } - _, err := ioutil.ReadFile(filePath) + _, err := os.ReadFile(filePath) if err != nil { t.Fatalf("err: %v", err) } @@ -197,7 +197,7 @@ func TestLockCommand_MonitorRetry_Lock_Default(t *testing.T) { if code != 0 { t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String()) } - _, err := ioutil.ReadFile(filePath) + _, err := os.ReadFile(filePath) if err != nil { t.Fatalf("err: %v", err) } @@ -236,7 +236,7 @@ func TestLockCommand_MonitorRetry_Semaphore_Default(t *testing.T) { if code != 0 { t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String()) } - _, err := ioutil.ReadFile(filePath) + _, err := os.ReadFile(filePath) if err != nil { t.Fatalf("err: %v", err) } @@ -275,7 +275,7 @@ func TestLockCommand_MonitorRetry_Lock_Arg(t *testing.T) { if code != 0 { t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String()) } - _, err := ioutil.ReadFile(filePath) + _, err := os.ReadFile(filePath) if err != nil { t.Fatalf("err: %v", err) } @@ -314,7 +314,7 @@ func TestLockCommand_MonitorRetry_Semaphore_Arg(t *testing.T) { if code != 0 { t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String()) } - _, err := ioutil.ReadFile(filePath) + _, err := os.ReadFile(filePath) if err != nil { t.Fatalf("err: %v", err) } diff --git a/command/login/login.go b/command/login/login.go index a8f58556accf..e4209eeda4af 100644 --- a/command/login/login.go +++ b/command/login/login.go @@ -3,7 +3,7 @@ package login import ( "flag" "fmt" - "io/ioutil" + "os" "strings" "github.com/hashicorp/consul/api" @@ -112,7 +112,7 @@ func (c *cmd) bearerTokenLogin() int { c.UI.Error("Missing required '-bearer-token-file' flag") return 1 } else { - data, err := ioutil.ReadFile(c.bearerTokenFile) + data, err := os.ReadFile(c.bearerTokenFile) if err != nil { c.UI.Error(err.Error()) return 1 diff --git a/command/login/login_test.go b/command/login/login_test.go index 6340d93f717c..e7297ffe5102 100644 --- a/command/login/login_test.go +++ b/command/login/login_test.go @@ -2,7 +2,6 @@ package login import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -173,7 +172,7 @@ func TestLoginCommand(t *testing.T) { t.Run("bearer-token-file is empty", func(t *testing.T) { defer os.Remove(tokenSinkFile) - require.NoError(t, ioutil.WriteFile(bearerTokenFile, []byte(""), 0600)) + require.NoError(t, os.WriteFile(bearerTokenFile, []byte(""), 0600)) ui := cli.NewMockUi() cmd := New(ui) @@ -191,7 +190,7 @@ func TestLoginCommand(t *testing.T) { require.Contains(t, ui.ErrorWriter.String(), "No bearer token found in") }) - require.NoError(t, ioutil.WriteFile(bearerTokenFile, []byte("demo-token"), 0600)) + require.NoError(t, os.WriteFile(bearerTokenFile, []byte("demo-token"), 0600)) t.Run("try login with no method configured", func(t *testing.T) { defer os.Remove(tokenSinkFile) @@ -285,7 +284,7 @@ func TestLoginCommand(t *testing.T) { require.Empty(t, ui.ErrorWriter.String()) require.Empty(t, ui.OutputWriter.String()) - raw, err := ioutil.ReadFile(tokenSinkFile) + raw, err := os.ReadFile(tokenSinkFile) require.NoError(t, err) token := strings.TrimSpace(string(raw)) @@ -309,7 +308,7 @@ func TestLoginCommand_k8s(t *testing.T) { bearerTokenFile := filepath.Join(testDir, "bearer.token") // the "B" jwt will be the one being reviewed - require.NoError(t, ioutil.WriteFile(bearerTokenFile, []byte(acl.TestKubernetesJWT_B), 0600)) + require.NoError(t, os.WriteFile(bearerTokenFile, []byte(acl.TestKubernetesJWT_B), 0600)) // spin up a fake api server testSrv := kubeauth.StartTestAPIServer(t) @@ -372,7 +371,7 @@ func TestLoginCommand_k8s(t *testing.T) { require.Empty(t, ui.ErrorWriter.String()) require.Empty(t, ui.OutputWriter.String()) - raw, err := ioutil.ReadFile(tokenSinkFile) + raw, err := os.ReadFile(tokenSinkFile) require.NoError(t, err) token := strings.TrimSpace(string(raw)) @@ -487,7 +486,7 @@ func TestLoginCommand_jwt(t *testing.T) { // Drop a JWT on disk. jwtData, err := oidcauthtest.SignJWT(privKey, cl, privateCl) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(bearerTokenFile, []byte(jwtData), 0600)) + require.NoError(t, os.WriteFile(bearerTokenFile, []byte(jwtData), 0600)) defer os.Remove(tokenSinkFile) ui := cli.NewMockUi() @@ -506,7 +505,7 @@ func TestLoginCommand_jwt(t *testing.T) { require.Empty(t, ui.ErrorWriter.String()) require.Empty(t, ui.OutputWriter.String()) - raw, err := ioutil.ReadFile(tokenSinkFile) + raw, err := os.ReadFile(tokenSinkFile) require.NoError(t, err) token := strings.TrimSpace(string(raw)) @@ -660,7 +659,7 @@ func TestLoginCommand_aws_iam(t *testing.T) { code := cmd.Run(args) require.Equal(t, 0, code, ui.ErrorWriter.String()) - raw, err := ioutil.ReadFile(tokenSinkFile) + raw, err := os.ReadFile(tokenSinkFile) require.NoError(t, err) token := strings.TrimSpace(string(raw)) diff --git a/command/logout/logout_test.go b/command/logout/logout_test.go index c5130fdf1b75..e41a33ef4d0f 100644 --- a/command/logout/logout_test.go +++ b/command/logout/logout_test.go @@ -225,9 +225,6 @@ func TestLogoutCommand_k8s(t *testing.T) { require.Contains(t, ui.ErrorWriter.String(), "403 (Permission denied: token wasn't created via login)") }) - // go to the trouble of creating a login token - // require.NoError(t, ioutil.WriteFile(bearerTokenFile, []byte(acl.TestKubernetesJWT_B), 0600)) - // spin up a fake api server testSrv := kubeauth.StartTestAPIServer(t) defer testSrv.Stop() diff --git a/command/members/members_test.go b/command/members/members_test.go index cc4a21742aec..c9a2d42b77d6 100644 --- a/command/members/members_test.go +++ b/command/members/members_test.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/consul/agent" consulapi "github.com/hashicorp/consul/api" - "github.com/hashicorp/consul/lib" ) // TODO(partitions): split these tests @@ -206,8 +205,6 @@ func zip(t *testing.T, k, v []string) map[string]string { } func TestSortByMemberNamePartitionAndSegment(t *testing.T) { - lib.SeedMathRand() - // For the test data we'll give them names that would sort them backwards // if we only sorted by name. newData := func() []*consulapi.AgentMember { diff --git a/command/operator/autopilot/state/operator_autopilot_state_test.go b/command/operator/autopilot/state/operator_autopilot_state_test.go index 00484974d531..332f53059c94 100644 --- a/command/operator/autopilot/state/operator_autopilot_state_test.go +++ b/command/operator/autopilot/state/operator_autopilot_state_test.go @@ -3,7 +3,7 @@ package state import ( "encoding/json" "flag" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -25,11 +25,11 @@ func golden(t *testing.T, name, got string) string { golden := filepath.Join("testdata", name+".golden") if *update && got != "" { - err := ioutil.WriteFile(golden, []byte(got), 0644) + err := os.WriteFile(golden, []byte(got), 0644) require.NoError(t, err) } - expected, err := ioutil.ReadFile(golden) + expected, err := os.ReadFile(golden) require.NoError(t, err) return string(expected) @@ -111,7 +111,7 @@ func TestStateCommand_Formatter(t *testing.T) { for _, name := range cases { t.Run(name, func(t *testing.T) { statePath := filepath.Join("testdata", name, "state.json") - input, err := ioutil.ReadFile(statePath) + input, err := os.ReadFile(statePath) require.NoError(t, err) var state api.AutopilotState diff --git a/command/snapshot/inspect/snapshot_inspect.go b/command/snapshot/inspect/snapshot_inspect.go index d0deec4435c6..2a09067a16b4 100644 --- a/command/snapshot/inspect/snapshot_inspect.go +++ b/command/snapshot/inspect/snapshot_inspect.go @@ -5,7 +5,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "path" "sort" @@ -123,7 +122,7 @@ func (c *cmd) Run(args []string) int { readFile = f // Assume the meta is colocated and error if not. - metaRaw, err := ioutil.ReadFile(path.Join(path.Dir(file), "meta.json")) + metaRaw, err := os.ReadFile(path.Join(path.Dir(file), "meta.json")) if err != nil { c.UI.Error(fmt.Sprintf("Error reading meta.json from internal snapshot dir: %s", err)) return 1 diff --git a/command/snapshot/inspect/snapshot_inspect_test.go b/command/snapshot/inspect/snapshot_inspect_test.go index 9d4add371dbc..5c302c6a7aaf 100644 --- a/command/snapshot/inspect/snapshot_inspect_test.go +++ b/command/snapshot/inspect/snapshot_inspect_test.go @@ -2,7 +2,7 @@ package inspect import ( "flag" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -21,11 +21,11 @@ func golden(t *testing.T, name, got string) string { golden := filepath.Join("testdata", name+".golden") if *update && got != "" { - err := ioutil.WriteFile(golden, []byte(got), 0644) + err := os.WriteFile(golden, []byte(got), 0644) require.NoError(t, err) } - expected, err := ioutil.ReadFile(golden) + expected, err := os.ReadFile(golden) require.NoError(t, err) return string(expected) diff --git a/command/snapshot/restore/snapshot_restore_test.go b/command/snapshot/restore/snapshot_restore_test.go index 8b1448460877..38a54967e1e9 100644 --- a/command/snapshot/restore/snapshot_restore_test.go +++ b/command/snapshot/restore/snapshot_restore_test.go @@ -4,7 +4,6 @@ import ( "crypto/rand" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -135,7 +134,7 @@ func TestSnapshotRestoreCommand_TruncatedSnapshot(t *testing.T) { require.NoError(t, err) defer rc.Close() - inputData, err = ioutil.ReadAll(rc) + inputData, err = io.ReadAll(rc) require.NoError(t, err) } @@ -150,7 +149,7 @@ func TestSnapshotRestoreCommand_TruncatedSnapshot(t *testing.T) { c := New(ui) file := filepath.Join(dir, "backup.tgz") - require.NoError(t, ioutil.WriteFile(file, data, 0644)) + require.NoError(t, os.WriteFile(file, data, 0644)) args := []string{ "-http-addr=" + a.HTTPAddr(), file, diff --git a/command/snapshot/save/snapshot_save_test.go b/command/snapshot/save/snapshot_save_test.go index 10e8abcfea60..3e964dbbf7e1 100644 --- a/command/snapshot/save/snapshot_save_test.go +++ b/command/snapshot/save/snapshot_save_test.go @@ -3,7 +3,7 @@ package save import ( "crypto/rand" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -136,7 +136,7 @@ func TestSnapshotSaveCommand_TruncatedStream(t *testing.T) { require.NoError(t, err) defer rc.Close() - inputData, err = ioutil.ReadAll(rc) + inputData, err = io.ReadAll(rc) require.NoError(t, err) } diff --git a/command/tls/ca/create/tls_ca_create_test.go b/command/tls/ca/create/tls_ca_create_test.go index b9ba9e0cdd0d..a349325b1e9d 100644 --- a/command/tls/ca/create/tls_ca_create_test.go +++ b/command/tls/ca/create/tls_ca_create_test.go @@ -4,7 +4,6 @@ import ( "crypto" "crypto/x509" "io/fs" - "io/ioutil" "os" "strings" "testing" @@ -129,9 +128,9 @@ func expectFiles(t *testing.T, caPath, keyPath string) (*x509.Certificate, crypt t.Fatalf("private key file %s: permissions: want: %o; have: %o", keyPath, want, have) } - caData, err := ioutil.ReadFile(caPath) + caData, err := os.ReadFile(caPath) require.NoError(t, err) - keyData, err := ioutil.ReadFile(keyPath) + keyData, err := os.ReadFile(keyPath) require.NoError(t, err) ca, err := connect.ParseCert(string(caData)) diff --git a/command/tls/cert/create/tls_cert_create.go b/command/tls/cert/create/tls_cert_create.go index b1cdaa131d27..75c9b1ada1fc 100644 --- a/command/tls/cert/create/tls_cert_create.go +++ b/command/tls/cert/create/tls_cert_create.go @@ -4,8 +4,8 @@ import ( "crypto/x509" "flag" "fmt" - "io/ioutil" "net" + "os" "strings" "github.com/hashicorp/consul/command/flags" @@ -150,12 +150,12 @@ func (c *cmd) Run(args []string) int { caFile := strings.Replace(c.ca, "#DOMAIN#", c.domain, 1) keyFile := strings.Replace(c.key, "#DOMAIN#", c.domain, 1) - cert, err := ioutil.ReadFile(caFile) + cert, err := os.ReadFile(caFile) if err != nil { c.UI.Error(fmt.Sprintf("Error reading CA: %s", err)) return 1 } - key, err := ioutil.ReadFile(keyFile) + key, err := os.ReadFile(keyFile) if err != nil { c.UI.Error(fmt.Sprintf("Error reading CA key: %s", err)) return 1 diff --git a/command/tls/cert/create/tls_cert_create_test.go b/command/tls/cert/create/tls_cert_create_test.go index cd81b75b9b38..abc23424d045 100644 --- a/command/tls/cert/create/tls_cert_create_test.go +++ b/command/tls/cert/create/tls_cert_create_test.go @@ -4,7 +4,6 @@ import ( "crypto" "crypto/x509" "io/fs" - "io/ioutil" "net" "os" "strings" @@ -251,9 +250,9 @@ func expectFiles(t *testing.T, certPath, keyPath string) (*x509.Certificate, cry t.Fatalf("private key file %s: permissions: want: %o; have: %o", keyPath, want, have) } - certData, err := ioutil.ReadFile(certPath) + certData, err := os.ReadFile(certPath) require.NoError(t, err) - keyData, err := ioutil.ReadFile(keyPath) + keyData, err := os.ReadFile(keyPath) require.NoError(t, err) cert, err := connect.ParseCert(string(certData)) diff --git a/command/validate/validate_test.go b/command/validate/validate_test.go index c8cc3bf4d128..29091f1292c6 100644 --- a/command/validate/validate_test.go +++ b/command/validate/validate_test.go @@ -1,7 +1,7 @@ package validate import ( - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -34,7 +34,7 @@ func TestValidateCommand_SucceedOnMinimalConfigFile(t *testing.T) { td := testutil.TempDir(t, "consul") fp := filepath.Join(td, "config.json") - err := ioutil.WriteFile(fp, []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) + err := os.WriteFile(fp, []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) require.Nilf(t, err, "err: %s", err) cmd := New(cli.NewMockUi()) @@ -49,7 +49,7 @@ func TestValidateCommand_SucceedWithMinimalJSONConfigFormat(t *testing.T) { td := testutil.TempDir(t, "consul") fp := filepath.Join(td, "json.conf") - err := ioutil.WriteFile(fp, []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) + err := os.WriteFile(fp, []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) require.Nilf(t, err, "err: %s", err) cmd := New(cli.NewMockUi()) @@ -64,7 +64,7 @@ func TestValidateCommand_SucceedWithMinimalHCLConfigFormat(t *testing.T) { td := testutil.TempDir(t, "consul") fp := filepath.Join(td, "hcl.conf") - err := ioutil.WriteFile(fp, []byte("bind_addr = \"10.0.0.1\"\ndata_dir = \""+td+"\""), 0644) + err := os.WriteFile(fp, []byte("bind_addr = \"10.0.0.1\"\ndata_dir = \""+td+"\""), 0644) require.Nilf(t, err, "err: %s", err) cmd := New(cli.NewMockUi()) @@ -79,7 +79,7 @@ func TestValidateCommand_SucceedWithJSONAsHCL(t *testing.T) { td := testutil.TempDir(t, "consul") fp := filepath.Join(td, "json.conf") - err := ioutil.WriteFile(fp, []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) + err := os.WriteFile(fp, []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) require.Nilf(t, err, "err: %s", err) cmd := New(cli.NewMockUi()) @@ -93,7 +93,7 @@ func TestValidateCommand_SucceedOnMinimalConfigDir(t *testing.T) { t.Parallel() td := testutil.TempDir(t, "consul") - err := ioutil.WriteFile(filepath.Join(td, "config.json"), []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) + err := os.WriteFile(filepath.Join(td, "config.json"), []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) require.Nilf(t, err, "err: %s", err) cmd := New(cli.NewMockUi()) @@ -108,7 +108,7 @@ func TestValidateCommand_FailForInvalidJSONConfigFormat(t *testing.T) { td := testutil.TempDir(t, "consul") fp := filepath.Join(td, "hcl.conf") - err := ioutil.WriteFile(fp, []byte(`bind_addr = "10.0.0.1"\ndata_dir = "`+td+`"`), 0644) + err := os.WriteFile(fp, []byte(`bind_addr = "10.0.0.1"\ndata_dir = "`+td+`"`), 0644) require.Nilf(t, err, "err: %s", err) cmd := New(cli.NewMockUi()) @@ -123,7 +123,7 @@ func TestValidateCommand_Quiet(t *testing.T) { td := testutil.TempDir(t, "consul") fp := filepath.Join(td, "config.json") - err := ioutil.WriteFile(fp, []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) + err := os.WriteFile(fp, []byte(`{"bind_addr":"10.0.0.1", "data_dir":"`+td+`"}`), 0644) require.Nilf(t, err, "err: %s", err) ui := cli.NewMockUi() diff --git a/command/version/formatter_test.go b/command/version/formatter_test.go index e532c487c02d..094f8ede17be 100644 --- a/command/version/formatter_test.go +++ b/command/version/formatter_test.go @@ -3,7 +3,7 @@ package version import ( "flag" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -21,11 +21,11 @@ func golden(t *testing.T, name, got string) string { golden := filepath.Join("testdata", name+".golden") if *update && got != "" { - err := ioutil.WriteFile(golden, []byte(got), 0644) + err := os.WriteFile(golden, []byte(got), 0644) require.NoError(t, err) } - expected, err := ioutil.ReadFile(golden) + expected, err := os.ReadFile(golden) require.NoError(t, err) return string(expected) diff --git a/command/watch/watch_test.go b/command/watch/watch_test.go index a2d15deb29ba..503a83dd038e 100644 --- a/command/watch/watch_test.go +++ b/command/watch/watch_test.go @@ -1,7 +1,6 @@ package watch import ( - "io/ioutil" "os" "path/filepath" "strings" @@ -58,7 +57,7 @@ func TestWatchCommand_loadToken(t *testing.T) { testDir := testutil.TempDir(t, "watchtest") fullname := filepath.Join(testDir, "token.txt") - require.NoError(t, ioutil.WriteFile(fullname, []byte(testToken), 0600)) + require.NoError(t, os.WriteFile(fullname, []byte(testToken), 0600)) resetEnv := func() { os.Unsetenv("CONSUL_HTTP_TOKEN") diff --git a/connect/certgen/certgen.go b/connect/certgen/certgen.go index 79b2b2205399..8701137f43e1 100644 --- a/connect/certgen/certgen.go +++ b/connect/certgen/certgen.go @@ -31,7 +31,6 @@ package main // import "github.com/hashicorp/consul/connect/certgen" import ( "flag" "fmt" - "io/ioutil" "log" "os" @@ -85,7 +84,7 @@ func main() { func writeFile(name, content string) { fmt.Println("Writing ", name) - err := ioutil.WriteFile(name, []byte(content), 0600) + err := os.WriteFile(name, []byte(content), 0600) if err != nil { log.Fatalf("failed writing file: %s", err) } diff --git a/connect/service_test.go b/connect/service_test.go index e72b501ed722..5405a32362b0 100644 --- a/connect/service_test.go +++ b/connect/service_test.go @@ -7,7 +7,6 @@ import ( "crypto/x509" "fmt" "io" - "io/ioutil" "net/http" "reflect" "sort" @@ -255,7 +254,7 @@ func TestService_HTTPClient(t *testing.T) { r.Check(err) defer resp.Body.Close() - bodyBytes, err := ioutil.ReadAll(resp.Body) + bodyBytes, err := io.ReadAll(resp.Body) r.Check(err) got := string(bodyBytes) diff --git a/connect/tls.go b/connect/tls.go index dd7fc1869eb9..b142515ecaf5 100644 --- a/connect/tls.go +++ b/connect/tls.go @@ -5,9 +5,9 @@ import ( "crypto/x509" "errors" "fmt" - "io/ioutil" "net" "net/url" + "os" "strings" "sync" @@ -89,7 +89,7 @@ func devTLSConfigFromFiles(caFile, certFile, roots := x509.NewCertPool() - bs, err := ioutil.ReadFile(caFile) + bs, err := os.ReadFile(caFile) if err != nil { return nil, err } diff --git a/go.mod b/go.mod index e30e32709c34..bcdc74558e3c 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/hashicorp/consul -go 1.19 +go 1.20 replace github.com/hashicorp/consul/api => ./api diff --git a/go.sum b/go.sum index 4be2d2973b87..9be76118954a 100644 --- a/go.sum +++ b/go.sum @@ -363,8 +363,6 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY= github.com/hashicorp/mdns v1.0.4 h1:sY0CMhFmjIPDMlTB+HfymFHCaYLhgifZ0QhjaYKD/UQ= github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/YAJqrc= -github.com/hashicorp/memberlist v0.3.0/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= -github.com/hashicorp/memberlist v0.3.1/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= github.com/hashicorp/memberlist v0.4.0 h1:k3uda5gZcltmafuFF+UFqNEl5PrH+yPZ4zkjp1f/H/8= github.com/hashicorp/memberlist v0.4.0/go.mod h1:yvyXLpo0QaGE59Y7hDTsTzDD25JYBZ4mHgHUZ8lrOI0= github.com/hashicorp/raft v1.1.0/go.mod h1:4Ak7FSPnuvmb0GV6vgIAJ4vYT4bek9bb6Q+7HVbyzqM= @@ -380,7 +378,6 @@ github.com/hashicorp/raft-boltdb v0.0.0-20211202195631-7d34b9fb3f42 h1:Ye8SofeDH github.com/hashicorp/raft-boltdb v0.0.0-20211202195631-7d34b9fb3f42/go.mod h1:wcXL8otVu5cpJVLjcmq7pmfdRCdaP+xnvu7WQcKJAhs= github.com/hashicorp/raft-boltdb/v2 v2.2.2 h1:rlkPtOllgIcKLxVT4nutqlTH2NRFn+tO1wwZk/4Dxqw= github.com/hashicorp/raft-boltdb/v2 v2.2.2/go.mod h1:N8YgaZgNJLpZC+h+by7vDu5rzsRgONThTEeUS3zWbfY= -github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= github.com/hashicorp/serf v0.10.0 h1:89qvvpfMQnz6c2y4pv7j2vUUmeT1+5TSZMexuTbtsPs= github.com/hashicorp/serf v0.10.0/go.mod h1:bXN03oZc5xlH46k/K1qTrpXb9ERKyY1/i/N5mxvgrZw= github.com/hashicorp/vault/api v1.0.5-0.20200717191844-f687267c8086 h1:OKsyxKi2sNmqm1Gv93adf2AID2FOBFdCbbZn9fGtIdg= @@ -429,7 +426,6 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3 github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -797,7 +793,6 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/internal/go-sso/oidcauth/oidcauthtest/testing.go b/internal/go-sso/oidcauth/oidcauthtest/testing.go index 8e20fb5750ae..46b1a8ff393f 100644 --- a/internal/go-sso/oidcauth/oidcauthtest/testing.go +++ b/internal/go-sso/oidcauth/oidcauthtest/testing.go @@ -14,7 +14,7 @@ import ( "encoding/json" "encoding/pem" "fmt" - "io/ioutil" + "io" "log" "net" "net/http" @@ -82,7 +82,7 @@ func Start(t TestingT) *Server { s.jwks = jwks s.httpServer = httptest.NewUnstartedServer(s) - s.httpServer.Config.ErrorLog = log.New(ioutil.Discard, "", 0) + s.httpServer.Config.ErrorLog = log.New(io.Discard, "", 0) s.httpServer.StartTLS() t.Cleanup(s.httpServer.Close) diff --git a/internal/testing/golden/golden.go b/internal/testing/golden/golden.go index 66ec2a0ffa87..50f0a4f65bfd 100644 --- a/internal/testing/golden/golden.go +++ b/internal/testing/golden/golden.go @@ -2,7 +2,6 @@ package golden import ( "flag" - "io/ioutil" "os" "path/filepath" "testing" @@ -26,11 +25,11 @@ func Get(t *testing.T, actual, filename string) string { if dir := filepath.Dir(path); dir != "." { require.NoError(t, os.MkdirAll(dir, 0755)) } - err := ioutil.WriteFile(path, []byte(actual), 0644) + err := os.WriteFile(path, []byte(actual), 0644) require.NoError(t, err) } - expected, err := ioutil.ReadFile(path) + expected, err := os.ReadFile(path) require.NoError(t, err) return string(expected) } diff --git a/internal/tools/proto-gen-rpc-glue/main_test.go b/internal/tools/proto-gen-rpc-glue/main_test.go index 77ded532aeef..9fcfb7ed4511 100644 --- a/internal/tools/proto-gen-rpc-glue/main_test.go +++ b/internal/tools/proto-gen-rpc-glue/main_test.go @@ -39,11 +39,11 @@ func golden(t *testing.T, actual, path string) string { if dir := filepath.Dir(path); dir != "." { require.NoError(t, os.MkdirAll(dir, 0755)) } - err := ioutil.WriteFile(path, []byte(actual), 0644) + err := os.WriteFile(path, []byte(actual), 0644) require.NoError(t, err) } - expected, err := ioutil.ReadFile(path) + expected, err := os.ReadFile(path) require.NoError(t, err) return string(expected) } diff --git a/lib/file/atomic_test.go b/lib/file/atomic_test.go index 8645b2d45ac3..575fc6067ce6 100644 --- a/lib/file/atomic_test.go +++ b/lib/file/atomic_test.go @@ -1,7 +1,6 @@ package file import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -13,7 +12,7 @@ import ( // tests that it just writes the file properly. I would love to test this // better but I'm not sure how. -mitchellh func TestWriteAtomic(t *testing.T) { - td, err := ioutil.TempDir("", "lib-file") + td, err := os.MkdirTemp("", "lib-file") require.NoError(t, err) defer os.RemoveAll(td) @@ -25,7 +24,7 @@ func TestWriteAtomic(t *testing.T) { require.NoError(t, WriteAtomic(path, expected)) // Read and verify - actual, err := ioutil.ReadFile(path) + actual, err := os.ReadFile(path) require.NoError(t, err) require.Equal(t, expected, actual) } diff --git a/lib/rand.go b/lib/rand.go deleted file mode 100644 index 22aa4f3544bb..000000000000 --- a/lib/rand.go +++ /dev/null @@ -1,34 +0,0 @@ -package lib - -import ( - crand "crypto/rand" - "math" - "math/big" - "math/rand" - "sync" - "time" -) - -var ( - once sync.Once - - // SeededSecurely is set to true if a cryptographically secure seed - // was used to initialize rand. When false, the start time is used - // as a seed. - SeededSecurely bool -) - -// SeedMathRand provides weak, but guaranteed seeding, which is better than -// running with Go's default seed of 1. A call to SeedMathRand() is expected -// to be called via init(), but never a second time. -func SeedMathRand() { - once.Do(func() { - n, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)) - if err != nil { - rand.Seed(time.Now().UTC().UnixNano()) - return - } - rand.Seed(n.Int64()) - SeededSecurely = true - }) -} diff --git a/logging/logfile_test.go b/logging/logfile_test.go index 96fc0e169644..09313a67cb70 100644 --- a/logging/logfile_test.go +++ b/logging/logfile_test.go @@ -1,7 +1,6 @@ package logging import ( - "io/ioutil" "os" "path/filepath" "sort" @@ -44,7 +43,7 @@ func TestLogFile_openNew(t *testing.T) { _, err = logFile.Write([]byte(msg)) require.NoError(t, err) - content, err := ioutil.ReadFile(logFile.FileInfo.Name()) + content, err := os.ReadFile(logFile.FileInfo.Name()) require.NoError(t, err) require.Contains(t, string(content), msg) } @@ -79,11 +78,11 @@ func TestLogFile_PruneFiles(t *testing.T) { sort.Strings(logFiles) require.Len(t, logFiles, 2) - content, err := ioutil.ReadFile(filepath.Join(tempDir, logFiles[0])) + content, err := os.ReadFile(filepath.Join(tempDir, logFiles[0])) require.NoError(t, err) require.Contains(t, string(content), "Second File") - content, err = ioutil.ReadFile(filepath.Join(tempDir, logFiles[1])) + content, err = os.ReadFile(filepath.Join(tempDir, logFiles[1])) require.NoError(t, err) require.Contains(t, string(content), "Third File") } diff --git a/main.go b/main.go index e7b04e241fb5..804635060a81 100644 --- a/main.go +++ b/main.go @@ -2,7 +2,7 @@ package main import ( "fmt" - "io/ioutil" + "io" "log" "os" @@ -11,20 +11,15 @@ import ( "github.com/hashicorp/consul/command" "github.com/hashicorp/consul/command/cli" "github.com/hashicorp/consul/command/version" - "github.com/hashicorp/consul/lib" _ "github.com/hashicorp/consul/service_os" ) -func init() { - lib.SeedMathRand() -} - func main() { os.Exit(realMain()) } func realMain() int { - log.SetOutput(ioutil.Discard) + log.SetOutput(io.Discard) ui := &cli.BasicUI{ BasicUi: mcli.BasicUi{Writer: os.Stdout, ErrorWriter: os.Stderr}, diff --git a/proto-public/go.mod b/proto-public/go.mod index 9870dccfb5e8..8216ca8817c3 100644 --- a/proto-public/go.mod +++ b/proto-public/go.mod @@ -1,6 +1,6 @@ module github.com/hashicorp/consul/proto-public -go 1.19 +go 1.20 require ( github.com/golang/protobuf v1.5.0 diff --git a/sdk/freeport/ephemeral_linux.go b/sdk/freeport/ephemeral_linux.go index 55200ad2acce..22cf4caee674 100644 --- a/sdk/freeport/ephemeral_linux.go +++ b/sdk/freeport/ephemeral_linux.go @@ -5,7 +5,7 @@ package freeport import ( "fmt" - "io/ioutil" + "os" "regexp" "strconv" ) @@ -15,7 +15,7 @@ const ephemeralPortRangeProcFile = "/proc/sys/net/ipv4/ip_local_port_range" var ephemeralPortRangePatt = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s*$`) func getEphemeralPortRange() (int, int, error) { - out, err := ioutil.ReadFile(ephemeralPortRangeProcFile) + out, err := os.ReadFile(ephemeralPortRangeProcFile) if err != nil { return 0, 0, err } diff --git a/sdk/freeport/freeport.go b/sdk/freeport/freeport.go index 6eda1d4279b9..6c275fe86674 100644 --- a/sdk/freeport/freeport.go +++ b/sdk/freeport/freeport.go @@ -114,7 +114,6 @@ func initialize() { panic("freeport: block size too big or too many blocks requested") } - rand.Seed(time.Now().UnixNano()) firstPort, lockLn = alloc() condNotEmpty = sync.NewCond(&mu) diff --git a/sdk/go.mod b/sdk/go.mod index 18b289a0e8ba..6488585e76f1 100644 --- a/sdk/go.mod +++ b/sdk/go.mod @@ -1,17 +1,23 @@ module github.com/hashicorp/consul/sdk -go 1.12 +go 1.20 require ( - github.com/fatih/color v1.9.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.1 github.com/hashicorp/go-hclog v0.12.0 github.com/hashicorp/go-uuid v1.0.1 - github.com/kr/pretty v0.2.0 // indirect - github.com/mattn/go-isatty v0.0.12 // indirect github.com/pkg/errors v0.8.1 github.com/stretchr/testify v1.4.0 golang.org/x/sys v0.0.0-20220412211240-33da011f77ad +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fatih/color v1.9.0 // indirect + github.com/kr/pretty v0.2.0 // indirect + github.com/mattn/go-colorable v0.1.4 // indirect + github.com/mattn/go-isatty v0.0.12 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect gopkg.in/yaml.v2 v2.2.8 // indirect ) diff --git a/sdk/testutil/io.go b/sdk/testutil/io.go index b46425a50abf..fb1a54f8a847 100644 --- a/sdk/testutil/io.go +++ b/sdk/testutil/io.go @@ -1,7 +1,6 @@ package testutil import ( - "io/ioutil" "os" "strings" "testing" @@ -19,7 +18,7 @@ func TempDir(t testing.TB, name string) string { } name = t.Name() + "-" + name name = strings.Replace(name, "/", "_", -1) - d, err := ioutil.TempDir("", name) + d, err := os.MkdirTemp("", name) if err != nil { t.Fatalf("err: %s", err) } @@ -45,7 +44,7 @@ func TempFile(t testing.TB, name string) *os.File { } name = t.Name() + "-" + name name = strings.Replace(name, "/", "_", -1) - f, err := ioutil.TempFile("", name) + f, err := os.CreateTemp("", name) if err != nil { t.Fatalf("err: %s", err) } diff --git a/sdk/testutil/server.go b/sdk/testutil/server.go index a657919adc24..62bcb152c20d 100644 --- a/sdk/testutil/server.go +++ b/sdk/testutil/server.go @@ -16,7 +16,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "os" @@ -252,7 +251,7 @@ func NewTestServerConfigT(t TestingTB, cb ServerConfigCallback) (*TestServer, er // Use test name for tmpdir if available prefix = strings.Replace(t.Name(), "/", "_", -1) } - tmpdir, err := ioutil.TempDir("", prefix) + tmpdir, err := os.MkdirTemp("", prefix) if err != nil { return nil, errors.Wrap(err, "failed to create tempdir") } @@ -271,7 +270,7 @@ func NewTestServerConfigT(t TestingTB, cb ServerConfigCallback) (*TestServer, er t.Logf("CONFIG JSON: %s", string(b)) configFile := filepath.Join(tmpdir, "config.json") - if err := ioutil.WriteFile(configFile, b, 0644); err != nil { + if err := os.WriteFile(configFile, b, 0644); err != nil { os.RemoveAll(tmpdir) return nil, errors.Wrap(err, "failed writing config content") } diff --git a/sdk/testutil/server_methods.go b/sdk/testutil/server_methods.go index 2695e88fb092..d25e66bc8d63 100644 --- a/sdk/testutil/server_methods.go +++ b/sdk/testutil/server_methods.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "log" "net/http" "testing" @@ -53,7 +52,7 @@ func (s *TestServer) GetKV(t testing.TB, key string) []byte { resp := s.get(t, "/v1/kv/"+key) defer resp.Body.Close() - raw, err := ioutil.ReadAll(resp.Body) + raw, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("failed to read body: %s", err) } @@ -93,7 +92,7 @@ func (s *TestServer) ListKV(t testing.TB, prefix string) []string { resp := s.get(t, "/v1/kv/"+prefix+"?keys") defer resp.Body.Close() - raw, err := ioutil.ReadAll(resp.Body) + raw, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("failed to read body: %s", err) } diff --git a/snapshot/archive.go b/snapshot/archive.go index 2c5efb381273..b0e9ca5211ba 100644 --- a/snapshot/archive.go +++ b/snapshot/archive.go @@ -18,7 +18,6 @@ import ( "fmt" "hash" "io" - "io/ioutil" "time" "github.com/hashicorp/raft" @@ -202,7 +201,7 @@ func read(in io.Reader, metadata *raft.SnapshotMeta, snap io.Writer) error { // turn made the snapshot verification fail. By explicitly reading the // whole thing first we ensure that we calculate the correct hash // independent of how json.Decode works internally. - buf, err := ioutil.ReadAll(io.TeeReader(archive, metaHash)) + buf, err := io.ReadAll(io.TeeReader(archive, metaHash)) if err != nil { return fmt.Errorf("failed to read snapshot metadata: %v", err) } diff --git a/snapshot/archive_test.go b/snapshot/archive_test.go index 67582af0998a..6a6e17d37fb4 100644 --- a/snapshot/archive_test.go +++ b/snapshot/archive_test.go @@ -5,7 +5,6 @@ import ( "crypto/rand" "fmt" "io" - "io/ioutil" "os" "reflect" "strings" @@ -75,7 +74,7 @@ func TestArchive_GoodData(t *testing.T) { defer f.Close() var metadata raft.SnapshotMeta - err = read(f, &metadata, ioutil.Discard) + err = read(f, &metadata, io.Discard) if err != nil { t.Fatalf("case %d: should've read the snapshot, but didn't: %v", i, err) } @@ -104,7 +103,7 @@ func TestArchive_BadData(t *testing.T) { defer f.Close() var metadata raft.SnapshotMeta - err = read(f, &metadata, ioutil.Discard) + err = read(f, &metadata, io.Discard) if err == nil || !strings.Contains(err.Error(), c.Error) { t.Fatalf("case %d (%s): %v", i, c.Name, err) } diff --git a/snapshot/snapshot.go b/snapshot/snapshot.go index 9437cfa11cd0..691f4bc8e114 100644 --- a/snapshot/snapshot.go +++ b/snapshot/snapshot.go @@ -7,7 +7,6 @@ import ( "compress/gzip" "fmt" "io" - "io/ioutil" "os" "github.com/hashicorp/go-hclog" @@ -47,7 +46,7 @@ func New(logger hclog.Logger, r *raft.Raft) (*Snapshot, error) { // Make a scratch file to receive the contents so that we don't buffer // everything in memory. This gets deleted in Close() since we keep it // around for re-reading. - archive, err := ioutil.TempFile("", "snapshot") + archive, err := os.CreateTemp("", "snapshot") if err != nil { return nil, fmt.Errorf("failed to create snapshot file: %v", err) } @@ -134,7 +133,7 @@ func Verify(in io.Reader) (*raft.SnapshotMeta, error) { // Read the archive, throwing away the snapshot data. var metadata raft.SnapshotMeta - if err := read(decomp, &metadata, ioutil.Discard); err != nil { + if err := read(decomp, &metadata, io.Discard); err != nil { return nil, fmt.Errorf("failed to read snapshot file: %v", err) } @@ -151,7 +150,7 @@ func Verify(in io.Reader) (*raft.SnapshotMeta, error) { // The docs for gzip.Reader say: "Clients should treat data returned by Read as // tentative until they receive the io.EOF marking the end of the data." func concludeGzipRead(decomp *gzip.Reader) error { - extra, err := ioutil.ReadAll(decomp) // ReadAll consumes the EOF + extra, err := io.ReadAll(decomp) // ReadAll consumes the EOF if err != nil { return err } else if len(extra) != 0 { @@ -175,7 +174,7 @@ func Read(logger hclog.Logger, in io.Reader) (*os.File, *raft.SnapshotMeta, erro // Make a scratch file to receive the contents of the snapshot data so // we can avoid buffering in memory. - snap, err := ioutil.TempFile("", "snapshot") + snap, err := os.CreateTemp("", "snapshot") if err != nil { return nil, nil, fmt.Errorf("failed to create temp snapshot file: %v", err) } diff --git a/test/integration/connect/envoy/main_test.go b/test/integration/connect/envoy/main_test.go index 6b60efab5d6b..ed511d332356 100644 --- a/test/integration/connect/envoy/main_test.go +++ b/test/integration/connect/envoy/main_test.go @@ -4,7 +4,6 @@ package envoy import ( - "io/ioutil" "os" "os/exec" "sort" @@ -57,7 +56,7 @@ func discoverCases() ([]string, error) { return nil, err } - dirs, err := ioutil.ReadDir(cwd) + dirs, err := os.ReadDir(cwd) if err != nil { return nil, err } diff --git a/test/integration/connect/envoy/test-sds-server/sds.go b/test/integration/connect/envoy/test-sds-server/sds.go index 30020daa3da4..cf878805aadd 100644 --- a/test/integration/connect/envoy/test-sds-server/sds.go +++ b/test/integration/connect/envoy/test-sds-server/sds.go @@ -2,7 +2,6 @@ package main import ( "context" - "io/ioutil" "net" "os" "os/signal" @@ -100,12 +99,12 @@ func loadCertsFromPath(cache *cache.LinearCache, log hclog.Logger, dir string) e } certName := strings.TrimSuffix(entry.Name(), ".crt") - cert, err := ioutil.ReadFile(filepath.Join(dir, entry.Name())) + cert, err := os.ReadFile(filepath.Join(dir, entry.Name())) if err != nil { return err } keyFile := certName + ".key" - key, err := ioutil.ReadFile(filepath.Join(dir, keyFile)) + key, err := os.ReadFile(filepath.Join(dir, keyFile)) if err != nil { return err } diff --git a/test/integration/consul-container/go.mod b/test/integration/consul-container/go.mod index e05d862cdbd4..5f96543fad0f 100644 --- a/test/integration/consul-container/go.mod +++ b/test/integration/consul-container/go.mod @@ -1,6 +1,6 @@ module github.com/hashicorp/consul/test/integration/consul-container -go 1.19 +go 1.20 require ( github.com/docker/docker v20.10.11+incompatible diff --git a/test/integration/consul-container/metrics/leader_test.go b/test/integration/consul-container/metrics/leader_test.go index 21200de8d999..1bc978882d37 100644 --- a/test/integration/consul-container/metrics/leader_test.go +++ b/test/integration/consul-container/metrics/leader_test.go @@ -3,7 +3,7 @@ package metrics import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" @@ -100,7 +100,7 @@ func getMetrics(t *testing.T, addr string, port int, path string) (string, error if err != nil { return "", fmt.Errorf("error get metrics: %v", err) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return "nil", fmt.Errorf("error read metrics: %v", err) } diff --git a/tlsutil/config.go b/tlsutil/config.go index 5660ad390c94..2492427330c1 100644 --- a/tlsutil/config.go +++ b/tlsutil/config.go @@ -4,7 +4,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -504,7 +503,7 @@ func LoadCAs(caFile, caPath string) ([]string, error) { pems := []string{} readFn := func(path string) error { - pem, err := ioutil.ReadFile(path) + pem, err := os.ReadFile(path) if err != nil { return fmt.Errorf("Error loading from %s: %s", path, err) } diff --git a/tlsutil/config_test.go b/tlsutil/config_test.go index eda15aecfae1..bc4845d7cc71 100644 --- a/tlsutil/config_test.go +++ b/tlsutil/config_test.go @@ -5,7 +5,6 @@ import ( "crypto/x509" "fmt" "io" - "io/ioutil" "net" "os" "path" @@ -754,7 +753,7 @@ func TestConfigurator_outgoingWrapperALPN_serverHasNoNodeNameInSAN(t *testing.T) _, err = wrap("dc1", "bob", "foo", client) require.Error(t, err) - _, ok := err.(x509.HostnameError) + _, ok := err.(*tls.CertificateVerificationError) require.True(t, ok) client.Close() @@ -1337,7 +1336,7 @@ func TestConfigurator_AuthorizeInternalRPCServerConn(t *testing.T) { dir := testutil.TempDir(t, "ca") caPath := filepath.Join(dir, "ca.pem") - err = ioutil.WriteFile(caPath, []byte(caPEM), 0600) + err = os.WriteFile(caPath, []byte(caPEM), 0600) require.NoError(t, err) // Cert and key are not used, but required to get past validation. @@ -1349,10 +1348,10 @@ func TestConfigurator_AuthorizeInternalRPCServerConn(t *testing.T) { }) require.NoError(t, err) certFile := filepath.Join("cert.pem") - err = ioutil.WriteFile(certFile, []byte(pub), 0600) + err = os.WriteFile(certFile, []byte(pub), 0600) require.NoError(t, err) keyFile := filepath.Join("cert.key") - err = ioutil.WriteFile(keyFile, []byte(pk), 0600) + err = os.WriteFile(keyFile, []byte(pk), 0600) require.NoError(t, err) cfg := Config{ @@ -1397,7 +1396,7 @@ func TestConfigurator_AuthorizeInternalRPCServerConn(t *testing.T) { dir := testutil.TempDir(t, "other") caPath := filepath.Join(dir, "ca.pem") - err = ioutil.WriteFile(caPath, []byte(caPEM), 0600) + err = os.WriteFile(caPath, []byte(caPEM), 0600) require.NoError(t, err) signer, err := ParseSigner(caPK) @@ -1623,7 +1622,7 @@ func startTLSServer(tlsConfigServer *tls.Config) (net.Conn, <-chan error, <-chan // server read any data from the client until error or // EOF, which will allow the client to Close(), and // *then* we Close() the server. - io.Copy(ioutil.Discard, tlsServer) + io.Copy(io.Discard, tlsServer) tlsServer.Close() }() return clientConn, errc, certc @@ -1632,14 +1631,14 @@ func startTLSServer(tlsConfigServer *tls.Config) (net.Conn, <-chan error, <-chan func loadFile(t *testing.T, path string) string { t.Helper() - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) require.NoError(t, err) return string(data) } func getExpectedCaPoolByFile(t *testing.T) *x509.CertPool { pool := x509.NewCertPool() - data, err := ioutil.ReadFile("../test/ca/root.cer") + data, err := os.ReadFile("../test/ca/root.cer") if err != nil { t.Fatal("could not open test file ../test/ca/root.cer for reading") } @@ -1659,7 +1658,7 @@ func getExpectedCaPoolByDir(t *testing.T) *x509.CertPool { for _, entry := range entries { filename := path.Join("../test/ca_path", entry.Name()) - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) if err != nil { t.Fatalf("could not open test file %s for reading", filename) }