Upgrade the linter and fix all new linter warnings

Also fix some tests that were broken by bumping golang and dependencies
in the previous commits.

Note that in addition to changes made to satisfy the linter which do not
impact the behavior of the code, this commit also adds ReadHeaderTimeout
to all usages of http.Server to satisfy the linter (and because it
seemed like a good suggestion).
This commit is contained in:
Ryan Richard 2022-08-24 14:45:55 -07:00
parent 03694d78a8
commit c6c2c525a6
105 changed files with 382 additions and 387 deletions

View File

@ -8,16 +8,13 @@ linters:
disable-all: true disable-all: true
enable: enable:
# default linters # default linters
- deadcode
- errcheck - errcheck
- gosimple - gosimple
- govet - govet
- ineffassign - ineffassign
- staticcheck - staticcheck
- structcheck
- typecheck - typecheck
- unused - unused
- varcheck
# additional linters for this project (we should disable these if they get annoying). # additional linters for this project (we should disable these if they get annoying).
- asciicheck - asciicheck

View File

@ -8,7 +8,6 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"io" "io"
"io/ioutil"
"log" "log"
"math" "math"
"os" "os"
@ -18,7 +17,7 @@ import (
_ "go.pinniped.dev/internal/crypto/ptls" _ "go.pinniped.dev/internal/crypto/ptls"
) )
//nolint: gochecknoglobals // these are swapped during unit tests. //nolint:gochecknoglobals // these are swapped during unit tests.
var ( var (
getenv = os.Getenv getenv = os.Getenv
fail = log.Fatalf fail = log.Fatalf
@ -35,11 +34,11 @@ func main() {
case "sleep": case "sleep":
sleep(math.MaxInt64) sleep(math.MaxInt64)
case "print": case "print":
certBytes, err := ioutil.ReadFile(getenv("CERT_PATH")) certBytes, err := os.ReadFile(getenv("CERT_PATH"))
if err != nil { if err != nil {
fail("could not read CERT_PATH: %v", err) 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 { if err != nil {
fail("could not read KEY_PATH: %v", err) fail("could not read KEY_PATH: %v", err)
} }

View File

@ -22,7 +22,7 @@ import (
supervisor "go.pinniped.dev/internal/supervisor/server" supervisor "go.pinniped.dev/internal/supervisor/server"
) )
// nolint: gochecknoglobals // these are swapped during unit tests. //nolint:gochecknoglobals // these are swapped during unit tests.
var ( var (
fail = plog.Fatal fail = plog.Fatal
subcommands = map[string]func(){ subcommands = map[string]func(){

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -7,7 +7,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
//nolint: gochecknoglobals //nolint:gochecknoglobals
var alphaCmd = &cobra.Command{ var alphaCmd = &cobra.Command{
Use: "alpha", Use: "alpha",
Short: "alpha", Short: "alpha",
@ -16,7 +16,7 @@ var alphaCmd = &cobra.Command{
Hidden: true, Hidden: true,
} }
//nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
rootCmd.AddCommand(alphaCmd) rootCmd.AddCommand(alphaCmd)
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -8,7 +8,7 @@ import (
"crypto/x509" "crypto/x509"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "os"
"strings" "strings"
"github.com/spf13/pflag" "github.com/spf13/pflag"
@ -85,7 +85,7 @@ func (f *caBundleFlag) String() string {
} }
func (f *caBundleFlag) Set(path string) error { func (f *caBundleFlag) Set(path string) error {
pem, err := ioutil.ReadFile(path) pem, err := os.ReadFile(path)
if err != nil { if err != nil {
return fmt.Errorf("could not read CA bundle path: %w", err) return fmt.Errorf("could not read CA bundle path: %w", err)
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -6,7 +6,7 @@ package cmd
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -54,10 +54,10 @@ func TestCABundleFlag(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
tmpdir := testutil.TempDir(t) tmpdir := testutil.TempDir(t)
emptyFilePath := filepath.Join(tmpdir, "empty") 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") 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{} f := caBundleFlag{}
require.Equal(t, "path", f.Type()) require.Equal(t, "path", f.Type())

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -14,7 +14,7 @@ import (
"github.com/spf13/cobra/doc" "github.com/spf13/cobra/doc"
) )
//nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
rootCmd.AddCommand(generateMarkdownHelpCommand()) rootCmd.AddCommand(generateMarkdownHelpCommand())
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -7,10 +7,10 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
//nolint: gochecknoglobals //nolint:gochecknoglobals
var getCmd = &cobra.Command{Use: "get", Short: "get"} var getCmd = &cobra.Command{Use: "get", Short: "get"}
//nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
rootCmd.AddCommand(getCmd) rootCmd.AddCommand(getCmd)
} }

View File

@ -10,7 +10,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"strconv" "strconv"
@ -48,7 +47,7 @@ func kubeconfigRealDeps() kubeconfigDeps {
} }
} }
// nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
getCmd.AddCommand(kubeconfigCommand(kubeconfigRealDeps())) getCmd.AddCommand(kubeconfigCommand(kubeconfigRealDeps()))
} }
@ -717,7 +716,7 @@ func validateKubeconfig(ctx context.Context, flags getKubeconfigParams, kubeconf
func countCACerts(pemData []byte) int { func countCACerts(pemData []byte) int {
pool := x509.NewCertPool() pool := x509.NewCertPool()
pool.AppendCertsFromPEM(pemData) pool.AppendCertsFromPEM(pemData)
return len(pool.Subjects()) // nolint: staticcheck // not system cert pool return len(pool.Subjects())
} }
func hasPendingStrategy(credentialIssuer *configv1alpha1.CredentialIssuer) bool { 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) 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 { if err != nil {
return nil, fmt.Errorf("unable to fetch IDP discovery data from issuer: could not read response body: %w", err) return nil, fmt.Errorf("unable to fetch IDP discovery data from issuer: could not read response body: %w", err)
} }

View File

@ -7,8 +7,8 @@ import (
"bytes" "bytes"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -34,12 +34,12 @@ func TestGetKubeconfig(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
tmpdir := testutil.TempDir(t) tmpdir := testutil.TempDir(t)
testOIDCCABundlePath := filepath.Join(tmpdir, "testca.pem") 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) testConciergeCA, err := certauthority.New("Test Concierge CA", 1*time.Hour)
require.NoError(t, err) require.NoError(t, err)
testConciergeCABundlePath := filepath.Join(tmpdir, "testconciergeca.pem") 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 { credentialIssuer := func() runtime.Object {
return &configv1alpha1.CredentialIssuer{ return &configv1alpha1.CredentialIssuer{
@ -2889,7 +2889,7 @@ func TestGetKubeconfig(t *testing.T) {
}) })
issuerEndpointPtr = &issuerEndpoint 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{ cmd := kubeconfigCommand(kubeconfigDeps{
getPathToSelf: func() (string, error) { getPathToSelf: func() (string, error) {
if tt.getPathToSelfErr != nil { if tt.getPathToSelfErr != nil {

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -9,7 +9,7 @@ import (
"k8s.io/client-go/tools/auth/exec" "k8s.io/client-go/tools/auth/exec"
) )
//nolint: gochecknoglobals //nolint:gochecknoglobals
var loginCmd = &cobra.Command{ var loginCmd = &cobra.Command{
Use: "login", Use: "login",
Short: "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. 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() { func init() {
rootCmd.AddCommand(loginCmd) rootCmd.AddCommand(loginCmd)
} }

View File

@ -9,7 +9,6 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@ -41,7 +40,7 @@ const (
upstreamIdentityProviderFlowEnvVarName = "PINNIPED_UPSTREAM_IDENTITY_PROVIDER_FLOW" upstreamIdentityProviderFlowEnvVarName = "PINNIPED_UPSTREAM_IDENTITY_PROVIDER_FLOW"
) )
// nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
loginCmd.AddCommand(oidcLoginCommand(oidcLoginCommandRealDeps())) loginCmd.AddCommand(oidcLoginCommand(oidcLoginCommandRealDeps()))
} }
@ -153,7 +152,7 @@ func runOIDCLogin(cmd *cobra.Command, deps oidcLoginCommandDeps, flags oidcLogin
// Initialize the login handler. // Initialize the login handler.
opts := []oidcclient.Option{ opts := []oidcclient.Option{
oidcclient.WithContext(cmd.Context()), 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.WithScopes(flags.scopes),
oidcclient.WithSessionCache(sessionCache), oidcclient.WithSessionCache(sessionCache),
} }
@ -317,7 +316,7 @@ func flowOptions(
func makeClient(caBundlePaths []string, caBundleData []string) (*http.Client, error) { func makeClient(caBundlePaths []string, caBundleData []string) (*http.Client, error) {
pool := x509.NewCertPool() pool := x509.NewCertPool()
for _, p := range caBundlePaths { for _, p := range caBundlePaths {
pem, err := ioutil.ReadFile(p) pem, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not read --ca-bundle: %w", err) 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 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 mustGetConfigDir returns a directory that follows the XDG base directory convention:
// 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 $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 { func mustGetConfigDir() string {
const xdgAppName = "pinniped" const xdgAppName = "pinniped"

View File

@ -8,7 +8,7 @@ import (
"context" "context"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io/ioutil" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
@ -36,7 +36,7 @@ func TestLoginOIDCCommand(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
tmpdir := testutil.TempDir(t) tmpdir := testutil.TempDir(t)
testCABundlePath := filepath.Join(tmpdir, "testca.pem") 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) time1 := time.Date(3020, 10, 12, 13, 14, 15, 16, time.UTC)
@ -483,8 +483,8 @@ func TestLoginOIDCCommand(t *testing.T) {
wantOptionsCount: 4, 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", 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{ 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:231 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:251 No concierge configured, skipping token credential exchange`,
}, },
}, },
{ {
@ -513,10 +513,10 @@ func TestLoginOIDCCommand(t *testing.T) {
wantOptionsCount: 11, wantOptionsCount: 11,
wantStdout: `{"kind":"ExecCredential","apiVersion":"client.authentication.k8s.io/v1beta1","spec":{"interactive":false},"status":{"token":"exchanged-token"}}` + "\n", wantStdout: `{"kind":"ExecCredential","apiVersion":"client.authentication.k8s.io/v1beta1","spec":{"interactive":false},"status":{"token":"exchanged-token"}}` + "\n",
wantLogs: []string{ 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:231 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: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:250 Successfully exchanged token for cluster credential.`, nowStr + ` pinniped-login cmd/login_oidc.go:249 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:256 caching cluster credential for future use.`,
}, },
}, },
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -21,7 +21,7 @@ import (
"go.pinniped.dev/pkg/oidcclient/oidctypes" "go.pinniped.dev/pkg/oidcclient/oidctypes"
) )
// nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
loginCmd.AddCommand(staticLoginCommand(staticLoginRealDeps())) loginCmd.AddCommand(staticLoginCommand(staticLoginRealDeps()))
} }

View File

@ -7,7 +7,7 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io/ioutil" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -32,7 +32,7 @@ func TestLoginStaticCommand(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
tmpdir := testutil.TempDir(t) tmpdir := testutil.TempDir(t)
testCABundlePath := filepath.Join(tmpdir, "testca.pem") 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") now, err := time.Parse(time.RFC3339Nano, "2038-12-07T23:37:26.953313745Z")
require.NoError(t, err) require.NoError(t, err)

View File

@ -11,7 +11,7 @@ import (
"go.pinniped.dev/internal/plog" "go.pinniped.dev/internal/plog"
) )
// nolint: gochecknoglobals //nolint:gochecknoglobals
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "pinniped", Use: "pinniped",
Short: "pinniped", Short: "pinniped",

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -10,7 +10,7 @@ import (
"k8s.io/component-base/version" "k8s.io/component-base/version"
) )
//nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
rootCmd.AddCommand(newVersionCommand()) rootCmd.AddCommand(newVersionCommand())
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package cmd package cmd
@ -24,7 +24,7 @@ import (
"go.pinniped.dev/internal/here" "go.pinniped.dev/internal/here"
) )
//nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
rootCmd.AddCommand(newWhoamiCommand(getRealConciergeClientset)) rootCmd.AddCommand(newWhoamiCommand(getRealConciergeClientset))
} }

View File

@ -13,7 +13,7 @@ import (
_ "go.pinniped.dev/internal/crypto/ptls" _ "go.pinniped.dev/internal/crypto/ptls"
) )
// nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
// browsers like chrome like to write to our std out which breaks our JSON ExecCredential output // 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 // thus we redirect the browser's std out to our std err

View File

@ -8,9 +8,14 @@ set -euo pipefail
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
cd "${ROOT}" cd "${ROOT}"
# Print the Go version.
go version
# Install the same version of the linter that is used in the CI pipelines # 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. # 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 # Whenever the linter is updated in the CI pipelines, it should also be
# updated here to make local development more convenient. # 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 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)."

View File

@ -10,22 +10,22 @@ import (
"k8s.io/apiserver/pkg/authentication/user" "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. // of a single token string.
// //
// The return values should be as follows. // The return values should be as follows.
// 1. For a successful authentication: // 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. // - A response which includes the username, uid, and groups in the userInfo. The username and uid must not be blank.
// - true // - true
// - nil error // - nil error
// 2. For an unsuccessful authentication, e.g. bad username or password: // 2. For an unsuccessful authentication, e.g. bad username or password:
// - nil response // - nil response
// - false // - false
// - nil error // - nil error
// 3. For an unexpected error, e.g. a network problem: // 3. For an unexpected error, e.g. a network problem:
// - nil response // - nil response
// - false // - false
// - an error // - an error
// Other combinations of return values must be avoided. // Other combinations of return values must be avoided.
// //
// See k8s.io/apiserver/pkg/authentication/authenticator/interfaces.go for the token authenticator // See k8s.io/apiserver/pkg/authentication/authenticator/interfaces.go for the token authenticator

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package certauthority package certauthority
@ -9,8 +9,8 @@ import (
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"os"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -23,10 +23,10 @@ import (
func loadFromFiles(t *testing.T, certPath string, keyPath string) (*CA, error) { func loadFromFiles(t *testing.T, certPath string, keyPath string) (*CA, error) {
t.Helper() t.Helper()
certPEM, err := ioutil.ReadFile(certPath) certPEM, err := os.ReadFile(certPath)
require.NoError(t, err) require.NoError(t, err)
keyPEM, err := ioutil.ReadFile(keyPath) keyPEM, err := os.ReadFile(keyPath)
require.NoError(t, err) require.NoError(t, err)
ca, err := Load(string(certPEM), string(keyPEM)) ca, err := Load(string(certPEM), string(keyPEM))
@ -206,7 +206,7 @@ func TestPool(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
pool := ca.Pool() pool := ca.Pool()
require.Len(t, pool.Subjects(), 1) // nolint: staticcheck // not system cert pool require.Len(t, pool.Subjects(), 1)
} }
type errSigner struct { type errSigner struct {

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package apiserver package apiserver
@ -76,7 +76,7 @@ func (c completedConfig) New() (*PinnipedServer, error) {
GenericAPIServer: genericServer, GenericAPIServer: genericServer,
} }
var errs []error //nolint: prealloc var errs []error //nolint:prealloc
for _, f := range []func() (schema.GroupVersionResource, rest.Storage){ for _, f := range []func() (schema.GroupVersionResource, rest.Storage){
func() (schema.GroupVersionResource, rest.Storage) { func() (schema.GroupVersionResource, rest.Storage) {
tokenCredReqGVR := c.ExtraConfig.LoginConciergeGroupVersion.WithResource("tokencredentialrequests") tokenCredReqGVR := c.ExtraConfig.LoginConciergeGroupVersion.WithResource("tokencredentialrequests")

View File

@ -643,7 +643,7 @@ func getTransportForUser(ctx context.Context, userInfo user.Info, delegate, dele
} }
func canImpersonateFully(userInfo user.Info) bool { 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 { if len(userInfo.GetUID()) == 0 {
return true return true
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
// Package concierge contains functionality to load/store Config's from/to // Package concierge contains functionality to load/store Config's from/to
@ -8,7 +8,7 @@ package concierge
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "os"
"strings" "strings"
"k8s.io/utils/pointer" "k8s.io/utils/pointer"
@ -43,7 +43,7 @@ const (
// This function will decode that base64-encoded data to PEM bytes to be stored // This function will decode that base64-encoded data to PEM bytes to be stored
// in the Config. // in the Config.
func FromPath(ctx context.Context, path string) (*Config, error) { func FromPath(ctx context.Context, path string) (*Config, error) {
data, err := ioutil.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { if err != nil {
return nil, fmt.Errorf("read file: %w", err) return nil, fmt.Errorf("read file: %w", err)
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package concierge package concierge
import ( import (
"context" "context"
"io/ioutil"
"os" "os"
"testing" "testing"
@ -585,7 +584,7 @@ func TestFromPath(t *testing.T) {
// this is a serial test because it sets the global logger // this is a serial test because it sets the global logger
// Write yaml to temp file // 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) require.NoError(t, err)
defer func() { defer func() {
err := os.Remove(f.Name()) err := os.Remove(f.Name())

View File

@ -8,8 +8,8 @@ package supervisor
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os"
"strings" "strings"
"k8s.io/utils/pointer" "k8s.io/utils/pointer"
@ -30,7 +30,7 @@ const (
// defaults (from the Config documentation), and verifies that the config is // defaults (from the Config documentation), and verifies that the config is
// valid (Config documentation). // valid (Config documentation).
func FromPath(ctx context.Context, path string) (*Config, error) { func FromPath(ctx context.Context, path string) (*Config, error) {
data, err := ioutil.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { if err != nil {
return nil, fmt.Errorf("read file: %w", err) return nil, fmt.Errorf("read file: %w", err)
} }

View File

@ -6,7 +6,6 @@ package supervisor
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"testing" "testing"
@ -427,7 +426,7 @@ func TestFromPath(t *testing.T) {
// this is a serial test because it sets the global logger // this is a serial test because it sets the global logger
// Write yaml to temp file // 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) require.NoError(t, err)
defer func() { defer func() {
err := os.Remove(f.Name()) err := os.Remove(f.Name())

View File

@ -143,7 +143,7 @@ func TestController(t *testing.T) {
if tt.initialCache != nil { if tt.initialCache != nil {
tt.initialCache(t, cache) 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() webhooks := informers.Authentication().V1alpha1().WebhookAuthenticators()
jwtAuthenticators := informers.Authentication().V1alpha1().JWTAuthenticators() jwtAuthenticators := informers.Authentication().V1alpha1().JWTAuthenticators()

View File

@ -375,7 +375,7 @@ func TestController(t *testing.T) {
fakeClient := pinnipedfake.NewSimpleClientset(tt.jwtAuthenticators...) fakeClient := pinnipedfake.NewSimpleClientset(tt.jwtAuthenticators...)
informers := pinnipedinformers.NewSharedInformerFactory(fakeClient, 0) informers := pinnipedinformers.NewSharedInformerFactory(fakeClient, 0)
cache := authncache.New() 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 { if tt.cache != nil {
tt.cache(t, cache, tt.wantClose) tt.cache(t, cache, tt.wantClose)

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
// Package webhookcachefiller implements a controller for filling an authncache.Cache with each added/updated WebhookAuthenticator. // Package webhookcachefiller implements a controller for filling an authncache.Cache with each added/updated WebhookAuthenticator.
@ -6,7 +6,6 @@ package webhookcachefiller
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"github.com/go-logr/logr" "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) 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 { if err != nil {
return fmt.Errorf("failed to build webhook config: %w", err) return fmt.Errorf("failed to build webhook config: %w", err)
} }

View File

@ -7,7 +7,7 @@ import (
"context" "context"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"testing" "testing"
@ -88,7 +88,7 @@ func TestController(t *testing.T) {
fakeClient := pinnipedfake.NewSimpleClientset(tt.webhooks...) fakeClient := pinnipedfake.NewSimpleClientset(tt.webhooks...)
informers := pinnipedinformers.NewSharedInformerFactory(fakeClient, 0) informers := pinnipedinformers.NewSharedInformerFactory(fakeClient, 0)
cache := authncache.New() 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) 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) { t.Run("marshal failure", func(t *testing.T) {
marshalError := func(_ clientcmdapi.Config, _ string) error { return fmt.Errorf("some marshal error") } 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.Nil(t, res)
require.EqualError(t, err, "unable to marshal kubeconfig: some marshal error") 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{ res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{
Endpoint: "https://example.com", Endpoint: "https://example.com",
TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: "invalid-base64"}, TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: "invalid-base64"},
}, ioutil.TempFile, clientcmd.WriteToFile) }, os.CreateTemp, clientcmd.WriteToFile)
require.Nil(t, res) require.Nil(t, res)
require.EqualError(t, err, "invalid TLS configuration: illegal base64 data at input byte 7") 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{ res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{
Endpoint: "https://example.com", Endpoint: "https://example.com",
TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte("bad data"))}, TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte("bad data"))},
}, ioutil.TempFile, clientcmd.WriteToFile) }, os.CreateTemp, clientcmd.WriteToFile)
require.Nil(t, res) 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") 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) { t.Run("valid config with no TLS spec", func(t *testing.T) {
res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{ res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{
Endpoint: "https://example.com", Endpoint: "https://example.com",
}, ioutil.TempFile, clientcmd.WriteToFile) }, os.CreateTemp, clientcmd.WriteToFile)
require.NotNil(t, res) require.NotNil(t, res)
require.NoError(t, err) require.NoError(t, err)
}) })
t.Run("success", func(t *testing.T) { t.Run("success", func(t *testing.T) {
caBundle, url := testutil.TLSTestServer(t, func(w http.ResponseWriter, r *http.Request) { 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.NoError(t, err)
require.Contains(t, string(body), "test-token") require.Contains(t, string(body), "test-token")
_, err = w.Write([]byte(`{}`)) _, err = w.Write([]byte(`{}`))
@ -166,7 +166,7 @@ func TestNewWebhookAuthenticator(t *testing.T) {
CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte(caBundle)), 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.NoError(t, err)
require.NotNil(t, res) require.NotNil(t, res)

View File

@ -11,7 +11,7 @@ import (
"encoding/pem" "encoding/pem"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"reflect" "reflect"
@ -92,7 +92,7 @@ func TestImpersonatorConfigControllerOptions(t *testing.T) {
nil, nil,
caSignerName, caSignerName,
nil, 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) credIssuerInformerFilter = observableWithInformerOption.GetFilterForInformer(credIssuerInformer)
servicesInformerFilter = observableWithInformerOption.GetFilterForInformer(servicesInformer) servicesInformerFilter = observableWithInformerOption.GetFilterForInformer(servicesInformer)
@ -360,10 +360,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) {
} }
testHTTPServerMutex.Lock() // this is to satisfy the race detector testHTTPServerMutex.Lock() // this is to satisfy the race detector
testHTTPServer = &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { testHTTPServer = &http.Server{
_, err := fmt.Fprint(w, fakeServerResponseBody) Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
r.NoError(err) _, err := fmt.Fprint(w, fakeServerResponseBody)
})} r.NoError(err)
}),
ReadHeaderTimeout: 10 * time.Second,
}
testHTTPServerMutex.Unlock() testHTTPServerMutex.Unlock()
// Start serving requests in the background. // Start serving requests in the background.
@ -480,7 +483,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) {
r.NoError(err) r.NoError(err)
r.Equal(http.StatusOK, resp.StatusCode) 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(resp.Body.Close())
r.NoError(err) r.NoError(err)
r.Equal(fakeServerResponseBody, string(body)) r.Equal(fakeServerResponseBody, string(body))
@ -560,7 +563,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) {
impersonatorFunc, impersonatorFunc,
caSignerName, caSignerName,
signingCertProvider, 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 { controllerlib.TestWrap(t, subject, func(syncer controllerlib.Syncer) controllerlib.Syncer {
tlsServingCertDynamicCertProvider = syncer.(*impersonatorConfigController).tlsServingCertDynamicCertProvider tlsServingCertDynamicCertProvider = syncer.(*impersonatorConfigController).tlsServingCertDynamicCertProvider

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
// Package issuerconfig contains helpers for updating CredentialIssuer status entries. // 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. // weights are a set of priorities for each strategy type.
//nolint: gochecknoglobals var weights = map[v1alpha1.StrategyType]int{ //nolint:gochecknoglobals
var weights = map[v1alpha1.StrategyType]int{
v1alpha1.KubeClusterSigningCertificateStrategyType: 2, // most preferred strategy v1alpha1.KubeClusterSigningCertificateStrategyType: 2, // most preferred strategy
v1alpha1.ImpersonationProxyStrategyType: 1, v1alpha1.ImpersonationProxyStrategyType: 1,
// unknown strategy types will have weight 0 by default // unknown strategy types will have weight 0 by default

View File

@ -145,12 +145,12 @@ type agentController struct {
var ( var (
// controllerManagerLabels are the Kubernetes labels we expect on the kube-controller-manager Pod. // 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", "component": "kube-controller-manager",
}) })
// agentLabels are the Kubernetes labels we always expect on the kube-controller-manager Pod. // 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, agentPodLabelKey: agentPodLabelValue,
}) })
) )
@ -179,7 +179,7 @@ func NewAgentController(
dynamicCertProvider, dynamicCertProvider,
&clock.RealClock{}, &clock.RealClock{},
cache.NewExpiring(), cache.NewExpiring(),
plog.Logr(), // nolint: staticcheck // old controller with lots of log statements plog.Logr(), //nolint:staticcheck // old controller with lots of log statements
) )
} }

View File

@ -1110,7 +1110,7 @@ func TestAgentController(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
if tt.wantAgentDeployment == nil { if tt.wantAgentDeployment == nil {
assert.Empty(t, deployments.Items, "did not expect an agent deployment") 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") { if assert.Len(t, deployments.Items, 1, "expected a single agent deployment") {
assert.Equal(t, tt.wantAgentDeployment, &deployments.Items[0]) assert.Equal(t, tt.wantAgentDeployment, &deployments.Items[0])
} }

View File

@ -149,7 +149,7 @@ func TestLegacyPodCleanerController(t *testing.T) {
} }
kubeInformers := informers.NewSharedInformerFactory(kubeClientset, 0) 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( controller := NewLegacyPodCleanerController(
AgentConfig{ AgentConfig{
Namespace: "concierge", Namespace: "concierge",

View File

@ -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 // 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 package generator
import ( import (
@ -24,8 +24,7 @@ import (
) )
// generateKey is stubbed out for the purpose of testing. The default behavior is to generate a symmetric key. // generateKey is stubbed out for the purpose of testing. The default behavior is to generate a symmetric key.
//nolint:gochecknoglobals var generateKey = generateSymmetricKey //nolint:gochecknoglobals
var generateKey = generateSymmetricKey
type supervisorSecretsController struct { type supervisorSecretsController struct {
labels map[string]string labels map[string]string

View File

@ -50,8 +50,7 @@ const (
) )
// generateKey is stubbed out for the purpose of testing. The default behavior is to generate an EC key. // generateKey is stubbed out for the purpose of testing. The default behavior is to generate an EC key.
//nolint:gochecknoglobals var generateKey = generateECKey //nolint:gochecknoglobals
var generateKey = generateECKey
func generateECKey(r io.Reader) (interface{}, error) { func generateECKey(r io.Reader) (interface{}, error) {
return ecdsa.GenerateKey(elliptic.P256(), r) return ecdsa.GenerateKey(elliptic.P256(), r)

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package supervisorconfig package supervisorconfig
@ -10,7 +10,7 @@ import (
"encoding/pem" "encoding/pem"
"errors" "errors"
"io" "io"
"io/ioutil" "os"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -259,7 +259,7 @@ func TestJWKSWriterControllerSync(t *testing.T) {
const namespace = "tuna-namespace" 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) require.NoError(t, err)
block, _ := pem.Decode(goodKeyPEM) block, _ := pem.Decode(goodKeyPEM)
require.NotNil(t, block, "expected block to be non-nil...is goodKeyPEM a valid PEM?") 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 { func readJWKJSON(t *testing.T, path string) []byte {
t.Helper() t.Helper()
data, err := ioutil.ReadFile(path) data, err := os.ReadFile(path)
require.NoError(t, err) require.NoError(t, err)
// Trim whitespace from our testdata so that we match the compact JSON encoding of // Trim whitespace from our testdata so that we match the compact JSON encoding of

View File

@ -67,7 +67,7 @@ const (
) )
var ( 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 // 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 // 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 // happily treat the user's config as an override. Users can already set the "client_id" and "scope" params

View File

@ -91,7 +91,7 @@ func TestOIDCUpstreamWatcherControllerFilterSecret(t *testing.T) {
nil, nil,
pinnipedInformers.IDP().V1alpha1().OIDCIdentityProviders(), pinnipedInformers.IDP().V1alpha1().OIDCIdentityProviders(),
secretInformer, secretInformer,
plog.Logr(), // nolint: staticcheck // old test with no log assertions plog.Logr(), //nolint:staticcheck // old test with no log assertions
withInformer.WithInformer, withInformer.WithInformer,
) )
@ -1400,7 +1400,7 @@ oidc: issuer did not match the issuer returned by provider, expected "` + testIs
pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0) pinnipedInformers := pinnipedinformers.NewSharedInformerFactory(fakePinnipedClient, 0)
fakeKubeClient := fake.NewSimpleClientset(tt.inputSecrets...) fakeKubeClient := fake.NewSimpleClientset(tt.inputSecrets...)
kubeInformers := informers.NewSharedInformerFactory(fakeKubeClient, 0) 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 := provider.NewDynamicUpstreamIDPProvider()
cache.SetOIDCIdentityProviders([]provider.UpstreamOIDCIdentityProviderI{ cache.SetOIDCIdentityProviders([]provider.UpstreamOIDCIdentityProviderI{
&upstreamoidc.ProviderConfig{Name: "initial-entry"}, &upstreamoidc.ProviderConfig{Name: "initial-entry"},

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package supervisorconfig package supervisorconfig
@ -6,8 +6,8 @@ package supervisorconfig
import ( import (
"context" "context"
"crypto/tls" "crypto/tls"
"io/ioutil"
"net/url" "net/url"
"os"
"testing" "testing"
"github.com/sclevine/spec" "github.com/sclevine/spec"
@ -170,7 +170,7 @@ func TestTLSCertObserverControllerSync(t *testing.T) {
} }
var readTestFile = func(path string) []byte { var readTestFile = func(path string) []byte {
data, err := ioutil.ReadFile(path) data, err := os.ReadFile(path)
r.NoError(err) r.NoError(err)
return data return data
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package controllerinit package controllerinit
@ -29,8 +29,8 @@ type Informer interface {
} }
// Prepare returns RunnerBuilder that, when called: // Prepare returns RunnerBuilder that, when called:
// 1. Starts all provided informers and waits for them sync (and fails if they hang) // 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 // 2.) Returns a Runner that combines the Runner and RunnerWrapper passed into Prepare.
func Prepare(controllers Runner, controllersWrapper RunnerWrapper, informers ...Informer) RunnerBuilder { func Prepare(controllers Runner, controllersWrapper RunnerWrapper, informers ...Informer) RunnerBuilder {
return func(ctx context.Context) (Runner, error) { return func(ctx context.Context) (Runner, error) {
for _, informer := range informers { for _, informer := range informers {

View File

@ -97,8 +97,7 @@ type Config struct {
} }
// PrepareControllers prepares the controllers and their informers and returns a function that will start them when called. // 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) { //nolint:funlen // Eh, fair, it is a really long function...but it is wiring the world...so...
func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) {
loginConciergeGroupData, identityConciergeGroupData := groupsuffix.ConciergeAggregatedGroups(c.APIGroupSuffix) loginConciergeGroupData, identityConciergeGroupData := groupsuffix.ConciergeAggregatedGroups(c.APIGroupSuffix)
dref, deployment, _, err := deploymentref.New(c.ServerInstallationInfo) dref, deployment, _, err := deploymentref.New(c.ServerInstallationInfo)
@ -223,7 +222,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) {
agentConfig, agentConfig,
client, client,
informers.installationNamespaceK8s.Core().V1().Pods(), 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, singletonWorker,
). ).
@ -233,7 +232,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) {
webhookcachefiller.New( webhookcachefiller.New(
c.AuthenticatorCache, c.AuthenticatorCache,
informers.pinniped.Authentication().V1alpha1().WebhookAuthenticators(), 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, singletonWorker,
). ).
@ -241,7 +240,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) {
jwtcachefiller.New( jwtcachefiller.New(
c.AuthenticatorCache, c.AuthenticatorCache,
informers.pinniped.Authentication().V1alpha1().JWTAuthenticators(), 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, singletonWorker,
). ).
@ -250,7 +249,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) {
c.AuthenticatorCache, c.AuthenticatorCache,
informers.pinniped.Authentication().V1alpha1().WebhookAuthenticators(), informers.pinniped.Authentication().V1alpha1().WebhookAuthenticators(),
informers.pinniped.Authentication().V1alpha1().JWTAuthenticators(), 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, singletonWorker,
). ).
@ -276,7 +275,7 @@ func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) {
impersonator.New, impersonator.New,
c.NamesConfig.ImpersonationSignerSecret, c.NamesConfig.ImpersonationSignerSecret,
c.ImpersonationSigningCertProvider, 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, singletonWorker,
). ).

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package crud package crud
@ -168,7 +168,7 @@ func validateSecret(resource string, secret *corev1.Secret) error {
return nil return nil
} }
//nolint: gochecknoglobals //nolint:gochecknoglobals
var b32 = base32.StdEncoding.WithPadding(base32.NoPadding) var b32 = base32.StdEncoding.WithPadding(base32.NoPadding)
func (s *secretsStorage) getName(signature string) string { func (s *secretsStorage) getName(signature string) string {

View File

@ -144,7 +144,7 @@ func TestMerge(t *testing.T) {
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
tls.TLS_ECDHE_RSA_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_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_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_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
tls.TLS_ECDHE_RSA_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_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_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", ServerName: "something-to-check-passthrough",
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{ 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_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
@ -219,7 +219,7 @@ func TestMerge(t *testing.T) {
ServerName: "a different thing for passthrough", ServerName: "a different thing for passthrough",
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{ 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_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_RSA_WITH_AES_256_GCM_SHA384,

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package deploymentref package deploymentref
@ -23,8 +23,7 @@ import (
// We would normally pass a kubernetes.Interface into New(), but the client we want to create in // 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 // the calling code depends on the return value of New() (i.e., on the kubeclient.Option for the
// OwnerReference). // OwnerReference).
//nolint: gochecknoglobals var getTempClient = func() (kubernetes.Interface, error) { //nolint:gochecknoglobals
var getTempClient = func() (kubernetes.Interface, error) {
client, err := kubeclient.New() client, err := kubeclient.New()
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
// Package downward implements a client interface for interacting with Kubernetes "downwardAPI" volumes. // Package downward implements a client interface for interacting with Kubernetes "downwardAPI" volumes.
@ -9,7 +9,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
@ -32,20 +32,20 @@ type PodInfo struct {
// Load pod metadata from a downwardAPI volume directory. // Load pod metadata from a downwardAPI volume directory.
func Load(directory string) (*PodInfo, error) { func Load(directory string) (*PodInfo, error) {
var result PodInfo var result PodInfo
ns, err := ioutil.ReadFile(filepath.Join(directory, "namespace")) ns, err := os.ReadFile(filepath.Join(directory, "namespace"))
if err != nil { if err != nil {
return nil, fmt.Errorf("could not load namespace: %w", err) return nil, fmt.Errorf("could not load namespace: %w", err)
} }
result.Namespace = strings.TrimSpace(string(ns)) 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 { if err != nil {
plog.Warning("could not read 'name' downward API file") plog.Warning("could not read 'name' downward API file")
} else { } else {
result.Name = strings.TrimSpace(string(name)) 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 { if err != nil {
return nil, fmt.Errorf("could not load labels: %w", err) return nil, fmt.Errorf("could not load labels: %w", err)
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package dynamiccert package dynamiccert
@ -41,7 +41,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) {
cert, err := tls.X509KeyPair(certPEM, keyPEM) cert, err := tls.X509KeyPair(certPEM, keyPEM)
require.NoError(t, err) 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() 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) cert, err := tls.X509KeyPair(certPEM, keyPEM)
require.NoError(t, err) 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()) ok := pool.AppendCertsFromPEM(ca.CurrentCABundleContent())
require.True(t, ok, "should have valid non-empty CA bundle") 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) err = ca.SetCertKeyContent(newOtherCA.Bundle(), caKey)
require.NoError(t, err) 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 { if pool == nil {
return nil return nil
} }
return pool.Subjects() // nolint: staticcheck // not system cert pool return pool.Subjects()
} }
func TestNewServingCert(t *testing.T) { func TestNewServingCert(t *testing.T) {

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package execcredcache package execcredcache
@ -6,7 +6,6 @@ package execcredcache
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"sort" "sort"
"time" "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. // 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) { func readCache(path string) (*credCache, error) {
cacheYAML, err := ioutil.ReadFile(path) cacheYAML, err := os.ReadFile(path)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
// If the file was not found, generate a freshly initialized empty cache. // 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. // Marshal the cache back to YAML and save it to the file.
cacheYAML, err := yaml.Marshal(c) cacheYAML, err := yaml.Marshal(c)
if err == nil { if err == nil {
err = ioutil.WriteFile(path, cacheYAML, 0600) err = os.WriteFile(path, cacheYAML, 0600)
} }
return err return err
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package execcredcache package execcredcache
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -52,7 +51,7 @@ func TestGet(t *testing.T) {
}, },
{ {
name: "file lock error", 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") }, 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 }, unlockFunc: func(t *testing.T) error { require.Fail(t, "should not be called"); return nil },
key: testKey{}, key: testKey{},
@ -61,7 +60,7 @@ func TestGet(t *testing.T) {
{ {
name: "invalid file", name: "invalid file",
makeTestFile: func(t *testing.T, tmp string) { 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{}, key: testKey{},
wantErrors: []string{ wantErrors: []string{
@ -70,7 +69,7 @@ func TestGet(t *testing.T) {
}, },
{ {
name: "invalid file, fail to unlock", 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 }, trylockFunc: func(t *testing.T) error { return nil },
unlockFunc: func(t *testing.T) error { return fmt.Errorf("some unlock error") }, unlockFunc: func(t *testing.T) error { return fmt.Errorf("some unlock error") },
key: testKey{}, key: testKey{},
@ -211,7 +210,7 @@ func TestPutToken(t *testing.T) {
{ {
name: "fail to create directory", name: "fail to create directory",
makeTestFile: func(t *testing.T, tmp string) { 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{ wantErrors: []string{
"could not create credential cache directory: mkdir TEMPDIR: not a directory", "could not create credential cache directory: mkdir TEMPDIR: not a directory",

View File

@ -235,6 +235,7 @@ const ExpectedAuthorizeCodeSessionJSONFromFuzzing = `{
"Host": "", "Host": "",
"Path": "", "Path": "",
"RawPath": "", "RawPath": "",
"OmitHost": false,
"ForceQuery": false, "ForceQuery": false,
"RawQuery": "", "RawQuery": "",
"Fragment": "", "Fragment": "",
@ -252,6 +253,7 @@ const ExpectedAuthorizeCodeSessionJSONFromFuzzing = `{
"Host": "", "Host": "",
"Path": "", "Path": "",
"RawPath": "", "RawPath": "",
"OmitHost": false,
"ForceQuery": false, "ForceQuery": false,
"RawQuery": "", "RawQuery": "",
"Fragment": "", "Fragment": "",
@ -269,6 +271,7 @@ const ExpectedAuthorizeCodeSessionJSONFromFuzzing = `{
"Host": "", "Host": "",
"Path": "", "Path": "",
"RawPath": "", "RawPath": "",
"OmitHost": false,
"ForceQuery": false, "ForceQuery": false,
"RawQuery": "", "RawQuery": "",
"Fragment": "", "Fragment": "",

View File

@ -100,7 +100,7 @@ func TestOpenIdConnectStorage(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, request, newRequest) 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) require.NoError(t, err)
testutil.LogActualJSONFromCreateAction(t, client, 0) // makes it easier to update expected values when needed testutil.LogActualJSONFromCreateAction(t, client, 0) // makes it easier to update expected values when needed

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package groupsuffix 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, // makes sure that the provided apiGroupSuffix is a valid DNS-1123 subdomain with at least one dot,
// to match Kubernetes behavior. // to match Kubernetes behavior.
func Validate(apiGroupSuffix string) error { func Validate(apiGroupSuffix string) error {
var errs []error // nolint: prealloc var errs []error //nolint:prealloc
if len(strings.Split(apiGroupSuffix, ".")) < 2 { if len(strings.Split(apiGroupSuffix, ".")) < 2 {
errs = append(errs, constable.Error("must contain '.'")) errs = append(errs, constable.Error("must contain '.'"))

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package securityheader package securityheader
import ( import (
"context" "context"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@ -74,7 +74,7 @@ func TestWrap(t *testing.T) {
defer resp.Body.Close() defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode) require.Equal(t, http.StatusOK, resp.StatusCode)
respBody, err := ioutil.ReadAll(resp.Body) respBody, err := io.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "hello world", string(respBody)) require.Equal(t, "hello world", string(respBody))

View File

@ -15,8 +15,7 @@ import (
) )
// defaultServerUrlFor was copied from k8s.io/client-go/rest/url_utils.go. // defaultServerUrlFor was copied from k8s.io/client-go/rest/url_utils.go.
//nolint:revive func defaultServerUrlFor(config *restclient.Config) (*url.URL, string, error) { //nolint:revive
func defaultServerUrlFor(config *restclient.Config) (*url.URL, string, error) {
hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0 hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0
hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0 hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0
defaultTLS := hasCA || hasCert || config.Insecure defaultTLS := hasCA || hasCert || config.Insecure

View File

@ -211,7 +211,7 @@ func AssertSecureTransport(rt http.RoundTripper) error {
tlsConfigCopy := tlsConfig.Clone() tlsConfigCopy := tlsConfig.Clone()
ptls.Merge(ptls.Secure, tlsConfigCopy) // only mutate the copy 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, if diff := cmp.Diff(tlsConfigCopy, tlsConfig,
cmpopts.IgnoreUnexported(tls.Config{}, x509.CertPool{}), cmpopts.IgnoreUnexported(tls.Config{}, x509.CertPool{}),
cmpopts.IgnoreFields(tls.Config{}, "GetClientCertificate"), cmpopts.IgnoreFields(tls.Config{}, "GetClientCertificate"),

View File

@ -949,7 +949,7 @@ func TestUnwrap(t *testing.T) {
server, restConfig := fakekubeapi.Start(t, nil) 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.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) 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) 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 // 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())
}) })
} }
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package kubeclient package kubeclient
@ -71,7 +71,7 @@ func (r *request) Namespace() string {
return r.namespace return r.namespace
} }
//nolint: gochecknoglobals //nolint:gochecknoglobals
var namespaceGVR = corev1.SchemeGroupVersion.WithResource("namespaces") var namespaceGVR = corev1.SchemeGroupVersion.WithResource("namespaces")
func (r *request) NamespaceScoped() bool { func (r *request) NamespaceScoped() bool {

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package kubeclient package kubeclient
@ -6,7 +6,7 @@ package kubeclient
import ( import (
"bytes" "bytes"
"context" "context"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"reflect" "reflect"
@ -142,7 +142,7 @@ func Test_updatePathNewGVK(t *testing.T) {
} }
func Test_reqWithoutPrefix(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 { newReq := func(rawurl string) *http.Request {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawurl, body) req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawurl, body)
require.NoError(t, err) require.NoError(t, err)

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package kubeclient package kubeclient
@ -6,7 +6,7 @@ package kubeclient
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
apiequality "k8s.io/apimachinery/pkg/api/equality" apiequality "k8s.io/apimachinery/pkg/api/equality"
@ -213,7 +213,7 @@ func handleCreateOrUpdate(
return true, nil, fmt.Errorf("get body failed: %w", err) return true, nil, fmt.Errorf("get body failed: %w", err)
} }
defer body.Close() defer body.Close()
data, err := ioutil.ReadAll(body) data, err := io.ReadAll(body)
if err != nil { if err != nil {
return true, nil, fmt.Errorf("read body failed: %w", err) 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 // always make sure we close the body, even if reading from it fails
defer resp.Body.Close() defer resp.Body.Close()
respData, err := ioutil.ReadAll(resp.Body) respData, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err) return nil, fmt.Errorf("failed to read response body: %w", err)
} }
@ -319,7 +319,7 @@ func handleResponseNewGVK(
newResp := &http.Response{} newResp := &http.Response{}
*newResp = *resp *newResp = *resp
newResp.Body = ioutil.NopCloser(bytes.NewBuffer(fixedRespData)) newResp.Body = io.NopCloser(bytes.NewBuffer(fixedRespData))
return newResp, nil return newResp, nil
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package kubeclient package kubeclient
@ -7,7 +7,6 @@ import (
stderrors "errors" stderrors "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 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... // from k8s.io/client-go/rest/request.go...
const maxBodySlurpSize = 2 << 10 const maxBodySlurpSize = 2 << 10
if resp.ContentLength <= maxBodySlurpSize { 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 { if close {
resp.Body.Close() resp.Body.Close()

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package leaderelection package leaderelection
@ -184,7 +184,7 @@ func (t *isLeaderTracker) start() {
} }
func (t *isLeaderTracker) stop() (didStop bool) { 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. // note that resourcelock.Interface is an internal, unstable interface.

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
// Package localuserauthenticator provides a authentication webhook program. // 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 return &cert, err
} }
server := http.Server{ server := http.Server{
Handler: w, Handler: w,
TLSConfig: c, TLSConfig: c,
ReadHeaderTimeout: 10 * time.Second,
} }
errCh := make(chan error) errCh := make(chan error)
@ -356,7 +357,7 @@ func run(ctx context.Context) error {
startControllers(ctx, dynamicCertProvider, client.Kubernetes, kubeInformers) startControllers(ctx, dynamicCertProvider, client.Kubernetes, kubeInformers)
plog.Debug("controllers are ready") 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") l, err := net.Listen("tcp", ":8443")
if err != nil { if err != nil {
return fmt.Errorf("cannot create listener: %w", err) return fmt.Errorf("cannot create listener: %w", err)

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package localuserauthenticator package localuserauthenticator
@ -10,7 +10,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -385,7 +384,7 @@ func TestWebhook(t *testing.T) {
url: goodURL, url: goodURL,
method: http.MethodPost, method: http.MethodPost,
headers: goodRequestHeaders, 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, 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) require.NoError(t, err)
if test.wantBody != nil { if test.wantBody != nil {
require.NoError(t, err) require.NoError(t, err)
@ -520,7 +519,7 @@ func newTokenReviewBodyWithGVK(token string, gvk *schema.GroupVersionKind) (io.R
}, },
} }
err := json.NewEncoder(buf).Encode(&tr) err := json.NewEncoder(buf).Encode(&tr)
return ioutil.NopCloser(buf), err return io.NopCloser(buf), err
} }
func unauthenticatedResponseJSON() *authenticationv1beta1.TokenReview { func unauthenticatedResponseJSON() *authenticationv1beta1.TokenReview {

View File

@ -54,10 +54,10 @@ func TestAuthorizationEndpoint(t *testing.T) {
oidcUpstreamSubject = "abc123-some guid" // has a space character which should get escaped in URL oidcUpstreamSubject = "abc123-some guid" // has a space character which should get escaped in URL
oidcUpstreamSubjectQueryEscaped = "abc123-some+guid" oidcUpstreamSubjectQueryEscaped = "abc123-some+guid"
oidcUpstreamUsername = "test-oidc-pinniped-username" oidcUpstreamUsername = "test-oidc-pinniped-username"
oidcUpstreamPassword = "test-oidc-pinniped-password" //nolint: gosec oidcUpstreamPassword = "test-oidc-pinniped-password" //nolint:gosec
oidcUpstreamUsernameClaim = "the-user-claim" oidcUpstreamUsernameClaim = "the-user-claim"
oidcUpstreamGroupsClaim = "the-groups-claim" oidcUpstreamGroupsClaim = "the-groups-claim"
oidcPasswordGrantUpstreamRefreshToken = "some-opaque-token" //nolint: gosec oidcPasswordGrantUpstreamRefreshToken = "some-opaque-token" //nolint:gosec
oidcUpstreamAccessToken = "some-access-token" oidcUpstreamAccessToken = "some-access-token"
downstreamIssuer = "https://my-downstream-issuer.com/some-path" downstreamIssuer = "https://my-downstream-issuer.com/some-path"

View File

@ -114,7 +114,7 @@ func (k KubeStorage) GetOpenIDConnectSession(ctx context.Context, fullAuthcode s
} }
func (k KubeStorage) DeleteOpenIDConnectSession(ctx context.Context, fullAuthcode string) error { 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.
} }
// //

View File

@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
// Package loginhtml defines HTML templates used by the Supervisor. // 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 package loginhtml
import ( import (
@ -15,6 +14,7 @@ import (
"go.pinniped.dev/internal/oidc/provider/csp" "go.pinniped.dev/internal/oidc/provider/csp"
) )
//nolint:gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init.
var ( var (
//go:embed login_form.css //go:embed login_form.css
rawCSS string rawCSS string
@ -22,20 +22,20 @@ var (
//go:embed login_form.gohtml //go:embed login_form.gohtml
rawHTMLTemplate string 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 { func panicOnError(s string, err error) string {
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -255,11 +255,12 @@ func FositeOauth2Helper(
// passed to a plog function (e.g., plog.Info()). // passed to a plog function (e.g., plog.Info()).
// //
// Sample usage: // Sample usage:
// err := someFositeLibraryFunction() //
// if err != nil { // err := someFositeLibraryFunction()
// plog.Info("some error", FositeErrorForLog(err)...) // if err != nil {
// ... // plog.Info("some error", FositeErrorForLog(err)...)
// } // ...
// }
func FositeErrorForLog(err error) []interface{} { func FositeErrorForLog(err error) []interface{} {
rfc6749Error := fosite.ErrorToRFC6749Error(err) rfc6749Error := fosite.ErrorToRFC6749Error(err)
keysAndValues := make([]interface{}, 0) keysAndValues := make([]interface{}, 0)

View File

@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
// Package formposthtml defines HTML templates used by the Supervisor. // 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 package formposthtml
import ( import (
@ -15,6 +14,7 @@ import (
"go.pinniped.dev/internal/oidc/provider/csp" "go.pinniped.dev/internal/oidc/provider/csp"
) )
//nolint:gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init.
var ( var (
//go:embed form_post.css //go:embed form_post.css
rawCSS string rawCSS string
@ -26,24 +26,24 @@ var (
//go:embed form_post.gohtml //go:embed form_post.gohtml
rawHTMLTemplate string 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 { func panicOnError(s string, err error) string {
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -8,7 +8,7 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@ -84,7 +84,7 @@ func TestManager(t *testing.T) {
// Minimal check to ensure that the right discovery endpoint was called // Minimal check to ensure that the right discovery endpoint was called
r.Equal(http.StatusOK, recorder.Code) r.Equal(http.StatusOK, recorder.Code)
responseBody, err := ioutil.ReadAll(recorder.Body) responseBody, err := io.ReadAll(recorder.Body)
r.NoError(err) r.NoError(err)
parsedDiscoveryResult := discovery.Metadata{} parsedDiscoveryResult := discovery.Metadata{}
err = json.Unmarshal(responseBody, &parsedDiscoveryResult) 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 // Minimal check to ensure that the right IDP discovery endpoint was called
r.Equal(http.StatusOK, recorder.Code) r.Equal(http.StatusOK, recorder.Code)
responseBody, err := ioutil.ReadAll(recorder.Body) responseBody, err := io.ReadAll(recorder.Body)
r.NoError(err) r.NoError(err)
r.Equal( r.Equal(
fmt.Sprintf(`{"pinniped_identity_providers":[{"name":"%s","type":"%s","flows":%s}]}`+"\n", expectedIDPName, expectedIDPType, expectedFlowsJSON), 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 // Minimal check to ensure that the right JWKS endpoint was called
r.Equal(http.StatusOK, recorder.Code) r.Equal(http.StatusOK, recorder.Code)
responseBody, err := ioutil.ReadAll(recorder.Body) responseBody, err := io.ReadAll(recorder.Body)
r.NoError(err) r.NoError(err)
parsedJWKSResult := jose.JSONWebKeySet{} parsedJWKSResult := jose.JSONWebKeySet{}
err = json.Unmarshal(responseBody, &parsedJWKSResult) err = json.Unmarshal(responseBody, &parsedJWKSResult)

View File

@ -14,7 +14,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@ -109,7 +108,7 @@ var (
fositeInvalidPayloadErrorBody = here.Doc(` fositeInvalidPayloadErrorBody = here.Doc(`
{ {
"error": "invalid_request", "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", name: "payload is not valid form serialization",
authcodeExchange: authcodeExchangeInputs{ authcodeExchange: authcodeExchangeInputs{
modifyTokenRequest: func(r *http.Request, authCode string) { 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{ want: tokenEndpointResponseExpectedValues{
wantStatus: http.StatusBadRequest, wantStatus: http.StatusBadRequest,
@ -3074,7 +3073,7 @@ func (b body) WithPKCE(verifier string) body {
} }
func (b body) ReadCloser() io.ReadCloser { 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 { func (b body) with(param, value string) body {

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package oidc package oidc
@ -16,9 +16,9 @@ import (
) )
const ( const (
tokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token" //nolint: gosec tokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token" //nolint:gosec
tokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" //nolint: gosec tokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" //nolint:gosec
pinnipedTokenExchangeScope = "pinniped:request-audience" //nolint: gosec pinnipedTokenExchangeScope = "pinniped:request-audience" //nolint:gosec
) )
type stsParams struct { type stsParams struct {

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package ownerref package ownerref
@ -64,7 +64,7 @@ func New(refObj kubeclient.Object) kubeclient.Middleware {
}) })
} }
//nolint: gochecknoglobals //nolint:gochecknoglobals
var namespaceGVK = corev1.SchemeGroupVersion.WithKind("Namespace") var namespaceGVK = corev1.SchemeGroupVersion.WithKind("Namespace")
func isNamespace(obj kubeclient.Object) bool { func isNamespace(obj kubeclient.Object) bool {

View File

@ -88,7 +88,7 @@ func ValidateAndSetLogLevelAndFormatGlobally(ctx context.Context, spec LogSpec)
setGlobalLoggers(log, flush) 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 { switch spec.Format {
case FormatCLI: case FormatCLI:
return nil // do not spawn go routines on the CLI to allow the CLI to call this more than once return nil // do not spawn go routines on the CLI to allow the CLI to call this more than once

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package plog package plog
@ -136,7 +136,7 @@ func TestFormat(t *testing.T) {
`go.pinniped.dev/internal/plog.TestFormat `go.pinniped.dev/internal/plog.TestFormat
%s/config_test.go:%d %s/config_test.go:%d
testing.tRunner testing.tRunner
%s/src/testing/testing.go:1439`, %s/src/testing/testing.go:1446`,
wd, startLogLine+2+13+14+11+12+24, runtime.GOROOT(), wd, startLogLine+2+13+14+11+12+24, runtime.GOROOT(),
), ),
), ),

View File

@ -15,7 +15,7 @@ import (
"k8s.io/klog/v2" "k8s.io/klog/v2"
) )
// nolint: gochecknoglobals //nolint:gochecknoglobals
var ( var (
// note that these globals have no locks on purpose - they are expected to be set at init and then again after config parsing. // 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 globalLevel zap.AtomicLevel
@ -26,7 +26,7 @@ var (
sinkMap sync.Map sinkMap sync.Map
) )
// nolint: gochecknoinits //nolint:gochecknoinits
func init() { func init() {
// make sure we always have a functional global logger // 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 globalLevel = zap.NewAtomicLevelAt(0) // log at the 0 verbosity level to start with, i.e. the "always" logs

View File

@ -71,7 +71,7 @@ func TestCreate(t *testing.T) {
it.Before(func() { it.Before(func() {
r = require.New(t) r = require.New(t)
ctrl = gomock.NewController(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 :( klog.SetLogger(logr.New(logger)) // this is unfortunately a global logger, so can't run these tests in parallel :(
}) })

View File

@ -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 handler = withBootstrapPaths(handler, "/healthz") // only health checks are allowed for bootstrap connections
server := http.Server{ server := http.Server{
Handler: handler, Handler: handler,
ConnContext: withBootstrapConnCtx, ConnContext: withBootstrapConnCtx,
ReadHeaderTimeout: 10 * time.Second,
} }
shutdown.Add(1) shutdown.Add(1)
@ -270,7 +271,7 @@ func prepareControllers(
pinnipedClient, pinnipedClient,
pinnipedInformers.IDP().V1alpha1().OIDCIdentityProviders(), pinnipedInformers.IDP().V1alpha1().OIDCIdentityProviders(),
secretInformer, 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, controllerlib.WithInformer,
), ),
singletonWorker). singletonWorker).

View File

@ -1,25 +1,28 @@
// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved. // Copyright 2021-2022 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 // 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. 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) { Usage:
// resources := map[string]kubeclient.Object{
// // store preexisting resources here func TestSomething(t *testing.T) {
// "/api/v1/namespaces/default/pods/some-pod-name": &corev1.Pod{...}, resources := map[string]kubeclient.Object{
// } // store preexisting resources here
// server, restConfig := fakekubeapi.Start(t, resources) "/api/v1/namespaces/default/pods/some-pod-name": &corev1.Pod{...},
// defer server.Close() }
// client := kubeclient.New(kubeclient.WithConfig(restConfig)) server, restConfig := fakekubeapi.Start(t, resources)
// // do stuff with client... defer server.Close()
// } client := kubeclient.New(kubeclient.WithConfig(restConfig))
// do stuff with client...
}
*/
package fakekubeapi package fakekubeapi
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"mime" "mime"
"net/http" "net/http"
"net/http/httptest" "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) 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 { if err != nil {
return nil, httperr.Wrap(http.StatusInternalServerError, "read body", err) return nil, httperr.Wrap(http.StatusInternalServerError, "read body", err)
} }
var obj runtime.Object var obj runtime.Object
var errs []error //nolint: prealloc var errs []error //nolint:prealloc
codecsThatWeUseInOurCode := []runtime.NegotiatedSerializer{ codecsThatWeUseInOurCode := []runtime.NegotiatedSerializer{
kubescheme.Codecs, kubescheme.Codecs,
aggregatorclientscheme.Codecs, aggregatorclientscheme.Codecs,

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package testutil package testutil
import ( import (
"io" "io"
"io/ioutil"
"os" "os"
"testing" "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 { func WriteStringToTempFile(t *testing.T, filename string, fileBody string) *os.File {
t.Helper() t.Helper()
f, err := ioutil.TempFile("", filename) f, err := os.CreateTemp("", filename)
require.NoError(t, err) require.NoError(t, err)
deferMe := func() { deferMe := func() {
err := os.Remove(f.Name()) err := os.Remove(f.Name())

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
//go:build !go1.14
// +build !go1.14 // +build !go1.14
package testutil package testutil

View File

@ -1,13 +1,13 @@
// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved. // Copyright 2020-2022 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
//nolint:goimports // not an import //go:build go1.14
// +build go1.14 // +build go1.14
package testutil package testutil
import ( import (
"io/ioutil" "io/ioutil" //nolint:staticcheck // ioutil is deprecated, but this file is for go1.14
"os" "os"
"testing" "testing"

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package testutil package testutil
@ -9,6 +9,7 @@ import (
"net" "net"
"net/http" "net/http"
"testing" "testing"
"time"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -33,8 +34,9 @@ func TLSTestServerWithCert(t *testing.T, handler http.HandlerFunc, certificate *
c.Certificates = []tls.Certificate{*certificate} c.Certificates = []tls.Certificate{*certificate}
server := http.Server{ server := http.Server{
TLSConfig: c, TLSConfig: c,
Handler: handler, Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
} }
l, err := net.Listen("tcp", "127.0.0.1:0") l, err := net.Listen("tcp", "127.0.0.1:0")

View File

@ -74,16 +74,16 @@ func TestProviderConfig(t *testing.T) {
// Test JWTs generated with https://smallstep.com/docs/cli/crypto/jwt/: // 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" // 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" // 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" // 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" 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" // 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) { t.Run("PasswordCredentialsGrantAndValidateTokens", func(t *testing.T) {
@ -699,7 +699,7 @@ func TestProviderConfig(t *testing.T) {
require.Equal(t, tt.wantNumRequests, numRequests, require.Equal(t, tt.wantNumRequests, numRequests,
"did not make expected number of requests to revocation endpoint") "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 != "" { if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr) require.EqualError(t, err, tt.wantErr)
} else { } else {

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package conciergeclient package conciergeclient
@ -8,7 +8,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"testing" "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, "/apis/login.concierge.pinniped.dev/v1alpha1/tokencredentialrequests", r.URL.Path)
require.Equal(t, "application/json", r.Header.Get("content-type")) 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.NoError(t, err)
require.JSONEq(t, require.JSONEq(t,
`{ `{

View File

@ -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 // 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 package filesession
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"reflect" "reflect"
"sort" "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. // 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) { func readSessionCache(path string) (*sessionCache, error) {
cacheYAML, err := ioutil.ReadFile(path) cacheYAML, err := os.ReadFile(path)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
// If the file was not found, generate a freshly initialized empty cache. // 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. // Marshal the session back to YAML and save it to the file.
cacheYAML, err := yaml.Marshal(c) cacheYAML, err := yaml.Marshal(c)
if err == nil { if err == nil {
err = ioutil.WriteFile(path, cacheYAML, 0600) err = os.WriteFile(path, cacheYAML, 0600)
} }
return err return err
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package filesession package filesession
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -49,7 +48,7 @@ func TestGetToken(t *testing.T) {
}, },
{ {
name: "file lock error", 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") }, 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 }, unlockFunc: func(t *testing.T) error { require.Fail(t, "should not be called"); return nil },
key: oidcclient.SessionCacheKey{}, key: oidcclient.SessionCacheKey{},
@ -58,7 +57,7 @@ func TestGetToken(t *testing.T) {
{ {
name: "invalid file", name: "invalid file",
makeTestFile: func(t *testing.T, tmp string) { 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{}, key: oidcclient.SessionCacheKey{},
wantErrors: []string{ wantErrors: []string{
@ -67,7 +66,7 @@ func TestGetToken(t *testing.T) {
}, },
{ {
name: "invalid file, fail to unlock", 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 }, trylockFunc: func(t *testing.T) error { return nil },
unlockFunc: func(t *testing.T) error { return fmt.Errorf("some unlock error") }, unlockFunc: func(t *testing.T) error { return fmt.Errorf("some unlock error") },
key: oidcclient.SessionCacheKey{}, key: oidcclient.SessionCacheKey{},
@ -262,7 +261,7 @@ func TestPutToken(t *testing.T) {
{ {
name: "fail to create directory", name: "fail to create directory",
makeTestFile: func(t *testing.T, tmp string) { 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{ wantErrors: []string{
"could not create session cache directory: mkdir TEMPDIR: not a directory", "could not create session cache directory: mkdir TEMPDIR: not a directory",

View File

@ -861,7 +861,7 @@ func (h *handlerState) handleAuthCodeCallback(w http.ResponseWriter, r *http.Req
}() }()
var params url.Values 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. // Return HTTP 405 for anything that's not a POST or an OPTIONS request.
if r.Method != http.MethodPost && r.Method != http.MethodOptions { 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) 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 := http.NewServeMux()
mux.Handle(h.callbackPath, httperr.HandlerFunc(h.handleAuthCodeCallback)) mux.Handle(h.callbackPath, httperr.HandlerFunc(h.handleAuthCodeCallback))
srv := http.Server{ srv := http.Server{
Handler: securityheader.Wrap(mux), Handler: securityheader.Wrap(mux),
BaseContext: func(_ net.Listener) context.Context { return h.ctx }, BaseContext: func(_ net.Listener) context.Context { return h.ctx },
ReadHeaderTimeout: 10 * time.Second,
} }
go func() { _ = srv.Serve(listener) }() go func() { _ = srv.Serve(listener) }()
return func() { return func() {

View File

@ -10,7 +10,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -72,7 +72,7 @@ func newClientForServer(server *httptest.Server) *http.Client {
return phttp.Default(pool) 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) time1 := time.Date(2035, 10, 12, 13, 14, 15, 16, time.UTC)
time1Unix := int64(2075807775) time1Unix := int64(2075807775)
require.Equal(t, time1Unix, time1.Add(2*time.Minute).Unix()) require.Equal(t, time1Unix, time1.Add(2*time.Minute).Unix())
@ -1040,7 +1040,7 @@ func TestLogin(t *testing.T) { // nolint:gocyclo
return &http.Response{ return &http.Response{
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Header: http.Header{"content-type": []string{"application/json"}}, Header: http.Header{"content-type": []string{"application/json"}},
Body: ioutil.NopCloser(strings.NewReader(string(jsonResponseBody))), Body: io.NopCloser(strings.NewReader(string(jsonResponseBody))),
}, nil }, nil
default: default:
require.FailNow(t, fmt.Sprintf("saw unexpected http call from the CLI: %s", req.URL.String())) 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 { for _, tt := range tests {
tt := tt tt := tt
t.Run(tt.name, func(t *testing.T) { 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) klog.SetLogger(testLogger.Logger)
tok, err := Login(tt.issuer, tt.clientID, tok, err := Login(tt.issuer, tt.clientID,
@ -2333,7 +2333,7 @@ func TestHandleAuthCodeCallback(t *testing.T) {
state: state.State("test-state"), state: state.State("test-state"),
pkce: pkce.Code("test-pkce"), pkce: pkce.Code("test-pkce"),
nonce: nonce.Nonce("test-nonce"), 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", issuer: "https://valid-issuer.com/with/some/path",
} }
if tt.opt != nil { if tt.opt != nil {

View File

@ -9,7 +9,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"os/exec" "os/exec"
@ -94,7 +93,7 @@ func TestCLIGetKubeconfigStaticToken_Parallel(t *testing.T) {
t.Run("whoami", func(t *testing.T) { t.Run("whoami", func(t *testing.T) {
// Validate that `pinniped whoami` returns the correct identity. // Validate that `pinniped whoami` returns the correct identity.
kubeconfigPath := filepath.Join(testutil.TempDir(t), "whoami-kubeconfig") 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( assertWhoami(
ctx, ctx,
t, t,
@ -174,7 +173,7 @@ func TestCLILoginOIDC_Browser(t *testing.T) {
env := testlib.IntegrationEnv(t) env := testlib.IntegrationEnv(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel() t.Cleanup(cancel)
// Build pinniped CLI. // Build pinniped CLI.
pinnipedExe := testlib.PinnipedCLIPath(t) 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 there is a custom CA bundle, pass it via --ca-bundle and a temporary file.
if env.CLIUpstreamOIDC.CABundle != "" { if env.CLIUpstreamOIDC.CABundle != "" {
path := filepath.Join(testutil.TempDir(t), "test-ca.pem") 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) cmd.Args = append(cmd.Args, "--ca-bundle", path)
} }

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package integration package integration
@ -18,10 +18,10 @@ import (
// Test certificate and private key that should get an authentication error. Generated with cfssl [1], like this: // Test certificate and private key that should get an authentication error. Generated with cfssl [1], like this:
// //
// $ brew install cfssl // $ brew install cfssl
// $ cfssl print-defaults csr | cfssl genkey -initca - | cfssljson -bare ca // $ 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 // $ 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 // $ cat client.pem client-key.pem
// //
// [1]: https://github.com/cloudflare/cfssl // [1]: https://github.com/cloudflare/cfssl
var ( var (

View File

@ -15,7 +15,7 @@ import (
"encoding/json" "encoding/json"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -1103,7 +1103,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl
localEchoFile := filepath.Join(tempDir, filepath.Base(remoteEchoFile)) localEchoFile := filepath.Join(tempDir, filepath.Base(remoteEchoFile))
_, err = runKubectl(t, kubeconfigPath, envVarsWithProxy, "cp", fmt.Sprintf("%s/%s:%s", runningTestPod.Namespace, runningTestPod.Name, remoteEchoFile), localEchoFile) _, err = runKubectl(t, kubeconfigPath, envVarsWithProxy, "cp", fmt.Sprintf("%s/%s:%s", runningTestPod.Namespace, runningTestPod.Name, remoteEchoFile), localEchoFile)
require.NoError(t, err, `"kubectl cp" failed`) require.NoError(t, err, `"kubectl cp" failed`)
localEchoFileData, err := ioutil.ReadFile(localEchoFile) localEchoFileData, err := os.ReadFile(localEchoFile)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, echoString+"\n", string(localEchoFileData)) 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()) }() defer func() { requireEventually.NoError(resp.Body.Close()) }()
} }
if err != nil && resp != nil { 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) t.Logf("websocket dial failed: %d:%s", resp.StatusCode, body)
} }
requireEventually.NoError(err) requireEventually.NoError(err)
@ -1283,7 +1283,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl
require.NoError(t, err) require.NoError(t, err)
response, err := httpClient.Do(getConfigmapRequest) response, err := httpClient.Do(getConfigmapRequest)
require.NoError(t, err) 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) 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/2.0", response.Proto)
require.Equal(t, http.StatusOK, response.StatusCode) 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. // Write the kubeconfig to a temp file.
kubeconfigPath := filepath.Join(tempDir, "kubeconfig.yaml") 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 return kubeconfigPath, envVarsWithProxy, tempDir
} }

View File

@ -11,7 +11,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"os/exec" "os/exec"
@ -84,7 +83,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
testCABundlePath := filepath.Join(testutil.TempDir(t), "test-ca.pem") testCABundlePath := filepath.Join(testutil.TempDir(t), "test-ca.pem")
testCABundlePEM := []byte(string(ca.Bundle()) + "\n" + env.SupervisorUpstreamOIDC.CABundle) testCABundlePEM := []byte(string(ca.Bundle()) + "\n" + env.SupervisorUpstreamOIDC.CABundle)
testCABundleBase64 := base64.StdEncoding.EncodeToString(testCABundlePEM) 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. // Use the CA to issue a TLS server cert.
t.Logf("issuing test certificate") t.Logf("issuing test certificate")
@ -304,7 +303,7 @@ func TestE2EFullIntegration_Browser(t *testing.T) {
t.Logf("waiting for kubectl to output namespace list") t.Logf("waiting for kubectl to output namespace list")
// Read all output from the subprocess until EOF. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes))
t.Logf("first kubectl command took %s", time.Since(start).String()) 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") t.Logf("waiting for kubectl to output namespace list")
// Read all output from the subprocess until EOF. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // Ignore any errors returned because there is always an error on linux.
kubectlPtyOutputBytes, _ := ioutil.ReadAll(ptyFile) kubectlPtyOutputBytes, _ := io.ReadAll(ptyFile)
if kubectlStdoutPipe != nil { if kubectlStdoutPipe != nil {
// On non-MacOS check that stdout of the CLI contains the expected output. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes))
} else { } else {
// On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. // 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. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes))
t.Logf("first kubectl command took %s", time.Since(start).String()) 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. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // Ignore any errors returned because there is always an error on linux.
kubectlOutputBytes, _ := ioutil.ReadAll(ptyFile) kubectlOutputBytes, _ := io.ReadAll(ptyFile)
kubectlOutput := string(kubectlOutputBytes) kubectlOutput := string(kubectlOutputBytes)
// The output should look like an authentication failure, because the OIDCIdentityProvider disallows password grants. // 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. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes))
t.Logf("first kubectl command took %s", time.Since(start).String()) 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. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes))
t.Logf("first kubectl command took %s", time.Since(start).String()) 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. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes))
t.Logf("first kubectl command took %s", time.Since(start).String()) 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. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlOutputBytes))
t.Logf("first kubectl command took %s", time.Since(start).String()) 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]) require.Equal(t, []string{"login", "oidc"}, restConfig.ExecProvider.Args[:2])
kubeconfigPath := filepath.Join(tempDir, "kubeconfig.yaml") 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 return kubeconfigPath
} }

View File

@ -10,7 +10,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -587,7 +586,7 @@ func requireSuccessEndpointResponse(t *testing.T, endpointURL, issuer, caBundle
requireEventually.Equal(http.StatusOK, response.StatusCode) requireEventually.Equal(http.StatusOK, response.StatusCode)
responseBody, err = ioutil.ReadAll(response.Body) responseBody, err = io.ReadAll(response.Body)
requireEventually.NoError(err) requireEventually.NoError(err)
}, 2*time.Minute, 200*time.Millisecond) }, 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)) caCertPool.AppendCertsFromPEM([]byte(caBundle))
c.Transport = &http.Transport{ c.Transport = &http.Transport{
DialContext: overrideDialContext, 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 { } else {
c.Transport = &http.Transport{ c.Transport = &http.Transport{

View File

@ -7,7 +7,7 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"testing" "testing"
"time" "time"
@ -58,7 +58,7 @@ func httpGet(ctx context.Context, t *testing.T, client *http.Client, url string,
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, expectedStatus, response.StatusCode) require.Equal(t, expectedStatus, response.StatusCode)
responseBody, err := ioutil.ReadAll(response.Body) responseBody, err := io.ReadAll(response.Body)
require.NoError(t, err) require.NoError(t, err)
err = response.Body.Close() err = response.Body.Close()
require.NoError(t, err) require.NoError(t, err)

View File

@ -10,7 +10,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@ -1701,7 +1701,7 @@ func requestAuthorizationUsingCLIPasswordFlow(t *testing.T, downstreamAuthorizeU
return false, nil return false, nil
} }
defer func() { _ = authResponse.Body.Close() }() defer func() { _ = authResponse.Body.Close() }()
responseBody, err = ioutil.ReadAll(authResponse.Body) responseBody, err = io.ReadAll(authResponse.Body)
if err != nil { if err != nil {
return false, nil return false, nil
} }

View File

@ -7,7 +7,6 @@ import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"os/exec" "os/exec"
@ -65,7 +64,7 @@ func TestSupervisorWarnings_Browser(t *testing.T) {
testCABundlePath := filepath.Join(tempDir, "test-ca.pem") testCABundlePath := filepath.Join(tempDir, "test-ca.pem")
testCABundlePEM := []byte(string(ca.Bundle()) + "\n" + env.SupervisorUpstreamOIDC.CABundle) testCABundlePEM := []byte(string(ca.Bundle()) + "\n" + env.SupervisorUpstreamOIDC.CABundle)
testCABundleBase64 := base64.StdEncoding.EncodeToString(testCABundlePEM) 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. // Use the CA to issue a TLS server cert.
t.Logf("issuing test certificate") t.Logf("issuing test certificate")
@ -149,10 +148,10 @@ func TestSupervisorWarnings_Browser(t *testing.T) {
t.Logf("waiting for kubectl to output namespace list") t.Logf("waiting for kubectl to output namespace list")
// Read all output from the subprocess until EOF. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // Ignore any errors returned because there is always an error on linux.
kubectlPtyOutputBytes, _ := ioutil.ReadAll(ptyFile) kubectlPtyOutputBytes, _ := io.ReadAll(ptyFile)
if kubectlStdoutPipe != nil { if kubectlStdoutPipe != nil {
// On non-MacOS check that stdout of the CLI contains the expected output. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes))
} else { } else {
// On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. // 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") t.Logf("waiting for kubectl to output namespace list")
// Read all output from the subprocess until EOF. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // Ignore any errors returned because there is always an error on linux.
kubectlPtyOutputBytes2, _ := ioutil.ReadAll(ptyFile2) kubectlPtyOutputBytes2, _ := io.ReadAll(ptyFile2)
if kubectlStdoutPipe2 != nil { if kubectlStdoutPipe2 != nil {
// On non-MacOS check that stdout of the CLI contains the expected output. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes2))
} else { } else {
// On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. // 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") t.Logf("waiting for kubectl to output namespace list")
// Read all output from the subprocess until EOF. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // Ignore any errors returned because there is always an error on linux.
kubectlPtyOutputBytes, _ := ioutil.ReadAll(ptyFile) kubectlPtyOutputBytes, _ := io.ReadAll(ptyFile)
if kubectlStdoutPipe != nil { if kubectlStdoutPipe != nil {
// On non-MacOS check that stdout of the CLI contains the expected output. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes))
} else { } else {
// On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. // 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") t.Logf("waiting for kubectl to output namespace list")
// Read all output from the subprocess until EOF. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // Ignore any errors returned because there is always an error on linux.
kubectlPtyOutputBytes2, _ := ioutil.ReadAll(ptyFile2) kubectlPtyOutputBytes2, _ := io.ReadAll(ptyFile2)
if kubectlStdoutPipe2 != nil { if kubectlStdoutPipe2 != nil {
// On non-MacOS check that stdout of the CLI contains the expected output. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes2))
} else { } else {
// On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. // 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") t.Logf("waiting for kubectl to output namespace list")
// Read all output from the subprocess until EOF. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // Ignore any errors returned because there is always an error on linux.
kubectlPtyOutputBytes, _ := ioutil.ReadAll(ptyFile) kubectlPtyOutputBytes, _ := io.ReadAll(ptyFile)
if kubectlStdoutPipe != nil { if kubectlStdoutPipe != nil {
// On non-MacOS check that stdout of the CLI contains the expected output. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes))
} else { } else {
// On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. // 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") t.Logf("waiting for kubectl to output namespace list")
// Read all output from the subprocess until EOF. // Read all output from the subprocess until EOF.
// Ignore any errors returned because there is always an error on linux. // Ignore any errors returned because there is always an error on linux.
kubectlPtyOutputBytes2, _ := ioutil.ReadAll(ptyFile2) kubectlPtyOutputBytes2, _ := io.ReadAll(ptyFile2)
if kubectlStdoutPipe2 != nil { if kubectlStdoutPipe2 != nil {
// On non-MacOS check that stdout of the CLI contains the expected output. // 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)) requireKubectlGetNamespaceOutput(t, env, string(kubectlStdOutOutputBytes2))
} else { } else {
// On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output. // On MacOS check that the pty (stdout+stderr+stdin) of the CLI contains the expected output.

View File

@ -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 // SPDX-License-Identifier: Apache-2.0
package testlib package testlib
import ( import (
"context" "context"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"testing" "testing"
@ -154,7 +153,7 @@ func runKubectlGetNamespaces(t *testing.T, kubeConfigYAML string) (string, error
f := writeStringToTempFile(t, "pinniped-generated-kubeconfig-*", kubeConfigYAML) 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( output, err := exec.Command(
"kubectl", "get", "namespace", "--kubeconfig", f.Name(), "kubectl", "get", "namespace", "--kubeconfig", f.Name(),
).CombinedOutput() ).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 { func writeStringToTempFile(t *testing.T, filename string, kubeConfigYAML string) *os.File {
t.Helper() t.Helper()
f, err := ioutil.TempFile("", filename) f, err := os.CreateTemp("", filename)
require.NoError(t, err) require.NoError(t, err)
deferMe := func() { deferMe := func() {
err := os.Remove(f.Name()) err := os.Remove(f.Name())

Some files were not shown because too many files have changed in this diff Show More