diff --git a/.golangci.yaml b/.golangci.yaml index 0d928cf3..44a71963 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -8,16 +8,13 @@ linters: disable-all: true enable: # default linters - - deadcode - errcheck - gosimple - govet - ineffassign - staticcheck - - structcheck - typecheck - unused - - varcheck # additional linters for this project (we should disable these if they get annoying). - asciicheck diff --git a/cmd/pinniped-concierge-kube-cert-agent/main.go b/cmd/pinniped-concierge-kube-cert-agent/main.go index 66de9af6..ad1186bf 100644 --- a/cmd/pinniped-concierge-kube-cert-agent/main.go +++ b/cmd/pinniped-concierge-kube-cert-agent/main.go @@ -8,7 +8,6 @@ import ( "encoding/base64" "encoding/json" "io" - "io/ioutil" "log" "math" "os" @@ -18,7 +17,7 @@ import ( _ "go.pinniped.dev/internal/crypto/ptls" ) -//nolint: gochecknoglobals // these are swapped during unit tests. +//nolint:gochecknoglobals // these are swapped during unit tests. var ( getenv = os.Getenv fail = log.Fatalf @@ -35,11 +34,11 @@ func main() { case "sleep": sleep(math.MaxInt64) case "print": - certBytes, err := ioutil.ReadFile(getenv("CERT_PATH")) + certBytes, err := os.ReadFile(getenv("CERT_PATH")) if err != nil { fail("could not read CERT_PATH: %v", err) } - keyBytes, err := ioutil.ReadFile(getenv("KEY_PATH")) + keyBytes, err := os.ReadFile(getenv("KEY_PATH")) if err != nil { fail("could not read KEY_PATH: %v", err) } diff --git a/cmd/pinniped-server/main.go b/cmd/pinniped-server/main.go index b70aed8f..b683b324 100644 --- a/cmd/pinniped-server/main.go +++ b/cmd/pinniped-server/main.go @@ -22,7 +22,7 @@ import ( supervisor "go.pinniped.dev/internal/supervisor/server" ) -// nolint: gochecknoglobals // these are swapped during unit tests. +//nolint:gochecknoglobals // these are swapped during unit tests. var ( fail = plog.Fatal subcommands = map[string]func(){ diff --git a/cmd/pinniped/cmd/alpha.go b/cmd/pinniped/cmd/alpha.go index db27150f..7d2ba865 100644 --- a/cmd/pinniped/cmd/alpha.go +++ b/cmd/pinniped/cmd/alpha.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" ) -//nolint: gochecknoglobals +//nolint:gochecknoglobals var alphaCmd = &cobra.Command{ Use: "alpha", Short: "alpha", @@ -16,7 +16,7 @@ var alphaCmd = &cobra.Command{ Hidden: true, } -//nolint: gochecknoinits +//nolint:gochecknoinits func init() { rootCmd.AddCommand(alphaCmd) } diff --git a/cmd/pinniped/cmd/flag_types.go b/cmd/pinniped/cmd/flag_types.go index 2bc55e06..18dacb63 100644 --- a/cmd/pinniped/cmd/flag_types.go +++ b/cmd/pinniped/cmd/flag_types.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -8,7 +8,7 @@ import ( "crypto/x509" "flag" "fmt" - "io/ioutil" + "os" "strings" "github.com/spf13/pflag" @@ -85,7 +85,7 @@ func (f *caBundleFlag) String() string { } func (f *caBundleFlag) Set(path string) error { - pem, err := ioutil.ReadFile(path) + pem, err := os.ReadFile(path) if err != nil { return fmt.Errorf("could not read CA bundle path: %w", err) } diff --git a/cmd/pinniped/cmd/flag_types_test.go b/cmd/pinniped/cmd/flag_types_test.go index 101191d5..1d731494 100644 --- a/cmd/pinniped/cmd/flag_types_test.go +++ b/cmd/pinniped/cmd/flag_types_test.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -6,7 +6,7 @@ package cmd import ( "bytes" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -54,10 +54,10 @@ func TestCABundleFlag(t *testing.T) { require.NoError(t, err) tmpdir := testutil.TempDir(t) emptyFilePath := filepath.Join(tmpdir, "empty") - require.NoError(t, ioutil.WriteFile(emptyFilePath, []byte{}, 0600)) + require.NoError(t, os.WriteFile(emptyFilePath, []byte{}, 0600)) testCAPath := filepath.Join(tmpdir, "testca.pem") - require.NoError(t, ioutil.WriteFile(testCAPath, testCA.Bundle(), 0600)) + require.NoError(t, os.WriteFile(testCAPath, testCA.Bundle(), 0600)) f := caBundleFlag{} require.Equal(t, "path", f.Type()) diff --git a/cmd/pinniped/cmd/generate_markdown_help.go b/cmd/pinniped/cmd/generate_markdown_help.go index 92cc66d8..9fe51b9c 100644 --- a/cmd/pinniped/cmd/generate_markdown_help.go +++ b/cmd/pinniped/cmd/generate_markdown_help.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -14,7 +14,7 @@ import ( "github.com/spf13/cobra/doc" ) -//nolint: gochecknoinits +//nolint:gochecknoinits func init() { rootCmd.AddCommand(generateMarkdownHelpCommand()) } diff --git a/cmd/pinniped/cmd/get.go b/cmd/pinniped/cmd/get.go index 4b86d5fc..f130c4b7 100644 --- a/cmd/pinniped/cmd/get.go +++ b/cmd/pinniped/cmd/get.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -7,10 +7,10 @@ import ( "github.com/spf13/cobra" ) -//nolint: gochecknoglobals +//nolint:gochecknoglobals var getCmd = &cobra.Command{Use: "get", Short: "get"} -//nolint: gochecknoinits +//nolint:gochecknoinits func init() { rootCmd.AddCommand(getCmd) } diff --git a/cmd/pinniped/cmd/kubeconfig.go b/cmd/pinniped/cmd/kubeconfig.go index 1e59f481..8c79fafd 100644 --- a/cmd/pinniped/cmd/kubeconfig.go +++ b/cmd/pinniped/cmd/kubeconfig.go @@ -10,7 +10,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "os" "strconv" @@ -48,7 +47,7 @@ func kubeconfigRealDeps() kubeconfigDeps { } } -// nolint: gochecknoinits +//nolint:gochecknoinits func init() { getCmd.AddCommand(kubeconfigCommand(kubeconfigRealDeps())) } @@ -717,7 +716,7 @@ func validateKubeconfig(ctx context.Context, flags getKubeconfigParams, kubeconf func countCACerts(pemData []byte) int { pool := x509.NewCertPool() pool.AppendCertsFromPEM(pemData) - return len(pool.Subjects()) // nolint: staticcheck // not system cert pool + return len(pool.Subjects()) } func hasPendingStrategy(credentialIssuer *configv1alpha1.CredentialIssuer) bool { @@ -815,7 +814,7 @@ func discoverAllAvailableSupervisorUpstreamIDPs(ctx context.Context, pinnipedIDP return nil, fmt.Errorf("unable to fetch IDP discovery data from issuer: unexpected http response status: %s", response.Status) } - rawBody, err := ioutil.ReadAll(response.Body) + rawBody, err := io.ReadAll(response.Body) if err != nil { return nil, fmt.Errorf("unable to fetch IDP discovery data from issuer: could not read response body: %w", err) } diff --git a/cmd/pinniped/cmd/kubeconfig_test.go b/cmd/pinniped/cmd/kubeconfig_test.go index 9c3ee5e0..c6efb522 100644 --- a/cmd/pinniped/cmd/kubeconfig_test.go +++ b/cmd/pinniped/cmd/kubeconfig_test.go @@ -7,8 +7,8 @@ import ( "bytes" "encoding/base64" "fmt" - "io/ioutil" "net/http" + "os" "path/filepath" "testing" "time" @@ -34,12 +34,12 @@ func TestGetKubeconfig(t *testing.T) { require.NoError(t, err) tmpdir := testutil.TempDir(t) testOIDCCABundlePath := filepath.Join(tmpdir, "testca.pem") - require.NoError(t, ioutil.WriteFile(testOIDCCABundlePath, testOIDCCA.Bundle(), 0600)) + require.NoError(t, os.WriteFile(testOIDCCABundlePath, testOIDCCA.Bundle(), 0600)) testConciergeCA, err := certauthority.New("Test Concierge CA", 1*time.Hour) require.NoError(t, err) testConciergeCABundlePath := filepath.Join(tmpdir, "testconciergeca.pem") - require.NoError(t, ioutil.WriteFile(testConciergeCABundlePath, testConciergeCA.Bundle(), 0600)) + require.NoError(t, os.WriteFile(testConciergeCABundlePath, testConciergeCA.Bundle(), 0600)) credentialIssuer := func() runtime.Object { return &configv1alpha1.CredentialIssuer{ @@ -2889,7 +2889,7 @@ func TestGetKubeconfig(t *testing.T) { }) issuerEndpointPtr = &issuerEndpoint - testLog := testlogger.NewLegacy(t) // nolint: staticcheck // old test with lots of log statements + testLog := testlogger.NewLegacy(t) //nolint:staticcheck // old test with lots of log statements cmd := kubeconfigCommand(kubeconfigDeps{ getPathToSelf: func() (string, error) { if tt.getPathToSelfErr != nil { diff --git a/cmd/pinniped/cmd/login.go b/cmd/pinniped/cmd/login.go index 95e2541d..4d8328cc 100644 --- a/cmd/pinniped/cmd/login.go +++ b/cmd/pinniped/cmd/login.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -9,7 +9,7 @@ import ( "k8s.io/client-go/tools/auth/exec" ) -//nolint: gochecknoglobals +//nolint:gochecknoglobals var loginCmd = &cobra.Command{ Use: "login", Short: "login", @@ -18,7 +18,7 @@ var loginCmd = &cobra.Command{ Hidden: true, // These commands are not really meant to be used directly by users, so it's confusing to have them discoverable. } -//nolint: gochecknoinits +//nolint:gochecknoinits func init() { rootCmd.AddCommand(loginCmd) } diff --git a/cmd/pinniped/cmd/login_oidc.go b/cmd/pinniped/cmd/login_oidc.go index b31f8dd6..13078c57 100644 --- a/cmd/pinniped/cmd/login_oidc.go +++ b/cmd/pinniped/cmd/login_oidc.go @@ -9,7 +9,6 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "net/http" "os" "path/filepath" @@ -41,7 +40,7 @@ const ( upstreamIdentityProviderFlowEnvVarName = "PINNIPED_UPSTREAM_IDENTITY_PROVIDER_FLOW" ) -// nolint: gochecknoinits +//nolint:gochecknoinits func init() { loginCmd.AddCommand(oidcLoginCommand(oidcLoginCommandRealDeps())) } @@ -153,7 +152,7 @@ func runOIDCLogin(cmd *cobra.Command, deps oidcLoginCommandDeps, flags oidcLogin // Initialize the login handler. opts := []oidcclient.Option{ oidcclient.WithContext(cmd.Context()), - oidcclient.WithLogger(plog.Logr()), // nolint: staticcheck // old code with lots of log statements + oidcclient.WithLogger(plog.Logr()), //nolint:staticcheck // old code with lots of log statements oidcclient.WithScopes(flags.scopes), oidcclient.WithSessionCache(sessionCache), } @@ -317,7 +316,7 @@ func flowOptions( func makeClient(caBundlePaths []string, caBundleData []string) (*http.Client, error) { pool := x509.NewCertPool() for _, p := range caBundlePaths { - pem, err := ioutil.ReadFile(p) + pem, err := os.ReadFile(p) if err != nil { return nil, fmt.Errorf("could not read --ca-bundle: %w", err) } @@ -361,10 +360,14 @@ func SetLogLevel(ctx context.Context, lookupEnv func(string) (string, bool)) (pl return logger, nil } -// mustGetConfigDir returns a directory that follows the XDG base directory convention: -// $XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should -// be stored. If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used. -// [1] https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html +/* +mustGetConfigDir returns a directory that follows the XDG base directory convention: + + $XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should + be stored. If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used. + +[1] https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html +*/ func mustGetConfigDir() string { const xdgAppName = "pinniped" diff --git a/cmd/pinniped/cmd/login_oidc_test.go b/cmd/pinniped/cmd/login_oidc_test.go index 2e4fbd45..b57bfcf9 100644 --- a/cmd/pinniped/cmd/login_oidc_test.go +++ b/cmd/pinniped/cmd/login_oidc_test.go @@ -8,7 +8,7 @@ import ( "context" "encoding/base64" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -36,7 +36,7 @@ func TestLoginOIDCCommand(t *testing.T) { require.NoError(t, err) tmpdir := testutil.TempDir(t) testCABundlePath := filepath.Join(tmpdir, "testca.pem") - require.NoError(t, ioutil.WriteFile(testCABundlePath, testCA.Bundle(), 0600)) + require.NoError(t, os.WriteFile(testCABundlePath, testCA.Bundle(), 0600)) time1 := time.Date(3020, 10, 12, 13, 14, 15, 16, time.UTC) @@ -483,8 +483,8 @@ func TestLoginOIDCCommand(t *testing.T) { wantOptionsCount: 4, wantStdout: `{"kind":"ExecCredential","apiVersion":"client.authentication.k8s.io/v1beta1","spec":{"interactive":false},"status":{"expirationTimestamp":"3020-10-12T13:14:15Z","token":"test-id-token"}}` + "\n", wantLogs: []string{ - nowStr + ` pinniped-login cmd/login_oidc.go:232 Performing OIDC login {"issuer": "test-issuer", "client id": "test-client-id"}`, - nowStr + ` pinniped-login cmd/login_oidc.go:252 No concierge configured, skipping token credential exchange`, + nowStr + ` pinniped-login cmd/login_oidc.go:231 Performing OIDC login {"issuer": "test-issuer", "client id": "test-client-id"}`, + nowStr + ` pinniped-login cmd/login_oidc.go:251 No concierge configured, skipping token credential exchange`, }, }, { @@ -513,10 +513,10 @@ func TestLoginOIDCCommand(t *testing.T) { wantOptionsCount: 11, wantStdout: `{"kind":"ExecCredential","apiVersion":"client.authentication.k8s.io/v1beta1","spec":{"interactive":false},"status":{"token":"exchanged-token"}}` + "\n", wantLogs: []string{ - nowStr + ` pinniped-login cmd/login_oidc.go:232 Performing OIDC login {"issuer": "test-issuer", "client id": "test-client-id"}`, - nowStr + ` pinniped-login cmd/login_oidc.go:242 Exchanging token for cluster credential {"endpoint": "https://127.0.0.1:1234/", "authenticator type": "webhook", "authenticator name": "test-authenticator"}`, - nowStr + ` pinniped-login cmd/login_oidc.go:250 Successfully exchanged token for cluster credential.`, - nowStr + ` pinniped-login cmd/login_oidc.go:257 caching cluster credential for future use.`, + nowStr + ` pinniped-login cmd/login_oidc.go:231 Performing OIDC login {"issuer": "test-issuer", "client id": "test-client-id"}`, + nowStr + ` pinniped-login cmd/login_oidc.go:241 Exchanging token for cluster credential {"endpoint": "https://127.0.0.1:1234/", "authenticator type": "webhook", "authenticator name": "test-authenticator"}`, + nowStr + ` pinniped-login cmd/login_oidc.go:249 Successfully exchanged token for cluster credential.`, + nowStr + ` pinniped-login cmd/login_oidc.go:256 caching cluster credential for future use.`, }, }, } diff --git a/cmd/pinniped/cmd/login_static.go b/cmd/pinniped/cmd/login_static.go index 2af80907..d8827a9f 100644 --- a/cmd/pinniped/cmd/login_static.go +++ b/cmd/pinniped/cmd/login_static.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -21,7 +21,7 @@ import ( "go.pinniped.dev/pkg/oidcclient/oidctypes" ) -// nolint: gochecknoinits +//nolint:gochecknoinits func init() { loginCmd.AddCommand(staticLoginCommand(staticLoginRealDeps())) } diff --git a/cmd/pinniped/cmd/login_static_test.go b/cmd/pinniped/cmd/login_static_test.go index 7af4ac85..f4a7d93f 100644 --- a/cmd/pinniped/cmd/login_static_test.go +++ b/cmd/pinniped/cmd/login_static_test.go @@ -7,7 +7,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -32,7 +32,7 @@ func TestLoginStaticCommand(t *testing.T) { require.NoError(t, err) tmpdir := testutil.TempDir(t) testCABundlePath := filepath.Join(tmpdir, "testca.pem") - require.NoError(t, ioutil.WriteFile(testCABundlePath, testCA.Bundle(), 0600)) + require.NoError(t, os.WriteFile(testCABundlePath, testCA.Bundle(), 0600)) now, err := time.Parse(time.RFC3339Nano, "2038-12-07T23:37:26.953313745Z") require.NoError(t, err) diff --git a/cmd/pinniped/cmd/root.go b/cmd/pinniped/cmd/root.go index 4345b6c8..f011f811 100644 --- a/cmd/pinniped/cmd/root.go +++ b/cmd/pinniped/cmd/root.go @@ -11,7 +11,7 @@ import ( "go.pinniped.dev/internal/plog" ) -// nolint: gochecknoglobals +//nolint:gochecknoglobals var rootCmd = &cobra.Command{ Use: "pinniped", Short: "pinniped", diff --git a/cmd/pinniped/cmd/version.go b/cmd/pinniped/cmd/version.go index bc927892..7f144f4e 100644 --- a/cmd/pinniped/cmd/version.go +++ b/cmd/pinniped/cmd/version.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -10,7 +10,7 @@ import ( "k8s.io/component-base/version" ) -//nolint: gochecknoinits +//nolint:gochecknoinits func init() { rootCmd.AddCommand(newVersionCommand()) } diff --git a/cmd/pinniped/cmd/whoami.go b/cmd/pinniped/cmd/whoami.go index cfacdd6a..b03b0ad8 100644 --- a/cmd/pinniped/cmd/whoami.go +++ b/cmd/pinniped/cmd/whoami.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cmd @@ -24,7 +24,7 @@ import ( "go.pinniped.dev/internal/here" ) -//nolint: gochecknoinits +//nolint:gochecknoinits func init() { rootCmd.AddCommand(newWhoamiCommand(getRealConciergeClientset)) } diff --git a/cmd/pinniped/main.go b/cmd/pinniped/main.go index 93433b66..b4825b1e 100644 --- a/cmd/pinniped/main.go +++ b/cmd/pinniped/main.go @@ -13,7 +13,7 @@ import ( _ "go.pinniped.dev/internal/crypto/ptls" ) -// nolint: gochecknoinits +//nolint:gochecknoinits func init() { // browsers like chrome like to write to our std out which breaks our JSON ExecCredential output // thus we redirect the browser's std out to our std err diff --git a/hack/install-linter.sh b/hack/install-linter.sh index e5414397..a631f50d 100755 --- a/hack/install-linter.sh +++ b/hack/install-linter.sh @@ -8,9 +8,14 @@ set -euo pipefail ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" cd "${ROOT}" +# Print the Go version. +go version + # Install the same version of the linter that is used in the CI pipelines # so you can get the same results when running the linter locally. # Whenever the linter is updated in the CI pipelines, it should also be # updated here to make local development more convenient. -go install -v github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.0 +go install -v github.com/golangci/golangci-lint/cmd/golangci-lint@v1.49.0 golangci-lint --version + +echo "Finished. You may need to run 'rehash' in your current shell before using the new version (e.g. if you are using gvm)." diff --git a/internal/authenticators/authenticators.go b/internal/authenticators/authenticators.go index e343ecd1..bfdf440c 100644 --- a/internal/authenticators/authenticators.go +++ b/internal/authenticators/authenticators.go @@ -10,22 +10,22 @@ import ( "k8s.io/apiserver/pkg/authentication/user" ) -// This interface is similar to the k8s token authenticator, but works with username/passwords instead +// UserAuthenticator is an interface is similar to the k8s token authenticator, but works with username/passwords instead // of a single token string. // // The return values should be as follows. // 1. For a successful authentication: -// - A response which includes the username, uid, and groups in the userInfo. The username and uid must not be blank. -// - true -// - nil error +// - A response which includes the username, uid, and groups in the userInfo. The username and uid must not be blank. +// - true +// - nil error // 2. For an unsuccessful authentication, e.g. bad username or password: -// - nil response -// - false -// - nil error +// - nil response +// - false +// - nil error // 3. For an unexpected error, e.g. a network problem: -// - nil response -// - false -// - an error +// - nil response +// - false +// - an error // Other combinations of return values must be avoided. // // See k8s.io/apiserver/pkg/authentication/authenticator/interfaces.go for the token authenticator diff --git a/internal/certauthority/certauthority_test.go b/internal/certauthority/certauthority_test.go index b61e2e86..b0ad5daa 100644 --- a/internal/certauthority/certauthority_test.go +++ b/internal/certauthority/certauthority_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package certauthority @@ -9,8 +9,8 @@ import ( "crypto/x509" "fmt" "io" - "io/ioutil" "net" + "os" "strings" "testing" "time" @@ -23,10 +23,10 @@ import ( func loadFromFiles(t *testing.T, certPath string, keyPath string) (*CA, error) { t.Helper() - certPEM, err := ioutil.ReadFile(certPath) + certPEM, err := os.ReadFile(certPath) require.NoError(t, err) - keyPEM, err := ioutil.ReadFile(keyPath) + keyPEM, err := os.ReadFile(keyPath) require.NoError(t, err) ca, err := Load(string(certPEM), string(keyPEM)) @@ -206,7 +206,7 @@ func TestPool(t *testing.T) { require.NoError(t, err) pool := ca.Pool() - require.Len(t, pool.Subjects(), 1) // nolint: staticcheck // not system cert pool + require.Len(t, pool.Subjects(), 1) } type errSigner struct { diff --git a/internal/concierge/apiserver/apiserver.go b/internal/concierge/apiserver/apiserver.go index bc08ad68..02fb89f7 100644 --- a/internal/concierge/apiserver/apiserver.go +++ b/internal/concierge/apiserver/apiserver.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package apiserver @@ -76,7 +76,7 @@ func (c completedConfig) New() (*PinnipedServer, error) { GenericAPIServer: genericServer, } - var errs []error //nolint: prealloc + var errs []error //nolint:prealloc for _, f := range []func() (schema.GroupVersionResource, rest.Storage){ func() (schema.GroupVersionResource, rest.Storage) { tokenCredReqGVR := c.ExtraConfig.LoginConciergeGroupVersion.WithResource("tokencredentialrequests") diff --git a/internal/concierge/impersonator/impersonator.go b/internal/concierge/impersonator/impersonator.go index 70155dba..6a9783dd 100644 --- a/internal/concierge/impersonator/impersonator.go +++ b/internal/concierge/impersonator/impersonator.go @@ -643,7 +643,7 @@ func getTransportForUser(ctx context.Context, userInfo user.Info, delegate, dele } func canImpersonateFully(userInfo user.Info) bool { - // nolint: gosimple // this structure is on purpose because we plan to expand this function + //nolint:gosimple // this structure is on purpose because we plan to expand this function if len(userInfo.GetUID()) == 0 { return true } diff --git a/internal/config/concierge/config.go b/internal/config/concierge/config.go index 605f72d4..a82f2540 100644 --- a/internal/config/concierge/config.go +++ b/internal/config/concierge/config.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package concierge contains functionality to load/store Config's from/to @@ -8,7 +8,7 @@ package concierge import ( "context" "fmt" - "io/ioutil" + "os" "strings" "k8s.io/utils/pointer" @@ -43,7 +43,7 @@ const ( // This function will decode that base64-encoded data to PEM bytes to be stored // in the Config. func FromPath(ctx context.Context, path string) (*Config, error) { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("read file: %w", err) } diff --git a/internal/config/concierge/config_test.go b/internal/config/concierge/config_test.go index ce7c9929..3422032f 100644 --- a/internal/config/concierge/config_test.go +++ b/internal/config/concierge/config_test.go @@ -1,11 +1,10 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package concierge import ( "context" - "io/ioutil" "os" "testing" @@ -585,7 +584,7 @@ func TestFromPath(t *testing.T) { // this is a serial test because it sets the global logger // Write yaml to temp file - f, err := ioutil.TempFile("", "pinniped-test-config-yaml-*") + f, err := os.CreateTemp("", "pinniped-test-config-yaml-*") require.NoError(t, err) defer func() { err := os.Remove(f.Name()) diff --git a/internal/config/supervisor/config.go b/internal/config/supervisor/config.go index 192d9790..0ec97f7e 100644 --- a/internal/config/supervisor/config.go +++ b/internal/config/supervisor/config.go @@ -8,8 +8,8 @@ package supervisor import ( "context" "fmt" - "io/ioutil" "net" + "os" "strings" "k8s.io/utils/pointer" @@ -30,7 +30,7 @@ const ( // defaults (from the Config documentation), and verifies that the config is // valid (Config documentation). func FromPath(ctx context.Context, path string) (*Config, error) { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("read file: %w", err) } diff --git a/internal/config/supervisor/config_test.go b/internal/config/supervisor/config_test.go index ac4651a7..6fc0c4ab 100644 --- a/internal/config/supervisor/config_test.go +++ b/internal/config/supervisor/config_test.go @@ -6,7 +6,6 @@ package supervisor import ( "context" "fmt" - "io/ioutil" "os" "testing" @@ -427,7 +426,7 @@ func TestFromPath(t *testing.T) { // this is a serial test because it sets the global logger // Write yaml to temp file - f, err := ioutil.TempFile("", "pinniped-test-config-yaml-*") + f, err := os.CreateTemp("", "pinniped-test-config-yaml-*") require.NoError(t, err) defer func() { err := os.Remove(f.Name()) diff --git a/internal/controller/authenticator/cachecleaner/cachecleaner_test.go b/internal/controller/authenticator/cachecleaner/cachecleaner_test.go index f287e915..2f3d3068 100644 --- a/internal/controller/authenticator/cachecleaner/cachecleaner_test.go +++ b/internal/controller/authenticator/cachecleaner/cachecleaner_test.go @@ -143,7 +143,7 @@ func TestController(t *testing.T) { if tt.initialCache != nil { tt.initialCache(t, cache) } - testLog := testlogger.NewLegacy(t) //nolint: staticcheck // old test with lots of log statements + testLog := testlogger.NewLegacy(t) //nolint:staticcheck // old test with lots of log statements webhooks := informers.Authentication().V1alpha1().WebhookAuthenticators() jwtAuthenticators := informers.Authentication().V1alpha1().JWTAuthenticators() diff --git a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go index be6e05c7..87a0d19e 100644 --- a/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go +++ b/internal/controller/authenticator/jwtcachefiller/jwtcachefiller_test.go @@ -375,7 +375,7 @@ func TestController(t *testing.T) { fakeClient := pinnipedfake.NewSimpleClientset(tt.jwtAuthenticators...) informers := pinnipedinformers.NewSharedInformerFactory(fakeClient, 0) cache := authncache.New() - testLog := testlogger.NewLegacy(t) //nolint: staticcheck // old test with lots of log statements + testLog := testlogger.NewLegacy(t) //nolint:staticcheck // old test with lots of log statements if tt.cache != nil { tt.cache(t, cache, tt.wantClose) diff --git a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go index 61354f61..c7b24cc6 100644 --- a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go +++ b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package webhookcachefiller implements a controller for filling an authncache.Cache with each added/updated WebhookAuthenticator. @@ -6,7 +6,6 @@ package webhookcachefiller import ( "fmt" - "io/ioutil" "os" "github.com/go-logr/logr" @@ -64,7 +63,7 @@ func (c *controller) Sync(ctx controllerlib.Context) error { return fmt.Errorf("failed to get WebhookAuthenticator %s/%s: %w", ctx.Key.Namespace, ctx.Key.Name, err) } - webhookAuthenticator, err := newWebhookAuthenticator(&obj.Spec, ioutil.TempFile, clientcmd.WriteToFile) + webhookAuthenticator, err := newWebhookAuthenticator(&obj.Spec, os.CreateTemp, clientcmd.WriteToFile) if err != nil { return fmt.Errorf("failed to build webhook config: %w", err) } diff --git a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go index 240cd0aa..29135800 100644 --- a/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go +++ b/internal/controller/authenticator/webhookcachefiller/webhookcachefiller_test.go @@ -7,7 +7,7 @@ import ( "context" "encoding/base64" "fmt" - "io/ioutil" + "io" "net/http" "os" "testing" @@ -88,7 +88,7 @@ func TestController(t *testing.T) { fakeClient := pinnipedfake.NewSimpleClientset(tt.webhooks...) informers := pinnipedinformers.NewSharedInformerFactory(fakeClient, 0) cache := authncache.New() - testLog := testlogger.NewLegacy(t) //nolint: staticcheck // old test with lots of log statements + testLog := testlogger.NewLegacy(t) //nolint:staticcheck // old test with lots of log statements controller := New(cache, informers.Authentication().V1alpha1().WebhookAuthenticators(), testLog.Logger) @@ -121,7 +121,7 @@ func TestNewWebhookAuthenticator(t *testing.T) { t.Run("marshal failure", func(t *testing.T) { marshalError := func(_ clientcmdapi.Config, _ string) error { return fmt.Errorf("some marshal error") } - res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{}, ioutil.TempFile, marshalError) + res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{}, os.CreateTemp, marshalError) require.Nil(t, res) require.EqualError(t, err, "unable to marshal kubeconfig: some marshal error") }) @@ -130,7 +130,7 @@ func TestNewWebhookAuthenticator(t *testing.T) { res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://example.com", TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: "invalid-base64"}, - }, ioutil.TempFile, clientcmd.WriteToFile) + }, os.CreateTemp, clientcmd.WriteToFile) require.Nil(t, res) require.EqualError(t, err, "invalid TLS configuration: illegal base64 data at input byte 7") }) @@ -139,7 +139,7 @@ func TestNewWebhookAuthenticator(t *testing.T) { res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://example.com", TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte("bad data"))}, - }, ioutil.TempFile, clientcmd.WriteToFile) + }, os.CreateTemp, clientcmd.WriteToFile) require.Nil(t, res) require.EqualError(t, err, "invalid TLS configuration: certificateAuthorityData is not valid PEM: data does not contain any valid RSA or ECDSA certificates") }) @@ -147,14 +147,14 @@ func TestNewWebhookAuthenticator(t *testing.T) { t.Run("valid config with no TLS spec", func(t *testing.T) { res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{ Endpoint: "https://example.com", - }, ioutil.TempFile, clientcmd.WriteToFile) + }, os.CreateTemp, clientcmd.WriteToFile) require.NotNil(t, res) require.NoError(t, err) }) t.Run("success", func(t *testing.T) { caBundle, url := testutil.TLSTestServer(t, func(w http.ResponseWriter, r *http.Request) { - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) require.NoError(t, err) require.Contains(t, string(body), "test-token") _, err = w.Write([]byte(`{}`)) @@ -166,7 +166,7 @@ func TestNewWebhookAuthenticator(t *testing.T) { CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte(caBundle)), }, } - res, err := newWebhookAuthenticator(spec, ioutil.TempFile, clientcmd.WriteToFile) + res, err := newWebhookAuthenticator(spec, os.CreateTemp, clientcmd.WriteToFile) require.NoError(t, err) require.NotNil(t, res) diff --git a/internal/controller/impersonatorconfig/impersonator_config_test.go b/internal/controller/impersonatorconfig/impersonator_config_test.go index 6b760d3d..b4f855ed 100644 --- a/internal/controller/impersonatorconfig/impersonator_config_test.go +++ b/internal/controller/impersonatorconfig/impersonator_config_test.go @@ -11,7 +11,7 @@ import ( "encoding/pem" "errors" "fmt" - "io/ioutil" + "io" "net" "net/http" "reflect" @@ -92,7 +92,7 @@ func TestImpersonatorConfigControllerOptions(t *testing.T) { nil, caSignerName, nil, - plog.Logr(), // nolint: staticcheck // old test with no log assertions + plog.Logr(), //nolint:staticcheck // old test with no log assertions ) credIssuerInformerFilter = observableWithInformerOption.GetFilterForInformer(credIssuerInformer) servicesInformerFilter = observableWithInformerOption.GetFilterForInformer(servicesInformer) @@ -360,10 +360,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { } testHTTPServerMutex.Lock() // this is to satisfy the race detector - testHTTPServer = &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - _, err := fmt.Fprint(w, fakeServerResponseBody) - r.NoError(err) - })} + testHTTPServer = &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + _, err := fmt.Fprint(w, fakeServerResponseBody) + r.NoError(err) + }), + ReadHeaderTimeout: 10 * time.Second, + } testHTTPServerMutex.Unlock() // Start serving requests in the background. @@ -480,7 +483,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { r.NoError(err) r.Equal(http.StatusOK, resp.StatusCode) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) r.NoError(resp.Body.Close()) r.NoError(err) r.Equal(fakeServerResponseBody, string(body)) @@ -560,7 +563,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) { impersonatorFunc, caSignerName, signingCertProvider, - plog.Logr(), // nolint: staticcheck // old test with no log assertions + plog.Logr(), //nolint:staticcheck // old test with no log assertions ) controllerlib.TestWrap(t, subject, func(syncer controllerlib.Syncer) controllerlib.Syncer { tlsServingCertDynamicCertProvider = syncer.(*impersonatorConfigController).tlsServingCertDynamicCertProvider diff --git a/internal/controller/issuerconfig/issuerconfig.go b/internal/controller/issuerconfig/issuerconfig.go index faa14695..136734bc 100644 --- a/internal/controller/issuerconfig/issuerconfig.go +++ b/internal/controller/issuerconfig/issuerconfig.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package issuerconfig contains helpers for updating CredentialIssuer status entries. @@ -60,8 +60,7 @@ func mergeStrategy(configToUpdate *v1alpha1.CredentialIssuerStatus, strategy v1a } // weights are a set of priorities for each strategy type. -//nolint: gochecknoglobals -var weights = map[v1alpha1.StrategyType]int{ +var weights = map[v1alpha1.StrategyType]int{ //nolint:gochecknoglobals v1alpha1.KubeClusterSigningCertificateStrategyType: 2, // most preferred strategy v1alpha1.ImpersonationProxyStrategyType: 1, // unknown strategy types will have weight 0 by default diff --git a/internal/controller/kubecertagent/kubecertagent.go b/internal/controller/kubecertagent/kubecertagent.go index c19b34b1..3dca335b 100644 --- a/internal/controller/kubecertagent/kubecertagent.go +++ b/internal/controller/kubecertagent/kubecertagent.go @@ -145,12 +145,12 @@ type agentController struct { var ( // controllerManagerLabels are the Kubernetes labels we expect on the kube-controller-manager Pod. - controllerManagerLabels = labels.SelectorFromSet(map[string]string{ // nolint: gochecknoglobals + controllerManagerLabels = labels.SelectorFromSet(map[string]string{ //nolint:gochecknoglobals "component": "kube-controller-manager", }) // agentLabels are the Kubernetes labels we always expect on the kube-controller-manager Pod. - agentLabels = labels.SelectorFromSet(map[string]string{ // nolint: gochecknoglobals + agentLabels = labels.SelectorFromSet(map[string]string{ //nolint:gochecknoglobals agentPodLabelKey: agentPodLabelValue, }) ) @@ -179,7 +179,7 @@ func NewAgentController( dynamicCertProvider, &clock.RealClock{}, cache.NewExpiring(), - plog.Logr(), // nolint: staticcheck // old controller with lots of log statements + plog.Logr(), //nolint:staticcheck // old controller with lots of log statements ) } diff --git a/internal/controller/kubecertagent/kubecertagent_test.go b/internal/controller/kubecertagent/kubecertagent_test.go index 3e8016b8..df98de47 100644 --- a/internal/controller/kubecertagent/kubecertagent_test.go +++ b/internal/controller/kubecertagent/kubecertagent_test.go @@ -1110,7 +1110,7 @@ func TestAgentController(t *testing.T) { require.NoError(t, err) if tt.wantAgentDeployment == nil { assert.Empty(t, deployments.Items, "did not expect an agent deployment") - } else { // nolint: gocritic + } else { //nolint:gocritic if assert.Len(t, deployments.Items, 1, "expected a single agent deployment") { assert.Equal(t, tt.wantAgentDeployment, &deployments.Items[0]) } diff --git a/internal/controller/kubecertagent/legacypodcleaner_test.go b/internal/controller/kubecertagent/legacypodcleaner_test.go index 9f4fc54e..211219af 100644 --- a/internal/controller/kubecertagent/legacypodcleaner_test.go +++ b/internal/controller/kubecertagent/legacypodcleaner_test.go @@ -149,7 +149,7 @@ func TestLegacyPodCleanerController(t *testing.T) { } kubeInformers := informers.NewSharedInformerFactory(kubeClientset, 0) - log := testlogger.NewLegacy(t) //nolint: staticcheck // old test with lots of log statements + log := testlogger.NewLegacy(t) //nolint:staticcheck // old test with lots of log statements controller := NewLegacyPodCleanerController( AgentConfig{ Namespace: "concierge", diff --git a/internal/controller/supervisorconfig/generator/supervisor_secrets.go b/internal/controller/supervisorconfig/generator/supervisor_secrets.go index 4075d0fc..bd01a9c7 100644 --- a/internal/controller/supervisorconfig/generator/supervisor_secrets.go +++ b/internal/controller/supervisorconfig/generator/supervisor_secrets.go @@ -1,7 +1,7 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -// Package secretgenerator provides a supervisorSecretsController that can ensure existence of a generated secret. +// Package generator provides a supervisorSecretsController that can ensure existence of a generated secret. package generator import ( @@ -24,8 +24,7 @@ import ( ) // generateKey is stubbed out for the purpose of testing. The default behavior is to generate a symmetric key. -//nolint:gochecknoglobals -var generateKey = generateSymmetricKey +var generateKey = generateSymmetricKey //nolint:gochecknoglobals type supervisorSecretsController struct { labels map[string]string diff --git a/internal/controller/supervisorconfig/jwks_writer.go b/internal/controller/supervisorconfig/jwks_writer.go index e8750a2c..7e5ec447 100644 --- a/internal/controller/supervisorconfig/jwks_writer.go +++ b/internal/controller/supervisorconfig/jwks_writer.go @@ -50,8 +50,7 @@ const ( ) // generateKey is stubbed out for the purpose of testing. The default behavior is to generate an EC key. -//nolint:gochecknoglobals -var generateKey = generateECKey +var generateKey = generateECKey //nolint:gochecknoglobals func generateECKey(r io.Reader) (interface{}, error) { return ecdsa.GenerateKey(elliptic.P256(), r) diff --git a/internal/controller/supervisorconfig/jwks_writer_test.go b/internal/controller/supervisorconfig/jwks_writer_test.go index f977c8f8..0d660493 100644 --- a/internal/controller/supervisorconfig/jwks_writer_test.go +++ b/internal/controller/supervisorconfig/jwks_writer_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package supervisorconfig @@ -10,7 +10,7 @@ import ( "encoding/pem" "errors" "io" - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/require" @@ -259,7 +259,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { const namespace = "tuna-namespace" - goodKeyPEM, err := ioutil.ReadFile("testdata/good-ec-key.pem") + goodKeyPEM, err := os.ReadFile("testdata/good-ec-key.pem") require.NoError(t, err) block, _ := pem.Decode(goodKeyPEM) require.NotNil(t, block, "expected block to be non-nil...is goodKeyPEM a valid PEM?") @@ -747,7 +747,7 @@ func TestJWKSWriterControllerSync(t *testing.T) { func readJWKJSON(t *testing.T, path string) []byte { t.Helper() - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) require.NoError(t, err) // Trim whitespace from our testdata so that we match the compact JSON encoding of diff --git a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher.go b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher.go index 2faff38c..ea60fae6 100644 --- a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher.go +++ b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher.go @@ -67,7 +67,7 @@ const ( ) var ( - disallowedAdditionalAuthorizeParameters = map[string]bool{ // nolint: gochecknoglobals + disallowedAdditionalAuthorizeParameters = map[string]bool{ //nolint:gochecknoglobals // Reject these AdditionalAuthorizeParameters to avoid allowing the user's config to overwrite the parameters // that are always used by Pinniped in authcode authorization requests. The OIDC library used would otherwise // happily treat the user's config as an override. Users can already set the "client_id" and "scope" params diff --git a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go index bbaeb2d4..6a17908c 100644 --- a/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go +++ b/internal/controller/supervisorconfig/oidcupstreamwatcher/oidc_upstream_watcher_test.go @@ -91,7 +91,7 @@ func TestOIDCUpstreamWatcherControllerFilterSecret(t *testing.T) { nil, pinnipedInformers.IDP().V1alpha1().OIDCIdentityProviders(), secretInformer, - plog.Logr(), // nolint: staticcheck // old test with no log assertions + plog.Logr(), //nolint:staticcheck // old test with no log assertions withInformer.WithInformer, ) @@ -1400,7 +1400,7 @@ oidc: issuer did not match the issuer returned by provider, expected "` + testIs pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) fakeKubeClient := fake.NewSimpleClientset(tt.inputSecrets...) kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) - testLog := testlogger.NewLegacy(t) // nolint: staticcheck // old test with lots of log statements + testLog := testlogger.NewLegacy(t) //nolint:staticcheck // old test with lots of log statements cache := provider.NewDynamicUpstreamIDPProvider() cache.SetOIDCIdentityProviders([]provider.UpstreamOIDCIdentityProviderI{ &upstreamoidc.ProviderConfig{Name: "initial-entry"}, diff --git a/internal/controller/supervisorconfig/tls_cert_observer_test.go b/internal/controller/supervisorconfig/tls_cert_observer_test.go index 670943f4..b83648c2 100644 --- a/internal/controller/supervisorconfig/tls_cert_observer_test.go +++ b/internal/controller/supervisorconfig/tls_cert_observer_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package supervisorconfig @@ -6,8 +6,8 @@ package supervisorconfig import ( "context" "crypto/tls" - "io/ioutil" "net/url" + "os" "testing" "github.com/sclevine/spec" @@ -170,7 +170,7 @@ func TestTLSCertObserverControllerSync(t *testing.T) { } var readTestFile = func(path string) []byte { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) r.NoError(err) return data } diff --git a/internal/controllerinit/controllerinit.go b/internal/controllerinit/controllerinit.go index dbc5dc09..12597466 100644 --- a/internal/controllerinit/controllerinit.go +++ b/internal/controllerinit/controllerinit.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package controllerinit @@ -29,8 +29,8 @@ type Informer interface { } // Prepare returns RunnerBuilder that, when called: -// 1. Starts all provided informers and waits for them sync (and fails if they hang) -// 2. Returns a Runner that combines the Runner and RunnerWrapper passed into Prepare +// 1.) Starts all provided informers and waits for them sync (and fails if they hang), and +// 2.) Returns a Runner that combines the Runner and RunnerWrapper passed into Prepare. func Prepare(controllers Runner, controllersWrapper RunnerWrapper, informers ...Informer) RunnerBuilder { return func(ctx context.Context) (Runner, error) { for _, informer := range informers { diff --git a/internal/controllermanager/prepare_controllers.go b/internal/controllermanager/prepare_controllers.go index eccbe2e6..041ebe32 100644 --- a/internal/controllermanager/prepare_controllers.go +++ b/internal/controllermanager/prepare_controllers.go @@ -97,8 +97,7 @@ type Config struct { } // PrepareControllers prepares the controllers and their informers and returns a function that will start them when called. -//nolint:funlen // Eh, fair, it is a really long function...but it is wiring the world...so... -func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) { +func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) { //nolint:funlen // Eh, fair, it is a really long function...but it is wiring the world...so... loginConciergeGroupData, identityConciergeGroupData := groupsuffix.ConciergeAggregatedGroups(c.APIGroupSuffix) dref, deployment, _, err := deploymentref.New(c.ServerInstallationInfo) @@ -223,7 +222,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) { agentConfig, client, informers.installationNamespaceK8s.Core().V1().Pods(), - plog.Logr(), // nolint: staticcheck // old controller with lots of log statements + plog.Logr(), //nolint:staticcheck // old controller with lots of log statements ), singletonWorker, ). @@ -233,7 +232,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) { webhookcachefiller.New( c.AuthenticatorCache, informers.pinniped.Authentication().V1alpha1().WebhookAuthenticators(), - plog.Logr(), // nolint: staticcheck // old controller with lots of log statements + plog.Logr(), //nolint:staticcheck // old controller with lots of log statements ), singletonWorker, ). @@ -241,7 +240,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) { jwtcachefiller.New( c.AuthenticatorCache, informers.pinniped.Authentication().V1alpha1().JWTAuthenticators(), - plog.Logr(), // nolint: staticcheck // old controller with lots of log statements + plog.Logr(), //nolint:staticcheck // old controller with lots of log statements ), singletonWorker, ). @@ -250,7 +249,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) { c.AuthenticatorCache, informers.pinniped.Authentication().V1alpha1().WebhookAuthenticators(), informers.pinniped.Authentication().V1alpha1().JWTAuthenticators(), - plog.Logr(), // nolint: staticcheck // old controller with lots of log statements + plog.Logr(), //nolint:staticcheck // old controller with lots of log statements ), singletonWorker, ). @@ -276,7 +275,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) { impersonator.New, c.NamesConfig.ImpersonationSignerSecret, c.ImpersonationSigningCertProvider, - plog.Logr(), // nolint: staticcheck // old controller with lots of log statements + plog.Logr(), //nolint:staticcheck // old controller with lots of log statements ), singletonWorker, ). diff --git a/internal/crud/crud.go b/internal/crud/crud.go index 57e73b2a..c70bde16 100644 --- a/internal/crud/crud.go +++ b/internal/crud/crud.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package crud @@ -168,7 +168,7 @@ func validateSecret(resource string, secret *corev1.Secret) error { return nil } -//nolint: gochecknoglobals +//nolint:gochecknoglobals var b32 = base32.StdEncoding.WithPadding(base32.NoPadding) func (s *secretsStorage) getName(signature string) string { diff --git a/internal/crypto/ptls/ptls_test.go b/internal/crypto/ptls/ptls_test.go index 2c3aab8e..e8475b95 100644 --- a/internal/crypto/ptls/ptls_test.go +++ b/internal/crypto/ptls/ptls_test.go @@ -144,7 +144,7 @@ func TestMerge(t *testing.T) { tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, //nolint: gosec // yeah, I know it is a bad cipher, but AD sucks + tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, //nolint:gosec // yeah, I know it is a bad cipher, but AD sucks tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, @@ -169,7 +169,7 @@ func TestMerge(t *testing.T) { tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, //nolint: gosec // yeah, I know it is a bad cipher, but AD sucks + tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, //nolint:gosec // yeah, I know it is a bad cipher, but AD sucks tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, @@ -187,7 +187,7 @@ func TestMerge(t *testing.T) { ServerName: "something-to-check-passthrough", MinVersion: tls.VersionTLS12, CipherSuites: []uint16{ - tls.TLS_RSA_WITH_AES_128_CBC_SHA, //nolint: gosec // yeah, I know it is a bad cipher, this is the legacy config + tls.TLS_RSA_WITH_AES_128_CBC_SHA, //nolint:gosec // yeah, I know it is a bad cipher, this is the legacy config tls.TLS_RSA_WITH_AES_256_CBC_SHA, tls.TLS_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_256_GCM_SHA384, @@ -219,7 +219,7 @@ func TestMerge(t *testing.T) { ServerName: "a different thing for passthrough", MinVersion: tls.VersionTLS12, CipherSuites: []uint16{ - tls.TLS_RSA_WITH_AES_128_CBC_SHA, //nolint: gosec // yeah, I know it is a bad cipher, this is the legacy config + tls.TLS_RSA_WITH_AES_128_CBC_SHA, //nolint:gosec // yeah, I know it is a bad cipher, this is the legacy config tls.TLS_RSA_WITH_AES_256_CBC_SHA, tls.TLS_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_256_GCM_SHA384, diff --git a/internal/deploymentref/deploymentref.go b/internal/deploymentref/deploymentref.go index a7a72ef6..6c2aaa58 100644 --- a/internal/deploymentref/deploymentref.go +++ b/internal/deploymentref/deploymentref.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package deploymentref @@ -23,8 +23,7 @@ import ( // We would normally pass a kubernetes.Interface into New(), but the client we want to create in // the calling code depends on the return value of New() (i.e., on the kubeclient.Option for the // OwnerReference). -//nolint: gochecknoglobals -var getTempClient = func() (kubernetes.Interface, error) { +var getTempClient = func() (kubernetes.Interface, error) { //nolint:gochecknoglobals client, err := kubeclient.New() if err != nil { return nil, err diff --git a/internal/downward/downward.go b/internal/downward/downward.go index 75119dc4..3181d702 100644 --- a/internal/downward/downward.go +++ b/internal/downward/downward.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package downward implements a client interface for interacting with Kubernetes "downwardAPI" volumes. @@ -9,7 +9,7 @@ import ( "bytes" "fmt" "io" - "io/ioutil" + "os" "path/filepath" "strconv" "strings" @@ -32,20 +32,20 @@ type PodInfo struct { // Load pod metadata from a downwardAPI volume directory. func Load(directory string) (*PodInfo, error) { var result PodInfo - ns, err := ioutil.ReadFile(filepath.Join(directory, "namespace")) + ns, err := os.ReadFile(filepath.Join(directory, "namespace")) if err != nil { return nil, fmt.Errorf("could not load namespace: %w", err) } result.Namespace = strings.TrimSpace(string(ns)) - name, err := ioutil.ReadFile(filepath.Join(directory, "name")) + name, err := os.ReadFile(filepath.Join(directory, "name")) if err != nil { plog.Warning("could not read 'name' downward API file") } else { result.Name = strings.TrimSpace(string(name)) } - labels, err := ioutil.ReadFile(filepath.Join(directory, "labels")) + labels, err := os.ReadFile(filepath.Join(directory, "labels")) if err != nil { return nil, fmt.Errorf("could not load labels: %w", err) } diff --git a/internal/dynamiccert/provider_test.go b/internal/dynamiccert/provider_test.go index 691e75eb..0125b2c2 100644 --- a/internal/dynamiccert/provider_test.go +++ b/internal/dynamiccert/provider_test.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package dynamiccert @@ -41,7 +41,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) { cert, err := tls.X509KeyPair(certPEM, keyPEM) require.NoError(t, err) - return pool.Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool + return pool.Subjects(), []tls.Certificate{cert} }, }, { @@ -69,7 +69,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) { certKey.UnsetCertKeyContent() - return pool.Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool + return pool.Subjects(), []tls.Certificate{cert} }, }, { @@ -87,7 +87,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) { cert, err := tls.X509KeyPair(certPEM, keyPEM) require.NoError(t, err) - return newCA.Pool().Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool + return newCA.Pool().Subjects(), []tls.Certificate{cert} }, }, { @@ -110,7 +110,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) { ok := pool.AppendCertsFromPEM(ca.CurrentCABundleContent()) require.True(t, ok, "should have valid non-empty CA bundle") - return pool.Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool + return pool.Subjects(), []tls.Certificate{cert} }, }, { @@ -137,7 +137,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) { err = ca.SetCertKeyContent(newOtherCA.Bundle(), caKey) require.NoError(t, err) - return newOtherCA.Pool().Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool + return newOtherCA.Pool().Subjects(), []tls.Certificate{cert} }, }, } @@ -221,7 +221,7 @@ func poolSubjects(pool *x509.CertPool) [][]byte { if pool == nil { return nil } - return pool.Subjects() // nolint: staticcheck // not system cert pool + return pool.Subjects() } func TestNewServingCert(t *testing.T) { diff --git a/internal/execcredcache/cachefile.go b/internal/execcredcache/cachefile.go index 07bd99ad..12aa6d98 100644 --- a/internal/execcredcache/cachefile.go +++ b/internal/execcredcache/cachefile.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package execcredcache @@ -6,7 +6,6 @@ package execcredcache import ( "errors" "fmt" - "io/ioutil" "os" "sort" "time" @@ -51,7 +50,7 @@ type ( // readCache loads a credCache from a path on disk. If the requested path does not exist, it returns an empty cache. func readCache(path string) (*credCache, error) { - cacheYAML, err := ioutil.ReadFile(path) + cacheYAML, err := os.ReadFile(path) if err != nil { if errors.Is(err, os.ErrNotExist) { // If the file was not found, generate a freshly initialized empty cache. @@ -87,7 +86,7 @@ func (c *credCache) writeTo(path string) error { // Marshal the cache back to YAML and save it to the file. cacheYAML, err := yaml.Marshal(c) if err == nil { - err = ioutil.WriteFile(path, cacheYAML, 0600) + err = os.WriteFile(path, cacheYAML, 0600) } return err } diff --git a/internal/execcredcache/execcredcache_test.go b/internal/execcredcache/execcredcache_test.go index eab53c8d..c9b161e5 100644 --- a/internal/execcredcache/execcredcache_test.go +++ b/internal/execcredcache/execcredcache_test.go @@ -1,11 +1,10 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package execcredcache import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -52,7 +51,7 @@ func TestGet(t *testing.T) { }, { name: "file lock error", - makeTestFile: func(t *testing.T, tmp string) { require.NoError(t, ioutil.WriteFile(tmp, []byte(""), 0600)) }, + makeTestFile: func(t *testing.T, tmp string) { require.NoError(t, os.WriteFile(tmp, []byte(""), 0600)) }, trylockFunc: func(t *testing.T) error { return fmt.Errorf("some lock error") }, unlockFunc: func(t *testing.T) error { require.Fail(t, "should not be called"); return nil }, key: testKey{}, @@ -61,7 +60,7 @@ func TestGet(t *testing.T) { { name: "invalid file", makeTestFile: func(t *testing.T, tmp string) { - require.NoError(t, ioutil.WriteFile(tmp, []byte("invalid yaml"), 0600)) + require.NoError(t, os.WriteFile(tmp, []byte("invalid yaml"), 0600)) }, key: testKey{}, wantErrors: []string{ @@ -70,7 +69,7 @@ func TestGet(t *testing.T) { }, { name: "invalid file, fail to unlock", - makeTestFile: func(t *testing.T, tmp string) { require.NoError(t, ioutil.WriteFile(tmp, []byte("invalid"), 0600)) }, + makeTestFile: func(t *testing.T, tmp string) { require.NoError(t, os.WriteFile(tmp, []byte("invalid"), 0600)) }, trylockFunc: func(t *testing.T) error { return nil }, unlockFunc: func(t *testing.T) error { return fmt.Errorf("some unlock error") }, key: testKey{}, @@ -211,7 +210,7 @@ func TestPutToken(t *testing.T) { { name: "fail to create directory", makeTestFile: func(t *testing.T, tmp string) { - require.NoError(t, ioutil.WriteFile(filepath.Dir(tmp), []byte{}, 0600)) + require.NoError(t, os.WriteFile(filepath.Dir(tmp), []byte{}, 0600)) }, wantErrors: []string{ "could not create credential cache directory: mkdir TEMPDIR: not a directory", diff --git a/internal/fositestorage/authorizationcode/authorizationcode.go b/internal/fositestorage/authorizationcode/authorizationcode.go index ecfad7be..9e10e5bd 100644 --- a/internal/fositestorage/authorizationcode/authorizationcode.go +++ b/internal/fositestorage/authorizationcode/authorizationcode.go @@ -235,6 +235,7 @@ const ExpectedAuthorizeCodeSessionJSONFromFuzzing = `{ "Host": "", "Path": "", "RawPath": "", + "OmitHost": false, "ForceQuery": false, "RawQuery": "", "Fragment": "", @@ -252,6 +253,7 @@ const ExpectedAuthorizeCodeSessionJSONFromFuzzing = `{ "Host": "", "Path": "", "RawPath": "", + "OmitHost": false, "ForceQuery": false, "RawQuery": "", "Fragment": "", @@ -269,6 +271,7 @@ const ExpectedAuthorizeCodeSessionJSONFromFuzzing = `{ "Host": "", "Path": "", "RawPath": "", + "OmitHost": false, "ForceQuery": false, "RawQuery": "", "Fragment": "", diff --git a/internal/fositestorage/openidconnect/openidconnect_test.go b/internal/fositestorage/openidconnect/openidconnect_test.go index 10979e9c..4fd59f10 100644 --- a/internal/fositestorage/openidconnect/openidconnect_test.go +++ b/internal/fositestorage/openidconnect/openidconnect_test.go @@ -100,7 +100,7 @@ func TestOpenIdConnectStorage(t *testing.T) { require.NoError(t, err) require.Equal(t, request, newRequest) - err = storage.DeleteOpenIDConnectSession(ctx, "fancy-code.fancy-signature") //nolint: staticcheck // we know this is deprecated and never called. our GC controller cleans these up. + err = storage.DeleteOpenIDConnectSession(ctx, "fancy-code.fancy-signature") //nolint:staticcheck // we know this is deprecated and never called. our GC controller cleans these up. require.NoError(t, err) testutil.LogActualJSONFromCreateAction(t, client, 0) // makes it easier to update expected values when needed diff --git a/internal/groupsuffix/groupsuffix.go b/internal/groupsuffix/groupsuffix.go index 1dc3397c..8d2d4477 100644 --- a/internal/groupsuffix/groupsuffix.go +++ b/internal/groupsuffix/groupsuffix.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package groupsuffix @@ -175,7 +175,7 @@ func Unreplace(baseAPIGroup, apiGroupSuffix string) (string, bool) { // makes sure that the provided apiGroupSuffix is a valid DNS-1123 subdomain with at least one dot, // to match Kubernetes behavior. func Validate(apiGroupSuffix string) error { - var errs []error // nolint: prealloc + var errs []error //nolint:prealloc if len(strings.Split(apiGroupSuffix, ".")) < 2 { errs = append(errs, constable.Error("must contain '.'")) diff --git a/internal/httputil/securityheader/securityheader_test.go b/internal/httputil/securityheader/securityheader_test.go index 639c495c..6181acc5 100644 --- a/internal/httputil/securityheader/securityheader_test.go +++ b/internal/httputil/securityheader/securityheader_test.go @@ -1,11 +1,11 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package securityheader import ( "context" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -74,7 +74,7 @@ func TestWrap(t *testing.T) { defer resp.Body.Close() require.Equal(t, http.StatusOK, resp.StatusCode) - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "hello world", string(respBody)) diff --git a/internal/kubeclient/copied.go b/internal/kubeclient/copied.go index ef40e939..a6314435 100644 --- a/internal/kubeclient/copied.go +++ b/internal/kubeclient/copied.go @@ -15,8 +15,7 @@ import ( ) // defaultServerUrlFor was copied from k8s.io/client-go/rest/url_utils.go. -//nolint:revive -func defaultServerUrlFor(config *restclient.Config) (*url.URL, string, error) { +func defaultServerUrlFor(config *restclient.Config) (*url.URL, string, error) { //nolint:revive hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0 hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0 defaultTLS := hasCA || hasCert || config.Insecure diff --git a/internal/kubeclient/kubeclient.go b/internal/kubeclient/kubeclient.go index 98d0b7f6..1f5c4322 100644 --- a/internal/kubeclient/kubeclient.go +++ b/internal/kubeclient/kubeclient.go @@ -211,7 +211,7 @@ func AssertSecureTransport(rt http.RoundTripper) error { tlsConfigCopy := tlsConfig.Clone() ptls.Merge(ptls.Secure, tlsConfigCopy) // only mutate the copy - //nolint: gosec // the empty TLS config here is not used + //nolint:gosec // the empty TLS config here is not used if diff := cmp.Diff(tlsConfigCopy, tlsConfig, cmpopts.IgnoreUnexported(tls.Config{}, x509.CertPool{}), cmpopts.IgnoreFields(tls.Config{}, "GetClientCertificate"), diff --git a/internal/kubeclient/kubeclient_test.go b/internal/kubeclient/kubeclient_test.go index b3640a43..57760d30 100644 --- a/internal/kubeclient/kubeclient_test.go +++ b/internal/kubeclient/kubeclient_test.go @@ -949,7 +949,7 @@ func TestUnwrap(t *testing.T) { server, restConfig := fakekubeapi.Start(t, nil) - serverSubjects := server.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs.Subjects() // nolint: staticcheck // not system cert pool + serverSubjects := server.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs.Subjects() t.Run("regular client", func(t *testing.T) { t.Parallel() // make sure to run in parallel to confirm that our client-go TLS cache busting works (i.e. assert no data races) @@ -1121,7 +1121,7 @@ func testUnwrap(t *testing.T, client *Client, serverSubjects [][]byte) { require.Equal(t, secureTLSConfig.NextProtos, tlsConfig.NextProtos) // x509.CertPool has some embedded functions that make it hard to compare so just look at the subjects - require.Equal(t, serverSubjects, tlsConfig.RootCAs.Subjects()) // nolint: staticcheck // not system cert pool + require.Equal(t, serverSubjects, tlsConfig.RootCAs.Subjects()) }) } } diff --git a/internal/kubeclient/middleware.go b/internal/kubeclient/middleware.go index f35b3532..15760592 100644 --- a/internal/kubeclient/middleware.go +++ b/internal/kubeclient/middleware.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package kubeclient @@ -71,7 +71,7 @@ func (r *request) Namespace() string { return r.namespace } -//nolint: gochecknoglobals +//nolint:gochecknoglobals var namespaceGVR = corev1.SchemeGroupVersion.WithResource("namespaces") func (r *request) NamespaceScoped() bool { diff --git a/internal/kubeclient/path_test.go b/internal/kubeclient/path_test.go index 20728ff6..db72a868 100644 --- a/internal/kubeclient/path_test.go +++ b/internal/kubeclient/path_test.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package kubeclient @@ -6,7 +6,7 @@ package kubeclient import ( "bytes" "context" - "io/ioutil" + "io" "net/http" "net/url" "reflect" @@ -142,7 +142,7 @@ func Test_updatePathNewGVK(t *testing.T) { } func Test_reqWithoutPrefix(t *testing.T) { - body := ioutil.NopCloser(bytes.NewBuffer([]byte("some body"))) + body := io.NopCloser(bytes.NewBuffer([]byte("some body"))) newReq := func(rawurl string) *http.Request { req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawurl, body) require.NoError(t, err) diff --git a/internal/kubeclient/roundtrip.go b/internal/kubeclient/roundtrip.go index 57c8714d..b6f8decf 100644 --- a/internal/kubeclient/roundtrip.go +++ b/internal/kubeclient/roundtrip.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package kubeclient @@ -6,7 +6,7 @@ package kubeclient import ( "bytes" "fmt" - "io/ioutil" + "io" "net/http" apiequality "k8s.io/apimachinery/pkg/api/equality" @@ -213,7 +213,7 @@ func handleCreateOrUpdate( return true, nil, fmt.Errorf("get body failed: %w", err) } defer body.Close() - data, err := ioutil.ReadAll(body) + data, err := io.ReadAll(body) if err != nil { return true, nil, fmt.Errorf("read body failed: %w", err) } @@ -296,7 +296,7 @@ func handleResponseNewGVK( // always make sure we close the body, even if reading from it fails defer resp.Body.Close() - respData, err := ioutil.ReadAll(resp.Body) + respData, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %w", err) } @@ -319,7 +319,7 @@ func handleResponseNewGVK( newResp := &http.Response{} *newResp = *resp - newResp.Body = ioutil.NopCloser(bytes.NewBuffer(fixedRespData)) + newResp.Body = io.NopCloser(bytes.NewBuffer(fixedRespData)) return newResp, nil } diff --git a/internal/kubeclient/watch.go b/internal/kubeclient/watch.go index a1817582..c4007b9b 100644 --- a/internal/kubeclient/watch.go +++ b/internal/kubeclient/watch.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package kubeclient @@ -7,7 +7,6 @@ import ( stderrors "errors" "fmt" "io" - "io/ioutil" "net/http" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -155,7 +154,7 @@ func drainAndMaybeCloseBody(resp *http.Response, close bool) { // from k8s.io/client-go/rest/request.go... const maxBodySlurpSize = 2 << 10 if resp.ContentLength <= maxBodySlurpSize { - _, _ = io.Copy(ioutil.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize}) + _, _ = io.Copy(io.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize}) } if close { resp.Body.Close() diff --git a/internal/leaderelection/leaderelection.go b/internal/leaderelection/leaderelection.go index 1d083065..a3cca966 100644 --- a/internal/leaderelection/leaderelection.go +++ b/internal/leaderelection/leaderelection.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package leaderelection @@ -184,7 +184,7 @@ func (t *isLeaderTracker) start() { } func (t *isLeaderTracker) stop() (didStop bool) { - return t.tracker.CAS(true, false) + return t.tracker.CompareAndSwap(true, false) } // note that resourcelock.Interface is an internal, unstable interface. diff --git a/internal/localuserauthenticator/localuserauthenticator.go b/internal/localuserauthenticator/localuserauthenticator.go index 6ef851df..a9f55034 100644 --- a/internal/localuserauthenticator/localuserauthenticator.go +++ b/internal/localuserauthenticator/localuserauthenticator.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package localuserauthenticator provides a authentication webhook program. @@ -79,8 +79,9 @@ func (w *webhook) start(ctx context.Context, l net.Listener) error { return &cert, err } server := http.Server{ - Handler: w, - TLSConfig: c, + Handler: w, + TLSConfig: c, + ReadHeaderTimeout: 10 * time.Second, } errCh := make(chan error) @@ -356,7 +357,7 @@ func run(ctx context.Context) error { startControllers(ctx, dynamicCertProvider, client.Kubernetes, kubeInformers) plog.Debug("controllers are ready") - // nolint: gosec // Intentionally binding to all network interfaces. + //nolint:gosec // Intentionally binding to all network interfaces. l, err := net.Listen("tcp", ":8443") if err != nil { return fmt.Errorf("cannot create listener: %w", err) diff --git a/internal/localuserauthenticator/localuserauthenticator_test.go b/internal/localuserauthenticator/localuserauthenticator_test.go index 6e188ff5..7df3d0ba 100644 --- a/internal/localuserauthenticator/localuserauthenticator_test.go +++ b/internal/localuserauthenticator/localuserauthenticator_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package localuserauthenticator @@ -10,7 +10,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -385,7 +384,7 @@ func TestWebhook(t *testing.T) { url: goodURL, method: http.MethodPost, headers: goodRequestHeaders, - body: func() (io.ReadCloser, error) { return ioutil.NopCloser(bytes.NewBuffer([]byte("invalid body"))), nil }, + body: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewBuffer([]byte("invalid body"))), nil }, wantStatus: http.StatusBadRequest, }, } @@ -416,7 +415,7 @@ func TestWebhook(t *testing.T) { } } - responseBody, err := ioutil.ReadAll(rsp.Body) + responseBody, err := io.ReadAll(rsp.Body) require.NoError(t, err) if test.wantBody != nil { require.NoError(t, err) @@ -520,7 +519,7 @@ func newTokenReviewBodyWithGVK(token string, gvk *schema.GroupVersionKind) (io.R }, } err := json.NewEncoder(buf).Encode(&tr) - return ioutil.NopCloser(buf), err + return io.NopCloser(buf), err } func unauthenticatedResponseJSON() *authenticationv1beta1.TokenReview { diff --git a/internal/oidc/auth/auth_handler_test.go b/internal/oidc/auth/auth_handler_test.go index 11431a0b..fc5d10d8 100644 --- a/internal/oidc/auth/auth_handler_test.go +++ b/internal/oidc/auth/auth_handler_test.go @@ -54,10 +54,10 @@ func TestAuthorizationEndpoint(t *testing.T) { oidcUpstreamSubject = "abc123-some guid" // has a space character which should get escaped in URL oidcUpstreamSubjectQueryEscaped = "abc123-some+guid" oidcUpstreamUsername = "test-oidc-pinniped-username" - oidcUpstreamPassword = "test-oidc-pinniped-password" //nolint: gosec + oidcUpstreamPassword = "test-oidc-pinniped-password" //nolint:gosec oidcUpstreamUsernameClaim = "the-user-claim" oidcUpstreamGroupsClaim = "the-groups-claim" - oidcPasswordGrantUpstreamRefreshToken = "some-opaque-token" //nolint: gosec + oidcPasswordGrantUpstreamRefreshToken = "some-opaque-token" //nolint:gosec oidcUpstreamAccessToken = "some-access-token" downstreamIssuer = "https://my-downstream-issuer.com/some-path" diff --git a/internal/oidc/kube_storage.go b/internal/oidc/kube_storage.go index 0de1731b..e7864c05 100644 --- a/internal/oidc/kube_storage.go +++ b/internal/oidc/kube_storage.go @@ -114,7 +114,7 @@ func (k KubeStorage) GetOpenIDConnectSession(ctx context.Context, fullAuthcode s } func (k KubeStorage) DeleteOpenIDConnectSession(ctx context.Context, fullAuthcode string) error { - return k.oidcStorage.DeleteOpenIDConnectSession(ctx, fullAuthcode) //nolint: staticcheck // we know this is deprecated and never called. our GC controller cleans these up. + return k.oidcStorage.DeleteOpenIDConnectSession(ctx, fullAuthcode) //nolint:staticcheck // we know this is deprecated and never called. our GC controller cleans these up. } // diff --git a/internal/oidc/login/loginhtml/loginhtml.go b/internal/oidc/login/loginhtml/loginhtml.go index 2cd97c57..eb4c59b8 100644 --- a/internal/oidc/login/loginhtml/loginhtml.go +++ b/internal/oidc/login/loginhtml/loginhtml.go @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 // Package loginhtml defines HTML templates used by the Supervisor. -//nolint: gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init. package loginhtml import ( @@ -15,6 +14,7 @@ import ( "go.pinniped.dev/internal/oidc/provider/csp" ) +//nolint:gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init. var ( //go:embed login_form.css rawCSS string @@ -22,20 +22,20 @@ var ( //go:embed login_form.gohtml rawHTMLTemplate string + + // Parse the Go templated HTML and inject functions providing the minified inline CSS and JS. + parsedHTMLTemplate = template.Must(template.New("login_form.gohtml").Funcs(template.FuncMap{ + "minifiedCSS": func() template.CSS { return template.CSS(CSS()) }, + }).Parse(rawHTMLTemplate)) + + // Generate the CSP header value once since it's effectively constant. + cspValue = strings.Join([]string{ + `default-src 'none'`, + `style-src '` + csp.Hash(minifiedCSS) + `'`, + `frame-ancestors 'none'`, + }, "; ") ) -// Parse the Go templated HTML and inject functions providing the minified inline CSS and JS. -var parsedHTMLTemplate = template.Must(template.New("login_form.gohtml").Funcs(template.FuncMap{ - "minifiedCSS": func() template.CSS { return template.CSS(CSS()) }, -}).Parse(rawHTMLTemplate)) - -// Generate the CSP header value once since it's effectively constant. -var cspValue = strings.Join([]string{ - `default-src 'none'`, - `style-src '` + csp.Hash(minifiedCSS) + `'`, - `frame-ancestors 'none'`, -}, "; ") - func panicOnError(s string, err error) string { if err != nil { panic(err) diff --git a/internal/oidc/oidc.go b/internal/oidc/oidc.go index 79380df7..a3caee7c 100644 --- a/internal/oidc/oidc.go +++ b/internal/oidc/oidc.go @@ -255,11 +255,12 @@ func FositeOauth2Helper( // passed to a plog function (e.g., plog.Info()). // // Sample usage: -// err := someFositeLibraryFunction() -// if err != nil { -// plog.Info("some error", FositeErrorForLog(err)...) -// ... -// } +// +// err := someFositeLibraryFunction() +// if err != nil { +// plog.Info("some error", FositeErrorForLog(err)...) +// ... +// } func FositeErrorForLog(err error) []interface{} { rfc6749Error := fosite.ErrorToRFC6749Error(err) keysAndValues := make([]interface{}, 0) diff --git a/internal/oidc/provider/formposthtml/formposthtml.go b/internal/oidc/provider/formposthtml/formposthtml.go index d1a26c34..4fd709c1 100644 --- a/internal/oidc/provider/formposthtml/formposthtml.go +++ b/internal/oidc/provider/formposthtml/formposthtml.go @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 // Package formposthtml defines HTML templates used by the Supervisor. -//nolint: gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init. package formposthtml import ( @@ -15,6 +14,7 @@ import ( "go.pinniped.dev/internal/oidc/provider/csp" ) +//nolint:gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init. var ( //go:embed form_post.css rawCSS string @@ -26,24 +26,24 @@ var ( //go:embed form_post.gohtml rawHTMLTemplate string + + // Parse the Go templated HTML and inject functions providing the minified inline CSS and JS. + parsedHTMLTemplate = template.Must(template.New("form_post.gohtml").Funcs(template.FuncMap{ + "minifiedCSS": func() template.CSS { return template.CSS(minifiedCSS) }, + "minifiedJS": func() template.JS { return template.JS(minifiedJS) }, //nolint:gosec // This is 100% static input, not attacker-controlled. + }).Parse(rawHTMLTemplate)) + + // Generate the CSP header value once since it's effectively constant. + cspValue = strings.Join([]string{ + `default-src 'none'`, + `script-src '` + csp.Hash(minifiedJS) + `'`, + `style-src '` + csp.Hash(minifiedCSS) + `'`, + `img-src data:`, + `connect-src *`, + `frame-ancestors 'none'`, + }, "; ") ) -// Parse the Go templated HTML and inject functions providing the minified inline CSS and JS. -var parsedHTMLTemplate = template.Must(template.New("form_post.gohtml").Funcs(template.FuncMap{ - "minifiedCSS": func() template.CSS { return template.CSS(minifiedCSS) }, - "minifiedJS": func() template.JS { return template.JS(minifiedJS) }, //nolint:gosec // This is 100% static input, not attacker-controlled. -}).Parse(rawHTMLTemplate)) - -// Generate the CSP header value once since it's effectively constant. -var cspValue = strings.Join([]string{ - `default-src 'none'`, - `script-src '` + csp.Hash(minifiedJS) + `'`, - `style-src '` + csp.Hash(minifiedCSS) + `'`, - `img-src data:`, - `connect-src *`, - `frame-ancestors 'none'`, -}, "; ") - func panicOnError(s string, err error) string { if err != nil { panic(err) diff --git a/internal/oidc/provider/manager/manager_test.go b/internal/oidc/provider/manager/manager_test.go index 1f18dcf7..f92609f1 100644 --- a/internal/oidc/provider/manager/manager_test.go +++ b/internal/oidc/provider/manager/manager_test.go @@ -8,7 +8,7 @@ import ( "crypto/ecdsa" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" @@ -84,7 +84,7 @@ func TestManager(t *testing.T) { // Minimal check to ensure that the right discovery endpoint was called r.Equal(http.StatusOK, recorder.Code) - responseBody, err := ioutil.ReadAll(recorder.Body) + responseBody, err := io.ReadAll(recorder.Body) r.NoError(err) parsedDiscoveryResult := discovery.Metadata{} err = json.Unmarshal(responseBody, &parsedDiscoveryResult) @@ -105,7 +105,7 @@ func TestManager(t *testing.T) { // Minimal check to ensure that the right IDP discovery endpoint was called r.Equal(http.StatusOK, recorder.Code) - responseBody, err := ioutil.ReadAll(recorder.Body) + responseBody, err := io.ReadAll(recorder.Body) r.NoError(err) r.Equal( fmt.Sprintf(`{"pinniped_identity_providers":[{"name":"%s","type":"%s","flows":%s}]}`+"\n", expectedIDPName, expectedIDPType, expectedFlowsJSON), @@ -230,7 +230,7 @@ func TestManager(t *testing.T) { // Minimal check to ensure that the right JWKS endpoint was called r.Equal(http.StatusOK, recorder.Code) - responseBody, err := ioutil.ReadAll(recorder.Body) + responseBody, err := io.ReadAll(recorder.Body) r.NoError(err) parsedJWKSResult := jose.JSONWebKeySet{} err = json.Unmarshal(responseBody, &parsedJWKSResult) diff --git a/internal/oidc/token/token_handler_test.go b/internal/oidc/token/token_handler_test.go index ea0d9290..38a848af 100644 --- a/internal/oidc/token/token_handler_test.go +++ b/internal/oidc/token/token_handler_test.go @@ -14,7 +14,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -109,7 +108,7 @@ var ( fositeInvalidPayloadErrorBody = here.Doc(` { "error": "invalid_request", - "error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. The POST body can not be empty." + "error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Unable to parse HTTP body, make sure to send a properly formatted form request body." } `) @@ -372,7 +371,7 @@ func TestTokenEndpointAuthcodeExchange(t *testing.T) { name: "payload is not valid form serialization", authcodeExchange: authcodeExchangeInputs{ modifyTokenRequest: func(r *http.Request, authCode string) { - r.Body = ioutil.NopCloser(strings.NewReader("this newline character is not allowed in a form serialization: \n")) + r.Body = io.NopCloser(strings.NewReader("this newline character is not allowed in a form serialization: \n")) }, want: tokenEndpointResponseExpectedValues{ wantStatus: http.StatusBadRequest, @@ -3074,7 +3073,7 @@ func (b body) WithPKCE(verifier string) body { } func (b body) ReadCloser() io.ReadCloser { - return ioutil.NopCloser(strings.NewReader(url.Values(b).Encode())) + return io.NopCloser(strings.NewReader(url.Values(b).Encode())) } func (b body) with(param, value string) body { diff --git a/internal/oidc/token_exchange.go b/internal/oidc/token_exchange.go index d6dc2d29..73fa8bf5 100644 --- a/internal/oidc/token_exchange.go +++ b/internal/oidc/token_exchange.go @@ -1,4 +1,4 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package oidc @@ -16,9 +16,9 @@ import ( ) const ( - tokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token" //nolint: gosec - tokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" //nolint: gosec - pinnipedTokenExchangeScope = "pinniped:request-audience" //nolint: gosec + tokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token" //nolint:gosec + tokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" //nolint:gosec + pinnipedTokenExchangeScope = "pinniped:request-audience" //nolint:gosec ) type stsParams struct { diff --git a/internal/ownerref/ownerref.go b/internal/ownerref/ownerref.go index 854f7547..d16e5fd4 100644 --- a/internal/ownerref/ownerref.go +++ b/internal/ownerref/ownerref.go @@ -1,4 +1,4 @@ -// Copyright 2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package ownerref @@ -64,7 +64,7 @@ func New(refObj kubeclient.Object) kubeclient.Middleware { }) } -//nolint: gochecknoglobals +//nolint:gochecknoglobals var namespaceGVK = corev1.SchemeGroupVersion.WithKind("Namespace") func isNamespace(obj kubeclient.Object) bool { diff --git a/internal/plog/config.go b/internal/plog/config.go index dd5d1f61..b5e7ad3c 100644 --- a/internal/plog/config.go +++ b/internal/plog/config.go @@ -88,7 +88,7 @@ func ValidateAndSetLogLevelAndFormatGlobally(ctx context.Context, spec LogSpec) setGlobalLoggers(log, flush) - // nolint: exhaustive // the switch above is exhaustive for format already + //nolint:exhaustive // the switch above is exhaustive for format already switch spec.Format { case FormatCLI: return nil // do not spawn go routines on the CLI to allow the CLI to call this more than once diff --git a/internal/plog/config_test.go b/internal/plog/config_test.go index 2cdd9f57..25cafadc 100644 --- a/internal/plog/config_test.go +++ b/internal/plog/config_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package plog @@ -136,7 +136,7 @@ func TestFormat(t *testing.T) { `go.pinniped.dev/internal/plog.TestFormat %s/config_test.go:%d testing.tRunner - %s/src/testing/testing.go:1439`, + %s/src/testing/testing.go:1446`, wd, startLogLine+2+13+14+11+12+24, runtime.GOROOT(), ), ), diff --git a/internal/plog/global.go b/internal/plog/global.go index dc4dfbcd..c6bbc578 100644 --- a/internal/plog/global.go +++ b/internal/plog/global.go @@ -15,7 +15,7 @@ import ( "k8s.io/klog/v2" ) -// nolint: gochecknoglobals +//nolint:gochecknoglobals var ( // note that these globals have no locks on purpose - they are expected to be set at init and then again after config parsing. globalLevel zap.AtomicLevel @@ -26,7 +26,7 @@ var ( sinkMap sync.Map ) -// nolint: gochecknoinits +//nolint:gochecknoinits func init() { // make sure we always have a functional global logger globalLevel = zap.NewAtomicLevelAt(0) // log at the 0 verbosity level to start with, i.e. the "always" logs diff --git a/internal/registry/credentialrequest/rest_test.go b/internal/registry/credentialrequest/rest_test.go index e7752e50..cd7a426b 100644 --- a/internal/registry/credentialrequest/rest_test.go +++ b/internal/registry/credentialrequest/rest_test.go @@ -71,7 +71,7 @@ func TestCreate(t *testing.T) { it.Before(func() { r = require.New(t) ctrl = gomock.NewController(t) - logger = testutil.NewTranscriptLogger(t) // nolint: staticcheck // old test with lots of log statements + logger = testutil.NewTranscriptLogger(t) //nolint:staticcheck // old test with lots of log statements klog.SetLogger(logr.New(logger)) // this is unfortunately a global logger, so can't run these tests in parallel :( }) diff --git a/internal/supervisor/server/server.go b/internal/supervisor/server/server.go index 772f0f5a..0d20e0ef 100644 --- a/internal/supervisor/server/server.go +++ b/internal/supervisor/server/server.go @@ -65,8 +65,9 @@ func startServer(ctx context.Context, shutdown *sync.WaitGroup, l net.Listener, handler = withBootstrapPaths(handler, "/healthz") // only health checks are allowed for bootstrap connections server := http.Server{ - Handler: handler, - ConnContext: withBootstrapConnCtx, + Handler: handler, + ConnContext: withBootstrapConnCtx, + ReadHeaderTimeout: 10 * time.Second, } shutdown.Add(1) @@ -270,7 +271,7 @@ func prepareControllers( pinnipedClient, pinnipedInformers.IDP().V1alpha1().OIDCIdentityProviders(), secretInformer, - plog.Logr(), // nolint: staticcheck // old controller with lots of log statements + plog.Logr(), //nolint:staticcheck // old controller with lots of log statements controllerlib.WithInformer, ), singletonWorker). diff --git a/internal/testutil/fakekubeapi/fakekubeapi.go b/internal/testutil/fakekubeapi/fakekubeapi.go index 2b4e20c3..7ac26ccc 100644 --- a/internal/testutil/fakekubeapi/fakekubeapi.go +++ b/internal/testutil/fakekubeapi/fakekubeapi.go @@ -1,25 +1,28 @@ // Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -// Package fakekubeapi contains a *very* simple httptest.Server that can be used to stand in for -// a real Kube API server in tests. -// -// Usage: -// func TestSomething(t *testing.T) { -// resources := map[string]kubeclient.Object{ -// // store preexisting resources here -// "/api/v1/namespaces/default/pods/some-pod-name": &corev1.Pod{...}, -// } -// server, restConfig := fakekubeapi.Start(t, resources) -// defer server.Close() -// client := kubeclient.New(kubeclient.WithConfig(restConfig)) -// // do stuff with client... -// } +/* +Package fakekubeapi contains a *very* simple httptest.Server that can be used to stand in for +a real Kube API server in tests. + +Usage: + + func TestSomething(t *testing.T) { + resources := map[string]kubeclient.Object{ + // store preexisting resources here + "/api/v1/namespaces/default/pods/some-pod-name": &corev1.Pod{...}, + } + server, restConfig := fakekubeapi.Start(t, resources) + defer server.Close() + client := kubeclient.New(kubeclient.WithConfig(restConfig)) + // do stuff with client... + } +*/ package fakekubeapi import ( "fmt" - "io/ioutil" + "io" "mime" "net/http" "net/http/httptest" @@ -104,13 +107,13 @@ func decodeObj(r *http.Request) (runtime.Object, error) { return nil, httperr.Wrap(http.StatusUnsupportedMediaType, "could not parse mime type from content-type header", err) } - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { return nil, httperr.Wrap(http.StatusInternalServerError, "read body", err) } var obj runtime.Object - var errs []error //nolint: prealloc + var errs []error //nolint:prealloc codecsThatWeUseInOurCode := []runtime.NegotiatedSerializer{ kubescheme.Codecs, aggregatorclientscheme.Codecs, diff --git a/internal/testutil/ioutil.go b/internal/testutil/ioutil.go index 9b1f086f..8a1e2d29 100644 --- a/internal/testutil/ioutil.go +++ b/internal/testutil/ioutil.go @@ -1,11 +1,10 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testutil import ( "io" - "io/ioutil" "os" "testing" @@ -23,7 +22,7 @@ func (e *ErrorWriter) Write([]byte) (int, error) { return 0, e.ReturnError } func WriteStringToTempFile(t *testing.T, filename string, fileBody string) *os.File { t.Helper() - f, err := ioutil.TempFile("", filename) + f, err := os.CreateTemp("", filename) require.NoError(t, err) deferMe := func() { err := os.Remove(f.Name()) diff --git a/internal/testutil/tempdir.go b/internal/testutil/tempdir.go index 4fca27a3..81c2759e 100644 --- a/internal/testutil/tempdir.go +++ b/internal/testutil/tempdir.go @@ -1,6 +1,7 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build !go1.14 // +build !go1.14 package testutil diff --git a/internal/testutil/tempdir_go1.14.go b/internal/testutil/tempdir_go1.14.go index 3d6f2335..7f3f1bcc 100644 --- a/internal/testutil/tempdir_go1.14.go +++ b/internal/testutil/tempdir_go1.14.go @@ -1,13 +1,13 @@ // Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//nolint:goimports // not an import +//go:build go1.14 // +build go1.14 package testutil import ( - "io/ioutil" + "io/ioutil" //nolint:staticcheck // ioutil is deprecated, but this file is for go1.14 "os" "testing" diff --git a/internal/testutil/tlsserver.go b/internal/testutil/tlsserver.go index b2d3eb46..4ebe526b 100644 --- a/internal/testutil/tlsserver.go +++ b/internal/testutil/tlsserver.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testutil @@ -9,6 +9,7 @@ import ( "net" "net/http" "testing" + "time" "github.com/stretchr/testify/require" @@ -33,8 +34,9 @@ func TLSTestServerWithCert(t *testing.T, handler http.HandlerFunc, certificate * c.Certificates = []tls.Certificate{*certificate} server := http.Server{ - TLSConfig: c, - Handler: handler, + TLSConfig: c, + Handler: handler, + ReadHeaderTimeout: 10 * time.Second, } l, err := net.Listen("tcp", "127.0.0.1:0") diff --git a/internal/upstreamoidc/upstreamoidc_test.go b/internal/upstreamoidc/upstreamoidc_test.go index f8f15ce1..2b403a9c 100644 --- a/internal/upstreamoidc/upstreamoidc_test.go +++ b/internal/upstreamoidc/upstreamoidc_test.go @@ -74,16 +74,16 @@ func TestProviderConfig(t *testing.T) { // Test JWTs generated with https://smallstep.com/docs/cli/crypto/jwt/: // step crypto keypair key.pub key.priv --kty RSA --no-password --insecure --force && echo '{"at_hash": "invalid-at-hash"}' | step crypto jwt sign --key key.priv --aud test-client-id --sub test-user --subtle --kid="test-kid" --jti="test-jti" - invalidAccessTokenHashIDToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRlc3Qta2lkIiwidHlwIjoiSldUIn0.eyJhdF9oYXNoIjoiaW52YWxpZC1hdC1oYXNoIiwiYXVkIjoidGVzdC1jbGllbnQtaWQiLCJpYXQiOjE2MDIyODM3OTEsImp0aSI6InRlc3QtanRpIiwibmJmIjoxNjAyMjgzNzkxLCJzdWIiOiJ0ZXN0LXVzZXIifQ.jryXr4jiwcf79wBLaHpjdclEYHoUFGhvTu95QyA6Hnk9NQ0x1vsWYurtj7a8uKydNPryC_HNZi9QTAE_tRIJjycseog3695-5y4B4EZlqL-a94rdOtffuF2O_lnPbKvoja9EKNrp0kLBCftFRHhLAEwuP0N9E5padZwPpIGK0yE_JqljnYgCySvzsQu7tasR38yaULny13h3mtp2WRHPG5DrLyuBuF8Z01hSgRi5hGcVpgzTwBgV5-eMaSUCUo-ZDkqUsLQI6dVlaikCSKYZRb53HeexH0tB_R9PJJHY7mIr-rS76kkQEx9pLuVnheIH9Oc6zbdYWg-zWMijopA8Pg" //nolint: gosec + invalidAccessTokenHashIDToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRlc3Qta2lkIiwidHlwIjoiSldUIn0.eyJhdF9oYXNoIjoiaW52YWxpZC1hdC1oYXNoIiwiYXVkIjoidGVzdC1jbGllbnQtaWQiLCJpYXQiOjE2MDIyODM3OTEsImp0aSI6InRlc3QtanRpIiwibmJmIjoxNjAyMjgzNzkxLCJzdWIiOiJ0ZXN0LXVzZXIifQ.jryXr4jiwcf79wBLaHpjdclEYHoUFGhvTu95QyA6Hnk9NQ0x1vsWYurtj7a8uKydNPryC_HNZi9QTAE_tRIJjycseog3695-5y4B4EZlqL-a94rdOtffuF2O_lnPbKvoja9EKNrp0kLBCftFRHhLAEwuP0N9E5padZwPpIGK0yE_JqljnYgCySvzsQu7tasR38yaULny13h3mtp2WRHPG5DrLyuBuF8Z01hSgRi5hGcVpgzTwBgV5-eMaSUCUo-ZDkqUsLQI6dVlaikCSKYZRb53HeexH0tB_R9PJJHY7mIr-rS76kkQEx9pLuVnheIH9Oc6zbdYWg-zWMijopA8Pg" //nolint:gosec // step crypto keypair key.pub key.priv --kty RSA --no-password --insecure --force && echo '{"nonce": "invalid-nonce"}' | step crypto jwt sign --key key.priv --aud test-client-id --sub test-user --subtle --kid="test-kid" --jti="test-jti" - invalidNonceIDToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRlc3Qta2lkIiwidHlwIjoiSldUIn0.eyJhdWQiOiJ0ZXN0LWNsaWVudC1pZCIsImlhdCI6MTYwMjI4Mzc0MSwianRpIjoidGVzdC1qdGkiLCJuYmYiOjE2MDIyODM3NDEsIm5vbmNlIjoiaW52YWxpZC1ub25jZSIsInN1YiI6InRlc3QtdXNlciJ9.PRpq-7j5djaIAkraL-8t8ad9Xm4hM8RW67gyD1VIe0BecWeBFxsTuh3SZVKM9zmcwTgjudsyn8kQOwipDa49IN4PV8FcJA_uUJZi2wiqGJUSTG2K5I89doV_7e0RM1ZYIDDW1G2heKJNW7MbKkX7iEPr7u4MyEzswcPcupbyDA-CQFeL95vgwawoqa6yO94ympTbozqiNfj6Xyw_nHtThQnstjWsJZ9s2mUgppZezZv4HZYTQ7c3e_bzwhWgCzh2CSDJn9_Ra_n_4GcVkpHbsHTP35dFsnf0vactPx6CAu6A1-Apk-BruCktpZ3B4Ercf1UnUOHdGqzQKJtqvB03xQ" //nolint: gosec + invalidNonceIDToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRlc3Qta2lkIiwidHlwIjoiSldUIn0.eyJhdWQiOiJ0ZXN0LWNsaWVudC1pZCIsImlhdCI6MTYwMjI4Mzc0MSwianRpIjoidGVzdC1qdGkiLCJuYmYiOjE2MDIyODM3NDEsIm5vbmNlIjoiaW52YWxpZC1ub25jZSIsInN1YiI6InRlc3QtdXNlciJ9.PRpq-7j5djaIAkraL-8t8ad9Xm4hM8RW67gyD1VIe0BecWeBFxsTuh3SZVKM9zmcwTgjudsyn8kQOwipDa49IN4PV8FcJA_uUJZi2wiqGJUSTG2K5I89doV_7e0RM1ZYIDDW1G2heKJNW7MbKkX7iEPr7u4MyEzswcPcupbyDA-CQFeL95vgwawoqa6yO94ympTbozqiNfj6Xyw_nHtThQnstjWsJZ9s2mUgppZezZv4HZYTQ7c3e_bzwhWgCzh2CSDJn9_Ra_n_4GcVkpHbsHTP35dFsnf0vactPx6CAu6A1-Apk-BruCktpZ3B4Ercf1UnUOHdGqzQKJtqvB03xQ" //nolint:gosec // step crypto keypair key.pub key.priv --kty RSA --no-password --insecure --force && echo '{"foo": "bar", "bat": "baz"}' | step crypto jwt sign --key key.priv --aud test-client-id --sub '' --subtle --kid="test-kid" --jti="test-jti" invalidSubClaim = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRlc3Qta2lkIiwidHlwIjoiSldUIn0.eyJhdWQiOiJ0ZXN0LWNsaWVudC1pZCIsImJhdCI6ImJheiIsImZvbyI6ImJhciIsImlhdCI6MTYxMDIxOTY5MCwianRpIjoidGVzdC1qdGkiLCJuYmYiOjE2MTAyMTk2OTB9.CXgUarh9A8QByF_ddw0W1Cldl_n1qmry2cZh9U0Avi5sl7hb1y22MadDLQslvnx0NKx6EdbwI-El7QxDy0SzwomJomFL7WNd5gGk-Ilq9O_emaHekbpphZ5kxyudsAGUYGxrg1zysv1k5JPhnLnOUMcE7wa0uPLDWnrlAMzqHvnbjI3lakZ8v4-dfAKUIUGi3ycwuAh9BdpydwAsSNOpGBM55-O8911dqVfZKiFNNUeHYE1qlnbhCz7_ykLrljao0nRBbEf9FXGolCdhIaglt0LtaZvll9T9StIbSpcRaBGuRm8toTezmhmHjU-iCc0jGeVKsp8eTyOuJllqDSS-uw" // step crypto keypair key.pub key.priv --kty RSA --no-password --insecure --force && echo '{"foo": "bar", "bat": "baz"}' | step crypto jwt sign --key key.priv --aud test-client-id --sub test-user --subtle --kid="test-kid" --jti="test-jti" - validIDToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRlc3Qta2lkIiwidHlwIjoiSldUIn0.eyJhdWQiOiJ0ZXN0LWNsaWVudC1pZCIsImJhdCI6ImJheiIsImZvbyI6ImJhciIsImlhdCI6MTYwNjc2ODU5MywianRpIjoidGVzdC1qdGkiLCJuYmYiOjE2MDY3Njg1OTMsInN1YiI6InRlc3QtdXNlciJ9.DuqVZ7pGhHqKz7gNr4j2W1s1N8YrSltktH4wW19L4oD1OE2-O72jAnNj5xdjilsa8l7h9ox-5sMF0Tkh3BdRlHQK9dEtNm9tW-JreUnWJ3LCqUs-LZp4NG7edvq2sH_1Bn7O2_NQV51s8Pl04F60CndjQ4NM-6WkqDQTKyY6vJXU7idvM-6TM2HJZK-Na88cOJ9KIK37tL5DhcbsHVF47Dq8uPZ0KbjNQjJLAIi_1GeQBgc6yJhDUwRY4Xu6S0dtTHA6xTI8oSXoamt4bkViEHfJBp97LZQiNz8mku5pVc0aNwP1p4hMHxRHhLXrJjbh-Hx4YFjxtOnIq9t1mHlD4A" //nolint: gosec + validIDToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRlc3Qta2lkIiwidHlwIjoiSldUIn0.eyJhdWQiOiJ0ZXN0LWNsaWVudC1pZCIsImJhdCI6ImJheiIsImZvbyI6ImJhciIsImlhdCI6MTYwNjc2ODU5MywianRpIjoidGVzdC1qdGkiLCJuYmYiOjE2MDY3Njg1OTMsInN1YiI6InRlc3QtdXNlciJ9.DuqVZ7pGhHqKz7gNr4j2W1s1N8YrSltktH4wW19L4oD1OE2-O72jAnNj5xdjilsa8l7h9ox-5sMF0Tkh3BdRlHQK9dEtNm9tW-JreUnWJ3LCqUs-LZp4NG7edvq2sH_1Bn7O2_NQV51s8Pl04F60CndjQ4NM-6WkqDQTKyY6vJXU7idvM-6TM2HJZK-Na88cOJ9KIK37tL5DhcbsHVF47Dq8uPZ0KbjNQjJLAIi_1GeQBgc6yJhDUwRY4Xu6S0dtTHA6xTI8oSXoamt4bkViEHfJBp97LZQiNz8mku5pVc0aNwP1p4hMHxRHhLXrJjbh-Hx4YFjxtOnIq9t1mHlD4A" //nolint:gosec ) t.Run("PasswordCredentialsGrantAndValidateTokens", func(t *testing.T) { @@ -699,7 +699,7 @@ func TestProviderConfig(t *testing.T) { require.Equal(t, tt.wantNumRequests, numRequests, "did not make expected number of requests to revocation endpoint") - if tt.wantErr != "" || tt.wantErrRegexp != "" { // nolint:nestif + if tt.wantErr != "" || tt.wantErrRegexp != "" { //nolint:nestif if tt.wantErr != "" { require.EqualError(t, err, tt.wantErr) } else { diff --git a/pkg/conciergeclient/conciergeclient_test.go b/pkg/conciergeclient/conciergeclient_test.go index 6787cc92..c0af26f4 100644 --- a/pkg/conciergeclient/conciergeclient_test.go +++ b/pkg/conciergeclient/conciergeclient_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package conciergeclient @@ -8,7 +8,7 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "testing" @@ -224,7 +224,7 @@ func TestExchangeToken(t *testing.T) { require.Equal(t, "/apis/login.concierge.pinniped.dev/v1alpha1/tokencredentialrequests", r.URL.Path) require.Equal(t, "application/json", r.Header.Get("content-type")) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) require.NoError(t, err) require.JSONEq(t, `{ diff --git a/pkg/oidcclient/filesession/cachefile.go b/pkg/oidcclient/filesession/cachefile.go index 9ea46bc0..fb857875 100644 --- a/pkg/oidcclient/filesession/cachefile.go +++ b/pkg/oidcclient/filesession/cachefile.go @@ -1,13 +1,12 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -// Package cachefile implements the file format for session caches. +// Package filesession implements the file format for session caches. package filesession import ( "errors" "fmt" - "io/ioutil" "os" "reflect" "sort" @@ -55,7 +54,7 @@ type ( // readSessionCache loads a sessionCache from a path on disk. If the requested path does not exist, it returns an empty cache. func readSessionCache(path string) (*sessionCache, error) { - cacheYAML, err := ioutil.ReadFile(path) + cacheYAML, err := os.ReadFile(path) if err != nil { if errors.Is(err, os.ErrNotExist) { // If the file was not found, generate a freshly initialized empty cache. @@ -91,7 +90,7 @@ func (c *sessionCache) writeTo(path string) error { // Marshal the session back to YAML and save it to the file. cacheYAML, err := yaml.Marshal(c) if err == nil { - err = ioutil.WriteFile(path, cacheYAML, 0600) + err = os.WriteFile(path, cacheYAML, 0600) } return err } diff --git a/pkg/oidcclient/filesession/filesession_test.go b/pkg/oidcclient/filesession/filesession_test.go index 4b7f8b0b..ed684825 100644 --- a/pkg/oidcclient/filesession/filesession_test.go +++ b/pkg/oidcclient/filesession/filesession_test.go @@ -1,11 +1,10 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package filesession import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -49,7 +48,7 @@ func TestGetToken(t *testing.T) { }, { name: "file lock error", - makeTestFile: func(t *testing.T, tmp string) { require.NoError(t, ioutil.WriteFile(tmp, []byte(""), 0600)) }, + makeTestFile: func(t *testing.T, tmp string) { require.NoError(t, os.WriteFile(tmp, []byte(""), 0600)) }, trylockFunc: func(t *testing.T) error { return fmt.Errorf("some lock error") }, unlockFunc: func(t *testing.T) error { require.Fail(t, "should not be called"); return nil }, key: oidcclient.SessionCacheKey{}, @@ -58,7 +57,7 @@ func TestGetToken(t *testing.T) { { name: "invalid file", makeTestFile: func(t *testing.T, tmp string) { - require.NoError(t, ioutil.WriteFile(tmp, []byte("invalid yaml"), 0600)) + require.NoError(t, os.WriteFile(tmp, []byte("invalid yaml"), 0600)) }, key: oidcclient.SessionCacheKey{}, wantErrors: []string{ @@ -67,7 +66,7 @@ func TestGetToken(t *testing.T) { }, { name: "invalid file, fail to unlock", - makeTestFile: func(t *testing.T, tmp string) { require.NoError(t, ioutil.WriteFile(tmp, []byte("invalid"), 0600)) }, + makeTestFile: func(t *testing.T, tmp string) { require.NoError(t, os.WriteFile(tmp, []byte("invalid"), 0600)) }, trylockFunc: func(t *testing.T) error { return nil }, unlockFunc: func(t *testing.T) error { return fmt.Errorf("some unlock error") }, key: oidcclient.SessionCacheKey{}, @@ -262,7 +261,7 @@ func TestPutToken(t *testing.T) { { name: "fail to create directory", makeTestFile: func(t *testing.T, tmp string) { - require.NoError(t, ioutil.WriteFile(filepath.Dir(tmp), []byte{}, 0600)) + require.NoError(t, os.WriteFile(filepath.Dir(tmp), []byte{}, 0600)) }, wantErrors: []string{ "could not create session cache directory: mkdir TEMPDIR: not a directory", diff --git a/pkg/oidcclient/login.go b/pkg/oidcclient/login.go index 3ff1b9a4..93b0b18a 100644 --- a/pkg/oidcclient/login.go +++ b/pkg/oidcclient/login.go @@ -861,7 +861,7 @@ func (h *handlerState) handleAuthCodeCallback(w http.ResponseWriter, r *http.Req }() var params url.Values - if h.useFormPost { // nolint:nestif + if h.useFormPost { //nolint:nestif // Return HTTP 405 for anything that's not a POST or an OPTIONS request. if r.Method != http.MethodPost && r.Method != http.MethodOptions { h.logger.V(plog.KlogLevelDebug).Info("Pinniped: Got unexpected request on callback listener", "method", r.Method) @@ -969,8 +969,9 @@ func (h *handlerState) serve(listener net.Listener) func() { mux := http.NewServeMux() mux.Handle(h.callbackPath, httperr.HandlerFunc(h.handleAuthCodeCallback)) srv := http.Server{ - Handler: securityheader.Wrap(mux), - BaseContext: func(_ net.Listener) context.Context { return h.ctx }, + Handler: securityheader.Wrap(mux), + BaseContext: func(_ net.Listener) context.Context { return h.ctx }, + ReadHeaderTimeout: 10 * time.Second, } go func() { _ = srv.Serve(listener) }() return func() { diff --git a/pkg/oidcclient/login_test.go b/pkg/oidcclient/login_test.go index 2d8b266e..11269fb7 100644 --- a/pkg/oidcclient/login_test.go +++ b/pkg/oidcclient/login_test.go @@ -10,7 +10,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/http/httptest" @@ -72,7 +72,7 @@ func newClientForServer(server *httptest.Server) *http.Client { return phttp.Default(pool) } -func TestLogin(t *testing.T) { // nolint:gocyclo +func TestLogin(t *testing.T) { //nolint:gocyclo time1 := time.Date(2035, 10, 12, 13, 14, 15, 16, time.UTC) time1Unix := int64(2075807775) require.Equal(t, time1Unix, time1.Add(2*time.Minute).Unix()) @@ -1040,7 +1040,7 @@ func TestLogin(t *testing.T) { // nolint:gocyclo return &http.Response{ StatusCode: http.StatusOK, Header: http.Header{"content-type": []string{"application/json"}}, - Body: ioutil.NopCloser(strings.NewReader(string(jsonResponseBody))), + Body: io.NopCloser(strings.NewReader(string(jsonResponseBody))), }, nil default: require.FailNow(t, fmt.Sprintf("saw unexpected http call from the CLI: %s", req.URL.String())) @@ -1890,7 +1890,7 @@ func TestLogin(t *testing.T) { // nolint:gocyclo for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { - testLogger := testlogger.NewLegacy(t) // nolint: staticcheck // old test with lots of log statements + testLogger := testlogger.NewLegacy(t) //nolint:staticcheck // old test with lots of log statements klog.SetLogger(testLogger.Logger) tok, err := Login(tt.issuer, tt.clientID, @@ -2333,7 +2333,7 @@ func TestHandleAuthCodeCallback(t *testing.T) { state: state.State("test-state"), pkce: pkce.Code("test-pkce"), nonce: nonce.Nonce("test-nonce"), - logger: plog.Logr(), // nolint: staticcheck // old test with no log assertions + logger: plog.Logr(), //nolint:staticcheck // old test with no log assertions issuer: "https://valid-issuer.com/with/some/path", } if tt.opt != nil { diff --git a/test/integration/cli_test.go b/test/integration/cli_test.go index 1e2d0357..1a2554d1 100644 --- a/test/integration/cli_test.go +++ b/test/integration/cli_test.go @@ -9,7 +9,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/url" "os" "os/exec" @@ -94,7 +93,7 @@ func TestCLIGetKubeconfigStaticToken_Parallel(t *testing.T) { t.Run("whoami", func(t *testing.T) { // Validate that `pinniped whoami` returns the correct identity. kubeconfigPath := filepath.Join(testutil.TempDir(t), "whoami-kubeconfig") - require.NoError(t, ioutil.WriteFile(kubeconfigPath, []byte(stdout), 0600)) + require.NoError(t, os.WriteFile(kubeconfigPath, []byte(stdout), 0600)) assertWhoami( ctx, t, @@ -174,7 +173,7 @@ func TestCLILoginOIDC_Browser(t *testing.T) { env := testlib.IntegrationEnv(t) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) - defer cancel() + t.Cleanup(cancel) // Build pinniped CLI. pinnipedExe := testlib.PinnipedCLIPath(t) @@ -426,7 +425,7 @@ func oidcLoginCommand(ctx context.Context, t *testing.T, pinnipedExe string, ses // If there is a custom CA bundle, pass it via --ca-bundle and a temporary file. if env.CLIUpstreamOIDC.CABundle != "" { path := filepath.Join(testutil.TempDir(t), "test-ca.pem") - require.NoError(t, ioutil.WriteFile(path, []byte(env.CLIUpstreamOIDC.CABundle), 0600)) + require.NoError(t, os.WriteFile(path, []byte(env.CLIUpstreamOIDC.CABundle), 0600)) cmd.Args = append(cmd.Args, "--ca-bundle", path) } diff --git a/test/integration/concierge_client_test.go b/test/integration/concierge_client_test.go index f5613d77..8a36f7f4 100644 --- a/test/integration/concierge_client_test.go +++ b/test/integration/concierge_client_test.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package integration @@ -18,10 +18,10 @@ import ( // Test certificate and private key that should get an authentication error. Generated with cfssl [1], like this: // -// $ brew install cfssl -// $ cfssl print-defaults csr | cfssl genkey -initca - | cfssljson -bare ca -// $ cfssl print-defaults csr | cfssl gencert -ca ca.pem -ca-key ca-key.pem -hostname=testuser - | cfssljson -bare client -// $ cat client.pem client-key.pem +// $ brew install cfssl +// $ cfssl print-defaults csr | cfssl genkey -initca - | cfssljson -bare ca +// $ cfssl print-defaults csr | cfssl gencert -ca ca.pem -ca-key ca-key.pem -hostname=testuser - | cfssljson -bare client +// $ cat client.pem client-key.pem // // [1]: https://github.com/cloudflare/cfssl var ( diff --git a/test/integration/concierge_impersonation_proxy_test.go b/test/integration/concierge_impersonation_proxy_test.go index c4831909..d09f7c82 100644 --- a/test/integration/concierge_impersonation_proxy_test.go +++ b/test/integration/concierge_impersonation_proxy_test.go @@ -15,7 +15,7 @@ import ( "encoding/json" "encoding/pem" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/url" @@ -1103,7 +1103,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl localEchoFile := filepath.Join(tempDir, filepath.Base(remoteEchoFile)) _, err = runKubectl(t, kubeconfigPath, envVarsWithProxy, "cp", fmt.Sprintf("%s/%s:%s", runningTestPod.Namespace, runningTestPod.Name, remoteEchoFile), localEchoFile) require.NoError(t, err, `"kubectl cp" failed`) - localEchoFileData, err := ioutil.ReadFile(localEchoFile) + localEchoFileData, err := os.ReadFile(localEchoFile) require.NoError(t, err) require.Equal(t, echoString+"\n", string(localEchoFileData)) @@ -1197,7 +1197,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl defer func() { requireEventually.NoError(resp.Body.Close()) }() } if err != nil && resp != nil { - body, _ := ioutil.ReadAll(resp.Body) + body, _ := io.ReadAll(resp.Body) t.Logf("websocket dial failed: %d:%s", resp.StatusCode, body) } requireEventually.NoError(err) @@ -1283,7 +1283,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl require.NoError(t, err) response, err := httpClient.Do(getConfigmapRequest) require.NoError(t, err) - body, _ := ioutil.ReadAll(response.Body) + body, _ := io.ReadAll(response.Body) t.Logf("http2 status code: %d, proto: %s, message: %s", response.StatusCode, response.Proto, body) require.Equal(t, "HTTP/2.0", response.Proto) require.Equal(t, http.StatusOK, response.StatusCode) @@ -2212,7 +2212,7 @@ func getImpersonationKubeconfig(t *testing.T, env *testlib.TestEnv, impersonatio // Write the kubeconfig to a temp file. kubeconfigPath := filepath.Join(tempDir, "kubeconfig.yaml") - require.NoError(t, ioutil.WriteFile(kubeconfigPath, []byte(kubeconfigYAML), 0600)) + require.NoError(t, os.WriteFile(kubeconfigPath, []byte(kubeconfigYAML), 0600)) return kubeconfigPath, envVarsWithProxy, tempDir } diff --git a/test/integration/e2e_test.go b/test/integration/e2e_test.go index 545abb6e..ea356fc7 100644 --- a/test/integration/e2e_test.go +++ b/test/integration/e2e_test.go @@ -11,7 +11,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/url" "os" "os/exec" @@ -84,7 +83,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { testCABundlePath := filepath.Join(testutil.TempDir(t), "test-ca.pem") testCABundlePEM := []byte(string(ca.Bundle()) + "\n" + env.SupervisorUpstreamOIDC.CABundle) testCABundleBase64 := base64.StdEncoding.EncodeToString(testCABundlePEM) - require.NoError(t, ioutil.WriteFile(testCABundlePath, testCABundlePEM, 0600)) + require.NoError(t, os.WriteFile(testCABundlePath, testCABundlePEM, 0600)) // Use the CA to issue a TLS server cert. t.Logf("issuing test certificate") @@ -304,7 +303,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { t.Logf("waiting for kubectl to output namespace list") // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlOutputBytes, _ := io.ReadAll(ptyFile) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes)) t.Logf("first kubectl command took %s", time.Since(start).String()) @@ -435,10 +434,10 @@ func TestE2EFullIntegration_Browser(t *testing.T) { t.Logf("waiting for kubectl to output namespace list") // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlPtyOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlPtyOutputBytes, _ := io.ReadAll(ptyFile) if kubectlStdoutPipe != nil { // On non-MacOS check that stdout of the CLI contains the expected output. - kubectlStdOutOutputBytes, _ := ioutil.ReadAll(kubectlStdoutPipe) + kubectlStdOutOutputBytes, _ := io.ReadAll(kubectlStdoutPipe) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes)) } else { // On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. @@ -535,7 +534,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlOutputBytes, _ := io.ReadAll(ptyFile) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes)) t.Logf("first kubectl command took %s", time.Since(start).String()) @@ -619,7 +618,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlOutputBytes, _ := io.ReadAll(ptyFile) kubectlOutput := string(kubectlOutputBytes) // The output should look like an authentication failure, because the OIDCIdentityProvider disallows password grants. @@ -676,7 +675,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlOutputBytes, _ := io.ReadAll(ptyFile) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes)) t.Logf("first kubectl command took %s", time.Since(start).String()) @@ -744,7 +743,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlOutputBytes, _ := io.ReadAll(ptyFile) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes)) t.Logf("first kubectl command took %s", time.Since(start).String()) @@ -808,7 +807,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlOutputBytes, _ := io.ReadAll(ptyFile) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes)) t.Logf("first kubectl command took %s", time.Since(start).String()) @@ -876,7 +875,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) { // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlOutputBytes, _ := io.ReadAll(ptyFile) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes)) t.Logf("first kubectl command took %s", time.Since(start).String()) @@ -1417,7 +1416,7 @@ func runPinnipedGetKubeconfig(t *testing.T, env *testlib.TestEnv, pinnipedExe st require.Equal(t, []string{"login", "oidc"}, restConfig.ExecProvider.Args[:2]) kubeconfigPath := filepath.Join(tempDir, "kubeconfig.yaml") - require.NoError(t, ioutil.WriteFile(kubeconfigPath, []byte(kubeconfigYAML), 0600)) + require.NoError(t, os.WriteFile(kubeconfigPath, []byte(kubeconfigYAML), 0600)) return kubeconfigPath } diff --git a/test/integration/supervisor_discovery_test.go b/test/integration/supervisor_discovery_test.go index 2d828e4c..404fceab 100644 --- a/test/integration/supervisor_discovery_test.go +++ b/test/integration/supervisor_discovery_test.go @@ -10,7 +10,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -587,7 +586,7 @@ func requireSuccessEndpointResponse(t *testing.T, endpointURL, issuer, caBundle requireEventually.Equal(http.StatusOK, response.StatusCode) - responseBody, err = ioutil.ReadAll(response.Body) + responseBody, err = io.ReadAll(response.Body) requireEventually.NoError(err) }, 2*time.Minute, 200*time.Millisecond) @@ -662,7 +661,7 @@ func newHTTPClient(t *testing.T, caBundle string, dnsOverrides map[string]string caCertPool.AppendCertsFromPEM([]byte(caBundle)) c.Transport = &http.Transport{ DialContext: overrideDialContext, - TLSClientConfig: &tls.Config{MinVersion: ptls.SecureTLSConfigMinTLSVersion, RootCAs: caCertPool}, //nolint: gosec // this seems to be a false flag, min tls version is 1.3 in normal mode or 1.2 in fips mode + TLSClientConfig: &tls.Config{MinVersion: ptls.SecureTLSConfigMinTLSVersion, RootCAs: caCertPool}, //nolint:gosec // this seems to be a false flag, min tls version is 1.3 in normal mode or 1.2 in fips mode } } else { c.Transport = &http.Transport{ diff --git a/test/integration/supervisor_healthz_test.go b/test/integration/supervisor_healthz_test.go index 8e4519af..d32d4a82 100644 --- a/test/integration/supervisor_healthz_test.go +++ b/test/integration/supervisor_healthz_test.go @@ -7,7 +7,7 @@ import ( "context" "crypto/tls" "fmt" - "io/ioutil" + "io" "net/http" "testing" "time" @@ -58,7 +58,7 @@ func httpGet(ctx context.Context, t *testing.T, client *http.Client, url string, require.NoError(t, err) require.Equal(t, expectedStatus, response.StatusCode) - responseBody, err := ioutil.ReadAll(response.Body) + responseBody, err := io.ReadAll(response.Body) require.NoError(t, err) err = response.Body.Close() require.NoError(t, err) diff --git a/test/integration/supervisor_login_test.go b/test/integration/supervisor_login_test.go index 47587db7..2c9294aa 100644 --- a/test/integration/supervisor_login_test.go +++ b/test/integration/supervisor_login_test.go @@ -10,7 +10,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" @@ -1701,7 +1701,7 @@ func requestAuthorizationUsingCLIPasswordFlow(t *testing.T, downstreamAuthorizeU return false, nil } defer func() { _ = authResponse.Body.Close() }() - responseBody, err = ioutil.ReadAll(authResponse.Body) + responseBody, err = io.ReadAll(authResponse.Body) if err != nil { return false, nil } diff --git a/test/integration/supervisor_warnings_test.go b/test/integration/supervisor_warnings_test.go index 74b5aab0..e9b546eb 100644 --- a/test/integration/supervisor_warnings_test.go +++ b/test/integration/supervisor_warnings_test.go @@ -7,7 +7,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" "net/url" "os" "os/exec" @@ -65,7 +64,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) { testCABundlePath := filepath.Join(tempDir, "test-ca.pem") testCABundlePEM := []byte(string(ca.Bundle()) + "\n" + env.SupervisorUpstreamOIDC.CABundle) testCABundleBase64 := base64.StdEncoding.EncodeToString(testCABundlePEM) - require.NoError(t, ioutil.WriteFile(testCABundlePath, testCABundlePEM, 0600)) + require.NoError(t, os.WriteFile(testCABundlePath, testCABundlePEM, 0600)) // Use the CA to issue a TLS server cert. t.Logf("issuing test certificate") @@ -149,10 +148,10 @@ func TestSupervisorWarnings_Browser(t *testing.T) { t.Logf("waiting for kubectl to output namespace list") // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlPtyOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlPtyOutputBytes, _ := io.ReadAll(ptyFile) if kubectlStdoutPipe != nil { // On non-MacOS check that stdout of the CLI contains the expected output. - kubectlStdOutOutputBytes, _ := ioutil.ReadAll(kubectlStdoutPipe) + kubectlStdOutOutputBytes, _ := io.ReadAll(kubectlStdoutPipe) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes)) } else { // On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. @@ -225,10 +224,10 @@ func TestSupervisorWarnings_Browser(t *testing.T) { t.Logf("waiting for kubectl to output namespace list") // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlPtyOutputBytes2, _ := ioutil.ReadAll(ptyFile2) + kubectlPtyOutputBytes2, _ := io.ReadAll(ptyFile2) if kubectlStdoutPipe2 != nil { // On non-MacOS check that stdout of the CLI contains the expected output. - kubectlStdOutOutputBytes2, _ := ioutil.ReadAll(kubectlStdoutPipe2) + kubectlStdOutOutputBytes2, _ := io.ReadAll(kubectlStdoutPipe2) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes2)) } else { // On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. @@ -292,10 +291,10 @@ func TestSupervisorWarnings_Browser(t *testing.T) { t.Logf("waiting for kubectl to output namespace list") // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlPtyOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlPtyOutputBytes, _ := io.ReadAll(ptyFile) if kubectlStdoutPipe != nil { // On non-MacOS check that stdout of the CLI contains the expected output. - kubectlStdOutOutputBytes, _ := ioutil.ReadAll(kubectlStdoutPipe) + kubectlStdOutOutputBytes, _ := io.ReadAll(kubectlStdoutPipe) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes)) } else { // On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. @@ -336,10 +335,10 @@ func TestSupervisorWarnings_Browser(t *testing.T) { t.Logf("waiting for kubectl to output namespace list") // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlPtyOutputBytes2, _ := ioutil.ReadAll(ptyFile2) + kubectlPtyOutputBytes2, _ := io.ReadAll(ptyFile2) if kubectlStdoutPipe2 != nil { // On non-MacOS check that stdout of the CLI contains the expected output. - kubectlStdOutOutputBytes2, _ := ioutil.ReadAll(kubectlStdoutPipe2) + kubectlStdOutOutputBytes2, _ := io.ReadAll(kubectlStdoutPipe2) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes2)) } else { // On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. @@ -460,10 +459,10 @@ func TestSupervisorWarnings_Browser(t *testing.T) { t.Logf("waiting for kubectl to output namespace list") // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlPtyOutputBytes, _ := ioutil.ReadAll(ptyFile) + kubectlPtyOutputBytes, _ := io.ReadAll(ptyFile) if kubectlStdoutPipe != nil { // On non-MacOS check that stdout of the CLI contains the expected output. - kubectlStdOutOutputBytes, _ := ioutil.ReadAll(kubectlStdoutPipe) + kubectlStdOutOutputBytes, _ := io.ReadAll(kubectlStdoutPipe) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes)) } else { // On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. @@ -536,10 +535,10 @@ func TestSupervisorWarnings_Browser(t *testing.T) { t.Logf("waiting for kubectl to output namespace list") // Read all output from the subprocess until EOF. // Ignore any errors returned because there is always an error on linux. - kubectlPtyOutputBytes2, _ := ioutil.ReadAll(ptyFile2) + kubectlPtyOutputBytes2, _ := io.ReadAll(ptyFile2) if kubectlStdoutPipe2 != nil { // On non-MacOS check that stdout of the CLI contains the expected output. - kubectlStdOutOutputBytes2, _ := ioutil.ReadAll(kubectlStdoutPipe2) + kubectlStdOutOutputBytes2, _ := io.ReadAll(kubectlStdoutPipe2) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes2)) } else { // On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. diff --git a/test/testlib/access.go b/test/testlib/access.go index dd299d09..98ad4664 100644 --- a/test/testlib/access.go +++ b/test/testlib/access.go @@ -1,11 +1,10 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testlib import ( "context" - "io/ioutil" "os" "os/exec" "testing" @@ -154,7 +153,7 @@ func runKubectlGetNamespaces(t *testing.T, kubeConfigYAML string) (string, error f := writeStringToTempFile(t, "pinniped-generated-kubeconfig-*", kubeConfigYAML) - //nolint: gosec // It's okay that we are passing f.Name() to an exec command here. It was created above. + //nolint:gosec // It's okay that we are passing f.Name() to an exec command here. It was created above. output, err := exec.Command( "kubectl", "get", "namespace", "--kubeconfig", f.Name(), ).CombinedOutput() @@ -164,7 +163,7 @@ func runKubectlGetNamespaces(t *testing.T, kubeConfigYAML string) (string, error func writeStringToTempFile(t *testing.T, filename string, kubeConfigYAML string) *os.File { t.Helper() - f, err := ioutil.TempFile("", filename) + f, err := os.CreateTemp("", filename) require.NoError(t, err) deferMe := func() { err := os.Remove(f.Name()) diff --git a/test/testlib/cli.go b/test/testlib/cli.go index b3cfc8b4..b347bf9c 100644 --- a/test/testlib/cli.go +++ b/test/testlib/cli.go @@ -1,10 +1,9 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testlib import ( - "io/ioutil" "os" "os/exec" "path/filepath" @@ -17,7 +16,7 @@ import ( "go.pinniped.dev/internal/testutil" ) -//nolint: gochecknoglobals +//nolint:gochecknoglobals var pinnipedCLIBinaryCache struct { buf []byte mutex sync.Mutex @@ -38,7 +37,7 @@ func PinnipedCLIPath(t *testing.T) string { path := filepath.Join(testutil.TempDir(t), "pinniped") if pinnipedCLIBinaryCache.buf != nil { t.Log("using previously built pinniped CLI binary") - require.NoError(t, ioutil.WriteFile(path, pinnipedCLIBinaryCache.buf, 0500)) + require.NoError(t, os.WriteFile(path, pinnipedCLIBinaryCache.buf, 0500)) return path } @@ -49,7 +48,7 @@ func PinnipedCLIPath(t *testing.T) string { t.Logf("built CLI binary in %s", time.Since(start).Round(time.Millisecond)) // Fill our cache so we don't have to do this again. - pinnipedCLIBinaryCache.buf, err = ioutil.ReadFile(path) + pinnipedCLIBinaryCache.buf, err = os.ReadFile(path) require.NoError(t, err, string(output)) return path diff --git a/test/testlib/client.go b/test/testlib/client.go index c5e96339..481adf90 100644 --- a/test/testlib/client.go +++ b/test/testlib/client.go @@ -1,4 +1,4 @@ -// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testlib @@ -10,7 +10,6 @@ import ( "encoding/hex" "fmt" "io" - "io/ioutil" "os" "testing" "time" @@ -54,7 +53,7 @@ func NewClientsetForKubeConfig(t *testing.T, kubeConfig string) kubernetes.Inter } func NewRestConfigFromKubeconfig(t *testing.T, kubeConfig string) *rest.Config { - kubeConfigFile, err := ioutil.TempFile("", "pinniped-cli-test-*") + kubeConfigFile, err := os.CreateTemp("", "pinniped-cli-test-*") require.NoError(t, err) defer func() { require.NoError(t, os.Remove(kubeConfigFile.Name())) diff --git a/test/testlib/env.go b/test/testlib/env.go index a1df0e97..fd79fd85 100644 --- a/test/testlib/env.go +++ b/test/testlib/env.go @@ -5,7 +5,6 @@ package testlib import ( "encoding/base64" - "io/ioutil" "os" "sort" "strings" @@ -118,7 +117,7 @@ func (e *TestEnv) ProxyEnv() []string { // memoizedTestEnvsByTest maps *testing.T pointers to *TestEnv. It exists so that we don't do all the // environment parsing N times per test and so that any implicit assertions happen only once. -var memoizedTestEnvsByTest sync.Map //nolint: gochecknoglobals +var memoizedTestEnvsByTest sync.Map //nolint:gochecknoglobals // IntegrationEnv gets the integration test environment from OS environment variables. This // method also implies SkipUnlessIntegration(). @@ -137,7 +136,7 @@ func IntegrationEnv(t *testing.T) *TestEnv { "must specify either PINNIPED_TEST_CLUSTER_CAPABILITY_YAML or PINNIPED_TEST_CLUSTER_CAPABILITY_FILE env var for integration tests", ) if capabilitiesDescriptionYAML == "" { - bytes, err := ioutil.ReadFile(capabilitiesDescriptionFile) + bytes, err := os.ReadFile(capabilitiesDescriptionFile) capabilitiesDescriptionYAML = string(bytes) require.NoError(t, err) } diff --git a/test/testlib/iplookup.go b/test/testlib/iplookup.go index 37ac68a8..1a6d5553 100644 --- a/test/testlib/iplookup.go +++ b/test/testlib/iplookup.go @@ -1,6 +1,7 @@ -// Copyright 2020 the Pinniped contributors. All Rights Reserved. +// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build !go1.14 // +build !go1.14 package testlib diff --git a/test/testlib/iplookup_go1.14.go b/test/testlib/iplookup_go1.14.go index 622e4236..42f18e89 100644 --- a/test/testlib/iplookup_go1.14.go +++ b/test/testlib/iplookup_go1.14.go @@ -1,7 +1,7 @@ // Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//nolint:goimports // not an import +//go:build go1.14 // +build go1.14 package testlib