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
enable:
# default linters
- deadcode
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- structcheck
- typecheck
- unused
- varcheck
# additional linters for this project (we should disable these if they get annoying).
- asciicheck

View File

@ -8,7 +8,6 @@ import (
"encoding/base64"
"encoding/json"
"io"
"io/ioutil"
"log"
"math"
"os"
@ -35,11 +34,11 @@ func main() {
case "sleep":
sleep(math.MaxInt64)
case "print":
certBytes, err := ioutil.ReadFile(getenv("CERT_PATH"))
certBytes, err := os.ReadFile(getenv("CERT_PATH"))
if err != nil {
fail("could not read CERT_PATH: %v", err)
}
keyBytes, err := ioutil.ReadFile(getenv("KEY_PATH"))
keyBytes, err := os.ReadFile(getenv("KEY_PATH"))
if err != nil {
fail("could not read KEY_PATH: %v", err)
}

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
package cmd

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

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
package cmd
@ -6,7 +6,7 @@ package cmd
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
@ -54,10 +54,10 @@ func TestCABundleFlag(t *testing.T) {
require.NoError(t, err)
tmpdir := testutil.TempDir(t)
emptyFilePath := filepath.Join(tmpdir, "empty")
require.NoError(t, ioutil.WriteFile(emptyFilePath, []byte{}, 0600))
require.NoError(t, os.WriteFile(emptyFilePath, []byte{}, 0600))
testCAPath := filepath.Join(tmpdir, "testca.pem")
require.NoError(t, ioutil.WriteFile(testCAPath, testCA.Bundle(), 0600))
require.NoError(t, os.WriteFile(testCAPath, testCA.Bundle(), 0600))
f := caBundleFlag{}
require.Equal(t, "path", f.Type())

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
package cmd

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
package cmd

View File

@ -10,7 +10,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
@ -717,7 +716,7 @@ func validateKubeconfig(ctx context.Context, flags getKubeconfigParams, kubeconf
func countCACerts(pemData []byte) int {
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(pemData)
return len(pool.Subjects()) // nolint: staticcheck // not system cert pool
return len(pool.Subjects())
}
func hasPendingStrategy(credentialIssuer *configv1alpha1.CredentialIssuer) bool {
@ -815,7 +814,7 @@ func discoverAllAvailableSupervisorUpstreamIDPs(ctx context.Context, pinnipedIDP
return nil, fmt.Errorf("unable to fetch IDP discovery data from issuer: unexpected http response status: %s", response.Status)
}
rawBody, err := ioutil.ReadAll(response.Body)
rawBody, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("unable to fetch IDP discovery data from issuer: could not read response body: %w", err)
}

View File

@ -7,8 +7,8 @@ import (
"bytes"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"testing"
"time"
@ -34,12 +34,12 @@ func TestGetKubeconfig(t *testing.T) {
require.NoError(t, err)
tmpdir := testutil.TempDir(t)
testOIDCCABundlePath := filepath.Join(tmpdir, "testca.pem")
require.NoError(t, ioutil.WriteFile(testOIDCCABundlePath, testOIDCCA.Bundle(), 0600))
require.NoError(t, os.WriteFile(testOIDCCABundlePath, testOIDCCA.Bundle(), 0600))
testConciergeCA, err := certauthority.New("Test Concierge CA", 1*time.Hour)
require.NoError(t, err)
testConciergeCABundlePath := filepath.Join(tmpdir, "testconciergeca.pem")
require.NoError(t, ioutil.WriteFile(testConciergeCABundlePath, testConciergeCA.Bundle(), 0600))
require.NoError(t, os.WriteFile(testConciergeCABundlePath, testConciergeCA.Bundle(), 0600))
credentialIssuer := func() runtime.Object {
return &configv1alpha1.CredentialIssuer{

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
package cmd

View File

@ -9,7 +9,6 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
@ -317,7 +316,7 @@ func flowOptions(
func makeClient(caBundlePaths []string, caBundleData []string) (*http.Client, error) {
pool := x509.NewCertPool()
for _, p := range caBundlePaths {
pem, err := ioutil.ReadFile(p)
pem, err := os.ReadFile(p)
if err != nil {
return nil, fmt.Errorf("could not read --ca-bundle: %w", err)
}
@ -361,10 +360,14 @@ func SetLogLevel(ctx context.Context, lookupEnv func(string) (string, bool)) (pl
return logger, nil
}
// mustGetConfigDir returns a directory that follows the XDG base directory convention:
// $XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should
// be stored. If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used.
// [1] https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
/*
mustGetConfigDir returns a directory that follows the XDG base directory convention:
$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should
be stored. If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used.
[1] https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
*/
func mustGetConfigDir() string {
const xdgAppName = "pinniped"

View File

@ -8,7 +8,7 @@ import (
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
@ -36,7 +36,7 @@ func TestLoginOIDCCommand(t *testing.T) {
require.NoError(t, err)
tmpdir := testutil.TempDir(t)
testCABundlePath := filepath.Join(tmpdir, "testca.pem")
require.NoError(t, ioutil.WriteFile(testCABundlePath, testCA.Bundle(), 0600))
require.NoError(t, os.WriteFile(testCABundlePath, testCA.Bundle(), 0600))
time1 := time.Date(3020, 10, 12, 13, 14, 15, 16, time.UTC)
@ -483,8 +483,8 @@ func TestLoginOIDCCommand(t *testing.T) {
wantOptionsCount: 4,
wantStdout: `{"kind":"ExecCredential","apiVersion":"client.authentication.k8s.io/v1beta1","spec":{"interactive":false},"status":{"expirationTimestamp":"3020-10-12T13:14:15Z","token":"test-id-token"}}` + "\n",
wantLogs: []string{
nowStr + ` pinniped-login cmd/login_oidc.go:232 Performing OIDC login {"issuer": "test-issuer", "client id": "test-client-id"}`,
nowStr + ` pinniped-login cmd/login_oidc.go:252 No concierge configured, skipping token credential exchange`,
nowStr + ` pinniped-login cmd/login_oidc.go:231 Performing OIDC login {"issuer": "test-issuer", "client id": "test-client-id"}`,
nowStr + ` pinniped-login cmd/login_oidc.go:251 No concierge configured, skipping token credential exchange`,
},
},
{
@ -513,10 +513,10 @@ func TestLoginOIDCCommand(t *testing.T) {
wantOptionsCount: 11,
wantStdout: `{"kind":"ExecCredential","apiVersion":"client.authentication.k8s.io/v1beta1","spec":{"interactive":false},"status":{"token":"exchanged-token"}}` + "\n",
wantLogs: []string{
nowStr + ` pinniped-login cmd/login_oidc.go:232 Performing OIDC login {"issuer": "test-issuer", "client id": "test-client-id"}`,
nowStr + ` pinniped-login cmd/login_oidc.go:242 Exchanging token for cluster credential {"endpoint": "https://127.0.0.1:1234/", "authenticator type": "webhook", "authenticator name": "test-authenticator"}`,
nowStr + ` pinniped-login cmd/login_oidc.go:250 Successfully exchanged token for cluster credential.`,
nowStr + ` pinniped-login cmd/login_oidc.go:257 caching cluster credential for future use.`,
nowStr + ` pinniped-login cmd/login_oidc.go:231 Performing OIDC login {"issuer": "test-issuer", "client id": "test-client-id"}`,
nowStr + ` pinniped-login cmd/login_oidc.go:241 Exchanging token for cluster credential {"endpoint": "https://127.0.0.1:1234/", "authenticator type": "webhook", "authenticator name": "test-authenticator"}`,
nowStr + ` pinniped-login cmd/login_oidc.go:249 Successfully exchanged token for cluster credential.`,
nowStr + ` pinniped-login cmd/login_oidc.go:256 caching cluster credential for future use.`,
},
},
}

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
package cmd

View File

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

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
package cmd

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
package cmd

View File

@ -8,9 +8,14 @@ set -euo pipefail
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
cd "${ROOT}"
# Print the Go version.
go version
# Install the same version of the linter that is used in the CI pipelines
# so you can get the same results when running the linter locally.
# Whenever the linter is updated in the CI pipelines, it should also be
# updated here to make local development more convenient.
go install -v github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.0
go install -v github.com/golangci/golangci-lint/cmd/golangci-lint@v1.49.0
golangci-lint --version
echo "Finished. You may need to run 'rehash' in your current shell before using the new version (e.g. if you are using gvm)."

View File

@ -10,7 +10,7 @@ import (
"k8s.io/apiserver/pkg/authentication/user"
)
// This interface is similar to the k8s token authenticator, but works with username/passwords instead
// UserAuthenticator is an interface is similar to the k8s token authenticator, but works with username/passwords instead
// of a single token string.
//
// The return values should be as follows.

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

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
package apiserver

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

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

View File

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

View File

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

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
// Package webhookcachefiller implements a controller for filling an authncache.Cache with each added/updated WebhookAuthenticator.
@ -6,7 +6,6 @@ package webhookcachefiller
import (
"fmt"
"io/ioutil"
"os"
"github.com/go-logr/logr"
@ -64,7 +63,7 @@ func (c *controller) Sync(ctx controllerlib.Context) error {
return fmt.Errorf("failed to get WebhookAuthenticator %s/%s: %w", ctx.Key.Namespace, ctx.Key.Name, err)
}
webhookAuthenticator, err := newWebhookAuthenticator(&obj.Spec, ioutil.TempFile, clientcmd.WriteToFile)
webhookAuthenticator, err := newWebhookAuthenticator(&obj.Spec, os.CreateTemp, clientcmd.WriteToFile)
if err != nil {
return fmt.Errorf("failed to build webhook config: %w", err)
}

View File

@ -7,7 +7,7 @@ import (
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"io"
"net/http"
"os"
"testing"
@ -121,7 +121,7 @@ func TestNewWebhookAuthenticator(t *testing.T) {
t.Run("marshal failure", func(t *testing.T) {
marshalError := func(_ clientcmdapi.Config, _ string) error { return fmt.Errorf("some marshal error") }
res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{}, ioutil.TempFile, marshalError)
res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{}, os.CreateTemp, marshalError)
require.Nil(t, res)
require.EqualError(t, err, "unable to marshal kubeconfig: some marshal error")
})
@ -130,7 +130,7 @@ func TestNewWebhookAuthenticator(t *testing.T) {
res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{
Endpoint: "https://example.com",
TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: "invalid-base64"},
}, ioutil.TempFile, clientcmd.WriteToFile)
}, os.CreateTemp, clientcmd.WriteToFile)
require.Nil(t, res)
require.EqualError(t, err, "invalid TLS configuration: illegal base64 data at input byte 7")
})
@ -139,7 +139,7 @@ func TestNewWebhookAuthenticator(t *testing.T) {
res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{
Endpoint: "https://example.com",
TLS: &auth1alpha1.TLSSpec{CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte("bad data"))},
}, ioutil.TempFile, clientcmd.WriteToFile)
}, os.CreateTemp, clientcmd.WriteToFile)
require.Nil(t, res)
require.EqualError(t, err, "invalid TLS configuration: certificateAuthorityData is not valid PEM: data does not contain any valid RSA or ECDSA certificates")
})
@ -147,14 +147,14 @@ func TestNewWebhookAuthenticator(t *testing.T) {
t.Run("valid config with no TLS spec", func(t *testing.T) {
res, err := newWebhookAuthenticator(&auth1alpha1.WebhookAuthenticatorSpec{
Endpoint: "https://example.com",
}, ioutil.TempFile, clientcmd.WriteToFile)
}, os.CreateTemp, clientcmd.WriteToFile)
require.NotNil(t, res)
require.NoError(t, err)
})
t.Run("success", func(t *testing.T) {
caBundle, url := testutil.TLSTestServer(t, func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
require.Contains(t, string(body), "test-token")
_, err = w.Write([]byte(`{}`))
@ -166,7 +166,7 @@ func TestNewWebhookAuthenticator(t *testing.T) {
CertificateAuthorityData: base64.StdEncoding.EncodeToString([]byte(caBundle)),
},
}
res, err := newWebhookAuthenticator(spec, ioutil.TempFile, clientcmd.WriteToFile)
res, err := newWebhookAuthenticator(spec, os.CreateTemp, clientcmd.WriteToFile)
require.NoError(t, err)
require.NotNil(t, res)

View File

@ -11,7 +11,7 @@ import (
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"reflect"
@ -360,10 +360,13 @@ func TestImpersonatorConfigControllerSync(t *testing.T) {
}
testHTTPServerMutex.Lock() // this is to satisfy the race detector
testHTTPServer = &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
testHTTPServer = &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
_, err := fmt.Fprint(w, fakeServerResponseBody)
r.NoError(err)
})}
}),
ReadHeaderTimeout: 10 * time.Second,
}
testHTTPServerMutex.Unlock()
// Start serving requests in the background.
@ -480,7 +483,7 @@ func TestImpersonatorConfigControllerSync(t *testing.T) {
r.NoError(err)
r.Equal(http.StatusOK, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
r.NoError(resp.Body.Close())
r.NoError(err)
r.Equal(fakeServerResponseBody, string(body))

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
// Package issuerconfig contains helpers for updating CredentialIssuer status entries.
@ -60,8 +60,7 @@ func mergeStrategy(configToUpdate *v1alpha1.CredentialIssuerStatus, strategy v1a
}
// weights are a set of priorities for each strategy type.
//nolint: gochecknoglobals
var weights = map[v1alpha1.StrategyType]int{
var weights = map[v1alpha1.StrategyType]int{ //nolint:gochecknoglobals
v1alpha1.KubeClusterSigningCertificateStrategyType: 2, // most preferred strategy
v1alpha1.ImpersonationProxyStrategyType: 1,
// unknown strategy types will have weight 0 by default

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

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

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

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

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.
//nolint:funlen // Eh, fair, it is a really long function...but it is wiring the world...so...
func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) {
func PrepareControllers(c *Config) (controllerinit.RunnerBuilder, error) { //nolint:funlen // Eh, fair, it is a really long function...but it is wiring the world...so...
loginConciergeGroupData, identityConciergeGroupData := groupsuffix.ConciergeAggregatedGroups(c.APIGroupSuffix)
dref, deployment, _, err := deploymentref.New(c.ServerInstallationInfo)

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
package crud

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

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

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
package dynamiccert
@ -41,7 +41,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) {
cert, err := tls.X509KeyPair(certPEM, keyPEM)
require.NoError(t, err)
return pool.Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool
return pool.Subjects(), []tls.Certificate{cert}
},
},
{
@ -69,7 +69,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) {
certKey.UnsetCertKeyContent()
return pool.Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool
return pool.Subjects(), []tls.Certificate{cert}
},
},
{
@ -87,7 +87,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) {
cert, err := tls.X509KeyPair(certPEM, keyPEM)
require.NoError(t, err)
return newCA.Pool().Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool
return newCA.Pool().Subjects(), []tls.Certificate{cert}
},
},
{
@ -110,7 +110,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) {
ok := pool.AppendCertsFromPEM(ca.CurrentCABundleContent())
require.True(t, ok, "should have valid non-empty CA bundle")
return pool.Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool
return pool.Subjects(), []tls.Certificate{cert}
},
},
{
@ -137,7 +137,7 @@ func TestProviderWithDynamicServingCertificateController(t *testing.T) {
err = ca.SetCertKeyContent(newOtherCA.Bundle(), caKey)
require.NoError(t, err)
return newOtherCA.Pool().Subjects(), []tls.Certificate{cert} // nolint: staticcheck // not system cert pool
return newOtherCA.Pool().Subjects(), []tls.Certificate{cert}
},
},
}
@ -221,7 +221,7 @@ func poolSubjects(pool *x509.CertPool) [][]byte {
if pool == nil {
return nil
}
return pool.Subjects() // nolint: staticcheck // not system cert pool
return pool.Subjects()
}
func TestNewServingCert(t *testing.T) {

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
package execcredcache
@ -6,7 +6,6 @@ package execcredcache
import (
"errors"
"fmt"
"io/ioutil"
"os"
"sort"
"time"
@ -51,7 +50,7 @@ type (
// readCache loads a credCache from a path on disk. If the requested path does not exist, it returns an empty cache.
func readCache(path string) (*credCache, error) {
cacheYAML, err := ioutil.ReadFile(path)
cacheYAML, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// If the file was not found, generate a freshly initialized empty cache.
@ -87,7 +86,7 @@ func (c *credCache) writeTo(path string) error {
// Marshal the cache back to YAML and save it to the file.
cacheYAML, err := yaml.Marshal(c)
if err == nil {
err = ioutil.WriteFile(path, cacheYAML, 0600)
err = os.WriteFile(path, cacheYAML, 0600)
}
return err
}

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

View File

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

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
package groupsuffix

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

View File

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

View File

@ -949,7 +949,7 @@ func TestUnwrap(t *testing.T) {
server, restConfig := fakekubeapi.Start(t, nil)
serverSubjects := server.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs.Subjects() // nolint: staticcheck // not system cert pool
serverSubjects := server.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs.Subjects()
t.Run("regular client", func(t *testing.T) {
t.Parallel() // make sure to run in parallel to confirm that our client-go TLS cache busting works (i.e. assert no data races)
@ -1121,7 +1121,7 @@ func testUnwrap(t *testing.T, client *Client, serverSubjects [][]byte) {
require.Equal(t, secureTLSConfig.NextProtos, tlsConfig.NextProtos)
// x509.CertPool has some embedded functions that make it hard to compare so just look at the subjects
require.Equal(t, serverSubjects, tlsConfig.RootCAs.Subjects()) // nolint: staticcheck // not system cert pool
require.Equal(t, serverSubjects, tlsConfig.RootCAs.Subjects())
})
}
}

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
package kubeclient

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

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

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
package kubeclient
@ -7,7 +7,6 @@ import (
stderrors "errors"
"fmt"
"io"
"io/ioutil"
"net/http"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -155,7 +154,7 @@ func drainAndMaybeCloseBody(resp *http.Response, close bool) {
// from k8s.io/client-go/rest/request.go...
const maxBodySlurpSize = 2 << 10
if resp.ContentLength <= maxBodySlurpSize {
_, _ = io.Copy(ioutil.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize})
_, _ = io.Copy(io.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize})
}
if close {
resp.Body.Close()

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
package leaderelection
@ -184,7 +184,7 @@ func (t *isLeaderTracker) start() {
}
func (t *isLeaderTracker) stop() (didStop bool) {
return t.tracker.CAS(true, false)
return t.tracker.CompareAndSwap(true, false)
}
// note that resourcelock.Interface is an internal, unstable interface.

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
// Package localuserauthenticator provides a authentication webhook program.
@ -81,6 +81,7 @@ func (w *webhook) start(ctx context.Context, l net.Listener) error {
server := http.Server{
Handler: w,
TLSConfig: c,
ReadHeaderTimeout: 10 * time.Second,
}
errCh := make(chan error)

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
package localuserauthenticator
@ -10,7 +10,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
@ -385,7 +384,7 @@ func TestWebhook(t *testing.T) {
url: goodURL,
method: http.MethodPost,
headers: goodRequestHeaders,
body: func() (io.ReadCloser, error) { return ioutil.NopCloser(bytes.NewBuffer([]byte("invalid body"))), nil },
body: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewBuffer([]byte("invalid body"))), nil },
wantStatus: http.StatusBadRequest,
},
}
@ -416,7 +415,7 @@ func TestWebhook(t *testing.T) {
}
}
responseBody, err := ioutil.ReadAll(rsp.Body)
responseBody, err := io.ReadAll(rsp.Body)
require.NoError(t, err)
if test.wantBody != nil {
require.NoError(t, err)
@ -520,7 +519,7 @@ func newTokenReviewBodyWithGVK(token string, gvk *schema.GroupVersionKind) (io.R
},
}
err := json.NewEncoder(buf).Encode(&tr)
return ioutil.NopCloser(buf), err
return io.NopCloser(buf), err
}
func unauthenticatedResponseJSON() *authenticationv1beta1.TokenReview {

View File

@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// Package loginhtml defines HTML templates used by the Supervisor.
//nolint: gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init.
package loginhtml
import (
@ -15,6 +14,7 @@ import (
"go.pinniped.dev/internal/oidc/provider/csp"
)
//nolint:gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init.
var (
//go:embed login_form.css
rawCSS string
@ -22,19 +22,19 @@ var (
//go:embed login_form.gohtml
rawHTMLTemplate string
)
// 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{
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{
cspValue = strings.Join([]string{
`default-src 'none'`,
`style-src '` + csp.Hash(minifiedCSS) + `'`,
`frame-ancestors 'none'`,
}, "; ")
)
func panicOnError(s string, err error) string {
if err != nil {

View File

@ -255,6 +255,7 @@ func FositeOauth2Helper(
// passed to a plog function (e.g., plog.Info()).
//
// Sample usage:
//
// err := someFositeLibraryFunction()
// if err != nil {
// plog.Info("some error", FositeErrorForLog(err)...)

View File

@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// Package formposthtml defines HTML templates used by the Supervisor.
//nolint: gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init.
package formposthtml
import (
@ -15,6 +14,7 @@ import (
"go.pinniped.dev/internal/oidc/provider/csp"
)
//nolint:gochecknoglobals // This package uses globals to ensure that all parsing and minifying happens at init.
var (
//go:embed form_post.css
rawCSS string
@ -26,16 +26,15 @@ var (
//go:embed form_post.gohtml
rawHTMLTemplate string
)
// 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{
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{
cspValue = strings.Join([]string{
`default-src 'none'`,
`script-src '` + csp.Hash(minifiedJS) + `'`,
`style-src '` + csp.Hash(minifiedCSS) + `'`,
@ -43,6 +42,7 @@ var cspValue = strings.Join([]string{
`connect-src *`,
`frame-ancestors 'none'`,
}, "; ")
)
func panicOnError(s string, err error) string {
if err != nil {

View File

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

View File

@ -14,7 +14,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
@ -109,7 +108,7 @@ var (
fositeInvalidPayloadErrorBody = here.Doc(`
{
"error": "invalid_request",
"error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. The POST body can not be empty."
"error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Unable to parse HTTP body, make sure to send a properly formatted form request body."
}
`)
@ -372,7 +371,7 @@ func TestTokenEndpointAuthcodeExchange(t *testing.T) {
name: "payload is not valid form serialization",
authcodeExchange: authcodeExchangeInputs{
modifyTokenRequest: func(r *http.Request, authCode string) {
r.Body = ioutil.NopCloser(strings.NewReader("this newline character is not allowed in a form serialization: \n"))
r.Body = io.NopCloser(strings.NewReader("this newline character is not allowed in a form serialization: \n"))
},
want: tokenEndpointResponseExpectedValues{
wantStatus: http.StatusBadRequest,
@ -3074,7 +3073,7 @@ func (b body) WithPKCE(verifier string) body {
}
func (b body) ReadCloser() io.ReadCloser {
return ioutil.NopCloser(strings.NewReader(url.Values(b).Encode()))
return io.NopCloser(strings.NewReader(url.Values(b).Encode()))
}
func (b body) with(param, value string) body {

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
package oidc

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
package ownerref

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

View File

@ -67,6 +67,7 @@ func startServer(ctx context.Context, shutdown *sync.WaitGroup, l net.Listener,
server := http.Server{
Handler: handler,
ConnContext: withBootstrapConnCtx,
ReadHeaderTimeout: 10 * time.Second,
}
shutdown.Add(1)

View File

@ -1,25 +1,28 @@
// Copyright 2021-2022 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package fakekubeapi contains a *very* simple httptest.Server that can be used to stand in for
// a real Kube API server in tests.
//
// Usage:
// func TestSomething(t *testing.T) {
// resources := map[string]kubeclient.Object{
// // store preexisting resources here
// "/api/v1/namespaces/default/pods/some-pod-name": &corev1.Pod{...},
// }
// server, restConfig := fakekubeapi.Start(t, resources)
// defer server.Close()
// client := kubeclient.New(kubeclient.WithConfig(restConfig))
// // do stuff with client...
// }
/*
Package fakekubeapi contains a *very* simple httptest.Server that can be used to stand in for
a real Kube API server in tests.
Usage:
func TestSomething(t *testing.T) {
resources := map[string]kubeclient.Object{
// store preexisting resources here
"/api/v1/namespaces/default/pods/some-pod-name": &corev1.Pod{...},
}
server, restConfig := fakekubeapi.Start(t, resources)
defer server.Close()
client := kubeclient.New(kubeclient.WithConfig(restConfig))
// do stuff with client...
}
*/
package fakekubeapi
import (
"fmt"
"io/ioutil"
"io"
"mime"
"net/http"
"net/http/httptest"
@ -104,7 +107,7 @@ func decodeObj(r *http.Request) (runtime.Object, error) {
return nil, httperr.Wrap(http.StatusUnsupportedMediaType, "could not parse mime type from content-type header", err)
}
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, httperr.Wrap(http.StatusInternalServerError, "read body", err)
}

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
package testutil
import (
"io"
"io/ioutil"
"os"
"testing"
@ -23,7 +22,7 @@ func (e *ErrorWriter) Write([]byte) (int, error) { return 0, e.ReturnError }
func WriteStringToTempFile(t *testing.T, filename string, fileBody string) *os.File {
t.Helper()
f, err := ioutil.TempFile("", filename)
f, err := os.CreateTemp("", filename)
require.NoError(t, err)
deferMe := func() {
err := os.Remove(f.Name())

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
//go:build !go1.14
// +build !go1.14
package testutil

View File

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

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
package testutil
@ -9,6 +9,7 @@ import (
"net"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/require"
@ -35,6 +36,7 @@ func TLSTestServerWithCert(t *testing.T, handler http.HandlerFunc, certificate *
server := http.Server{
TLSConfig: c,
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
}
l, err := net.Listen("tcp", "127.0.0.1:0")

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
package conciergeclient
@ -8,7 +8,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/url"
"testing"
@ -224,7 +224,7 @@ func TestExchangeToken(t *testing.T) {
require.Equal(t, "/apis/login.concierge.pinniped.dev/v1alpha1/tokencredentialrequests", r.URL.Path)
require.Equal(t, "application/json", r.Header.Get("content-type"))
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
require.JSONEq(t,
`{

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
// Package cachefile implements the file format for session caches.
// Package filesession implements the file format for session caches.
package filesession
import (
"errors"
"fmt"
"io/ioutil"
"os"
"reflect"
"sort"
@ -55,7 +54,7 @@ type (
// readSessionCache loads a sessionCache from a path on disk. If the requested path does not exist, it returns an empty cache.
func readSessionCache(path string) (*sessionCache, error) {
cacheYAML, err := ioutil.ReadFile(path)
cacheYAML, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// If the file was not found, generate a freshly initialized empty cache.
@ -91,7 +90,7 @@ func (c *sessionCache) writeTo(path string) error {
// Marshal the session back to YAML and save it to the file.
cacheYAML, err := yaml.Marshal(c)
if err == nil {
err = ioutil.WriteFile(path, cacheYAML, 0600)
err = os.WriteFile(path, cacheYAML, 0600)
}
return err
}

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

View File

@ -971,6 +971,7 @@ func (h *handlerState) serve(listener net.Listener) func() {
srv := http.Server{
Handler: securityheader.Wrap(mux),
BaseContext: func(_ net.Listener) context.Context { return h.ctx },
ReadHeaderTimeout: 10 * time.Second,
}
go func() { _ = srv.Serve(listener) }()
return func() {

View File

@ -10,7 +10,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/http/httptest"
@ -1040,7 +1040,7 @@ func TestLogin(t *testing.T) { // nolint:gocyclo
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"content-type": []string{"application/json"}},
Body: ioutil.NopCloser(strings.NewReader(string(jsonResponseBody))),
Body: io.NopCloser(strings.NewReader(string(jsonResponseBody))),
}, nil
default:
require.FailNow(t, fmt.Sprintf("saw unexpected http call from the CLI: %s", req.URL.String()))

View File

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

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
package integration

View File

@ -15,7 +15,7 @@ import (
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/url"
@ -1103,7 +1103,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl
localEchoFile := filepath.Join(tempDir, filepath.Base(remoteEchoFile))
_, err = runKubectl(t, kubeconfigPath, envVarsWithProxy, "cp", fmt.Sprintf("%s/%s:%s", runningTestPod.Namespace, runningTestPod.Name, remoteEchoFile), localEchoFile)
require.NoError(t, err, `"kubectl cp" failed`)
localEchoFileData, err := ioutil.ReadFile(localEchoFile)
localEchoFileData, err := os.ReadFile(localEchoFile)
require.NoError(t, err)
require.Equal(t, echoString+"\n", string(localEchoFileData))
@ -1197,7 +1197,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl
defer func() { requireEventually.NoError(resp.Body.Close()) }()
}
if err != nil && resp != nil {
body, _ := ioutil.ReadAll(resp.Body)
body, _ := io.ReadAll(resp.Body)
t.Logf("websocket dial failed: %d:%s", resp.StatusCode, body)
}
requireEventually.NoError(err)
@ -1283,7 +1283,7 @@ func TestImpersonationProxy(t *testing.T) { //nolint:gocyclo // yeah, it's compl
require.NoError(t, err)
response, err := httpClient.Do(getConfigmapRequest)
require.NoError(t, err)
body, _ := ioutil.ReadAll(response.Body)
body, _ := io.ReadAll(response.Body)
t.Logf("http2 status code: %d, proto: %s, message: %s", response.StatusCode, response.Proto, body)
require.Equal(t, "HTTP/2.0", response.Proto)
require.Equal(t, http.StatusOK, response.StatusCode)
@ -2212,7 +2212,7 @@ func getImpersonationKubeconfig(t *testing.T, env *testlib.TestEnv, impersonatio
// Write the kubeconfig to a temp file.
kubeconfigPath := filepath.Join(tempDir, "kubeconfig.yaml")
require.NoError(t, ioutil.WriteFile(kubeconfigPath, []byte(kubeconfigYAML), 0600))
require.NoError(t, os.WriteFile(kubeconfigPath, []byte(kubeconfigYAML), 0600))
return kubeconfigPath, envVarsWithProxy, tempDir
}

View File

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

View File

@ -10,7 +10,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
@ -587,7 +586,7 @@ func requireSuccessEndpointResponse(t *testing.T, endpointURL, issuer, caBundle
requireEventually.Equal(http.StatusOK, response.StatusCode)
responseBody, err = ioutil.ReadAll(response.Body)
responseBody, err = io.ReadAll(response.Body)
requireEventually.NoError(err)
}, 2*time.Minute, 200*time.Millisecond)

View File

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

View File

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

View File

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

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
package testlib
import (
"context"
"io/ioutil"
"os"
"os/exec"
"testing"
@ -164,7 +163,7 @@ func runKubectlGetNamespaces(t *testing.T, kubeConfigYAML string) (string, error
func writeStringToTempFile(t *testing.T, filename string, kubeConfigYAML string) *os.File {
t.Helper()
f, err := ioutil.TempFile("", filename)
f, err := os.CreateTemp("", filename)
require.NoError(t, err)
deferMe := func() {
err := os.Remove(f.Name())

View File

@ -1,10 +1,9 @@
// Copyright 2020-2021 the Pinniped contributors. All Rights Reserved.
// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package testlib
import (
"io/ioutil"
"os"
"os/exec"
"path/filepath"
@ -38,7 +37,7 @@ func PinnipedCLIPath(t *testing.T) string {
path := filepath.Join(testutil.TempDir(t), "pinniped")
if pinnipedCLIBinaryCache.buf != nil {
t.Log("using previously built pinniped CLI binary")
require.NoError(t, ioutil.WriteFile(path, pinnipedCLIBinaryCache.buf, 0500))
require.NoError(t, os.WriteFile(path, pinnipedCLIBinaryCache.buf, 0500))
return path
}
@ -49,7 +48,7 @@ func PinnipedCLIPath(t *testing.T) string {
t.Logf("built CLI binary in %s", time.Since(start).Round(time.Millisecond))
// Fill our cache so we don't have to do this again.
pinnipedCLIBinaryCache.buf, err = ioutil.ReadFile(path)
pinnipedCLIBinaryCache.buf, err = os.ReadFile(path)
require.NoError(t, err, string(output))
return path

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
package testlib
@ -10,7 +10,6 @@ import (
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"os"
"testing"
"time"
@ -54,7 +53,7 @@ func NewClientsetForKubeConfig(t *testing.T, kubeConfig string) kubernetes.Inter
}
func NewRestConfigFromKubeconfig(t *testing.T, kubeConfig string) *rest.Config {
kubeConfigFile, err := ioutil.TempFile("", "pinniped-cli-test-*")
kubeConfigFile, err := os.CreateTemp("", "pinniped-cli-test-*")
require.NoError(t, err)
defer func() {
require.NoError(t, os.Remove(kubeConfigFile.Name()))

View File

@ -5,7 +5,6 @@ package testlib
import (
"encoding/base64"
"io/ioutil"
"os"
"sort"
"strings"
@ -137,7 +136,7 @@ func IntegrationEnv(t *testing.T) *TestEnv {
"must specify either PINNIPED_TEST_CLUSTER_CAPABILITY_YAML or PINNIPED_TEST_CLUSTER_CAPABILITY_FILE env var for integration tests",
)
if capabilitiesDescriptionYAML == "" {
bytes, err := ioutil.ReadFile(capabilitiesDescriptionFile)
bytes, err := os.ReadFile(capabilitiesDescriptionFile)
capabilitiesDescriptionYAML = string(bytes)
require.NoError(t, err)
}

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
//go:build !go1.14
// +build !go1.14
package testlib

View File

@ -1,7 +1,7 @@
// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//nolint:goimports // not an import
//go:build go1.14
// +build go1.14
package testlib